-
Notifications
You must be signed in to change notification settings - Fork 0
/
parnik-temp.cpp
441 lines (329 loc) · 9.48 KB
/
parnik-temp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <EEPROM.h>
#include "sht30.h"
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>
extern "C" {
#include <user_interface.h>
}
#define MQTT_MAX_PACKET_SIZE 200
#define MQTT_SUB_TIMEOUT 1000
#define tempChangeThr 2.0f
#define humChangeThr 5.0f
#define voltChangeThr 0.01f
#define EEPROM_ADDR 0
//#define DEBUG 1
#ifdef DEBUG
#define SLEEP_TIME 20
#else
#define SLEEP_TIME 300
#endif
typedef struct {
float temp;
float hum;
float volt;
bool forceTrx;
} _Data;
_Data newData, oldData;
struct {
uint32_t crc32;
_Data data;
} memData;
struct {
uint32_t crc32;
uint32_t runCount;
} rtcData;
SHT3X sht30(0x45);
WiFiClient espClient;
PubSubClient client(espClient);
ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;
const char* ssid = "*****";
const char* password = "********";
const char* mqttServer = "192.168.1.110";
const int mqttPort = 1883;
const char* mqttUser = "";
const char* mqttPassword = "";
const char* mqttTopicData = "parnik/SENSOR";
const char* mqttTopicStat = "parnik/STAT";
const char* mqttTopicIn = "parnik/cmd";
const uint sleepSeconds = SLEEP_TIME;
int errStatus,cmd;
long RSSI;
bool dataOk, gotCmd, debugmode, isUpdateServer;
void readSensorData();
void wifiinit(void);
void initmqtt(void);
bool isDataChanged();
void sendData();
void debugOutput(const char *msg);
void proceedRtcCounter();
void readEEPROM(),writeEEPROM();
uint32_t calculateCRC32(const uint8_t *data, size_t length);
void callback(char* topic, byte* payload, unsigned int length);
void normalloop(),otaloop();
void initUpdateServer();
//void callback(char* topic, byte* payload, unsigned int length);
void setup() {
#ifdef DEBUG
Serial.begin(115200);
delay(2000);
Serial.setDebugOutput(true);
Serial.println("WakeUp");
#endif
pinMode(D0, WAKEUP_PULLUP);
pinMode(A0, INPUT);
WiFi.mode( WIFI_OFF );
delay(1);
WiFi.forceSleepBegin();
newData.hum = 0;
newData.temp = 0;
newData.volt = 0;
oldData.forceTrx = false;
gotCmd = false;
cmd = 0;
debugmode = false;
isUpdateServer = false;
proceedRtcCounter();
}
void loop() {
if(debugmode) otaloop(); else normalloop();
}
void otaloop(){
client.subscribe(mqttTopicIn);
client.loop();
debugOutput("Debug mode on!");
if(!isUpdateServer) initUpdateServer();
httpServer.handleClient();
if (gotCmd && cmd==2 ) {
gotCmd = false;
debugmode = false;
debugOutput("Mqtt command to normal mode!");
client.unsubscribe(mqttTopicIn);
client.publish(mqttTopicIn,"",true);
client.publish(mqttTopicStat,"{\"DEBUG\":OFF)}");
}
yield();
}
void initUpdateServer(){
debugOutput("Init update http server");
isUpdateServer = true;
MDNS.begin("esp8266");
httpUpdater.setup(&httpServer);
httpServer.begin();
MDNS.addService("http", "tcp", 80);
debugOutput("Ready!");
debugOutput(String(WiFi.localIP()).c_str());
}
void normalloop(){
errStatus=0;
readSensorData();
readEEPROM();
if (rtcData.runCount % 12 == 0) {
oldData.forceTrx = true;
}
if (isDataChanged() || oldData.forceTrx ) {
wifiinit();
if (errStatus == 0) {
initmqtt();
if (errStatus == 0) {
debugOutput("Sending data");
sendData();
double t = millis();
while (millis() - t < MQTT_SUB_TIMEOUT){
client.loop();
if (gotCmd && cmd==1 ) {
gotCmd = false;
debugmode = true;
debugOutput("Mqtt command to debug mode!");
client.unsubscribe(mqttTopicIn);
client.publish(mqttTopicIn,"",true);
client.publish(mqttTopicStat,"{\"DEBUG\":ON)}");
}
}
}
}
if (errStatus == 1 || errStatus ==2){
newData.forceTrx = true;
String msg = "Transmission failed. error code "+String(errStatus);
debugOutput(msg.c_str());
}
writeEEPROM();
}
if(debugmode) return;
WiFi.disconnect( true );
delay( 1 );
ESP.deepSleep(sleepSeconds * 1000000, RF_DISABLED);
}
void debugOutput(const char *msg){
#ifdef DEBUG
Serial.println(msg);
#endif
delay(1);
}
void wifiinit(){
int i = 0;
errStatus = 0;
IPAddress ip( 192, 168, 1, 141 );
IPAddress gateway( 192, 168, 1, 1 );
IPAddress subnet( 255, 255, 255, 0 );
WiFi.forceSleepWake();
delay( 1 );
WiFi.persistent( false );
WiFi.mode( WIFI_STA );
WiFi.config( ip, gateway, subnet );
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
i++;
if (i>5) {
errStatus = 1;
return;
};
delay(2000);
}
espClient.setNoDelay(true);
RSSI = WiFi.RSSI();
}
void initmqtt(){
int i = 0;
client.setServer(mqttServer, mqttPort);
debugOutput("Trying to connect to MQTT");
client.setCallback(callback);
client.connect("ESP32Client", mqttUser, mqttPassword );
while (!client.connected()) {
i++;
if (i>5) {
errStatus = 2;
debugOutput("Failed to connect to MQTT");
return;
};
delay(2000);
}
client.subscribe(mqttTopicIn);
client.loop();
}
void readSensorData(){
if(sht30.get()==0){
debugOutput("Got temp&hum data");
newData.temp = sht30.cTemp;
newData.hum = sht30.humidity;
}
else
{
debugOutput("Sensor read error");
newData.temp = newData.hum = 0;
}
newData.volt = analogRead(A0)/1023.0*4.2;
}
bool isDataChanged(){
if( abs(newData.temp-oldData.temp) > tempChangeThr || abs(newData.hum-oldData.hum) > humChangeThr || abs(newData.volt - oldData.volt) > voltChangeThr ) {
debugOutput("Sensor data changed");
return true; }
else {
debugOutput("Sensor data not changed");
return false;}
}
void sendData(){
String msg, msg_stat;
char str_humidity[10], str_temperature[10], str_voltage[10];
// Convert the floats to strings and round to 2 decimal places
dtostrf(newData.hum, 1, 2, str_humidity);
dtostrf(newData.temp, 1, 2, str_temperature);
dtostrf(newData.volt, 1, 2, str_voltage);
msg = "{\"Time\":\"2018-05-20T16:47:35\",\"SHT30\":{\"Temperature\":"+String(str_temperature)+",\"Humidity\":"+String(str_humidity)+"},\"TempUnit\":\"C\"}";
msg_stat = "{\"Time\":\"2018-05-20T20:35:29\",\"Uptime\":"+String(millis()/1000+rtcData.runCount*sleepSeconds)+",\"Vcc\":"+String(str_voltage)+",\"POWER\":\"ON\",\"Wifi\":{\"AP\":2,\"SSId\":\"iho\",\"RSSI\":"+String(RSSI)+",\"APMac\":\"64:66:B3:F8:70:50\"}}";
debugOutput(msg.c_str());
debugOutput(msg_stat.c_str());
if (client.connected()) {
client.publish(mqttTopicData, msg.c_str(),true);
client.publish(mqttTopicStat, msg_stat.c_str(),true);
client.loop();
}
}
uint32_t calculateCRC32(const uint8_t *data, size_t length){
uint32_t crc = 0xffffffff;
while (length--) {
uint8_t c = *data++;
for (uint32_t i = 0x80; i > 0; i >>= 1) {
bool bit = crc & 0x80000000;
if (c & i) {
bit = !bit;}
crc <<= 1;
if (bit) {
crc ^= 0x04c11db7;}
}
}
debugOutput(String(crc).c_str());
return crc;
}
void proceedRtcCounter(){
rst_info * ri;
ri = ESP.getResetInfoPtr();
ESP.rtcUserMemoryRead(0,(uint32_t *) &rtcData,sizeof(rtcData));
if (calculateCRC32((uint8_t *)&rtcData.runCount, sizeof(uint32_t)) != rtcData.crc32){
debugOutput("RTC data corrupted");
dataOk = false;
} else {
debugOutput("RTC data CRC ok");
dataOk = true;
}
if (ri->reason != 5 || !dataOk) {
rtcData.runCount = 0;
rtcData.crc32 = calculateCRC32((uint8_t *)&rtcData.runCount, sizeof(uint32_t));
ESP.rtcUserMemoryWrite(0,(uint32_t *) &rtcData,sizeof(rtcData));
} else {
rtcData.runCount++;
rtcData.crc32 = calculateCRC32((uint8_t *)&rtcData.runCount, sizeof(uint32_t));
ESP.rtcUserMemoryWrite(0,(uint32_t *) &rtcData,sizeof(rtcData));
}
String msg = "Run count"+String(rtcData.runCount);
debugOutput(msg.c_str());
}
void readEEPROM(){
uint32_t CRC;
EEPROM.begin(sizeof(memData));
EEPROM.get(EEPROM_ADDR,memData);
debugOutput("Stored CRC:");
debugOutput(String(memData.crc32).c_str());
CRC = calculateCRC32((uint8_t *) &memData.data,sizeof(_Data));
debugOutput("Calculated CRC:");
debugOutput(String(CRC).c_str());
if ( CRC != memData.crc32 ){
debugOutput("CRC check failed!");
oldData.temp = newData.temp;
oldData.hum = newData.hum;
oldData.volt = newData.volt;
oldData.forceTrx = true;
} else {
debugOutput("CRC check sucsessfull");
oldData.temp = memData.data.temp;
oldData.hum = memData.data.hum;
oldData.volt = memData.data.volt;
oldData.forceTrx = memData.data.forceTrx;}
}
void writeEEPROM(){
memData.data.hum = newData.hum;
memData.data.temp = newData.temp;
memData.data.volt = newData.volt;
memData.data.forceTrx = newData.forceTrx;
memData.crc32 = calculateCRC32((uint8_t *) &memData.data,sizeof(_Data));
EEPROM.put(EEPROM_ADDR,memData);
debugOutput("Storing data in EEPROM");
EEPROM.commit();
}
void callback(char* topic, byte* payload, unsigned int length) {
byte* p = (byte*)malloc(length);
// Copy the payload to the new buffer
memcpy(p,payload,length);
cmd = atoi((char *)p);
if (cmd == 1 || cmd == 2) {
debugOutput(String(cmd).c_str());
gotCmd = true;
}
else debugOutput("Unknown command");
free(p);
}