Browse code

Adaptat facilitatile din Dallas la Releu ToDO: 1. posibilitatea de a folosi un buton local pt comenzi releu si pe viitor eventual sa treaca in mod AP etc. 2. putem salva starea releului in memorie alaturi de credentiale astfel incat sa oferim optiunea ca la boot releul sa fie: on/off/last state

Andrei Bucur authored on 02/03/2018 11:24:38
Showing 1 changed files
1 1
old mode 100644
2 2
new mode 100755
... ...
@@ -1,37 +1,65 @@
1
+#include <FS.h>                   //this needs to be first, e folosit de salvarea credentialelor pe FS
1 2
 #include <ESP8266WiFi.h>
2 3
 #include <PubSubClient.h>
3 4
 #include <WiFiManager.h>        //https://github.com/tzapu/WiFiManager
5
+#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson pentru salvarea credentialelor in eprom
4 6
 #include <WiFiClient.h> 
5 7
 #include <OneWire.h>
8
+#include <DallasTemperature.h>
6 9
 #include <ESP8266HTTPClient.h>
7 10
 #include <ESP8266httpUpdate.h>
8 11
 
9
-#define RELAY D2 //  pinul de date (la mine am pus releu pe D2)
12
+#define DEBUG 0 //0=off 1=on
13
+#define RELAY LED_BUILTIN //  pinul de date D1 la care se conecteaza releul
10 14
 
11
-// Modifica cu datele tale
12
-const char* mqttUser = "qbzesh";
13
-const char* mqttPassword = "8219CHqbzesh";
14
-const char* mqttSUB = "cmnd/qbzesh-1432/ESP";
15
-const char* mqttESP = "stat/qbzesh-1432/ESP";
16
-const char* mqttRELAY = "stat/qbzesh-1432/RELAY";
17
-const char* mqttLWT = "tele/qbzesh-1432/LWT";
18
-const char* espName ="qbzesh-1432";
15
+char mqtt_user[9]; //le va lua din FS
16
+char mqtt_devid[5]; //le va lua din FS
17
+char mqttPassword[15]; //urmatoarele le va genera cu functia gen
18
+char mqttSUB[22];
19
+char espName[13];
20
+char mqttESP[22];
21
+char mqttRELAY[23];
22
+char mqttLWT[22];
19 23
 
20
-//#######################################################################
21
-// NU EDITA MAI JOS
22
-//#######################################################################
23 24
 const String model = "NodeMCU Releu";
24
-const String ver = "v1.0.5";
25
+const String ver = "v2.0.0";
25 26
 const char* mqttServer = "mqtt.clickhome.ro";
26 27
 const int mqttPort = 1883;
27 28
 long loopTimer = 900000; // miliseconds - by default trimite la 15 minute
28 29
 long lastMsg = 0;
29 30
 float loopTemp = 0;
31
+int inPin = 5;
30 32
 String mqttMessage;
31 33
 
32 34
 WiFiClient espClient;
33 35
 PubSubClient client(espClient);
