-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy paththermostat.ino
727 lines (679 loc) · 21 KB
/
thermostat.ino
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
//// ESP8266/WeMos D1 Mini Pro - DS18B20 IoT Thermostat
//// Copyright 2018 © Hugo
//// https://github.com/netphantm/Arduino
//// include third party libraries
#include <WiFiManager.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <FS.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "SSD1306Wire.h"
#include <ArduinoJson.h>
#include <TFT_eSPI.h>
#include <SPI.h>
#include "Free_Fonts.h" // Include the header file attached to this sketch
//// define variables / hardware
#define ONE_WIRE_BUS D4 // DS18B20 pin D4 = GPIO2
#define RELAISPIN D1 // or D0?
#define TOUCHPIN D0
#define PBSTR "|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
#define PBWIDTH 79
#define dsp_small
const size_t bufferSize = JSON_OBJECT_SIZE(6) + 160;
const static String sFile = "/settings.txt";
const static String configHost = "http://temperature.hugo.ro"; // chicken/egg situation, you have to get initial config somewhere
unsigned long uptime = (millis() / 1000 );
unsigned long prevTime = 0;
unsigned long prevTimeIP = 0;
bool emptyFile = false;
bool heater = true;
bool manual = false;
bool debug = true;
bool button = false;
char lanIP[16];
String inetIP;
String mode;
String WiFi_Name;
uint8_t sha1[20];
float temp_c;
String webString;
String relaisState;
String SHA1;
String loghost;
String epochTime;
uint16_t color;
int httpsPort;
int interval;
int cursorX;
int cursorY;
float temp_min;
float temp_max;
float temp_dev;
#if defined (dsp_small)
String hostname = "Clamps";
SSD1306Wire tft(0x3c, D6, D5);
#else
String hostname = "Joey";
TFT_eSPI tft = TFT_eSPI();
#endif
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
ESP8266WebServer server(80);
//// read temperature from sensor / switch relay on or off
void getTemperature() {
Serial.print("= getTemperature: ");
float last_temp_c = temp_c;
uptime = (millis() / 1000 ); // Refresh uptime
delay(10);
DS18B20.requestTemperatures(); // initialize temperature sensor
temp_c = float(DS18B20.getTempCByIndex(0)); // read sensor
yield();
if (temp_c < -120)
temp_c = last_temp_c;
temp_c = temp_c + temp_dev; // calibrating sensor
Serial.println(temp_c);
}
void switchRelais(String sw = "TOGGLE") { // if no parameter given, assume TOGGLE
Serial.print("= switchRelais: ");
if (sw == "TOGGLE") {
if (digitalRead(RELAISPIN) == 1) {
digitalWrite(RELAISPIN, 0);
relaisState = "OFF";
} else {
digitalWrite(RELAISPIN, 1);
relaisState = "ON";
}
Serial.println(relaisState);
return;
} else {
if (sw == "ON") {
digitalWrite(RELAISPIN, 1);
relaisState = "ON";
} else if (sw == "OFF") {
digitalWrite(RELAISPIN, 0);
relaisState = "OFF";
}
Serial.println(relaisState);
}
}
void autoSwitchRelais() {
Serial.print("= autoSwitchRelais: ");
if (manual) {
delay(10);
return;
} else {
if (heater) {
if (temp_c <= temp_min) {
switchRelais("ON");
} else if (temp_c >= temp_max) {
switchRelais("OFF");
}
} else {
if (temp_c >= temp_max) {
switchRelais("ON");
} else if (temp_c <= temp_min) {
switchRelais("OFF");
}
}
}
delay(10);
}
//// settings read / write / clear SPIFFS
void clearSpiffs() {
Serial.println("= clearSpiffs");
Serial.println("Please wait for SPIFFS to be formatted");
SPIFFS.format();
yield();
Serial.println("SPIFFS formatted");
emptyFile = true; // mark file as empty
server.send(200, "text/plain", "200: OK, SPIFFS formatted, settings cleared\n");
}
int readSettingsWeb() { // use plain http, as SHA1 fingerprint not known yet
Serial.println("= readSettingsWeb");
String pathQuery = "/settings-";
pathQuery += hostname;
pathQuery += ".json";
if (debug) {
Serial.print(F("Getting settings from "));
Serial.print(configHost);
Serial.print(pathQuery);
}
WiFiClient client;
HTTPClient http;
http.begin(client, configHost + pathQuery);
http.addHeader("Content-Type", "application/json");
int httpCode = http.GET();
if(httpCode > 0) {
String webJson = String(http.getString());
if (debug) {
Serial.print(F(": "));
Serial.println(httpCode);
Serial.print(F("Got settings JSON from webserver: "));
Serial.println(webJson);
}
deserializeJson(webJson);
} else {
Serial.print(F("HTTP GET ERROR: failed getting settings from web! Error: "));
Serial.println(http.errorToString(httpCode).c_str());
}
http.end();
return httpCode;
}
void readSettingsFile() {
Serial.println("= readSettingsFile");
File f = SPIFFS.open(sFile, "r"); // open file for reading
if (!f) {
Serial.println(F("Settings file read open failed"));
emptyFile = true;
return;
}
while (f.available()) {
String fileJson = f.readStringUntil('\n');
deserializeJson(fileJson);
}
f.close();
}
void deserializeJson(String json) {
// deserialize JSON
StaticJsonBuffer<512> jsonBuffer;
JsonObject &root = jsonBuffer.parseObject(json);
if (!root.success()) {
Serial.println(F("Error deserializing json!"));
emptyFile = true;
return;
} else {
SHA1 = root["SHA1"].as<String>();
loghost = root["loghost"].as<String>(), sizeof(loghost);
httpsPort = root["httpsPort"].as<int>(), sizeof(httpsPort);
interval = root["interval"].as<long>(), sizeof(interval);
temp_min = root["temp_min"].as<float>(), sizeof(temp_min);
temp_max = root["temp_max"].as<float>(), sizeof(temp_max);
temp_dev = root["temp_dev"].as<float>(), sizeof(temp_dev);
heater = root["heater"].as<bool>(), sizeof(heater);
manual = root["manual"].as<bool>(), sizeof(manual);
debug = root["debug"].as<bool>(), sizeof(debug);
if (debug)
Serial.println(F("Deserialized JSON"));
emptyFile = false; // mark file as not empty
}
}
void updateSettings() {
Serial.println("\n= updateSettings");
if (server.args() < 1 || server.args() > 10 || !server.arg("SHA1") || !server.arg("loghost")) {
server.send(200, "text/html", "400: Invalid Request\n");
return;
}
Serial.println("Got new settings from webform");
SHA1 = server.arg("SHA1");
loghost = server.arg("loghost");
httpsPort = server.arg("httpsPort").toInt();
interval = server.arg("interval").toInt();
temp_min = server.arg("temp_min").toFloat();
temp_max = server.arg("temp_max").toFloat();
temp_dev = server.arg("temp_dev").toFloat();
heater = server.arg("heater").toInt();
manual = server.arg("manual").toInt();
debug = server.arg("debug").toInt();
writeSettingsFile();
server.send(200, "text/html", webString);
}
void writeSettingsFile() {
Serial.print("= writeSettingsFile: ");
File f = SPIFFS.open(sFile, "w"); // open file for writing
if (!f) {
Serial.println(F("Failed to create settings file"));
server.send(200, "text/html", "200: OK, File write open failed! settings not saved\n");
return;
}
// serialize JSON
StaticJsonBuffer<256> jsonBuffer;
JsonObject &root = jsonBuffer.createObject();
root["SHA1"] = SHA1;
root["loghost"] = loghost;
root["httpsPort"] = httpsPort;
root["interval"] = interval;
root["temp_min"] = temp_min;
root["temp_max"] = temp_max;
root["temp_dev"] = temp_dev;
root["heater"] = heater;
root["manual"] = manual;
root["debug"] = debug;
String outputJson;
root.printTo(outputJson);
if (debug) {
Serial.print(F("- outputJson: "));
Serial.println(outputJson);
}
// write JSON to file
if (root.printTo(f) == 0) {
Serial.println(F("Failed to write to file"));
webString += "Failed to write to file\n";
} else {
Serial.println("OK");
// prepare webpage for output
webString = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n";
webString += "<head>\n";
webString += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n<style>\n";
webString += "\tbody { \n\t\tpadding: 3rem; \n\t\tfont-size: 16px;\n\t}\n";
webString += "\tform { \n\t\tdisplay: inline; \n\t}\n</style>\n";
webString += "</head>\n<body>\n";
webString += "200: OK, Got new settings<br>\n";
webString += "Settings file updated.\n<br>\nBack to \n";
webString += "<form method='POST' action='https://temperature.hugo.ro'>";
webString += "\n<button name='device' value='";
webString += hostname;
webString += "'>Graph</button>\n";
webString += "</form>\n<br>\n";
webString += "JSON root: \n<br>\n";
webString += "<div id='debug'></div>\n";
webString += "<script src='https://temperature.hugo.ro/prettyprint.js'></script>\n";
webString += "<script>\n\tvar root = ";
webString += outputJson;
webString += ";\n\tvar tbl = prettyPrint(root);\n";
webString += "\tdocument.getElementById('debug').appendChild(tbl);\n</script>\n";
webString += "</body>\n";
emptyFile = false; // mark file as not empty
}
f.close();
}
//// local webserver handlers / send data to logserver
void handleRoot() {
server.send(200, "text/html", "<html><head></head><body><div align=\"center\"><h1>Nothing to see here! Move along...</h1></div></body></html>\n");
}
void handleNotFound(){
server.send(404, "text/plain", "404: File not found!\n");
}
void logToWebserver() {
Serial.println("= logToWebserver");
// configure path + query for sending to logserver
if (emptyFile) {
Serial.println(F("Empty settings file, maybe you cleared it? Not updating logserver"));
return;
}
String pathQuery = "/logtemp.php?&status=";
pathQuery += relaisState;
pathQuery += "&temperature=";
pathQuery += temp_c;
pathQuery += "&hostname=";
pathQuery += hostname;
pathQuery += "&temp_min=";
pathQuery += temp_min;
pathQuery += "&temp_max=";
pathQuery += temp_max;
pathQuery += "&temp_dev=";
pathQuery += temp_dev;
pathQuery += "&interval=";
pathQuery += interval;
pathQuery += "&heater=";
pathQuery += heater;
pathQuery += "&manual=";
pathQuery += manual;
pathQuery += "&debug=";
pathQuery += debug;
if (debug) {
Serial.print(F("Connecting to https://"));
Serial.print(loghost);
Serial.println(pathQuery);
}
BearSSL::WiFiClientSecure webClient;
from_str();
webClient.setFingerprint(sha1);
HTTPClient https;
if (https.begin(webClient, loghost, httpsPort, pathQuery)) {
int httpCode = https.GET();
if (httpCode > 0) {
if (debug) {
Serial.print(F("HTTP GET OK: "));
Serial.println(httpCode);
}
if (httpCode == HTTP_CODE_OK) {
epochTime = https.getString();
Serial.print("Timestamp on log update: ");
Serial.println(epochTime);
}
} else {
Serial.print(F("HTTP GET ERROR: failed logging to webserver! Error: "));
Serial.println(https.errorToString(httpCode).c_str());
}
https.end();
} else {
Serial.println(F("HTTP ERROR: Unable to connect"));
}
}
////// Miscellaneous functions
//// print variables for debug
void debug_vars() {
Serial.println(F("# DEBUG:"));
Serial.print(F("- hostname: "));
Serial.println(hostname);
Serial.print(F("- LAN IP: "));
Serial.println(lanIP);
Serial.print(F("- Inet IP: "));
Serial.println(inetIP);
Serial.print(F("- uptime: "));
Serial.println(uptime);
Serial.print(F("- Temperature: "));
Serial.println(temp_c);
Serial.print(F("- RelaisState: "));
Serial.println(relaisState);
Serial.print(F("- heater: "));
Serial.println(heater);
Serial.print(F("- manual: "));
Serial.println(manual);
Serial.print(F("- button: "));
Serial.println(button);
if (emptyFile) {
Serial.print(F("- emptyFile: "));
Serial.println(emptyFile);
return;
}
Serial.print(F("- SHA1: "));
Serial.println(SHA1);
Serial.print(F("- loghost: "));
Serial.println(loghost);
Serial.print(F("- httpsPort: "));
Serial.println(httpsPort);
Serial.print(F("- interval: "));
Serial.println(interval);
Serial.print(F("- temp_min: "));
Serial.println(temp_min);
Serial.print(F("- temp_max: "));
Serial.println(temp_max);
Serial.print(F("- temp_dev: "));
Serial.println(temp_dev);
Serial.print(F("- MEM free heap: "));
Serial.println(system_get_free_heap_size());
}
//// transform SHA1 to hex format needed for setFingerprint (from aa:ab:etc. to 0xaa, 0xab, etc.)
void from_str() {
int j = 0;
for (int i = 0; i < 60; i = i + 3) {
String x = ("0x" + SHA1.substring(i, i+2));
sha1[j] = strtoul(x.c_str(), NULL, 16);
j++;
}
}
//// print progress bar to console
void printProgress (unsigned long percentage) {
long val = (unsigned long) (percentage + 1);
unsigned long lpad = (unsigned long) (val * PBWIDTH /100);
unsigned long rpad = PBWIDTH - lpad;
printf ("\r%3d%% [%.*s%*s]", val, lpad, PBSTR, rpad, "");
fflush (stdout);
}
//// write to tft display
void updateDisplay() {
#if defined (dsp_small)
if (manual) {
mode = "Manual";
} else {
mode = "Automatic";
}
String state = "Relais: " + relaisState + " / " + mode;
tft.init();
tft.setTextAlignment(TEXT_ALIGN_LEFT);
tft.setFont(ArialMT_Plain_10);
tft.drawString(0, 0, "Connected to WiFi");
tft.drawString(0, 10, "SSID: " + WiFi.SSID());
tft.drawString(0, 20, "LAN IP: " + String("") + lanIP);
tft.drawString(0, 30, "Inet IP: " + inetIP);
tft.drawString(0, 40, "Temperature: " + String(temp_c, 2) + "°C");
tft.drawString(0, 50, state);
tft.display();
#else
tft.fillScreen(TFT_BLACK);
tft.setCursor(0, 0);
tft.setTextFont(0);
tft.setTextColor(TFT_YELLOW);
tft.setTextSize(1);
tft.println("Connected to SSID:");
if (WiFi.SSID().length() < 11)
tft.setTextSize(2);
tft.println(WiFi.SSID());
tft.setTextColor(TFT_WHITE);
tft.setTextSize(1);
tft.println("LAN:" + String("") + lanIP);
tft.println("Inet:" + inetIP);
tft.println("Temperature:\n");
cursorY = tft.getCursorY() - 4;
tft.drawRoundRect(1, cursorY, 127, 22, 3, TFT_WHITE);
if (temp_c < temp_min) {
color = 0x001F;
} else if (temp_c > temp_max) {
color = 0xFFC8;
} else {
color = 0xFFE0;
}
tft.setTextColor(color);
tft.setTextSize(1);
tft.print(" ");
tft.setTextSize(2);
tft.print(String(temp_c, 2));
tft.setTextSize(1);
tft.print(" ");
tft.setTextSize(2);
cursorX = tft.getCursorX() + 5;
cursorY = tft.getCursorY() + 2;
tft.drawCircle(cursorX, cursorY, 2.5, color);
//tft.print((char)247);
tft.println(" C");
tft.setTextSize(1);
tft.println("");
tft.setTextColor(TFT_WHITE);
tft.println("MIN: " + String(temp_min, 1) + " " + (char)45 + " MAX: " + String(temp_max, 1) + "\n");
tft.setTextSize(2);
if (heater) {
tft.setTextColor(TFT_RED);
tft.print("Heater:");
} else {
tft.setTextColor(TFT_BLUE);
tft.print("Cooler:");
}
if (relaisState == "ON") {
tft.setTextColor(TFT_RED);
tft.println(relaisState);
} else {
tft.setTextColor(TFT_GREEN);
tft.println(relaisState);
}
if (manual) {
mode = "Manual";
tft.setTextColor(0xFFC8);
} else {
mode = "Automatic";
tft.setTextColor(TFT_GREEN);
}
tft.println(mode);
#endif
}
//// get internet IP (for display)
void getInetIP() {
Serial.print(F("= getInetIP"));
unsigned long presTimeIP = millis();
unsigned long passedIP = presTimeIP - prevTimeIP;
if (presTimeIP < 60000 || passedIP > 3600000) { // update every hour, so we don't piss of the guys @ ipinfo.io
WiFiClient client;
HTTPClient http;
http.begin(client, "http://ipinfo.io/ip");
http.addHeader("Content-Type", "application/text");
int httpCode = http.GET();
if(httpCode > 0) {
inetIP = String(http.getString());
inetIP.trim();
Serial.print(F(": "));
Serial.print(inetIP);
prevTimeIP = presTimeIP; // save the last time Ip was updated
} else {
Serial.print(F("HTTPS GET ERROR: failed getting internet IP! Error: "));
Serial.println(http.errorToString(httpCode).c_str());
inetIP == "Error:" + httpCode;
}
http.end();
}
Serial.println();
}
//// convert sizes in bytes to KB and MB
String formatBytes(size_t bytes) {
if (bytes < 1024) {
return String(bytes) + "B";
} else if (bytes < (1024 * 1024)) {
return String(bytes / 1024.0) + "KB";
} else if (bytes < (1024 * 1024 * 1024)) {
return String(bytes / 1024.0 / 1024.0) + "MB";
}
}
//// WiFi config mode
void configModeCallback (WiFiManager *myWiFiManager) {
Serial.println("Opening configuration portal");
#if defined (dsp_small)
tft.init();
tft.setTextAlignment(TEXT_ALIGN_LEFT);
tft.setFont(ArialMT_Plain_10);
tft.drawString(0, 10, "# Entered config mode #");
tft.drawString(0, 30, "ID/pass: NDND/pass4esp");
tft.drawString(0, 40, "Config IP: 10.0.1.1");
tft.display();
#else
tft.fillScreen(TFT_BLACK); // Black screen fill
tft.setTextColor(TFT_YELLOW);
tft.setTextSize(2);
tft.println("WiFi Conf.\n");
tft.setTextColor(TFT_BLUE);
tft.println("IP:");
tft.setTextColor(TFT_GREEN);
tft.println(" 10.0.1.1");
tft.setTextColor(TFT_BLUE);
tft.println("SSID:");
tft.setTextColor(TFT_GREEN);
tft.println(" " + hostname);
tft.setTextColor(TFT_BLUE);
tft.println("Password: ");
tft.setTextColor(TFT_GREEN);
tft.println(" pass4esp");
#endif
}
//// setup / first run
void setup(void) {
Serial.begin(115200);
DS18B20.begin();
delay(10);
pinMode(RELAISPIN, OUTPUT);
tft.init();
WiFiManager wifiManager;
wifiManager.setTimeout(300);
wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
wifiManager.setDebugOutput(false);
wifiManager.setAPCallback(configModeCallback);
if(!wifiManager.autoConnect("Joey","pass4esp")) {
delay(1000);
Serial.println(F("Failed to connect and hit timeout, restarting..."));
ESP.reset();
}
Serial.print(F("Seconds in void setup() WiFi connection: "));
int connRes = WiFi.waitForConnectResult();
Serial.println(connRes);
if (WiFi.status()!=WL_CONNECTED) {
Serial.println(F("Failed to connect to WiFi, resetting in 5 seconds"));
delay(5000);
ESP.reset();
} else {
if (!MDNS.begin("esp8266"))
Serial.println(F("Error setting up mDNS responder"));
}
IPAddress ip = WiFi.localIP();
sprintf(lanIP, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
SPIFFS.begin(); // initialize SPIFFS
Serial.println("SPIFFS started. Contents:");
Dir dir = SPIFFS.openDir("/");
while (dir.next()) { // List the file system contents
String fileName = dir.fileName();
size_t fileSize = dir.fileSize();
Serial.printf("\tFS File: %s, size: %s\r\n", fileName.c_str(), formatBytes(fileSize).c_str());
}
Serial.println("\n");
switchRelais("OFF"); // start with relais OFF
if (readSettingsWeb() != 200) // first, try reading settings from webserver
readSettingsFile(); // if failed, read settings from SPIFFS
getInetIP();
getTemperature();
autoSwitchRelais();
updateDisplay();
// local webserver client handlers
server.onNotFound(handleNotFound);
server.on("/", handleRoot);
server.on("/update", []() {
updateSettings();
getTemperature();
autoSwitchRelais();
updateDisplay();
if (debug)
debug_vars();
});
server.on("/clear", clearSpiffs);
server.begin();
}
//// start main loop
void loop(void) {
bool hold = true;
while (digitalRead(TOUCHPIN) == 1) { // hold here as long as sensor is touched to avoid switching on every loop pass
button = true;
if (hold) { // avoid switching more than once (hangs up the device)
manual = true;
delay(500);
while (digitalRead(TOUCHPIN) == 1) { // if touch sensor is still triggered, switch back to auto mode
manual = false;
}
yield();
}
yield();
hold = false;
}
if (button) {
if (manual) {
switchRelais("TOGGLE");
updateDisplay();
Serial.println(F("\nSwitched to Manual mode"));
} else {
autoSwitchRelais();
if (temp_c > temp_min || temp_c < temp_max) // if in hysteresis, switch relais off
switchRelais("OFF");
updateDisplay();
Serial.println(F("\nSwitched to Automatic mode"));
}
button = false;
}
unsigned long presTime = millis();
unsigned long passed = presTime - prevTime;
if (passed > interval) {
Serial.println(F("\nInterval passed"));
getInetIP();
if (readSettingsWeb() != 200) // first, try reading settings from webserver
readSettingsFile(); // if failed, read settings from SPIFFS
prevTime = presTime; // save the last time sensor was read
if (emptyFile) { // settings file does not exist
if (readSettingsWeb() != 200) { // first, try reading settings from webserver
Serial.println(F("Switching relais off: no settings found on SPIFFS OR webserver!"));
switchRelais("OFF");
debug_vars();
Serial.println(F("Waiting for settings to be sent..."));
delay(500);
} else {
writeSettingsFile();
}
} else {
getTemperature();
autoSwitchRelais();
if (debug)
debug_vars();
updateDisplay();
logToWebserver();
}
if (interval < 4999) // set a failsafe interval
interval = 20000; // 20 secs
} else {
printProgress(passed * 100 / interval);
}
server.handleClient();
}