Browse code

Minor change: Am trecut pe pinul D1 si am indentat.

Liviu Pislaru authored on 01/03/2018 17:05:08
Showing 1 changed files
1 1
old mode 100755
2 2
new mode 100644
... ...
@@ -1,17 +1,20 @@
1
-#include <FS.h>                   //this needs to be first, e folosit de salvarea credentialelor pe FS
1
+#include <FS.h> // librarie folosita de salvarea credentialelor pe FS
2 2
 #include <ESP8266WiFi.h>
3 3
 #include <PubSubClient.h>
4
-#include <WiFiManager.h>        //https://github.com/tzapu/WiFiManager
5
-#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson pentru salvarea credentialelor in eprom
6
-#include <WiFiClient.h> 
4
+#include <WiFiManager.h> // librarie folosita pentru salvarea credentialelor WIFI in eprom
5
+#include <ArduinoJson.h> // librarie folosita pentru salvarea credentialelor MQTT in eprom
6
+#include <WiFiClient.h>
7 7
 #include <OneWire.h>
8 8
 #include <DallasTemperature.h>
9 9
 #include <ESP8266HTTPClient.h>
10 10
 #include <ESP8266httpUpdate.h>
11 11
 
12
-char mqtt_user[9]; //le va lua din FS
13
-char mqtt_devid[5]; //le va lua din FS
14
-char mqttPassword[15]; //urmatoarele le va genera cu functia gen
12
+// variabilele user si devid sunt incarcate din eprom folosind FS
13
+char mqtt_user[9];
14
+char mqtt_devid[5];
15
+
16
+// variabile generate cu functia generate_vars, folosind user si devid
17
+char mqttPassword[15];
15 18
 char mqttSUB[22];
16 19
 char espName[13];
17 20
 char mqttESP[22];
... ...
@@ -19,28 +22,22 @@ char mqttTEMP[23];
19 19
 char mqttLWT[22];
20 20
 
21 21
 const String model = "NodeMCU Dallas";
22
-const String ver = "v2.1.0";
22
+const String ver = "v2.0.2";
23 23
 const char* mqttServer = "mqtt.clickhome.ro";
24 24
 const int mqttPort = 1883;
25
-long loopTimer = 900000; // miliseconds - by default trimite la 15 minute
25
+long loopTimer = 900000; // by default trimite temperatura la 15 minute
26 26
 long lastMsg = 0;
27 27
 float loopTemp = 0;
28 28
 int inPin = 5;
29 29
 String mqttMessage;
30 30
 
31
-// senzor de temperatura DALLAS
32
-#define ONE_WIRE_BUS D4  // pinul de date (la mine am pus senzor pe D4)
31
+#define ONE_WIRE_BUS D1  // pinul de date folosit la nodeMCU este D1
33 32
 OneWire oneWire(ONE_WIRE_BUS);
34 33
 DallasTemperature sensors(&oneWire);
35
-
36
-//*********************************************************************
37
-
38 34
 WiFiClient espClient;
39 35
 PubSubClient client(espClient);
40
-bool readConfigFile();
41
-
42 36
 