34
- 
36
+bool readConfigFile();
37
+
38
+void generate_vars(){
39
+  strcpy (mqttPassword, "8219CH");
40
+  strcat (mqttPassword, mqtt_user);
41
+
42
+  strcpy (espName, mqtt_user);
43
+  strcat (espName, "-");
44
+  strcat (espName, mqtt_devid);
45
+
46
+  strcpy (mqttSUB, "cmnd/");
47
+  strcat (mqttSUB, espName);
48
+  strcat (mqttSUB, "/ESP");
49
+
50
+  strcpy (mqttESP, "stat/");
51
+  strcat (mqttESP, espName);
52
+  strcat (mqttESP, "/ESP");
53
+
54
+  strcpy (mqttRELAY, "stat/");
55
+  strcat (mqttRELAY, espName);
56
+  strcat (mqttRELAY, "/RELAY");
57
+
58
+  strcpy (mqttLWT, "tele/");
59
+  strcat (mqttLWT, espName);
60
+  strcat (mqttLWT, "/LWT");
61
+}
62
+
35 63
 String ipToString(IPAddress ip){
36 64
   String s="";
37 65
   for (int i=0; i<4; i++)
... ...
@@ -51,16 +79,26 @@ String getMacAddress() {
51 51
   return cMac;
52 52
 }
53 53
 
54
-void reconnect() 
55
-{
56
-  while (!client.connected()) 
57
-  {
54
+void reconectez() {
55
+  while (String(mqtt_user)==""){
56
+    #if DEBUG
57
+    Serial.println("Invalid user!");
58
+    #endif
59
+    delay(99999999);
60
+  }
61
+  
62
+  // ma conectez la mqtt server
63
+  while (!client.connected()) {
64
+    client.setServer(mqttServer, mqttPort);
65
+    #if DEBUG
58 66
     Serial.print("AtloopTempting MQTT connection...");
59
-     // Incerc sa ma reconectez cu LWT din 60 in 60 secunde
60
-    if (client.connect(espName, mqttUser, mqttPassword, mqttLWT, 1, 1, "Offline")) 
61
-    {
62
-        Serial.println("Releu reconectat la MQTT.");
63
-        client.publish(mqttLWT,"Online",TRUE);
67
+    #endif
68
+    // Incerc sa ma reconectez cu LWT din 5 in 5 secunde
69
+    if (client.connect(espName, mqtt_user, mqttPassword, mqttLWT, 1, 1, "Offline")) {
70
+      #if DEBUG
71
+      Serial.println("connected");
72
+      #endif
73
+      client.publish(mqttLWT,"Online",TRUE);
64 74
         // trimit informatii utile cand ma conectez
65 75
         String esp_info = "{\"ESPMac\":\"";
66 76
         esp_info += getMacAddress();
... ...
@@ -74,89 +112,88 @@ void reconnect()
74 74
         netinfo += "\"}";            
75 75
         
76 76
         client.publish(mqttESP, netinfo.c_str(),TRUE);
77
+        #if DEBUG
77 78
         Serial.println(netinfo);
79
+        #endif
78 80
         client.publish(mqttESP, esp_info.c_str(),TRUE);
81
+        #if DEBUG
79 82
         Serial.println(esp_info);
83
+        #endif
84
+    
85
+        // citesc starea si o trimit cand se reconecteaza si la boot
86
+        String json = "{\"Relay\":\"";
87
+        json += String (digitalRead(RELAY));
88
+        json += "\"}";
89
+        client.publish(mqttRELAY, json.c_str(),TRUE);
90
+
80 91
         client.subscribe(mqttSUB);
81
-    } 
82
-    else {
83
-        Serial.println("Reconectare MQTT esuata: ");
84
-        Serial.println(client.state());
85
-        Serial.println("fac o alta incercare in 60 de secunde");
86
-        delay(60000);
92
+    } else {
93
+      #if DEBUG
94
+      Serial.print("failed, rc=");
95
+      Serial.print(client.state());
96
+      Serial.println(" try again in 60 seconds");
97
+      #endif
98
+      // Wait 60 seconds before retrying
99
+      delay(60000);
87 100
     }
88 101
   }
89 102
 }
90
- 
103
+
104
+
91 105
 void setup()
92 106
 {
93
-  Serial.begin(115200);
94 107
   pinMode(RELAY,OUTPUT);
95 108
 
109
+  #if DEBUG
110
+  Serial.begin(115200);
111
+  #endif
112
+
113
+  // Mount the filesystem
114
+  bool result = SPIFFS.begin();
115
+  #if DEBUG
116
+  //Serial.println("SPIFFS opened: " + result);
117
+  #endif
118
+  
119
+  readConfigFile(); //citesc user si devid din memorie
120
+  generate_vars(); //genereaza topicurile de mqtt in baza mqtt_user si mqtt_devid
121
+
96 122
   // ma conectez la AP via wifi
97 123
    WiFiManager wifi;
124
+   wifi.setConfigPortalTimeout(120); // a timeout so the ESP doesn't hang waiting to be configured, for instance after a power failure
98 125
    wifi.setTimeout(180); // sta AP 3 minute apoi se reseteaza din nou
99 126
    if (!wifi.autoConnect("ClickHome")) {
127
+     #if DEBUG
100 128
      Serial.println("timeout - going to sleep");
129
+     #endif
101 130
   }
102 131
   delay(200);
103
- 
104
-  // ma conectez la mqtt server
105
-  client.setServer(mqttServer, mqttPort);
106
-    while (!client.connected()) {
107
-    Serial.println("Connecting to MQTT...");
108
-    // fac connect cu LWT
109
-    if (client.connect(espName, mqttUser, mqttPassword, mqttLWT, 1, 1, "Offline")) {
110
-      // trimit starea Online pe topic LWT cand ma conectez
111
-      client.publish(mqttLWT,"Online",TRUE);
112
-      // trimit starea OFF cand il aprind
113
-      digitalWrite(RELAY,LOW);
114
-      client.publish(mqttRELAY, "{\"Relay\":\"0\"}", TRUE);
115
-      Serial.println("connected");
116
-      // trimit informatii utile cand ma conectez
117
-        String esp_info = "{\"ESPMac\":\"";
118
-        esp_info += getMacAddress();
119
-        esp_info += "\", \"IPAddress\":\"";
120
-        esp_info += ipToString(WiFi.localIP());    
121
-        esp_info += "\"}";       
122
-        String netinfo = "{\"Module\":\"";
123
-        netinfo += String (model);
124
-        netinfo += "\", \"Version\":\"";
125
-        netinfo += String (ver);
126
-        netinfo += "\"}";            
127
-        
128
-        client.publish(mqttESP, netinfo.c_str(),TRUE);
129
-        Serial.println(netinfo);
130
-        client.publish(mqttESP, esp_info.c_str(),TRUE);
131
-        Serial.println(esp_info);
132
-      client.subscribe(mqttSUB);
133
-    } 
134
-      else {
135
-        Serial.print("Conectare MQTT esuata: ");
136
-        Serial.print(client.state());
137
-        delay(2000);
138
-    }
139
-  }
140
-  // astept mesajul de la serverul MQTT
141
-  client.setCallback(getMessage);
142
- // pinMode(RELAY,OUTPUT);
132
+
133
+  reconectez();
134
+  client.setCallback(getMessage); //setez functia care parseaza mesajele venite prin mqtt
135
+
143 136
 }
144 137
 
145 138
 void getMessage(char* topic, byte* payload, unsigned int length) {
146 139
   float t = 0;
147 140
   mqttMessage="";
141
+  #if DEBUG
148 142
   Serial.print("Message arrived in topic: ");
149 143
   Serial.println(topic);
150 144
   Serial.print("Message:");
145
+  #endif
151 146
   for (int i = 0; i < length; i++) {
152 147
     mqttMessage += (char)payload[i];
153 148
   }
149
+  #if DEBUG
154 150
   Serial.println(mqttMessage);
151
+  #endif
155 152
  
156 153
   // daca a primit on
157 154
   if (mqttMessage == "ON")
158 155
   {
156
+    #if DEBUG
159 157
     Serial.println("Pornesc releu");
158
+    #endif
160 159
     digitalWrite(RELAY,HIGH);
161 160
     String json = "{\"Relay\":\"1\"}";
162 161
     client.publish(mqttRELAY, json.c_str(),TRUE);
... ...
@@ -164,13 +201,15 @@ void getMessage(char* topic, byte* payload, unsigned int length) {
164 164
   if (mqttMessage == "OFF")
165 165
   {
166 166
      long now = millis(); 
167
+    #if DEBUG
167 168
     Serial.println("Opresc releu");
168 169
     Serial.println(now);
170
+    #endif
169 171
     digitalWrite(RELAY,LOW);
170 172
     String json = "{\"Relay\":\"0\"}";
171 173
     client.publish(mqttRELAY, json.c_str(),TRUE);
172 174
   }
173
-   // procedura de software update via WEB
175
+// procedura de software update via WEB
174 176
    if (mqttMessage == "update")
175 177
    {
176 178
         String msg="Software update: ";
... ...
@@ -191,7 +230,9 @@ void getMessage(char* topic, byte* payload, unsigned int length) {
191 191
                msg.concat(" success.");
192 192
                break;
193 193
         }
194
+        #if DEBUG
194 195
         Serial.println(msg);
196
+        #endif
195 197
    }
196 198
 
197 199
   if (mqttMessage == "stare")
... ...
@@ -203,17 +244,60 @@ void getMessage(char* topic, byte* payload, unsigned int length) {
203 203
     client.publish(mqttRELAY, json.c_str(),TRUE);
204 204
   }
205 205
 }
206
+
207
+bool readConfigFile() {
208
+  // this opens the config file in read-mode
209
+  File f = SPIFFS.open("/config.json", "r");
210
+  
211
+  if (!f) {
212
+    #if DEBUG
213
+    Serial.println("Configuration file not found");
214
+    #endif
215
+    return false;
216
+  } else {
217
+    // we could open the file
218
+    size_t size = f.size();
219
+    // Allocate a buffer to store contents of the file.
220
+    std::unique_ptr<char[]> buf(new char[size]);
221
+
222
+    // Read and store file contents in buf
223
+    f.readBytes(buf.get(), size);
224
+    // Closing file
225
+    f.close();
226
+    // Using dynamic JSON buffer which is not the recommended memory model, but anyway
227
+    // See https://github.com/bblanchon/ArduinoJson/wiki/Memory%20model
228
+    DynamicJsonBuffer jsonBuffer;
229
+    // Parse JSON string
230
+    JsonObject& json = jsonBuffer.parseObject(buf.get());
231
+    // Test if parsing succeeds.
232
+    if (!json.success()) {
233
+      #if DEBUG
234
+      Serial.println("JSON parseObject() failed");
235
+      #endif
236
+      return false;
237
+    }
238
+    #if DEBUG
239
+    json.printTo(Serial);
240
+    #endif
241
+    strcpy(mqtt_user, json["mqtt_user"]);
242
+    strcpy(mqtt_devid, json["mqtt_devid"]);
243
+  }
244
+  return true;
245
+}
246
+
206 247
 void loop()
207 248
 {
208 249
   if (!client.connected()) 
209 250
   {
210
-    reconnect();
251
+    reconectez();
211 252
   }
212 253
   client.loop();
213 254
   long now = millis(); 
214 255
   if (now - lastMsg > loopTimer) 
215 256
   {
216 257
     lastMsg = now;
217
-       Serial.println("Nu fac nimic in bucla");
258
+    #if DEBUG
259
+    Serial.println("Nu fac nimic in bucla");
260
+    #endif
218 261
   }
219
-}
262
+}