-
Notifications
You must be signed in to change notification settings - Fork 0
/
esp8266-weather-station-bme680_v1.ino
1735 lines (1525 loc) · 61.8 KB
/
esp8266-weather-station-bme680_v1.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
/**The MIT License (MIT) ********************************************************
Copyright (c) 2018 by Daniel Eichhorn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
See more at https://blog.squix.org
https://github.com/ThingPulse/minigrafx/blob/master/src/MiniGrafx.h
https://arduinojson.org/v6/api/jsondocument/
https://www.arduinoslovakia.eu/blog/2019/2/esp8266---suborovy-system-spiffs?lang=en
Colors: https://github.com/ThingPulse/minigrafx/blob/master/src/ILI9341_SPI.h
https://www.arduino.cc/en/Tutorial/StringToInt
Aenderungen: 31.3.2019_js: Anpassungen an BME680 begonnen.
Workaround: TouchControllerWS::getPoint() invert Xpos for touch.
See settings.h for hardware configuration!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Install the following libraries through Arduino Library Manager
* - Mini Grafx by Daniel Eichhorn
* - ESP8266 WeatherStation by Daniel Eichhorn
* - Json Streaming Parser by Daniel Eichhorn
* - simpleDSTadjust by neptune2
* //https://github.com/tzapu/WiFiManager WiFi Configuration Magic
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Thanks to Joerg Herrmann: using herrmannj's IAQ/VOC calculation
********************************************************************************/
#include <FS.h> //--- must be first
//--- configure your settings in settings.h !
#include "settings.h"
#include "config_website.h"
#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#if defined(ESP8266)
#include <ESP8266WiFi.h> //--- ESP8266 Core WiFi Library
#else
#include <WiFi.h> //--- ESP32 Core WiFi Library
#endif
#include <ArduinoJson.h>
#include <DNSServer.h>
#include <XPT2046_Touchscreen.h>
#include "TouchControllerWS.h"
#include <JsonListener.h>
#include <OpenWeatherMapCurrent.h>
#include <OpenWeatherMapForecast.h>
#include <Astronomy.h>
#include <MiniGrafx.h>
#include <Carousel.h>
#include <ILI9341_SPI.h>
#include "ArialRounded.h"
#include "moonphases.h"
#include "weathericons.h"
#include <ESPAsyncWebServer.h> //Local WebServer used to serve the configuration portal
#include <ESPAsyncWiFiManager.h> //https://github.com/tzapu/WiFiManager WiFi Configuration Magic
//--- include Adafruit lib, which could be found at Github
#include <Adafruit_BME680.h> //--- Adafruit BME680 library
//---------------------------------------------------------------------------------
//--- WEMOS D1 mini: Arduino Board Lolin/Wemos D1 R2 & mini
//--- uncomment for Serial debugging statements
#define DEBUG_SERIAL
#ifdef DEBUG_SERIAL
#define DEBUG_BEGIN Serial.begin(115200)
#define DEBUG_PRINT(x) Serial.println(x)
#define DEBUG_OUT(y) Serial.print(y)
#define DEBUG_OUT2(x,y) Serial.print(x,y)
#else
#define DEBUG_PRINT(x)
#define DEBUG_OUT(x)
#define DEBUG_OUT2(x,y)
#define DEBUG_BEGIN
#endif
#define MINI_BLACK 0
#define MINI_WHITE 1
#define MINI_YELLOW 2
#define MINI_BLUE 3
#define MAX_FORECASTS_DEF 12
#define HAS_BME680MCU false //--- serial interfacing
#define HAS_BME680I2C true //--- hard wired i2c interface, not spi
#if HAS_BME680MCU
//--- TODO
#endif
//---------------------------------------------------------------------------------
//--- defines the colors usable in the paletted 16 color frame buffer
uint16_t palette[] = {ILI9341_BLACK, // 0
ILI9341_WHITE, // 1
ILI9341_YELLOW, // 2
0x7E3C }; //3
int SCREEN_WIDTH = 240;
int SCREEN_HEIGHT = 320;
//--- limited to 4 colors, due to memory constraints
int BITS_PER_PIXEL = 2; // 2^2 = 4 colors
//--- object instances
AsyncWebServer server(80);
DNSServer dns;
ILI9341_SPI tft = ILI9341_SPI(TFT_CS, TFT_DC);
MiniGrafx gfx = MiniGrafx(&tft, BITS_PER_PIXEL, palette);
Carousel carousel(&gfx, 0, 0, 240, 100);
XPT2046_Touchscreen ts(TOUCH_CS, TOUCH_IRQ);
TouchControllerWS touchController(&ts);
OpenWeatherMapCurrentData currentWeather;
OpenWeatherMapForecastData forecasts[MAX_FORECASTS_DEF];
simpleDSTadjust dstAdjusted(StartRule, EndRule);
Astronomy::MoonData moonData;
//--- I2C Pin D1= SCL D2=SDA
#define BME680_DEBUG 1
Adafruit_BME680 bme680; //--- BME680 sensor object
//Adafruit_BME680 bme680(BME_CS); // hardware SPI
//Adafruit_BME680 bme680(BME_CS, BME_MOSI, BME_MISO, BME_SCK);
//ADC_MODE(ADC_VCC); //--- comment this line as ADC pin will be externally connected
int LDRReading; //--- ldr data
void calibrationCallback(int16_t x, int16_t y);
CalibrationCallback calibration = &calibrationCallback;
unsigned long prevBme680Millis = millis(); // counter main loop for BME 680
unsigned long intervalBme680 = 10000; // 10 sec update interval default
float resFiltered; // low pass
float aF = 0;
float tVoc = 0;
bool bme680VocValid = false; // true if filter is initialized, ramp-up after start
char bme680Msg[128]; // payload
//--- automatic baseline correction
uint32_t bme680_baseC = 0; // highest adjusted r (lowest voc) in current time period
float bme680_baseH = 0; // abs hum (g/m3)
unsigned long prevBme680AbcMillis = 0; // ts of last save to nv
unsigned long intervalBme680NV = 604800000; // 7 days of ms
uint8_t bDelay = 0;
//--- TODO: clear defaults
struct
{
float t_offset = -.5; // offset temperature sensor
float h_offset = 1.5; // offset humitidy sensor
uint32_t vocBaseR = 0; // base value for VOC resistance clean air, abc
uint32_t vocBaseC = 0; // base value for VOC resistance clean air, abc
float vocHum = 0; // reserved, abc
uint32_t signature = 0x49415143; // 'IAQC'
} preload, param; //--- stable new baseline counter (avoid short-term noise)
//--- global
float humidity = 0.0;
float temperature = 0.0;
typedef struct
{
String temperature = "";
String humidity = "";
String abshum = "";
String pressure = "";
String tvoc = "";
String dewpoint = "";
String gas = "";
String altitude = "";
} GDATA_TYP;
GDATA_TYP gdata;
//--- prototypes
void readConfig();
void writeConfig();
String form_input(const String& name, const String& info, const String& value, const int length);
String form_checkbox(const String& name, const String& info, const bool checked);
String line_from_value(const String& name, const String& value);
String form_select_frame();
void notFound(AsyncWebServerRequest *request);
void configModeCallback (AsyncWiFiManager *myWiFiManager);
void drawIndoorData();
void ldr(); //--- get ambient illuminance
void updateData();
void drawProgress(uint8_t percentage, String text);
void drawTime();
void drawWifiQuality();
void drawCurrentWeather();
void drawForecast();
void drawForecastDetail(uint16_t x, uint16_t y, uint8_t dayIndex);
void drawAstronomy();
void drawCurrentWeatherDetail();
void drawLabelValue(uint8_t line, String label, String value);
void drawForecastTable(uint8_t start);
void drawAbout();
void drawSeparator(uint16_t y);
String getTime(time_t *timestamp);
const char* getMeteoconIconFromProgmem(String iconText);
const char* getMiniMeteoconIconFromProgmem(String iconText);
const char* PARAM_MESSAGE = "message";
void drawForecast1(MiniGrafx *display, CarouselState* state, int16_t x, int16_t y);
void drawForecast2(MiniGrafx *display, CarouselState* state, int16_t x, int16_t y);
void drawForecast3(MiniGrafx *display, CarouselState* state, int16_t x, int16_t y);
float absHum(float temp, float hum);
float dewPoint(float temp, float hum);
void getBme680Readings();
uint32_t bme680Abc(uint32_t r, float a);
FrameCallback frames_1[] = { drawForecast1 };
FrameCallback frames_2[] = { drawForecast1, drawForecast2 };
FrameCallback frames_3[] = { drawForecast1, drawForecast3, drawForecast2 };
//--- how many different screens do we have?
int screenCount = 6; //--- (0..5)
long lastDownloadUpdate = millis();
String moonAgeImage = "";
uint8_t moonAge = 0;
uint16_t screen = 0;
long timerPress;
bool canBtnPress;
time_t dstOffset = 0;
bool config_needs_write = false;
long lastDrew = 0;
bool btnClick;
uint8_t MAX_TOUCHPOINTS = 10;
TS_Point points[10];
uint8_t currentTouchPoint = 0;
//----------------------------------------------------------------------
//--- simple function to scan for I2C devices on the bus
void I2C_scan()
{
// scan for i2c devices
byte error, address;
int nDevices;
DEBUG_PRINT(F("Scanning I2C..."));
nDevices = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
DEBUG_OUT("I2C device found at address 0x");
if (address<16)
DEBUG_OUT("0");
DEBUG_OUT2(address,HEX);
DEBUG_PRINT(" !");
nDevices++;
}
else if (error==4)
{
DEBUG_OUT("Unknown error at address 0x");
if (address<16)
DEBUG_OUT("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0)
DEBUG_PRINT("No I2C devices found\n");
else
DEBUG_PRINT("done\n");
}
//----------------------------------------------------------------------
void spiff_info()
{
FSInfo fs_info;
SPIFFS.info(fs_info);
DEBUG_OUT("fs_info.totalBytes = ");
DEBUG_PRINT(fs_info.totalBytes);
DEBUG_OUT("fs_info.usedBytes = ");
DEBUG_PRINT(fs_info.usedBytes);
DEBUG_OUT("fs_info.blockSize = ");
DEBUG_PRINT(fs_info.blockSize);
DEBUG_OUT("fs_info.pageSize = ");
DEBUG_PRINT(fs_info.pageSize);
DEBUG_OUT("fs_info.maxOpenFiles = ");
DEBUG_PRINT(fs_info.maxOpenFiles);
DEBUG_OUT("fs_info.maxPathLength = ");
DEBUG_PRINT(fs_info.maxPathLength);
DEBUG_PRINT("");
}
//----------------------------------------------------------------------
void sleep(uint32_t t_ms)
{
delay(t_ms);
yield();
}
///////////////////////////////////////////////////////////////////////////
// BME 680
///////////////////////////////////////////////////////////////////////////
float absHum(float temp, float hum)
{
double sdd, dd;
sdd=6.1078 * pow(10,(7.5*temp)/(237.3+temp));
dd=hum/100.0*sdd;
return (float)216.687*dd/(273.15+temp);
};
//----------------------------------------------------------------------
float dewPoint(float temp, float hum)
{
double A = (hum/100) * pow(10, (7.5*temp / (237+temp)));
return (float) 237*log10(A)/(7.5-log10(A));
};
//----------------------------------------------------------------------
int64_t get_timestamp_us()
{
return (int64_t)millis() * 1000;
}
//----------------------------------------------------------------------
int64_t serial_timestamp()
{
//--- a jumper to GND on D10 does the job, when needed!
/* if (digitalRead(PIN_ENABLE_TIMESTAMP_IN_OUTPUT) == LOW){ */
DEBUG_OUT("["); DEBUG_OUT(get_timestamp_us() / 1e6); DEBUG_OUT("] ");
//}
}
//----------------------------------------------------------------------
void getBme680Readings()
{
prevBme680Millis = millis(); // counter main loop for BME 680
if (! bme680.performReading())
{
DEBUG_PRINT("BME680-I2C: Failed to perform reading :(");
return;
};
//DEBUG_OUT( get_timestamp_us() );
//DEBUG_OUT(" ");
serial_timestamp();
DEBUG_OUT(" ");
DEBUG_OUT("Temperature = ");
DEBUG_OUT(bme680.temperature);
DEBUG_OUT(" *C ");
DEBUG_OUT("Pressure = ");
DEBUG_OUT(bme680.pressure / 100.0);
DEBUG_OUT(" hPa ");
DEBUG_OUT("Humidity = ");
DEBUG_OUT(bme680.humidity);
DEBUG_OUT(" % ");
DEBUG_OUT("Gas = ");
DEBUG_OUT(bme680.gas_resistance / 1000.0);
DEBUG_OUT(" KOhms ");
#define SEALEVELPRESSURE_HPA (1013.25)
DEBUG_OUT("Approx. Altitude = ");
DEBUG_OUT(bme680.readAltitude(SEALEVELPRESSURE_HPA));
DEBUG_OUT(" m ");
//DEBUG_PRINT();
char str_temp[6];
char str_hum[6];
char str_absHum[6];
char str_dewPoint[6];
char str_pressure[16];
char str_altitude[8];
char str_tVoc[8];
char str_gas[8];
float t = bme680.temperature + param.t_offset;
float h = bme680.humidity + param.h_offset;
float a = absHum(t, h);
aF = (aF == 0 || a < aF)?a:aF + 0.2 * (a - aF);
float d = dewPoint(t, h);
float p = bme680.pressure /100.0F;
uint32_t r = bme680.gas_resistance; // raw R VOC
if (!bme680VocValid )
{
//--- get first readings without tvoc
dtostrf(t, 4, 2, str_temp);
dtostrf(h, 4, 2, str_hum);
dtostrf(a, 4, 2, str_absHum);
dtostrf(d, 4, 2, str_dewPoint);
dtostrf(p, 3, 1, str_pressure);
dtostrf(r, 3, 1, str_gas);
gdata.temperature = str_temp;
gdata.humidity = str_hum;
gdata.abshum = str_absHum;
gdata.dewpoint = str_dewPoint;
gdata.pressure = str_pressure;
gdata.gas = str_gas;
gdata.tvoc = "0"; //--- not enough data yet
gdata.altitude = "-.-";
}
if (r == 0) return; //--- first reading !=0 accepted, 0 is invalid
uint32_t base = bme680Abc(r, a); // update base resistance
if (!bme680VocValid && (millis() > 300000))
{
//--- allow 300 sec warm-up for stable voc resistance (300000ms)
resFiltered = r; // preload low pass filter
bme680VocValid = true;
};
DEBUG_PRINT("");
if (!bme680VocValid ) return;
resFiltered += 0.1 * (r - resFiltered);
//float ratio = (float)base / (resFiltered * a * 7.0F); // filter removed
float ratio = (float)base / (r * aF * 7.0F);
float tV = (1250 * log(ratio)) + 125; // approximation
tVoc = (tVoc == 0)?tV:tVoc + 0.1 * (tV - tVoc);
dtostrf(t, 4, 2, str_temp);
dtostrf(h, 4, 2, str_hum);
dtostrf(a, 4, 2, str_absHum);
dtostrf(d, 4, 2, str_dewPoint);
dtostrf(p, 3, 1, str_pressure);
dtostrf(r, 3, 1, str_gas);
dtostrf(tVoc, 1, 0, str_tVoc);
String str_press_val = String(p,2);
gdata.temperature = str_temp;
gdata.humidity = str_hum;
gdata.abshum = str_absHum;
gdata.dewpoint = str_dewPoint;
gdata.pressure = str_press_val;
gdata.gas = str_gas;
gdata.tvoc = String(tVoc, 0);
gdata.altitude = "0";
serial_timestamp();
DEBUG_OUT ("Taupunkt: "); DEBUG_OUT (str_dewPoint); DEBUG_OUT (" ");
DEBUG_OUT ("tVOC: "); DEBUG_PRINT (str_tVoc);
//--- DEBUG
char str_filtered[16];
dtostrf(resFiltered, 4, 3, str_filtered);
char str_ratio[16];
dtostrf(ratio, 4, 4, str_ratio);
/* prepare to send UDP-message to fhem
snprintf(bme680Msg
, sizeof(bme680Msg)
, "F:THPV;T:%s;H:%s;AH:%s;D:%s;P:%s;V:%s;R:%lu;DB:%lu;DF:%s;DR:%s;"
, str_temp
, str_hum
, str_absHum
, str_dewPoint
, str_pressure
, str_tVoc
, r
, base
, str_filtered
, str_ratio);
DEBUG_PRINT(bme680Msg);
*/
DEBUG_PRINT("BME680-Reading done.");
};
//----------------------------------------------------------------------
uint32_t bme680Abc(uint32_t r, float a)
{
//--- automatic baseline correction
uint32_t b = r * a * 7.0F;
if (b > bme680_baseC && bDelay > 5)
{
// ensure that new baseC is stable for at least >5*10sec (clean air)
bme680_baseC = b;
bme680_baseH = a;
} else if (b > bme680_baseC)
{
bDelay++;
//return b;
} else
{
bDelay = 0;
};
//--- store baseline to nv
unsigned long currentMillis = millis();
if (currentMillis - prevBme680AbcMillis > intervalBme680NV)
{
// prevBme680AbcMillis = currentMillis;
// //---store baseline
// param.vocBase = bme680CurrentHigh;
// bme680CurrentHigh = 0;
};
return (param.vocBaseC > bme680_baseC)?param.vocBaseC:bme680_baseC;
};
//----------------------------------------------------------------
void setup()
{
DEBUG_BEGIN; //Serial.begin(115200);
// wait debug console to settle
delay(3000);
DEBUG_PRINT("*** Started!");
/*
//--- enable I2C for ESP8266 NodeMCU boards [VDD to 3V3, GND to GND, SDA to D2, SCL to D1]
Wire.begin(SDA, SCL);
Wire.setClockStretchLimit(1000); // Default is 230us, see line78 of https://github.com/esp8266/Arduino/blob/master/cores/esp8266/core_esp8266_si2c.c
//--- nicht für STM32
#ifdef ESP8266
Wire.setClock(400000);
#endif
*/
//--- (SDA,SCL) D1, D2
// Enable I2C for Wemos D1 mini SDA:D2 / SCL:D1
Wire.begin(D2, D1);
I2C_scan();
if (!bme680.begin())
{
DEBUG_PRINT("I2C-Error: Could not find a valid BME680 sensor, check wiring!");
while (1);
} else
{
DEBUG_PRINT("I2C-: ok BME680 sensor found!");
}
// Set up oversampling and filter initialization
bme680.setTemperatureOversampling(BME680_OS_8X);
bme680.setHumidityOversampling(BME680_OS_2X);
bme680.setPressureOversampling(BME680_OS_4X);
bme680.setIIRFilterSize(BME680_FILTER_SIZE_3);
bme680.setGasHeater(320, 150); // 320*C for 150 ms
//--- LED pin needs to set HIGH
//--- use this pin to save energy
//--- turn on the background LED
//Serial.println(TFT_LED);
//pinMode(TFT_LED, OUTPUT);
//digitalWrite(TFT_LED, HIGH); // HIGH to Turn on;
gfx.init();
gfx.fillBuffer(MINI_BLACK);
gfx.commit();
DEBUG_PRINT("Initializing touch screen...");
ts.begin();
ldr();
drawProgress(70, "FileSystem: Mounting...");
delay(1000);
DEBUG_PRINT("Mounting file system...");
bool isFSMounted = SPIFFS.begin();
if (!isFSMounted)
{
DEBUG_PRINT("Not mounted, formatting file system ...");
drawProgress(90,"Formatting file system");
SPIFFS.format();
}
else
{
spiff_info();
}
drawProgress(100,"SPIFFS - Formatting done");
//--- get spiffs data
readConfig();
gfx.fillBuffer(MINI_BLACK);
gfx.setFont(ArialRoundedMTBold_14);
drawProgress(10, "WiFiManager: Initializing...");
DEBUG_PRINT("WiFiManager! Setup!");
delay(1000);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
AsyncWiFiManager wifiManager(&server,&dns);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
wifiManager.setAPCallback(configModeCallback);
drawProgress(10, "Touch, to reset WiFiManager ...");
sleep(3000);
if (touchController.isTouched(1000))
{
drawProgress(10, "WiFiManager: Resetting...");
delay(1000);
if (!touchController.isTouched(1000))
{
drawProgress(10, "WiFiManager: Resetting...");
delay(1000);
wifiManager.resetSettings();
}
else
{
drawProgress(10, "WiFiManager: Initializing...");
delay(1000);
}
}
drawProgress(30, "WiFiManager: Auto Connect...");
delay(1000);
if(!wifiManager.autoConnect(WM_SSID, WM_PASS))
{
DEBUG_PRINT("failed to connect and hit timeout");
drawProgress(80, "WiFiManager: Failed, will reset...");
delay(1000);
//--- reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(1000);
}
drawProgress(50, "WiFiManager: Connected...");
delay(1000);
//---if you get here you have connected to the WiFi
DEBUG_PRINT("wlan connected...yeey :)");
//SPIFFS.remove("/calibration.txt");
boolean isCalibrationAvailable = touchController.loadCalibration();
if (!isCalibrationAvailable)
{
DEBUG_PRINT("Calibration not available");
touchController.startCalibration(&calibration);
while (!touchController.isCalibrationFinished())
{
gfx.fillBuffer(0);
gfx.setColor(MINI_YELLOW);
gfx.setTextAlignment(TEXT_ALIGN_CENTER);
gfx.drawString(120, 160, "Please calibrate\ntouch screen by\ntouch point");
touchController.continueCalibration();
gfx.commit();
yield();
}
touchController.saveCalibration();
}
gfx.fillBuffer(MINI_BLACK);
gfx.setFont(ArialRoundedMTBold_14);
#if HAS_BME280
drawProgress(10, "Sensors: Scanning BME280...");
delay(1000);
if (!bme.begin())
{
DEBUG_PRINT("Could not find a valid BME280 sensor, check wiring!");
screenCount = 5;
drawProgress(50, "Sensors: BME280 not found...");
delay(1000);
}
else
{
drawProgress(50, "Sensors: BME280 found...");
delay(1000);
}
#elif HAS_BME680MCU
//**** TODO
drawProgress(10, "Sensors: Scanning BME680_MCU...");
delay(1000);
#else
//**** TODO
drawProgress(10, "Sensors: Scanning BME680_I2C...");
delay(1000);
#endif
//Set the direction if the automatic transitioning
carousel.setAutoTransitionBackwards(); //--- without transition goes wrong direction
//Set the approx. time a transition will take
carousel.setTimePerTransition(1000); //--- without transition are 2x faster
switch (FRAME_COUNT)
{
case (1):
carousel.disableAutoTransition();
carousel.setFrames(frames_1, FRAME_COUNT);
break;
case (2):
carousel.setFrames(frames_2, FRAME_COUNT);
break;
case (3):
carousel.setFrames(frames_3, FRAME_COUNT);
break;
otherwise:
carousel.setFrames(frames_3, FRAME_COUNT);
break;
}
carousel.disableAllIndicators();
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
String content = "";
content += FPSTR(WEB_PAGE_HEADER);
content += FPSTR(WEB_ROOT_PAGE_CONTENT);
content += FPSTR(WEB_PAGE_FOOTER_III);
content.replace("{h}", "Hauptmenü");
content.replace("{n}", "");
content.replace("{t}", "");
request->send(200, "text/html; charset=utf-8", content);
});
server.on("/config", HTTP_GET, [](AsyncWebServerRequest *request){
String content = "";
content += FPSTR(WEB_PAGE_HEADER);
content += "<hr/><b>Open Weather Map</b><br/><br/>";
content += "<form method='POST' action'/config'>";
content += F("<table>");
content += form_input(F("OPEN_WEATHER_MAP_APP_ID"), F("APP-ID: "), OPEN_WEATHER_MAP_APP_ID, 360);
content += form_input(F("OPEN_WEATHER_MAP_LOCATION_ID"), F("LOCATION-ID: "), OPEN_WEATHER_MAP_LOCATION_ID, 360);
content += form_input(F("DISPLAYED_CITY_NAME"), F("CITY-Name: "), DISPLAYED_CITY_NAME, 360);
content += form_input(F("OPEN_WEATHER_MAP_LANGUAGE"), F("Language: "), OPEN_WEATHER_MAP_LANGUAGE, 360);
content += F("</table><br/>");
content += "<hr/><b>Wetter Station</b><br/><br/>";
content += F("<table>");
content += form_checkbox(F("IS_METRIC"), F("Metrisches System"), IS_METRIC);
content += form_checkbox(F("IS_STYLE_12HR"), F("12h Zeitformat"), IS_STYLE_12HR);
content += F("</table><br/>");
content += F("<table>");
content += form_select_frame();
content += F("</table><br/>");
content += F("<table>");
content += form_input(F("NTP_SERVERS_1"), F("NTP Server 1: "), NTP_SERVERS_1, 80);
content += form_input(F("NTP_SERVERS_2"), F("NTP Server 2: "), NTP_SERVERS_2, 80);
content += form_input(F("NTP_SERVERS_3"), F("NTP Server 3: "), NTP_SERVERS_3, 80);
content += form_input(F("UPDATE_INTERVAL_SECS"), F("Update Intervall (sec): "), String(UPDATE_INTERVAL_SECS), 80);
content += F("</table><br/>");
content += "<tr><td> </td><td><input type='submit' name='submit' value='Speichern' /></form></td></tr><br/><br/>";
content += FPSTR(WEB_PAGE_FOOTER);
content.replace("{h}", "Konfiguration");
content.replace("{n}", "");
content.replace("{t}", "");
DEBUG_PRINT("SERVER: html generated");
request->send(200, "text/html; charset=utf-8", content);
});
server.on("/config", HTTP_POST, [](AsyncWebServerRequest * request){
int params = request->params();
String content = "";
content += FPSTR(WEB_PAGE_HEADER);
DEBUG_PRINT("SERVER: react on submit: " + String(params));
for(int i = 0; i < params; i++){
AsyncWebParameter* p = request->getParam(i);
if(p->isFile()){ //p->isPost() is also true
Serial.printf("FILE[%s]: %s, size: %u\n", p->name().c_str(), p->value().c_str(), p->size());
} else if(p->isPost()){
Serial.printf("POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
if (p->name() == "OPEN_WEATHER_MAP_APP_ID") {
OPEN_WEATHER_MAP_APP_ID = p->value();
DEBUG_PRINT("Updated: OPEN_WEATHER_MAP_APP_ID = " + OPEN_WEATHER_MAP_APP_ID);
content += line_from_value(F("APP-ID"), OPEN_WEATHER_MAP_APP_ID);
}
if (p->name() == "OPEN_WEATHER_MAP_LOCATION_ID") {
OPEN_WEATHER_MAP_LOCATION_ID = p->value();
DEBUG_PRINT("Updated: OPEN_WEATHER_MAP_LOCATION_ID = " + OPEN_WEATHER_MAP_LOCATION_ID);
content += line_from_value(F("LOCATION-ID"), OPEN_WEATHER_MAP_LOCATION_ID);
}
if (p->name() == "DISPLAYED_CITY_NAME") {
DISPLAYED_CITY_NAME = p->value();
DEBUG_PRINT("Updated: DISPLAYED_CITY_NAME = " + DISPLAYED_CITY_NAME);
content += line_from_value(F("CITY-Name"), DISPLAYED_CITY_NAME);
}
if (p->name() == "OPEN_WEATHER_MAP_LANGUAGE") {
OPEN_WEATHER_MAP_LANGUAGE = p->value();
DEBUG_PRINT("Updated: OPEN_WEATHER_MAP_LANGUAGE = " + OPEN_WEATHER_MAP_LANGUAGE);
content += line_from_value(F("Language"), OPEN_WEATHER_MAP_LANGUAGE);
}
if (p->name() == "IS_METRIC") {
IS_METRIC = p->value().toInt();
DEBUG_PRINT("Updated: IS_METRIC = " + String(IS_METRIC));
content += line_from_value(F("Metrisches System"), String(IS_METRIC));
}
if (p->name() == "IS_STYLE_12HR") {
IS_STYLE_12HR = p->value().toInt();
DEBUG_PRINT("Updated: IS_STYLE_12HR = " + String(IS_STYLE_12HR));
content += line_from_value(F("12h Zeitformat"), String(IS_STYLE_12HR));
}
if (p->name() == "FRAME_COUNT") {
FRAME_COUNT = p->value().toInt();
DEBUG_PRINT("Updated: FRAME_COUNT = " + String(FRAME_COUNT));
content += line_from_value(F("Number of Frames"), String(FRAME_COUNT));
}
if (p->name() == "NTP_SERVERS_1") {
NTP_SERVERS_1 = p->value();
DEBUG_PRINT("Updated: NTP_SERVERS_1 = " + NTP_SERVERS_1);
content += line_from_value(F("NTP Server 1"), NTP_SERVERS_1);
}
if (p->name() == "NTP_SERVERS_2") {
NTP_SERVERS_2 = p->value();
DEBUG_PRINT("Updated: NTP_SERVERS_2 = " + NTP_SERVERS_2);
content += line_from_value(F("NTP Server 2"), NTP_SERVERS_2);
}
if (p->name() == "NTP_SERVERS_3") {
NTP_SERVERS_3 = p->value();
DEBUG_PRINT("Updated: NTP_SERVERS_3 = " + NTP_SERVERS_3);
content += line_from_value(F("NTP Server 3"), NTP_SERVERS_3);
}
if (p->name() == "UPDATE_INTERVAL_SECS") {
UPDATE_INTERVAL_SECS = p->value().toInt();
DEBUG_PRINT("Updated: UPDATE_INTERVAL_SECS = " + String(UPDATE_INTERVAL_SECS));
content += line_from_value(F("Update Intervall (sec)"), String(UPDATE_INTERVAL_SECS));
}
} else {
Serial.printf("GET[%s]: %s\n", p->name().c_str(), p->value().c_str());
}
} // for(int i = 0; i < params; i++)
content += FPSTR(WEB_PAGE_FOOTER_II);
content.replace("{h}", "Konfiguration wurde gespeichert.");
content.replace("{n}", "");
content.replace("{t}", "");
writeConfig();
request->send(200, "text/html; charset=utf-8", content);
}); // server.on
/*
server.on("/removeConfig", HTTP_GET, [](AsyncWebServerRequest *request){
String content = "";
content += FPSTR(WEB_PAGE_HEADER);
content += "Konfiguration löschen";
content += FPSTR(WEB_PAGE_FOOTER);
content.replace("{h}", "Konfiguration löschen");
content.replace("{n}", "");
content.replace("{t}", "");
request->send(200, "text/html; charset=utf-8", content);
});
*/
server.on("/reset", HTTP_GET, [](AsyncWebServerRequest *request){
String content = "";
content += FPSTR(WEB_PAGE_HEADER);
content += FPSTR(WEB_RESET_CONTENT);
content.replace("{h}", "");
content.replace("{n}", "");
content.replace("{t}", "");
content.replace("{q}", "Wetterstation wirklich neu starten");
content.replace("{b}", "Neu starten");
content.replace("{c}", "Abbrechen");
request->send(200, "text/html; charset=utf-8", content);
});
server.on("/reset", HTTP_POST, [](AsyncWebServerRequest * request){
int params = request->params();
String content = "";
content += FPSTR(WEB_PAGE_HEADER);
DEBUG_PRINT("SERVER: react on submit: " + String(params));
for(int i = 0; i < params; i++){
AsyncWebParameter* p = request->getParam(i);
if(p->isFile()){ //p->isPost() is also true
Serial.printf("FILE[%s]: %s, size: %u\n", p->name().c_str(), p->value().c_str(), p->size());
} else if(p->isPost()){
Serial.printf("POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
delay(1500);
ESP.restart();
} else {
Serial.printf("GET[%s]: %s\n", p->name().c_str(), p->value().c_str());
}
} // for(int i = 0; i < params; i++)
request->send(200, "text/html; charset=utf-8", content);
}); //--- of server.on
server.onNotFound(notFound);
server.begin();
//--- update the weather information
updateData();
timerPress = millis();
canBtnPress = true;
}
//----------------------------------------------------------------
void loop()
{
ldr(); // LED display brightness adjustment routine depending on the ambient illuminance
//DEBUG_PRINT(LDRReading); // see the measurement result on monitor
gfx.fillBuffer(MINI_BLACK);
if (touchController.isTouched(0))
{
TS_Point p = touchController.getPoint();
if (p.y < 80)
{
IS_STYLE_12HR = IS_STYLE_12HR;
} else
{
screen = (screen + 1) % screenCount;
}
}
switch (screen)
{
case 0:
{
drawTime();
drawWifiQuality();
int remainingTimeBudget = carousel.update();
if (remainingTimeBudget > 0)
{
//--- You can do some work here
//--- Don't do stuff if you are below your time budget.
delay(remainingTimeBudget);
}
drawCurrentWeather();
drawAstronomy();
}
break;
case 1:
drawCurrentWeatherDetail();
break;
case 2:
drawForecastTable(0);
break;
case 3:
drawForecastTable(4);
break;
case 4:
drawAbout();
break;
case 5:
{
unsigned long currentMillis = millis();
gfx.setFont(ArialMT_Plain_10);
gfx.setColor(MINI_WHITE);
gfx.setTextAlignment(TEXT_ALIGN_RIGHT);
gfx.drawString(228, 9, String(5) );
//---bme680 data screen added
if (currentMillis - prevBme680Millis > intervalBme680)
{
getBme680Readings();
}
}
drawBME680Data(gdata.temperature, gdata.humidity,gdata.pressure, gdata.altitude,gdata.tvoc);
break;
} //--- of switch
gfx.commit();
// Check if we should update weather information
if (millis() - lastDownloadUpdate > 1000 * UPDATE_INTERVAL_SECS)
{
updateData();
lastDownloadUpdate = millis();
}