Browse code

rollback la commitul: 019f90900b674728ebf6bc870f235ae0a57a64b4 folosind comanda "git checkout 019f90900b674728ebf6bc870f235ae0a57a64b4 ."

Liviu Pislaru authored on 01/03/2018 16:58:59
Showing 1 changed files
1 1
new file mode 100755
... ...
@@ -0,0 +1,306 @@
0
+#include <FS.h>                   //this needs to be first, e folosit de salvarea credentialelor pe FS
1
+#include <ESP8266WiFi.h>
2
+#include <PubSubClient.h>
3
+#include <WiFiManager.h>        //https://github.com/tzapu/WiFiManager
4
+#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson pentru salvarea credentialelor in eprom
5
+#include <WiFiClient.h> 
6
+#include <OneWire.h>
7
+#include <DallasTemperature.h>
8
+#include <ESP8266HTTPClient.h>
9
+#include <ESP8266httpUpdate.h>
10
+
11
+char mqtt_user[9]; //le va lua din FS
12
+char mqtt_devid[5]; //le va lua din FS
13
+char mqttPassword[15]; //urmatoarele le va genera cu functia gen
14
+char mqttSUB[22];
15
+char espName[13];
16
+char mqttESP[22];
17
+char mqttTEMP[23];
18
+char mqttLWT[22];
19
+
20
+const String model = "NodeMCU Dallas";
21
+const String ver = "v2.1.0";
22
+const char* mqttServer = "mqtt.clickhome.ro";
23
+const int mqttPort = 1883;
24
+long loopTimer = 900000; // miliseconds - by default trimite la 15 minute
25
+long lastMsg = 0;
26
+float loopTemp = 0;
27
+int inPin = 5;
28
+String mqttMessage;
29
+
30
+// senzor de temperatura DALLAS
31
+#define ONE_WIRE_BUS D4  // pinul de date (la mine am pus senzor pe D4)
32
+OneWire oneWire(ONE_WIRE_BUS);
33
+DallasTemperature sensors(&oneWire);
34
+
35
+//*********************************************************************
36
+
37
+WiFiClient espClient;
38
+PubSubClient client(espClient);
39
+bool readConfigFile();
40
+
41
+
42
+void generate_vars(){
43
+  strcpy (mqttPassword, "8219CH");
44
+  strcat (mqttPassword, mqtt_user);
45
+
46
+  strcpy (espName, mqtt_user);
47
+  strcat (espName, "-");
48
+  strcat (espName, mqtt_devid);
49
+
50
+  strcpy (mqttSUB, "cmnd/");
51
+  strcat (mqttSUB, espName);
52
+  strcat (mqttSUB, "/ESP");
53
+
54
+  strcpy (mqttESP, "stat/");
55
+  strcat (mqttESP, espName);
56
+  strcat (mqttESP, "/ESP");
57
+
58
+  strcpy (mqttTEMP, "stat/");
59
+  strcat (mqttTEMP, espName);
60
+  strcat (mqttTEMP, "/TEMP");
61
+
62
+  strcpy (mqttLWT, "tele/");
63
+  strcat (mqttLWT, espName);
64
+  strcat (mqttLWT, "/LWT");
65
+}
66
+
67
+String ipToString(IPAddress ip){
68
+  String s="";
69
+  for (int i=0; i<4; i++)
70
+    s += i  ? "." + String(ip[i]) : String(ip[i]);
71
+  return s;
72
+}
73
+
74
+String getMacAddress() {
75
+  byte mac[6];
76
+  WiFi.macAddress(mac);
77
+  String cMac = "";
78
+  for (int i = 0; i < 6; ++i) {
79
+    cMac += String(mac[i],HEX);
80
+    if(i<5)
81
+    cMac += "-";
82
+  }
83
+  cMac.toUpperCase();
84
+  return cMac;
85
+}
86
+
87
+void reconectez() {
88
+  while (String(mqtt_user)==""){
89
+    Serial.println("Invalid user!");
90
+    delay(99999999);
91
+  }
92
+  
93
+  // ma conectez la mqtt server
94
+  while (!client.connected()) {
95
+    client.setServer(mqttServer, mqttPort);
96
+    Serial.print("AtloopTempting MQTT connection...");
97
+    // Incerc sa ma reconectez cu LWT din 5 in 5 secunde
98
+    if (client.connect(espName, mqtt_user, mqttPassword, mqttLWT, 1, 1, "Offline")) {
99
+      Serial.println("connected");
100
+      client.publish(mqttLWT,"Online",TRUE);
101
+      // trimit informatii utile cand ma conectez
102
+        String esp_info = "{\"ESPMac\":\"";
103
+        esp_info += getMacAddress();
104
+        esp_info += "\", \"IPAddress\":\"";
105
+        esp_info += ipToString(WiFi.localIP());    
106
+        esp_info += "\"}";       
107
+        String netinfo = "{\"Module\":\"";
108
+        netinfo += String (model);
109
+        netinfo += "\", \"Version\":\"";
110
+        netinfo += String (ver);
111
+        netinfo += "\"}";            
112
+        
113
+        client.publish(mqttESP, netinfo.c_str(),TRUE);
114
+        Serial.println(netinfo);
115
+        client.publish(mqttESP, esp_info.c_str(),TRUE);
116
+        Serial.println(esp_info);
117
+        client.publish(mqttESP, "15 minute",TRUE); // trimit intervalul default
118
+        client.subscribe(mqttSUB);
119
+    } else {
120
+      Serial.print("failed, rc=");
121
+      Serial.print(client.state());
122
+      Serial.println(" try again in 60 seconds");
123
+      // Wait 60 seconds before retrying
124
+      delay(60000);
125
+    }
126
+  }
127
+}
128
+
129
+void setup()
130
+{
131
+  Serial.begin(115200);
132
+
133
+  // Mount the filesystem
134
+  bool result = SPIFFS.begin();
135
+  //Serial.println("SPIFFS opened: " + result);
136
+  
137
+  readConfigFile(); //citesc user si devid din memorie
138
+  generate_vars(); //genereaza topicurile de mqtt in baza mqtt_user si mqtt_devid
139
+  
140
+  // ma conectez la AP via wifi
141
+   WiFiManager wifi;
142
+   wifi.setConfigPortalTimeout(120); // a timeout so the ESP doesn't hang waiting to be configured, for instance after a power failure
143
+   wifi.setTimeout(180); // sta AP 3 minute apoi se reseteaza din nou
144
+   if (!wifi.autoConnect("ClickHome")) {
145
+     Serial.println("timeout - going to sleep");
146
+  }
147
+  delay(200);
148
+
149
+  reconectez();
150
+  client.setCallback(getMessage); //setez functia care parseaza mesajele venite prin mqtt
151
+
152
+  pinMode(inPin, INPUT);
153
+  sensors.begin();
154
+}
155
+
156
+void getMessage(char* topic, byte* payload, unsigned int length) {
157
+  float t = 0;
158
+  mqttMessage="";
159
+  Serial.print("Message arrived in topic: ");
160
+  Serial.println(topic);
161
+  Serial.print("Message:");
162
+  for (int i = 0; i < length; i++) {
163
+    mqttMessage += (char)payload[i];
164
+  }
165
+  Serial.println(mqttMessage);
166
+ 
167
+  // daca a primit sendTemp trimite temperatura 
168
+  if (mqttMessage == "temp")
169
+  {
170
+    Serial.println("Trimit temperatura");
171
+    sensors.setResolution(12);
172
+    sensors.requestTemperatures(); // Send the command to get Temperatures
173
+    t = sensors.getTempCByIndex(0);
174
+      String json = "{\"Temp\":";
175
+      json += String (t);
176
+      json += "}";
177
+      client.publish(mqttTEMP, json.c_str(),TRUE);
178
+      Serial.println(json);
179
+  }  
180
+// reset la ESP
181
+  if (mqttMessage == "reset")
182
+  {
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
+// procedura de software update via WEB
190
+   if (mqttMessage == "update")
191
+   {
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 a primit valoarea in minute seteaza loopTimer si-l trimite in DB
215
+  
216
+   if (mqttMessage == "debug")
217
+   {
218
+        loopTimer=30000; // setez sa trimita valori la 30 de secunde ca sa fac debug
219
+        client.publish(mqttESP, "{\"LoopInterval\":\"30 secunde\"}",TRUE);   
220
+   }
221
+   if (mqttMessage == "10")
222
+   {
223
+        loopTimer=600000; // setez sa trimita valori la 10 minute   
224
+        client.publish(mqttESP, "{\"LoopInterval\":\"10 minute\"}",TRUE);
225
+   }
226
+   if (mqttMessage == "15")
227
+   {
228
+        loopTimer=900000; // setez sa trimita valori la 15 minute
229
+        client.publish(mqttESP, "{\"LoopInterval\":\"15 minute\"}",TRUE);   
230
+   }
231
+   if (mqttMessage == "30")
232
+   {
233
+        loopTimer=1800000; // setez sa trimita valori la 30 de minute
234
+        client.publish(mqttESP, "{\"LoopInterval\":\"30 de minute\"}",TRUE);   
235
+   }   
236
+   if (mqttMessage == "60")
237
+   {
238
+        loopTimer=3600000; // setez sa trimita valori la o ora
239
+        client.publish(mqttESP, "{\"LoopInterval\":\"o ora\"}",TRUE);   
240
+   }
241
+   if (mqttMessage == "stop")
242
+   {
243
+        loopTimer=3600000000; // setez sa nu trimita valori
244
+        client.publish(mqttESP, "{\"LoopInterval\":\"oprit\"}",TRUE);
245
+   }  
246
+}
247
+
248
+bool readConfigFile() {
249
+  // this opens the config file in read-mode
250
+  File f = SPIFFS.open("/config.json", "r");
251
+  
252
+  if (!f) {
253
+    Serial.println("Configuration file not found");
254
+    return false;
255
+  } else {
256
+    // we could open the file
257
+    size_t size = f.size();
258
+    // Allocate a buffer to store contents of the file.
259
+    std::unique_ptr<char[]> buf(new char[size]);
260
+
261
+    // Read and store file contents in buf
262
+    f.readBytes(buf.get(), size);
263
+    // Closing file
264
+    f.close();
265
+    // Using dynamic JSON buffer which is not the recommended memory model, but anyway
266
+    // See https://github.com/bblanchon/ArduinoJson/wiki/Memory%20model
267
+    DynamicJsonBuffer jsonBuffer;
268
+    // Parse JSON string
269
+    JsonObject& json = jsonBuffer.parseObject(buf.get());
270
+    // Test if parsing succeeds.
271
+    if (!json.success()) {
272
+      Serial.println("JSON parseObject() failed");
273
+      return false;
274
+    }
275
+    json.printTo(Serial);
276
+    strcpy(mqtt_user, json["mqtt_user"]);
277
+    strcpy(mqtt_devid, json["mqtt_devid"]);
278
+  }
279
+  return true;
280
+}
281
+
282
+
283
+void loop()
284
+{
285
+  if (!client.connected()) {
286
+    reconectez();
287
+  }
288
+  client.loop();
289
+  long now = millis();
290
+  if (now - lastMsg > loopTimer) {
291
+    lastMsg = now;
292
+    sensors.setResolution(12);
293
+    sensors.requestTemperatures(); // Send the command to get loopTemperatures
294
+    loopTemp = sensors.getTempCByIndex(0);
295
+    Serial.println(loopTemp);
296
+    if((loopTemp > -20) && (loopTemp <60))
297
+      {
298
+     String val = "{\"Temp\":";
299
+      val += String (loopTemp);
300
+      val += "}";
301
+      client.publish(mqttESP, val.c_str(),TRUE);
302
+      }
303
+  }
304
+}
305
+