Browse code

Fac din nou rollback la commitul: 019f90900b674728ebf6bc870f235ae0a57a64b4 ... am modificat softul fara sa ma sincronizez cu masterul si a iesit 'muci' :)

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