43
-void generate_vars(){
37
+void generate_vars() {
44 38
   strcpy (mqttPassword, "8219CH");
45 39
   strcat (mqttPassword, mqtt_user);
46 40
 
... ...
@@ -65,7 +62,7 @@ void generate_vars(){
65 65
   strcat (mqttLWT, "/LWT");
66 66
 }
67 67
 
68
-String ipToString(IPAddress ip){
68
+String ipToString(IPAddress ip) {
69 69
   String s="";
70 70
   for (int i=0; i<4; i++)
71 71
     s += i  ? "." + String(ip[i]) : String(ip[i]);
... ...
@@ -86,11 +83,11 @@ String getMacAddress() {
86 86
 }
87 87
 
88 88
 void reconectez() {
89
-  while (String(mqtt_user)==""){
90
-    Serial.println("Invalid user!");
91
-    delay(99999999);
89
+  // daca nu am credentialele MQTT, nu fac nimic, delay 1000 de ore
90
+  while (String(mqtt_user)=="") {
91
+    Serial.println("User MQTT invalid!");
92
+    delay(3600000000);
92 93
   }
93
-  
94 94
   // ma conectez la mqtt server
95 95
   while (!client.connected()) {
96 96
     client.setServer(mqttServer, mqttPort);
... ...
@@ -100,56 +97,57 @@ void reconectez() {
100 100
       Serial.println("connected");
101 101
       client.publish(mqttLWT,"Online",TRUE);
102 102
       // trimit informatii utile cand ma conectez
103
-        String esp_info = "{\"ESPMac\":\"";
104
-        esp_info += getMacAddress();
105
-        esp_info += "\", \"IPAddress\":\"";
106
-        esp_info += ipToString(WiFi.localIP());    
107
-        esp_info += "\"}";       
108
-        String netinfo = "{\"Module\":\"";
109
-        netinfo += String (model);
110
-        netinfo += "\", \"Version\":\"";
111
-        netinfo += String (ver);
112
-        netinfo += "\"}";            
113
-        
114
-        client.publish(mqttESP, netinfo.c_str(),TRUE);
115
-        Serial.println(netinfo);
116
-        client.publish(mqttESP, esp_info.c_str(),TRUE);
117
-        Serial.println(esp_info);
118
-        client.publish(mqttESP, "15 minute",TRUE); // trimit intervalul default
119
-        client.subscribe(mqttSUB);
120
-    } else {
103
+      String esp_info = " {\"ESPMac\":\"";
104
+      esp_info += getMacAddress();
105
+      esp_info += "\", \"IPAddress\":\"";
106
+      esp_info += ipToString(WiFi.localIP());
107
+      esp_info += "\"}";
108
+      String netinfo = " {\"Module\":\"";
109
+      netinfo += String (model);
110
+      netinfo += "\", \"Version\":\"";
111
+      netinfo += String (ver);
112
+      netinfo += "\"}";
113
+
114
+      client.publish(mqttESP, netinfo.c_str(),TRUE);
115
+      Serial.println(netinfo);
116
+      client.publish(mqttESP, esp_info.c_str(),TRUE);
117
+      Serial.println(esp_info);
118
+      client.publish(mqttESP, "15 minute",TRUE); // trimit intervalul default
119
+      client.subscribe(mqttSUB);
120
+    }
121
+    else {
121 122
       Serial.print("failed, rc=");
122 123
       Serial.print(client.state());
123
-      Serial.println(" try again in 60 seconds");
124
-      // Wait 60 seconds before retrying
124
+      Serial.println("Incerc din nou in 60 de secunde");
125 125
       delay(60000);
126 126
     }
127 127
   }
128 128
 }
129 129
 
130
-void setup()
131
-{
130
+void setup() {
132 131
   Serial.begin(115200);
133
-
134
-  // Mount the filesystem
135
-  bool result = SPIFFS.begin();
136
-  //Serial.println("SPIFFS opened: " + result);
137
-  
138
-  readConfigFile(); //citesc user si devid din memorie
139
-  generate_vars(); //genereaza topicurile de mqtt in baza mqtt_user si mqtt_devid
140
-  
132
+  //generez variabilele
133
+  readFS();
134
+  WiFiManagerParameter custom_mqtt_user("user", "mqtt user", mqtt_user, 9);
135
+  WiFiManagerParameter custom_mqtt_devid("devid", "mqtt devid", mqtt_devid, 5);
141 136
   // ma conectez la AP via wifi
142
-   WiFiManager wifi;
143
-   wifi.setConfigPortalTimeout(120); // a timeout so the ESP doesn't hang waiting to be configured, for instance after a power failure
144
-   wifi.setTimeout(180); // sta AP 3 minute apoi se reseteaza din nou
145
-   if (!wifi.autoConnect("ClickHome")) {
146
-     Serial.println("timeout - going to sleep");
137
+  WiFiManager wifi;
138
+  // ESP-ul asteapta ca sa fie configurat 2 minute
139
+  wifi.setConfigPortalTimeout(120);
140
+  // sta AP 3 minute apoi se reseteaza din nou
141
+  wifi.setTimeout(180);
142
+  if (!wifi.autoConnect("ClickHome")) {
143
+    Serial.println("timeout - going to sleep"); // EU aici nu am inteles ce se intampla ... poate ii punem un delay!!
147 144
   }
148 145
   delay(200);
149
-
146
+  //citesc datele salvate anterior pe FS
147
+  strcpy(mqtt_user, custom_mqtt_user.getValue());
148
+  strcpy(mqtt_devid, custom_mqtt_devid.getValue());
149
+  //genereaza topicurile de mqtt in baza mqtt_user si mqtt_devid
150
+  generate_vars();
150 151
   reconectez();
151
-  client.setCallback(getMessage); //setez functia care parseaza mesajele venite prin mqtt
152
-
152
+  //setez functia care parseaza mesajele venite prin mqtt
153
+  client.setCallback(getMessage);
153 154
   pinMode(inPin, INPUT);
154 155
   sensors.begin();
155 156
 }
... ...
@@ -157,132 +155,120 @@ void setup()
157 157
 void getMessage(char* topic, byte* payload, unsigned int length) {
158 158
   float t = 0;
159 159
   mqttMessage="";
160
-  Serial.print("Message arrived in topic: ");
160
+  Serial.print("Mesaj primit pe topicul: ");
161 161
   Serial.println(topic);
162
-  Serial.print("Message:");
162
+  Serial.print("Mesaj:");
163 163
   for (int i = 0; i < length; i++) {
164 164
     mqttMessage += (char)payload[i];
165 165
   }
166 166
   Serial.println(mqttMessage);
167
- 
168
-  // daca a primit sendTemp trimite temperatura 
169
-  if (mqttMessage == "temp")
170
-  {
167
+
168
+  // daca primeste 'temp' pe mqtt, trimite temperatura
169
+  if (mqttMessage == "temp") {
171 170
     Serial.println("Trimit temperatura");
172 171
     sensors.setResolution(12);
173 172
     sensors.requestTemperatures(); // Send the command to get Temperatures
174 173
     t = sensors.getTempCByIndex(0);
175
-      String json = "{\"Temp\":";
174
+      String json = " {\"Temp\":";
176 175
       json += String (t);
177 176
       json += "}";
178 177
       client.publish(mqttTEMP, json.c_str(),TRUE);
179 178
       Serial.println(json);
180
-  }  
181
-// reset la ESP
182
-  if (mqttMessage == "reset")
183
-  {
184
-      String lastwords="Am fost resetat ...";
185
-      client.publish(mqttESP, lastwords.c_str(), TRUE);
186
-      delay (3000);
187
-      ESP.reset();
188
-      delay (5000);
189 179
   }
190
-// procedura de software update via WEB
191
-   if (mqttMessage == "update")
192
-   {
193
-        String msg="Software update: ";
194
-        t_httpUpdate_return ret; 
195
-        //ESPhttpUpdate.rebootOnUpdate(false);
196
-        ret = ESPhttpUpdate.update("http://update.clickhome.ro/senzor/dallas/arduino.bin");  
197
-        //ret = ESPhttpUpdate.update("update.clickhome.ro", 80, "/senzor/dallas/arduino.bin");
198
-        switch(ret) {
199
-           case HTTP_UPDATE_FAILED:
200
-               msg.concat(" eroare:");
201
-               msg.concat(ESPhttpUpdate.getLastError());
202
-               msg.concat(" motiv:");
203
-               msg.concat(ESPhttpUpdate.getLastErrorString().c_str());
204
-               break;
205
-           case HTTP_UPDATE_NO_UPDATES:
206
-               msg.concat(" no update.");
207
-               break;
208
-           case HTTP_UPDATE_OK:
209
-               msg.concat(" success.");
210
-               break;
211
-        }
212
-        Serial.println(msg);
213
-   }
214 180
 
215
-  // daca a primit valoarea in minute seteaza loopTimer si-l trimite in DB
216
-  
217
-   if (mqttMessage == "debug")
218
-   {
219
-        loopTimer=30000; // setez sa trimita valori la 30 de secunde ca sa fac debug
220
-        client.publish(mqttESP, "{\"LoopInterval\":\"30 secunde\"}",TRUE);   
181
+  // daca primeste 'reset' pe mqtt, isi da reset
182
+  if (mqttMessage == "reset") {
183
+    String lastwords="Am fost resetat ...";
184
+    client.publish(mqttESP, lastwords.c_str(), TRUE);
185
+    delay (3000);
186
+    ESP.reset();
187
+    delay (5000);
188
+  }
189
+
190
+  // daca primeste 'update' isi face software update via WEB
191
+  if (mqttMessage == "update") {
192
+    String msg="Software update: ";
193
+    t_httpUpdate_return ret;
194
+    //ESPhttpUpdate.rebootOnUpdate(false);
195
+    ret = ESPhttpUpdate.update("http://update.clickhome.ro/senzor/dallas/arduino.bin");
196
+    //ret = ESPhttpUpdate.update("update.clickhome.ro", 80, "/senzor/dallas/arduino.bin");
197
+    switch(ret) {
198
+      case HTTP_UPDATE_FAILED:
199
+        msg.concat(" eroare:");
200
+        msg.concat(ESPhttpUpdate.getLastError());
201
+        msg.concat(" motiv:");
202
+        msg.concat(ESPhttpUpdate.getLastErrorString().c_str());
203
+      break;
204
+      case HTTP_UPDATE_NO_UPDATES:
205
+        msg.concat(" no update.");
206
+      break;
207
+      case HTTP_UPDATE_OK:
208
+        msg.concat(" success.");
209
+      break;
210
+    }
211
+    Serial.println(msg);
212
+  }
213
+
214
+  // daca primeste valoarea in minute seteaza loopTimer si-l trimite in DB
215
+  if (mqttMessage == "debug") {
216
+    loopTimer=30000;
217
+    client.publish(mqttESP, " {\"LoopInterval\":\"30 secunde\"}",TRUE);
218
+   }
219
+   if (mqttMessage == "10") {
220
+     loopTimer=600000;
221
+     client.publish(mqttESP, " {\"LoopInterval\":\"10 minute\"}",TRUE);
221 222
    }
222
-   if (mqttMessage == "10")
223
-   {
224
-        loopTimer=600000; // setez sa trimita valori la 10 minute   
225
-        client.publish(mqttESP, "{\"LoopInterval\":\"10 minute\"}",TRUE);
223
+   if (mqttMessage == "15") {
224
+     loopTimer=900000;
225
+     client.publish(mqttESP, " {\"LoopInterval\":\"15 minute\"}",TRUE);
226 226
    }
227
-   if (mqttMessage == "15")
228
-   {
229
-        loopTimer=900000; // setez sa trimita valori la 15 minute
230
-        client.publish(mqttESP, "{\"LoopInterval\":\"15 minute\"}",TRUE);   
227
+   if (mqttMessage == "30") {
228
+     loopTimer=1800000;
229
+     client.publish(mqttESP, " {\"LoopInterval\":\"30 de minute\"}",TRUE);
231 230
    }
232
-   if (mqttMessage == "30")
233
-   {
234
-        loopTimer=1800000; // setez sa trimita valori la 30 de minute
235
-        client.publish(mqttESP, "{\"LoopInterval\":\"30 de minute\"}",TRUE);   
236
-   }   
237
-   if (mqttMessage == "60")
238
-   {
239
-        loopTimer=3600000; // setez sa trimita valori la o ora
240
-        client.publish(mqttESP, "{\"LoopInterval\":\"o ora\"}",TRUE);   
231
+   if (mqttMessage == "60") {
232
+     loopTimer=3600000;
233
+     client.publish(mqttESP, " {\"LoopInterval\":\"o ora\"}",TRUE);
234
+   }
235
+   if (mqttMessage == "stop") {
236
+     loopTimer=3600000000; // setez sa nu trimita valori, 1000 de ore
237
+     client.publish(mqttESP, " {\"LoopInterval\":\"oprit\"}",TRUE);
241 238
    }
242
-   if (mqttMessage == "stop")
243
-   {
244
-        loopTimer=3600000000; // setez sa nu trimita valori
245
-        client.publish(mqttESP, "{\"LoopInterval\":\"oprit\"}",TRUE);
246
-   }  
247 239
 }
248 240
 
249
-bool readConfigFile() {
250
-  // this opens the config file in read-mode
251
-  File f = SPIFFS.open("/config.json", "r");
252
-  
253
-  if (!f) {
254
-    Serial.println("Configuration file not found");
255
-    return false;
256
-  } else {
257
-    // we could open the file
258
-    size_t size = f.size();
259
-    // Allocate a buffer to store contents of the file.
260
-    std::unique_ptr<char[]> buf(new char[size]);
261
-
262
-    // Read and store file contents in buf
263
-    f.readBytes(buf.get(), size);
264
-    // Closing file
265
-    f.close();
266
-    // Using dynamic JSON buffer which is not the recommended memory model, but anyway
267
-    // See https://github.com/bblanchon/ArduinoJson/wiki/Memory%20model
268
-    DynamicJsonBuffer jsonBuffer;
269
-    // Parse JSON string
270
-    JsonObject& json = jsonBuffer.parseObject(buf.get());
271
-    // Test if parsing succeeds.
272
-    if (!json.success()) {
273
-      Serial.println("JSON parseObject() failed");
274
-      return false;
241
+void readFS() {
242
+  if (SPIFFS.begin()) {
243
+    //Serial.println("mounted file system");
244
+    if (SPIFFS.exists("/config.json")) {
245
+      //file exists, reading and loading
246
+      //Serial.println("reading config file");
247
+      File configFile = SPIFFS.open("/config.json", "r");
248
+      if (configFile) {
249
+        //Serial.println("opened config file");
250
+        size_t size = configFile.size();
251
+        // Allocate a buffer to store contents of the file.
252
+        std::unique_ptr<char[]> buf(new char[size]);
253
+        configFile.readBytes(buf.get(), size);
254
+        DynamicJsonBuffer jsonBuffer;
255
+        JsonObject& json = jsonBuffer.parseObject(buf.get());
256
+        //json.printTo(Serial);
257
+        if (json.success()) {
258
+          //Serial.println("\nparsed json");
259
+          strcpy(mqtt_user, json["mqtt_user"]);
260
+          strcpy(mqtt_devid, json["mqtt_devid"]);
261
+        }
262
+        else {
263
+          //Serial.println("failed to load json config");
264
+        }
265
+      }
275 266
     }
276
-    json.printTo(Serial);
277
-    strcpy(mqtt_user, json["mqtt_user"]);
278
-    strcpy(mqtt_devid, json["mqtt_devid"]);
279 267
   }
280
-  return true;
268
+  else {
269
+    //Serial.println("failed to mount FS");
270
+  }
281 271
 }
282 272
 
283
-
284
-void loop()
285
-{
273
+void loop() {
286 274
   if (!client.connected()) {
287 275
     reconectez();
288 276
   }
... ...
@@ -291,16 +277,15 @@ void loop()
291 291
   if (now - lastMsg > loopTimer) {
292 292
     lastMsg = now;
293 293
     sensors.setResolution(12);
294
-    sensors.requestTemperatures(); // Send the command to get loopTemperatures
294
+    sensors.requestTemperatures();
295 295
     loopTemp = sensors.getTempCByIndex(0);
296 296
     Serial.println(loopTemp);
297
-    if((loopTemp > -20) && (loopTemp <60))
298
-      {
299
-     String val = "{\"Temp\":";
297
+    if((loopTemp > -20) && (loopTemp <60)) {
298
+      String val = " {\"Temp\":";
300 299
       val += String (loopTemp);
301 300
       val += "}";
302 301
       client.publish(mqttESP, val.c_str(),TRUE);
303
-      }
302
+    }
304 303
   }
305 304
 }
306
-
305
+