-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenWeather.ino
1193 lines (992 loc) · 34.9 KB
/
openWeather.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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Open Weather - the open source weatherbeacon that also looks good.
We connect to your home wifi and send a http request to open weathermap every hour to update the free 3 hour forecast.
depending on the weather-id (https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2) another led will light up
in a predefined colour to resemble weather and temperature and hightlight the respective icon.
See Full documentation on https://daniel-strohbach.de/diy-esp8266-wetterstation
Parts needed:
- ESP8266 or ESP32 Board, alternatively arduino nano with wifi shield will do as well but not coded here
- Optional: DHT22 or DHT11 Sensor to measure Indoor Temp and Humidity
- 4x WS2812 (aka NeoPixel) LED
Solder the 4 LEDs into a tiny LED Strip and connect to Dev Board:
Board LED LED LED LED
3V3 - VCC - VCC - VCC - VCC
GND - GND - GND - GND - GND
D8 - I/0 - I/O - I/O - I
Connect DHT22 / DHT11 to
Board DHT
3V3 - +
GND - -
D4 - OUT
Pixel-ID Icon reference (take care when assembling or switch in the code
0 - clear sky
1 - cloudy
2 - rainy
3 - snow
Outdoortemperature & Colours:
> 30°C - Red
> 21°C - Warm yellow
< 18°C - Light blue
< 00°C - Blue
Thunderstorm: Yellow
Fog: White
Red: Wifi related error
green: connecting
Optional: Send the measured DHT Data to an MQTT Broker (topics are customizable within captive portal)
receive Data:
temperature: stat/openWeather/Temperatur
Humidity: stat/openWeather/Feuchtigkeit
HeatIndex: stat/openWeather/HeatIndex
control openWeather:
light on: cmnd/openWeather/power - payload on
light off: cmnd/openWeather/power - payload off
switch to party mode: cmnd/openWeather/state - PixelParty1 or PixelParty2
upon receiving a command it sends back on stat/openWeather/power and stat/openWeather/state which mode it is in.
Dependencies:
PubSubClient
ArduinoJson
ESP8266 Libs
ESP32 Libs
DHT Sensor library for ESPx
WifiManager
LittleFS
Now with Wifi Manager or HardCoded Wifi credentials optional.
Thanks to https://github.com/CurlyWurly-1/ESP8266-WIFIMANAGER-MQTT/blob/master/MQTT_with_WiFiManager.ino
Now with OTA Update via ArduinoOTA
Made By Daniel Strohbach www.daniel-strohbach.de/
*/
//--- USER CONFIG ---
//Do you want to use MQTT?
#define USEMQTT
//Do you want to use Managed WIFI or Hardcoded Wifi?
#define USEWIFIMANAGER
// #define USEWIFI //if so, do not forget to enter your credentials in line 116/117
//Do you want to use DHT?
#define USEDHT
//Do you use ESP8266 or ESP32? -> Switch to the correct one, if needed
#define ESP8266
//Do you want to use Serial Monitor for Debugging?
#define DEBUGING
//Which Board?
#ifdef ESP8266
#include <ESP8266WiFi.h> // for WiFi functionality
#include <ESP8266HTTPClient.h> //for the API-Request
#include <ESP8266WebServer.h>
//#include "SPIFFS.h"
#include <LittleFS.h> //for ESP82
#define SPIFFS LittleFS
#endif
#ifdef ESP32
#include <WiFi.h> //in case you are on esp32 we switch to this line
#include <HTTPClient.h>
#include <ESP32WebServer.h>
//#include "SPIFFS.h"
#include <LITTLEFS.h> //for ESP32
#define SPIFFS LITTLEFS
#endif
//WIfi-Manager and Captive Portal
#include <DNSServer.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
//OTA Updates
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
//Colours and Position
int GcolourR, GcolourG, GcolourB, Gposition;
// Please Change to your WIFI-Credentials
#ifdef USEWIFI
const char* ssid = "SSID";
const char* password = "PW";
#endif
//What citiy you want to receive the weather from?
const char* city = "Munich,de"; //City and Country like this Oldenburg,de
//Here please add your Open Weathermap API Key from https://home.openweathermap.org/api_keys
#define openWeatherAPI "API"
//What units do you use?
const char* unitSystem = "metric";
#include <ArduinoJson.h> //JSON String conversion for Open Weathermap API Request and WifiManager
// We use Neopixel to Control the WS2812. In my build i use a node mcu esp8266 and pin d8 to drive the pixels
#include <Adafruit_NeoPixel.h>
#define LEDPIN D8 //neopixels to pin d8
#define NUMPIXELS 4 // My Vesion has 4 Pixels
Adafruit_NeoPixel pixels(NUMPIXELS, LEDPIN, NEO_GRB + NEO_KHZ800); //build the neopixel constructor
#ifdef USEWIFIMANAGER
WiFiManager wifiManager;
#endif
//--- MQTT ---
#ifdef USEMQTT
#include <PubSubClient.h>
bool mqttConnected = false;
//define your default values here, if there are different values in config.json, they are overwritten.
#define mqttServer "192.168.178.XX"
#define mqttUsername "mqtt-user"
#define mqttPassword "PW"
#define mqttPort "1883"
#define mqttDeviceID "openWeather"
//i use something quite similar to tasmota, but feel free to change
#define subTopic "cmnd/openWeather/state"
#define subTopic1 "cmnd/openWeather/power"
#define resTopic "stat/openWeather/state"
#define resTopic1 "stat/openWeather/power"
#define temperatureTopic "stat/openWeather/Temperatur"
#define humidityTopic "stat/openWeather/Feuchtigkeit"
#define heatIndexTopic "stat/openWeather/HeatIndex"
unsigned long lastMsg = 0;
WiFiClient openWeather;
PubSubClient MQTTclient(openWeather);
void callback(char* topic, byte* message, unsigned int length);
#endif
//--- DHT ---
#ifdef USEDHT
#include "DHTesp.h"
#define DHTPIN D4
DHTesp dht;
//--- Global Variables for Sensor storage--- // not elegant, but it works :)
float temperature, humidity, heatIndex;
#endif
//--- Timer Stuff ---
#ifdef USEDHT
unsigned long previousMillisMes; //previous timer time
const unsigned long measureIntervall = 500; //update sensor every 500ms
#endif
#ifdef USEMQTT
unsigned long previousMillisPub; //for timer to publish to mqtt broker
const unsigned long publishIntervall = 5000; //publish mqtt every 5 sekonds
#endif
unsigned long previousMillisReq; //for timer to request the weather data from openWeathermap
const unsigned long requestIntervall = 3600000; //drive http request every hour
int modus = 0; //for different control modes
bool firstloop = true; //well, self explanatory
//flag for saving data
#ifdef USEWIFIMANAGER
bool shouldSaveConfig = false;
#endif
//---------------------------------------------- ARDUINO SETUP ------------------------------------------------------
void setup() {
//Begin serial connection
#ifdef DEBUGING
Serial.begin(9600);
Serial.println();
Serial.println();
//Welcome to Serial Monitor
Serial.println("openWeather: Erfasse Wetter, Temperatur, Feuchtigkeit on: ");
String thisBoard = ARDUINO_BOARD;
Serial.println(thisBoard);
#endif
//--Neopixel
pixels.begin(); // INITIALIZE NeoPixel strip object
pixels.clear(); // Set all pixel colors to 'off'
#ifdef USEWIFIMANAGER
//Wifi-Manager
setup_wifimanager();
#endif
#ifdef USEWIFI
//--Wifi
setup_wifi();
#endif
//--MQTT
#ifdef USEMQTT
MQTTclient.setServer(mqttServer, atoi(mqttPort));
#ifdef DEBUGING
Serial.println("MQTT Setup: Server and Port are Set to: ");
#endif
MQTTclient.setCallback(callback);
#ifdef DEBUGING
Serial.println("MQTT Setup: callback function set");
#endif
MQTTclient.subscribe(subTopic);
#ifdef DEBUGING
Serial.println("MQTT Setup: subscribed to subTopic");
#endif
MQTTclient.setKeepAlive(90);
#ifdef DEBUGING
Serial.println("MQTT Setup: set KeepAlive to 90");
#endif
reconnect(); //establish connection to mqtt server
#ifdef DEBUGING
Serial.println("MQTT Setup: finished");
#endif
#endif
//--DHT
#ifdef USEDHT
dht.setup(DHTPIN, DHTesp::DHT22); // Connect DHT sensor to GPIO 17
#ifdef DEBUGING
Serial.println("DHT Setup: Sensor connected to GPIO");
#endif
#endif
//--OTA UPDATES
// Port defaults to 8266
// ArduinoOTA.setPort(8266);
// Hostname defaults to esp8266-[ChipID]
ArduinoOTA.setHostname("openWeather");
// No authentication by default
ArduinoOTA.setPassword("admin");
// Password can be set with it's md5 value as well
// MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
// ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
ArduinoOTA.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH) {
type = "sketch";
} else { // U_FS
type = "filesystem";
}
// NOTE: if updating FS this would be the place to unmount FS using FS.end()
#ifdef DEBUGING
Serial.println("Start updating " + type);
#endif
});
ArduinoOTA.onEnd([]() {
#ifdef DEBUGING
Serial.println("\nEnd");
#endif
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
#ifdef DEBUGING
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
#endif
});
ArduinoOTA.onError([](ota_error_t error) {
#ifdef DEBUGING
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) {
Serial.println("Auth Failed");
} else if (error == OTA_BEGIN_ERROR) {
Serial.println("Begin Failed");
} else if (error == OTA_CONNECT_ERROR) {
Serial.println("Connect Failed");
} else if (error == OTA_RECEIVE_ERROR) {
Serial.println("Receive Failed");
} else if (error == OTA_END_ERROR) {
Serial.println("End Failed");
}
#endif
});
ArduinoOTA.begin();
} // end of void setup
//--- ARDUINO LOOP ---
void loop() {
#ifdef DEBUGING
Serial.println("void loop: Started... ");
Serial.print("Wifi Connected: ");
if ((WiFi.status() == WL_CONNECTED)) {
Serial.println("true");
} else {
Serial.println("false");
}
#ifdef USEMQTT
Serial.print("MQTT Connected: ");
if ((MQTTclient.state() == 0)) {
Serial.println("true");
} else {
Serial.println("false");
}
#endif
#endif
ArduinoOTA.handle(); //handles the ota update stuff
//if mqtt is not connected, try again
#ifdef USEMQTT
if ((!MQTTclient.state() == 0)) {
reconnect();
}
#endif
//what mode are we in? (light on or off, party mode or not)
#ifdef DEBUGING
Serial.print("void loop: Modus: ");
Serial.println(modus);
#endif
//if we are in the first loop, we already want to fetch the weather data, afterwards only every hour
if (firstloop) {
getWeather();
firstloop = false;
#ifdef DEBUGING
Serial.print("first loop: fetching weather data: ");
#endif
}
//get Weatherdata every hour (or what you did custom)
if (millis() - previousMillisReq >= requestIntervall) {
previousMillisReq = millis();
if (modus == 0) {
getWeather();
#ifdef DEBUGING
Serial.print("timer: fetching weather data: ");
#endif
}
}
//read sensor data
#ifdef USEDHT
//read sensor
if (millis() - previousMillisMes >= measureIntervall) {
previousMillisMes = millis();
getDHT();
#ifdef DEBUGING
Serial.print("timer: fetching dht sensor data: ");
#endif
}
#endif
//send the data to mqtt broker
#ifdef USEMQTT
//publish to MQTT Broker
if (millis() - previousMillisPub >= publishIntervall) {
previousMillisPub = millis();
publishMQTT();
#ifdef DEBUGING
Serial.print("timer: sending mqtt data: ");
#endif
}
#endif
//keep mqtt connection alive
#ifdef USEMQTT
if (MQTTclient.loop()) {
#ifdef DEBUGING
Serial.println("MQTT Client.loop called successfull");
#endif
} else {
#ifdef DEBUGING
Serial.println("MQTT Client.loop call failed");
#endif
}
#endif
//some remote control for different uses - maybe switch case is better?!
if (modus == 1) {
pixelParty();
}
if (modus == 2) {
rainbowFade(3, 3, 1);
}
if (modus == 3) { //weather icon is off
pixels.clear();
pixels.show();
}
if (modus == 0) { // weather icon is on again
pixels.clear();
showWeather();
}
} //end of void loop
//--- CUSTOM CLASSES ---
//--callback notifying us of the need to save config
void saveConfigCallback() {
#ifdef DEBUGING
Serial.println("Should save config");
#endif
shouldSaveConfig = true;
}
//------------------------Wifi-Manager-----------------------------
#ifdef USEWIFIMANAGER
void setup_wifimanager() {
//clean FS for testing
// SPIFFS.format();
//read configuration from FS json
#ifdef DEBUGING
Serial.println("Using Wifi Manager");
Serial.println("mounting FS...");
#endif
if (SPIFFS.begin()) {
#ifdef DEBUGING
Serial.println("mounted file system");
#endif
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
#ifdef DEBUGING
Serial.println("reading config file");
#endif
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
#ifdef DEBUGING
Serial.println("opened config file");
#endif
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonDocument doc(2048);
deserializeJson(doc, buf.get());
auto error = serializeJson(doc, Serial);
if (!error) {
#ifdef DEBUGING
Serial.println("\nparsed json");
#endif
strcpy(mqttServer, doc["mqttServer"]);
strcpy(mqttPort, doc["mqttPort"]);
strcpy(mqttUsername, doc["mqttUsername"]);
strcpy(mqttPassword, doc["mqttPassword"]);
strcpy(mqttDeviceID, doc["mqttDeviceID"]);
strcpy(openWeatherAPI, doc["openWeatherAPI"]);
strcpy(subTopic, doc["subTopic"]);
strcpy(subTopic1, doc["subTopic1"]);
strcpy(resTopic, doc["resTopic"]);
strcpy(resTopic1, doc["resTopic1"]);
strcpy(temperatureTopic, doc["temperatureTopic"]);
strcpy(humidityTopic, doc["humidityTopic"]);
strcpy(heatIndexTopic, doc["heatIndexTopic"]);
} else {
#ifdef DEBUGING
Serial.println("failed to load json config");
#endif
}
}
}
} else {
#ifdef DEBUGING
Serial.println("failed to mount FS");
#endif
}
//end read
// The extra parameters to be configured (can be either global or just in the setup)
// After connecting, parameter.getValue() will get you the configured value
// id/name placeholder/prompt default length
WiFiManagerParameter custom_mqttServer("server", "mqtt server", mqttServer, 100);
WiFiManagerParameter custom_mqttPort("port", "mqtt port", mqttPort, 20);
WiFiManagerParameter custom_mqttUsername("user", "mqtt user", mqttUsername, 100);
WiFiManagerParameter custom_mqttPassword("pass", "mqtt pass", mqttPassword, 100);
WiFiManagerParameter custom_mqttDeviceID("deviceID", "mqtt deviceid", mqttDeviceID, 100);
WiFiManagerParameter custom_openWeatherAPI("API", "openWeather API", openWeatherAPI, 160);
WiFiManagerParameter custom_subTopic("Sub", "Sub Topic", subTopic, 100);
WiFiManagerParameter custom_subTopic1("Sub1", "Sub Topic1", subTopic1, 100);
WiFiManagerParameter custom_resTopic("res", "Res Topic", resTopic, 100);
WiFiManagerParameter custom_resTopic1("res1", "Res Topic1", resTopic1, 100);
WiFiManagerParameter custom_temperatureTopic("temp", "Temperature Topic", temperatureTopic, 100);
WiFiManagerParameter custom_humidityTopic("humid", "Humidity Topic", humidityTopic, 100);
WiFiManagerParameter custom_heatIndexTopic("HI", "Heat Index Topic", heatIndexTopic, 100);
//Wifi-Manager
WiFiManager wifiManager;
//wifiManager.autoConnect("openWeather-AP");
//Reset Wifi settings for testing
// wifiManager.resetSettings();
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
//add all your parameters here
wifiManager.addParameter(&custom_mqttServer);
wifiManager.addParameter(&custom_mqttPort);
wifiManager.addParameter(&custom_mqttUsername);
wifiManager.addParameter(&custom_mqttPassword);
wifiManager.addParameter(&custom_mqttDeviceID);
wifiManager.addParameter(&custom_openWeatherAPI);
wifiManager.addParameter(&custom_subTopic);
wifiManager.addParameter(&custom_subTopic1);
wifiManager.addParameter(&custom_resTopic);
wifiManager.addParameter(&custom_resTopic1);
wifiManager.addParameter(&custom_temperatureTopic);
wifiManager.addParameter(&custom_humidityTopic);
wifiManager.addParameter(&custom_heatIndexTopic);
//reset settings - for testing
// wifiManager.resetSettings();
//set minimum quality of signal so it ignores AP's under that quality
//defaults to 8%
//wifiManager.setMinimumSignalQuality();
//sets timeout until configuration portal gets turned off
//useful to make it all retry or go to sleep
//in seconds
//wifiManager.setTimeout(120);
//little animation to signal whats going on
//Signal wifi connecting with green animation
for (int i = 0; i < NUMPIXELS; i++) { // For each pixel...
// pixels.Color() takes RGB values, from 0,0,0 up to 255,255,255
// Here we're using a moderately bright green color:
pixels.setPixelColor(i, pixels.Color(0, 255, 0));
pixels.show(); // Send the updated pixel colors to the hardware.
delay(500); // Pause before next pass through loop
}
//fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect("openWeather-Accesspoint")) {
#ifdef DEBUGING
Serial.println("failed to connect and hit timeout");
#endif
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(5000);
}
//if you get here you have connected to the WiFi
#ifdef DEBUGING
Serial.println("connected to wifi: ");
#endif
//read updated parameters
strcpy(mqttServer, custom_mqttServer.getValue());
strcpy(mqttPort, custom_mqttPort.getValue());
strcpy(mqttUsername, custom_mqttUsername.getValue());
strcpy(mqttPassword, custom_mqttPassword.getValue());
strcpy(mqttDeviceID, custom_mqttDeviceID.getValue());
strcpy(openWeatherAPI, custom_openWeatherAPI.getValue());
strcpy(subTopic, custom_subTopic.getValue());
strcpy(subTopic1, custom_subTopic1.getValue());
strcpy(resTopic, custom_resTopic.getValue());
strcpy(resTopic1, custom_resTopic1.getValue());
strcpy(temperatureTopic, custom_temperatureTopic.getValue());
strcpy(humidityTopic, custom_humidityTopic.getValue());
strcpy(heatIndexTopic, custom_heatIndexTopic.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
#ifdef DEBUGING
Serial.println("saving config: ");
#endif
DynamicJsonDocument json(2048);
json["mqttServer"] = mqttServer;
json["mqttPort"] = mqttPort;
json["mqttUsername"] = mqttUsername;
json["mqttPassword"] = mqttPassword;
json["mqttDeviceID"] = mqttDeviceID;
json["openWeatherAPI"] = openWeatherAPI;
json["subTopic"] = subTopic;
json["subTopic1"] = subTopic1;
json["resTopic"] = resTopic;
json["resTopic1"] = resTopic1;
json["temperatureTopic"] = temperatureTopic;
json["humidityTopic"] = humidityTopic;
json["heatIndexTopic"] = heatIndexTopic;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
#ifdef DEBUGING
Serial.println("failed to open config file for writing");
#endif
}
serializeJson(json, Serial);
serializeJson(json, configFile);
configFile.close();
//end save
}
#ifdef DEBUGING
Serial.print("local ip: ");
Serial.println(WiFi.localIP());
#endif
}
#endif
//--------------------------------------------Wifi------------------------------------
#ifdef USEWIFI
void setup_wifi() {
#ifdef DEBUGING
Serial.println("setup_wifi: Started... ");
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to: ");
Serial.println(ssid);
#endif
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
//Signal wifi connecting with green animation
for (int i = 0; i < NUMPIXELS; i++) { // For each pixel...
// pixels.Color() takes RGB values, from 0,0,0 up to 255,255,255
// Here we're using a moderately bright green color:
pixels.setPixelColor(i, pixels.Color(0, 255, 0));
pixels.show(); // Send the updated pixel colors to the hardware.
delay(500); // Pause before next pass through loop
}
#ifdef DEBUGING
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
#endif
}
#endif
//----------------------------------- RECONNECT MQTT ---------------------
#ifdef USEMQTT
void reconnect() {
// Loop until we're reconnected
#ifdef DEBUGING
Serial.println("MQTT reconnect: ");
#endif
int errorcounter = 0;
while (!MQTTclient.connected()) {
#ifdef DEBUGING
Serial.println("MQTT reconnect: Attempting MQTT connection...");
Serial.println("Credentials:");
Serial.print("MQTT Server: ");
Serial.println(mqttServer);
Serial.print("MQTT Port: ");
Serial.println(mqttPort);
Serial.print("MQTT Username: ");
Serial.println(mqttUsername);
Serial.print("MQTT Password: ");
Serial.println(mqttPassword);
Serial.print("MQTT DeviceID: ");
Serial.println(mqttDeviceID);
#endif
//connection animation - did cause some errors
// pixels.clear();
// for (int i = 0; i < NUMPIXELS; i++) { // For each pixel...
// // pixels.Color() takes RGB values, from 0,0,0 up to 255,255,255
// // Here we're using a moderately bright green color:
// pixels.setPixelColor(i, pixels.Color(0, 0, 255));
// pixels.show(); // Send the updated pixel colors to the hardware.
// delay(500); // Pause before next pass through loop
// }
// Attempt to connect
if (MQTTclient.connect(mqttDeviceID, mqttUsername, mqttPassword)) {
mqttConnected = true;
//keep alive
MQTTclient.loop();
//connect callback function
MQTTclient.setCallback(callback);
#ifdef DEBUGING
Serial.println("MQTT reconnect: callback function set");
#endif
//subscribe to command topics
MQTTclient.subscribe(subTopic);
MQTTclient.subscribe(subTopic1);
#ifdef DEBUGING
Serial.println("MQTT reconnect: subscribed to subTopic");
#endif
#ifdef DEBUGING
Serial.println("MQTT reconnect: connected");
#endif
} else {
mqttConnected = false;
#ifdef DEBUGING
Serial.print("MQTT reconnect: failed, rc=");
Serial.print(MQTTclient.state());
Serial.println(" MQTT reconnect: try again in 5 seconds");
#endif
// Wait 5 seconds before retrying
delay(5000);
if (MQTTclient.state() == 2 || MQTTclient.state() == 3 || MQTTclient.state() == 4 || MQTTclient.state() == 5) {
errorcounter++;
if (errorcounter = 5) {
errorcounter = 0;
#ifdef DEBUGING
Serial.println("5 Wrong tries, resetting to AP Mode...");
#endif
wifiManager.resetSettings();
ESP.reset();
}
}
}
}
}
#endif
//----------------------------------- CALLBACK MQTT ---------------------
// you can use this to send commands to the weather beacon.
#ifdef USEMQTT
void callback(char* topic, byte* message, unsigned int length) {
#ifdef DEBUGING
Serial.println("callback: ");
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
#endif
String messageTemp;
for (int i = 0; i < length; i++) {
#ifdef DEBUGING
Serial.print((char)message[i]);
#endif
messageTemp += (char)message[i];
}
#ifdef DEBUGING
Serial.println();
#endif
// Feel free to add more if statements to control more GPIOs with MQTT
// If a message is received on the topic, you check if the message is either "on" or "off".
// Changes the output state according to the message
if (String(topic) == subTopic || String(topic) == subTopic1) {
#ifdef DEBUGING
Serial.print("Changing output to: ");
#endif
if (messageTemp == "PixelParty1") {
MQTTclient.publish("stat/openWeather/state", "PixelParty1");
#ifdef DEBUGING
Serial.println("PixelParty1");
#endif
modus = 1;
} else if (messageTemp == "PixelParty2") {
MQTTclient.publish("stat/openWeather/state", "PixelParty2");
#ifdef DEBUGING
Serial.println("PixelParty2");
#endif
modus = 2;
} else if (messageTemp == "off") {
MQTTclient.publish("stat/openWeather/power", "off");
#ifdef DEBUGING
Serial.println("Off");
#endif
modus = 3;
pixels.clear();
} else if (messageTemp == "endParty" || messageTemp == "on") {
MQTTclient.publish("stat/openWeather/power", "on");
#ifdef DEBUGING
Serial.println("The Party is over");
#endif
modus = 0;
pixels.clear();
//firstloop = true;
} else {
#ifdef DEBUGING
Serial.println("not set anything different.");
#endif
}
}
}
#endif
//----------------------------------- Publish MQTT ---------------------
#ifdef USEMQTT
void publishMQTT() {
#ifdef DEBUGING
Serial.println("publishMQTT: Sende Nachrichten...");
#endif
unsigned long now = millis();
if (now - lastMsg > 5000) { //Sending every 5 seconds
lastMsg = now;
if (MQTTclient.state() == 0) {
if (MQTTclient.publish(temperatureTopic, String(temperature).c_str())) {
Serial.println("Send was Successfull");
}
#ifdef DEBUGING
Serial.print("Temperature: ");
Serial.println(String(temperature).c_str());
#endif
MQTTclient.publish(humidityTopic, String(humidity).c_str());
MQTTclient.publish(heatIndexTopic, String(heatIndex).c_str());
} else {
MQTTclient.connect(mqttDeviceID, mqttUsername, mqttPassword);
if (MQTTclient.publish(temperatureTopic, String(temperature).c_str())) {
Serial.println("Send was Successfull");
}
#ifdef DEBUGING
Serial.print("Temperature: ");
Serial.println(String(temperature).c_str());
#endif
}
}
}
#endif
//-- Get the Weather from Open Weather Map --
void getWeather() {
pixels.clear();
#ifdef DEBUGING
Serial.println("getWeather: Stelle OpenWeathermap HTTP Request...");
#endif
if ((WiFi.status() == WL_CONNECTED)) { //Checks if we are connected to a wifi
#ifdef DEBUGING
Serial.println("getWeather: Wifi stabil...");
#endif
HTTPClient http; //starting an instance of httpclient named http
#ifdef DEBUGING
Serial.println("getWeather: Starte HTTPClient...");
#endif
http.begin(openWeather, "http://api.openweathermap.org/data/2.5/weather?q=" + String(city) + "&units=" + String(unitSystem) + "&appid=" + String(openWeatherAPI)); //URL für die Abfrage
#ifdef DEBUGING
Serial.println("getWeather: Verbinde zu URL: ");
Serial.println("http://api.openweathermap.org/data/2.5/weather?q=" + String(city) + "&units=" + String(unitSystem) + "&appid=" + String(openWeatherAPI));
#endif
int httpCode = http.GET(); //get answer from server
#ifdef DEBUGING
Serial.print("getWeather: Antwort des Servers: ");
Serial.println(httpCode); //print the answer to serial monitor
#endif
if (httpCode == 200) { //if the answer is 200
String payload = http.getString(); //Store the string from server to string payload on esp
const size_t capacity = JSON_ARRAY_SIZE(1) + 2 * JSON_OBJECT_SIZE(1) + 2 * JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(6) + JSON_OBJECT_SIZE(14) + 290;
DynamicJsonDocument doc(capacity); //dynamic switch size for json string buffer
DeserializationError error = deserializeJson(doc, payload); //JSON parsing
http.end(); //End Serverconnection.
if (error) { //Fehlermeldung bei fehlerhafter Verarbeitung
#ifdef DEBUGING
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
#endif
return;
}
//---Temperature LOGIC ---
JsonObject main = doc["main"];
int outdoor_temp = (int)main["temp"]; // Convert data to type INT and store to outdoor_temp
#ifdef DEBUGING
Serial.print("Received Outdoor Temperature: ");
if (unitSystem == "metric") {
Serial.println(String(outdoor_temp) + " °C"); //add a nice little c for celsius
} else if (unitSystem == "imperial") {
Serial.println(String(outdoor_temp) + " °F"); //or F for Fahrenheit
}
#endif
int colourR, colourG, colourB;
//if temperature is below zero °C
if (outdoor_temp < 0) {
colourR = 30;
colourG = 50;
colourB = 255;
}
//if it is below 10 °C
else if (outdoor_temp < 10) {
colourR = 50;
colourG = 150;
colourB = 220;
}
//if it is below 20 °C
else if (outdoor_temp < 20) {
colourR = 100;
colourG = 150;
colourB = 150;
}
//if it is above 25 °C
else if (outdoor_temp > 25) {
colourR = 240;
colourG = 150;
colourB = 20;
}
//if it is above 30 °C
else if (outdoor_temp > 30) {
colourR = 230;
colourG = 130;
colourB = 35;
}
//if it is above 40 °C