-
Notifications
You must be signed in to change notification settings - Fork 6
/
esp8266-WindStation.ino
1069 lines (941 loc) · 40.5 KB
/
esp8266-WindStation.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
#include <FS.h> //this needs to be first, or it all crashes and burns...
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Ticker.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecure.h>
#include <ESP8266httpUpdate.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <DNSServer.h>
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
#include "DHT.h" //https://github.com/adafruit/DHT-sensor-library
#include "TimeLib.h"
#define VERSION "\n\n----------------- Wind Station v1.8 OTA -----------------"
#define NameAP "WindStationAP"
#define PasswordAP "87654321"
#define FirmwareURL "http://yoursite.com/firmware.bin" //URL of firmware file for http OTA update by secret MQTT command "flash"
char mqtt_server[30];
char mqtt_port[6];
char mqtt_user[20];
char mqtt_pass[20];
char kc_wind[4] = "100";
char windguru_uid[30];
char windguru_pass[20];
char vaneMaxADC[5] = "1024"; // ADC range for input voltage 0..1V
char vaneOffset[4] = "0"; // define the offset for caclulating wind direction
char OWM_key[36] = ""; // OpenWeatherMap.org key
char OWM_lat[8] = "42.96";
char OWM_lon[8] = "27.90";
char WindyComApiKey[128] = "";
char WindyComName[16] = "";
char WindyAppSecret[16] = "";
char WindyAppID[16] = "";
WiFiManager wifiManager;
// 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_mqtt_server("server", "mqtt server", mqtt_server, 30);
WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
WiFiManagerParameter custom_mqtt_user("user", "mqtt user", mqtt_user, 20);
WiFiManagerParameter custom_mqtt_pass("pass", "mqtt password", mqtt_pass, 20);
WiFiManagerParameter custom_kc_wind("kc_wind", "wind correction 1-999%", kc_wind, 4);
WiFiManagerParameter custom_windguru_uid("windguru_uid", "windguru station UID", windguru_uid, 30);
WiFiManagerParameter custom_windguru_pass("windguru_pass", "windguru API pass", windguru_pass, 20);
WiFiManagerParameter custom_vaneMaxADC("vaneMaxADC", "Max ADC value 1-1024", vaneMaxADC, 5);
WiFiManagerParameter custom_vaneOffset("vaneOffset", "Wind vane offset 0-359", vaneOffset, 4);
WiFiManagerParameter custom_OWM_key("OWM_key", "OpenWeatherMap key", OWM_key, 36);
WiFiManagerParameter custom_OWM_lat("OWM_lat", "Lat **.**", OWM_lat, 8);
WiFiManagerParameter custom_OWM_lon("OWM_lon", "Lon **.**", OWM_lon, 8);
WiFiManagerParameter custom_WindyComApiKey("WindyComApiKey", "Windy.com ApiKey", WindyComApiKey, 128);
WiFiManagerParameter custom_WindyComName("WindyComName", "Windy.com Name", WindyComName, 16);
WiFiManagerParameter custom_WindyAppSecret("WindyAppSecret", "Windy.app Secret", WindyAppSecret, 16);
WiFiManagerParameter custom_WindyAppID("WindyAppID", "Windy.app ID", WindyAppID, 16);
String st;
String content;
int statusCode;
int debouncing_time = 10000; // time in microseconds!
unsigned long last_micros = 0;
volatile int windimpulse = 0;
//#define USE_Narodmon
#define USE_Windguru
#define USE_OpenWeatherMap //If you do not have a wind direction sensor, you can get an approximate value from the website OpenWeatherMap
#define USE_Windy_com
#define USE_Windy_app
//#define DeepSleepMODE // !!! To enable Deep-sleep, you need to connect GPIO16 (D0 for NodeMcu) to the EXT_RSTB/REST (RST for NodeMcu) pin
//#define NightSleepMODE // Enable deep-sleep only in night time
#if defined(DeepSleepMODE) || defined(NightSleepMODE) // Deep-sleep mode power consumption ~6mAh (3*5=15sec work/5 min sleep), instead ~80mAh in default "Always On" mode
#define SLEEPDAY 5 // deep sleep time in minutes, minimum 5min for use narodmon.com and reasonable power saving
#define SLEEPNIGHT 10
#define TIMEZONE 2 // UTC offset
#define TIMEMORNING 5 // night end at...
#define TIMEEVENING 20 // night start at...
#include "NtpClientLib.h" //https://github.com/gmag11/NtpClient
#endif
//#define MOSFETPIN 15 // Experemental!!! GPIO15 (D8 for NodeMcu). MosFET's gate pin for power supply sensors, off for current drain minimize. Not connect this GPIO directly to sensors you burning it! The maximum source current of GPIO is about 12mA
#define BUTTON 4 // optional, GPIO4 for Witty Cloud. GPIO0/D3 for NodeMcu (Flash) - not work with deepsleep, set 4!
#define LED 2 // GPIO2 for Witty Cloud. GPIO16/D0 for NodeMcu - not work with deepsleep, set 2!
//#define DHTPIN 14 // GPIO14 (D5 for NodeMcu)
#define WINDPIN 5 // GPIO5 (D1 for NodeMcu)
#define MQTT_TOPIC "windpoint" // mqtt topic (Must be unique for each device)
#define MQTT_TOPICm "windpoint/m"
#define MQTT_TOPICo "windpoint/o"
#ifdef DHTPIN
#define DHTTYPE DHT11 // DHT11, DHT22, DHT21, AM2301
DHT dht(DHTPIN, DHTTYPE); //
#endif
extern "C" {
#include "user_interface.h"
}
bool sendStatus = true;
bool sensorReport = false;
bool resetWind = true;
bool firstRun = true;
int errors_count = 0;
int kUpdFreq = 1; //minutes
int kRetries = 10;
int kNarodmon = 0;
int kOpenWeatherMap = 0;
int meterWind = 0;
int calDirection = 0; // calibrated direction of wind vane after offset applied
const float kKnots = 1.94; // m/s to knots conversion
const int windPeriodSec = 10; // wind measurement period in seconds 1-10sec
float dhtH, dhtT, windMS = 0;
float WindMax = 0, WindAvr = 0, WindMin = 0, WindNarodmon = 0;
String str;
unsigned long TTasks;
unsigned long secTTasks;
unsigned long count_btn = 0;
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
#define MSG_BUFFER_SIZE (50)
char msg_buff[MSG_BUFFER_SIZE];
Ticker btn_timer;
//------------------------------------------------------------------------------------------------------------------------------
void IRAM_ATTR windcount() {
//if((long)(micros() - last_micros) >= debouncing_time) {
windimpulse++;
//last_micros = micros();
//digitalWrite(LED, ((windimpulse % 2) == 0) );
switch (windimpulse % 4) {
case 1:
digitalWrite(LED, true);
break;
case 3:
digitalWrite(LED, false);
break;
}
//}
}
void callback(char* topic, byte* payload, unsigned int length) {
String payload_string = String((char*)payload);
payload_string = payload_string.substring(0, length);
Serial.println("MQTT Topic: " + String(topic) + " MQTT Payload: " + payload_string);
if (payload_string == "stat") {
}
else if (payload_string == "reset") {
errors_count = 100;
}
else if (payload_string == "sensor") {
if (minute()<10)
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug",String(hour()) + ":0" + String(minute())).set_retain().set_qos(1));
mqttClient.publish("debug", (String(hour()) + ":0" + String(minute())).c_str());
else
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug",String(hour()) + ":" + String(minute())).set_retain().set_qos(1));
mqttClient.publish("debug", (String(hour()) + ":" + String(minute())).c_str());
sensorReport = true;
}
else if (payload_string == "adc") {
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug","ADC:" + String(analogRead(A0)) + " error:" + String(errors_count)).set_retain().set_qos(1));
mqttClient.publish("debug",("ADC:" + String(analogRead(A0)) + " error:" + String(errors_count)).c_str());
}
else if (payload_string == "flash") {
Serial.println("HTTP_UPDATE FILE: " + String(FirmwareURL));
//noInterrupts();
detachInterrupt(digitalPinToInterrupt(WINDPIN));
WiFiClient client;
ESPhttpUpdate.setLedPin(LED, LOW);
t_httpUpdate_return ret = ESPhttpUpdate.update(client, FirmwareURL);
attachInterrupt(WINDPIN, windcount, FALLING);
switch (ret) {
case HTTP_UPDATE_FAILED:
Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug", ESPhttpUpdate.getLastErrorString().c_str()).set_retain().set_qos(1));
break;
case HTTP_UPDATE_NO_UPDATES:
Serial.println("HTTP_UPDATE_NO_UPDATES");
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug", "HTTP_UPDATE_NO_UPDATES").set_retain().set_qos(1));
break;
case HTTP_UPDATE_OK:
Serial.println("HTTP_UPDATE_OK");
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug", "HTTP_UPDATE_OK").set_retain().set_qos(1));
break;
}
}
else {
str = payload_string;
int i = atoi(str.c_str());
if ((i >= 0) && (i < 9999)) {
if (String(topic) == MQTT_TOPIC) //we got kc_wind?
strcpy(kc_wind, String(i).c_str());
else
if (String(topic) == MQTT_TOPICm) //we got vaneMaxADC?
strcpy(vaneMaxADC, String(i).c_str());
else
if (String(topic) == MQTT_TOPICo) //we got vaneOffset?
strcpy(vaneOffset, String(i).c_str());
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug","saving config").set_retain().set_qos(1));
mqttClient.publish("debug","saving config");
Serial.println("saving config");
SaveConfig(false);
sendStatus = true;
}
}
}
void SaveConfig(bool NeedReadParams) {
Serial.println("saving config");
//read updated parameters
if (NeedReadParams) {
strcpy(mqtt_server, custom_mqtt_server.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue());
strcpy(mqtt_user, custom_mqtt_user.getValue());
strcpy(mqtt_pass, custom_mqtt_pass.getValue());
strcpy(kc_wind, custom_kc_wind.getValue());
strcpy(windguru_uid, custom_windguru_uid.getValue());
strcpy(windguru_pass, custom_windguru_pass.getValue());
strcpy(vaneMaxADC, custom_vaneMaxADC.getValue());
strcpy(vaneOffset, custom_vaneOffset.getValue());
strcpy(OWM_key, custom_OWM_key.getValue());
strcpy(OWM_lat, custom_OWM_lat.getValue());
strcpy(OWM_lon, custom_OWM_lon.getValue());
strcpy(WindyComApiKey, custom_WindyComApiKey.getValue());
strcpy(WindyComName, custom_WindyComName.getValue());
strcpy(WindyAppSecret, custom_WindyAppSecret.getValue());
strcpy(WindyAppID, custom_WindyAppID.getValue());
}
//DynamicJsonDocument json(1024);
JsonDocument json;
json["mqtt_server"] = mqtt_server;
json["mqtt_port"] = mqtt_port;
json["mqtt_user"] = mqtt_user;
json["mqtt_pass"] = mqtt_pass;
json["kc_wind"] = kc_wind;
json["windguru_uid"] = windguru_uid;
json["windguru_pass"] = windguru_pass;
json["vaneMaxADC"] = vaneMaxADC;
json["vaneOffset"] = vaneOffset;
json["OWM_key"] = OWM_key;
json["OWM_lat"] = OWM_lat;
json["OWM_lon"] = OWM_lon;
json["WindyComApiKey"] = WindyComApiKey;
json["WindyComName"] = WindyComName;
json["WindyAppSecret"] = WindyAppSecret;
json["WindyAppID"] = WindyAppID;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
serializeJson(json, Serial);
serializeJson(json, configFile);
configFile.close();
//end save parameters
}
//callback notifying us of the need to save config
void saveConfigCallback () {
Serial.println("Should save config");
}
void saveParamsCallback () {
Serial.println("Should save params");
SaveConfig(true);
}
void setup() {
Serial.begin(115200);
Serial.println(VERSION);
Serial.print("\nESP ChipID: ");
Serial.println(ESP.getChipId(), HEX);
//clean FS, erase config.json in case of damaged file
//SPIFFS.format();
//read configuration from FS json
Serial.println("mounting FS...");
if (SPIFFS.begin()) {
Serial.println("mounted file system");
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
Serial.println("reading config file");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
Serial.println("opened config file");
//DynamicJsonDocument json(1024);
JsonDocument json;
DeserializationError error = deserializeJson(json, configFile);
if (error) {
Serial.print(F("deserializeJson() failed with code "));
Serial.println(error.c_str());
} else {
serializeJson(json, Serial);
Serial.println("\nparsed json, size:" + String(json.size()));
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
strcpy(mqtt_user, json["mqtt_user"]);
strcpy(mqtt_pass, json["mqtt_pass"]);
strcpy(kc_wind, json["kc_wind"]);
strcpy(windguru_uid, json["windguru_uid"]);
strcpy(windguru_pass, json["windguru_pass"]);
strcpy(vaneMaxADC, json["vaneMaxADC"]);
strcpy(vaneOffset, json["vaneOffset"]);
if (json.size() > 9) { //compability with old config file
strcpy(OWM_key, json["OWM_key"]);
strcpy(OWM_lat, json["OWM_lat"]);
strcpy(OWM_lon, json["OWM_lon"]);
strcpy(WindyComApiKey, json["WindyComApiKey"]);
strcpy(WindyComName, json["WindyComName"]);
strcpy(WindyAppSecret, json["WindyAppSecret"]);
strcpy(WindyAppID, json["WindyAppID"]);
}
}
}
}
} else {
Serial.println("failed to mount FS");
}
//end read configuration
#ifdef MOSFETPIN
pinMode(MOSFETPIN, OUTPUT);
digitalWrite(MOSFETPIN, HIGH);
#endif
pinMode(LED, OUTPUT);
pinMode(BUTTON, INPUT);
pinMode(WINDPIN, INPUT_PULLUP);
digitalWrite(LED, HIGH);
firstRun = true;
btn_timer.attach(0.05, button);
mqttClient.setCallback(callback);
wifiManager.setBreakAfterConfig(true); //if this is set, it will exit after config, even if connection is unsuccessful.
wifiManager.setSaveConfigCallback(saveConfigCallback); //set config save notify callback
wifiManager.setSaveParamsCallback(saveParamsCallback); //set params save notify callback
std::vector<const char *> menu = {"wifi","info","param","update","close","sep","erase","restart","exit"};
wifiManager.setMenu(menu); // custom menu, pass vector
custom_mqtt_server.setValue(mqtt_server, 30);
custom_mqtt_port.setValue(mqtt_port, 6);
custom_mqtt_user.setValue(mqtt_user, 20);
custom_mqtt_pass.setValue(mqtt_pass, 20);
custom_kc_wind.setValue(kc_wind, 4);
custom_windguru_uid.setValue(windguru_uid, 30);
custom_windguru_pass.setValue(windguru_pass, 20);
custom_vaneMaxADC.setValue(vaneMaxADC, 5);
custom_vaneOffset.setValue(vaneOffset, 4);
custom_OWM_key.setValue(OWM_key, 36);
custom_OWM_lat.setValue(OWM_lat, 8);
custom_OWM_lon.setValue(OWM_lon, 8);
custom_WindyComApiKey.setValue(WindyComApiKey, 128);
custom_WindyComName.setValue(WindyComName, 16);
custom_WindyAppSecret.setValue(WindyAppSecret, 16);
custom_WindyAppID.setValue(WindyAppID,16);
#ifdef DeepSleepMODE
wifiManager.setTimeout(60); //sets timeout until configuration portal gets turned off
#else
wifiManager.setTimeout(180); //sets timeout until configuration portal gets turned off
#endif
//add all your parameters here
wifiManager.addParameter(&custom_mqtt_server);
wifiManager.addParameter(&custom_mqtt_port);
wifiManager.addParameter(&custom_mqtt_user);
wifiManager.addParameter(&custom_mqtt_pass);
wifiManager.addParameter(&custom_kc_wind);
#ifdef USE_Windguru
wifiManager.addParameter(&custom_windguru_uid);
wifiManager.addParameter(&custom_windguru_pass);
#endif
#ifdef USE_OpenWeatherMap
wifiManager.addParameter(&custom_OWM_key);
wifiManager.addParameter(&custom_OWM_lat);
wifiManager.addParameter(&custom_OWM_lon);
#else
wifiManager.addParameter(&custom_vaneMaxADC);
wifiManager.addParameter(&custom_vaneOffset);
#endif
#ifdef USE_Windy_com
wifiManager.addParameter(&custom_WindyComApiKey);
wifiManager.addParameter(&custom_WindyComName);
#endif
#ifdef USE_Windy_app
wifiManager.addParameter(&custom_WindyAppSecret);
wifiManager.addParameter(&custom_WindyAppID);
#endif
if(!wifiManager.autoConnect(NameAP, PasswordAP)) {
Serial.println("failed to connect and hit timeout");
delay(1000);
//reset and try again, or maybe put it to deep sleep
#if defined(DeepSleepMODE) || defined(NightSleepMODE)
ESP.deepSleep(SLEEPNIGHT*60000000); // Sleep for x* minute(s)
#else
ESP.reset();
#endif
delay(5000);
}
Serial.print("\nConnecting to WiFi");
while ((WiFi.status() != WL_CONNECTED) && kRetries --) {
delay(500);
Serial.print(" .");
}
if (WiFi.status() == WL_CONNECTED) {
#if defined(DeepSleepMODE) || defined(NightSleepMODE)
NTP.begin ("pool.ntp.org", TIMEZONE, true); // ntpServerName, NTP_TIMEZONE, daylight = false
NTP.setInterval(10, 600); // ShortInterval, LongInterval
#endif
Serial.println(" DONE");
Serial.print("IP Address is: "); Serial.println(WiFi.localIP());
Serial.print("macAddress is: "); Serial.println(WiFi.macAddress());
Serial.print("Connecting to ");Serial.print(mqtt_server);Serial.print(" Broker . .");
delay(500);
mqttClient.setServer(mqtt_server, atoi(mqtt_port));
mqttClient.setSocketTimeout(70);
mqttClient.setKeepAlive(70);
while (!mqttClient.connected()&& kRetries --) {
//while (!mqttClient.connect(MQTT::Connect(String(ESP.getChipId(), HEX)).set_keepalive(90).set_auth(mqtt_user, mqtt_pass)) && kRetries --) {
String str = String(ESP.getChipId(), HEX);
mqttClient.connect(str.c_str(), mqtt_user, mqtt_pass);
Serial.print(" .");
delay(1000);
}
if(mqttClient.connected()) {
Serial.println(" DONE");
Serial.println("\n---------------------------- Logs ----------------------------");
Serial.println();
mqttClient.subscribe(MQTT_TOPIC);
mqttClient.subscribe(MQTT_TOPICm);
mqttClient.subscribe(MQTT_TOPICo);
blinkLED(LED, 40, 8);
digitalWrite(LED, LOW);
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug", "Compiled: " __DATE__ " / " __TIME__).set_retain().set_qos(1));
mqttClient.publish("debug", "Compiled: " __DATE__ " / " __TIME__);
}
else {
Serial.println(" FAILED!");
Serial.println("\n----------------------------------------------------------------");
Serial.println();
digitalWrite(LED, HIGH);
}
}
else {
Serial.println(" WiFi FAILED!");
Serial.println("\n----------------------------------------------------------------");
Serial.println();
}
attachInterrupt(WINDPIN, windcount, FALLING);
}
void loop() {
mqttClient.loop();
timedTasks();
checkStatus();
if (sensorReport) {
getSensors();
}
}
void blinkLED(int pin, int duration, int n) {
for(int i=0; i<n; i++) {
digitalWrite(pin, HIGH);
delay(duration);
digitalWrite(pin, LOW);
delay(duration);
}
}
void button() {
if (!digitalRead(BUTTON)) {
count_btn++;
}
else {
if (count_btn > 1 && count_btn <= 40) {
digitalWrite(LED, !digitalRead(LED));
sendStatus = true;
}
else if (count_btn > 40){
Serial.println("\n\nESP8266 Rebooting . . . . . . . . Please Wait");
errors_count = 100;
}
count_btn=0;
}
}
void checkConnection() {
if (WiFi.status() == WL_CONNECTED) {
if (mqttClient.connected()) {
Serial.println("mqtt broker connection . . . . . . . . . . OK");
}
else {
errors_count = errors_count + 5;
Serial.println("mqtt broker connection . . . . . . . . . . LOST errors_count = " + String(errors_count));
}
}
else {
errors_count = errors_count + 10;
Serial.println("WiFi connection . . . . . . . . . . LOST errors_count = " + String(errors_count));
}
}
void checkStatus() {
if (sendStatus) {
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/kc_wind", String(kc_wind)).set_retain().set_qos(1));
mqttClient.publish("kc_wind", String(kc_wind).c_str());
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/adc", "{\"ADC\":" + String(analogRead(A0)) +", "+"\"MaxADC\":" + String(vaneMaxADC) + ", " + "\"Offset\":"+String(vaneOffset)+ "}").set_retain().set_qos(1));
mqttClient.publish("adc", ("{\"ADC\":" + String(analogRead(A0)) +", "+"\"MaxADC\":" + String(vaneMaxADC) + ", " + "\"Offset\":"+String(vaneOffset)+ "}").c_str());
sendStatus = false;
}
if (errors_count >= 100) {
blinkLED(LED, 400, 4);
ESP.restart();
delay(500);
}
}
void getSensors() {
String pubString;
#ifdef DHTPIN
Serial.print("DHT read . . . . . . . . . . . . . . . . . ");
dhtH = dht.readHumidity();
dhtT = dht.readTemperature();
if(digitalRead(LED) == LOW) {
blinkLED(LED, 100, 1);
} else {
blinkLED(LED, 100, 1);
digitalWrite(LED, HIGH);
}
if (isnan(dhtH) || isnan(dhtT)) {
if (mqttClient.connected())
mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug","DHT Read Error").set_retain().set_qos(1));
Serial.println("ERROR");
} else {
pubString = "{\"Temp\": "+String(dhtT)+", "+"\"Humidity\": "+String(dhtH) + "}";
pubString.toCharArray(message_buff, pubString.length()+1);
if (mqttClient.connected())
mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/temp", message_buff).set_retain().set_qos(1));
Serial.println("OK");
}
#endif
// Get Wind Direction
int a0 = analogRead(A0);
#ifdef DeepSleepMODE
if (mqttClient.connected())
mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug","ADC:" + String(a0) + " " + NTP.getTimeDateString ()).set_retain().set_qos(1));
#endif
#ifndef USE_OpenWeatherMap
//calDirection = map(a0, 0, atoi(vaneMaxADC), 0, 359) + atoi(vaneOffset);
// --------------- Wind Direction only for Ambient Weather WS-1080/WS-1090 !!!!!!!!!!!!-------------------
/*
calDirection = 0;
if (a0 >= atoi(vaneMaxADC)) calDirection = 90; //East wind direction is the vaneMaxADC
else
if (a0 < 0.796*atoi(vaneMaxADC)) calDirection = 270;
else
if (a0 < 0.881*atoi(vaneMaxADC)) calDirection = 315;
else
if (a0 < 0.945*atoi(vaneMaxADC)) calDirection = 0;
else
if (a0 < 0.977*atoi(vaneMaxADC)) calDirection = 225;
else
if (a0 < 0.989*atoi(vaneMaxADC)) calDirection = 45;
else
if (a0 < 0.997*atoi(vaneMaxADC)) calDirection = 180;
else
if (a0 < atoi(vaneMaxADC)) calDirection = 135;
*/
if (a0 < 5) calDirection = calDirection;
// skip calculation of direction if value a0 less than 50, use previous calDirection
else
{
/*if (a0 < 207) calDirection = 270;
else
if (a0 < 335) calDirection = 315;
else
if (a0 < 510) calDirection = 0;
else
if (a0 < 691) calDirection = 225;
else
if (a0 < 842) calDirection = 45;
else
if (a0 < 944) calDirection = 180;
else
if (a0 < 1002) calDirection = 135;
else*/
if (a0 < 15) calDirection = 270;
else
if (a0 < 31) calDirection = 315;
else
if (a0 < 63) calDirection = 0;
else
if (a0 < 123) calDirection = 225;
else
if (a0 < 237) calDirection = 45;
else
if (a0 < 390) calDirection = 180;
else
if (a0 < 623) calDirection = 135;
else
calDirection = 90; //East wind direction is the vaneMaxADC
calDirection = calDirection + atoi(vaneOffset);
}
// --------------- Wind Direction only for Ambient Weather WS-1080/WS-1090 !!!!!!!!!!!!-------------------
if(calDirection > 360)
calDirection = calDirection - 360;
#endif
if (meterWind > 0) { //already made measurement wind power
pubString = "{\"Min\": "+String(WindMin, 2)+", "+"\"Avr\": "+String(WindAvr/meterWind, 2)+", "+"\"Max\": "+String(WindMax, 2)+", "+"\"Dir\": "+String(calDirection) + "}";
pubString.toCharArray(msg_buff, pubString.length()+1);
if (mqttClient.connected())
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/wind", message_buff).set_retain().set_qos(1));
mqttClient.publish("wind", msg_buff);
Serial.println(" Wind Min: " + String(WindMin, 2) + " Avr: " + String(WindAvr/meterWind, 2) + " Max: " + String(WindMax, 2) + " Dir: " + String(calDirection)+ " ");
WindNarodmon = WindAvr/meterWind;
}
resetWind = true;
sensorReport = false;
}
void timedTasks() {
//windPeriodSec*1sec timer
if ((millis() > secTTasks + (windPeriodSec*1000)) || (millis() < secTTasks)) {
windMS = (float) windimpulse * atoi(kc_wind) /(millis() - secTTasks);
//Serial.println("windimpulse: " + String(windimpulse) + " milis: " + String(millis() - secTTasks));
windimpulse = 0;
secTTasks = millis();
if (firstRun) {
firstRun = false;
} else {
if (resetWind) {
WindMin = windMS;
WindAvr = windMS;
WindMax = windMS;
meterWind = 1;
resetWind = false;
} else {
if (((windMS > 10) && (WindMin < 1 )) || ((windMS > 15) && (WindMin < 2 )) || ((windMS > 20) && (WindMin < 3 ))) { //try to filter errors of measurement as result of contact bounce (chatter)
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug","cur:"+String(windMS,2) + " min:"+String(WindMin,2) + " avr:"+String(WindAvr/meterWind,2) +" max:"+String(WindMax,2)).set_retain().set_qos(1));
mqttClient.publish("debug", ("cur:" + String(windMS,2) + " min:"+String(WindMin,2) + " avr:" + String(WindAvr/meterWind,2) +" max:" + String(WindMax,2)).c_str());
} else {
if (WindMax < windMS) WindMax = windMS;
if (WindMin > windMS) WindMin = windMS;
WindAvr = WindAvr + windMS;
meterWind++;
}
}
}
}
//Serial.println(" meterWind: " + String(meterWind) + " windMS: " + String(windMS, 2));
#ifdef DeepSleepMODE
if (meterWind == 3) { //after 3 measurements send data and go to sleep
getSensors();
#ifdef USE_Narodmon
SendToNarodmon();
//SendToNarodmonGet();
#endif
#ifdef USE_Windguru
SendToWindguru();
#endif
#ifdef USE_Windy_com
SendToWindy();
#endif
//digitalWrite(MOSFETPIN, LOW);
//-------------------------------------------
time_t time_sync = NTP.getLastNTPSync ();
//int hours = (time_sync / 3600) % 24;
int hours = hour();
Serial.print (NTP.getTimeDateString ()); Serial.print (". ");
Serial.print (NTP.isSummerTime () ? "Summer Time. " : "Winter Time. ");
//-------------------------------------------
if ((time_sync!=0) && ((hours < TIMEMORNING) || (hours >= TIMEEVENING)) ){
Serial.println("Good night sleep");
ESP.deepSleep(SLEEPNIGHT*60000000); // Sleep for night SLEEPTIME*1 minute(s)
} else {
Serial.println("Good day sleep");
ESP.deepSleep(SLEEPDAY*60000000); // Sleep for day SLEEPTIME*1 minute(s)
}
delay(500);
}
#endif
#ifdef NightSleepMODE
if (meterWind == 3) { //after 3 measurements send data and go to sleep, but only in night time!
time_t time_sync = NTP.getLastNTPSync ();
if (time_sync!=0) {
//int hours = (time_sync / 3600) % 24;
int hours = hour();
Serial.print ("Hours: " + String(hours));
if ((hours < TIMEMORNING) || (hours >= TIMEEVENING)){
getSensors();
#ifdef USE_Narodmon
SendToNarodmon();
//SendToNarodmonGet();
#endif
#ifdef USE_Windguru
SendToWindguru();
#endif
#ifdef USE_Windy_com
SendToWindy();
#endif
Serial.println(" Good night sleep");
ESP.deepSleep(SLEEPNIGHT*60000000); // Sleep for night SLEEPTIME*1 minute(s);
delay(500);
}
} else {
if (millis() > 120000) {
NTP.getTime(); //if after 2 min of working not any time sync try force update
}
}
}
#endif
//kUpdFreq minutes timer
if ((millis() > TTasks + (kUpdFreq*60000)) || (millis() < TTasks)) {
if ((WindMax > 2) && (WindMin == WindMax)) errors_count = errors_count + 25; // check for freeze CPU
TTasks = millis();
checkConnection();
//sensorReport = true;
getSensors();
#ifdef USE_OpenWeatherMap
if (kOpenWeatherMap == 0) {
if (!GetOpenWeatherMap())
errors_count++;
}
if (kOpenWeatherMap >= 9)
kOpenWeatherMap = 0;
else
kOpenWeatherMap++;
#endif
#ifdef USE_Narodmon
if (kNarodmon >= 4) {
if (SendToNarodmon()) kNarodmon = 0;
//SendToNarodmonGet();
} else
kNarodmon++;
#endif
#ifdef USE_Windguru
if (!SendToWindguru()) errors_count++;
#endif
#ifdef USE_Windy_com
if (!SendToWindyCom()) errors_count++;
#endif
#ifdef USE_Windy_app
if (!SendToWindyApp()) errors_count++;
#endif
}
}
bool SendToNarodmon() { //send info to narodmon.com
WiFiClient client;
String buf;
buf = "#" + WiFi.macAddress() + "\r\n"; // header
#ifdef DHTPIN
if (!isnan(dhtT)) buf = buf + "#T1#" + String(dhtT) + "\r\n";
if (!isnan(dhtH)) buf = buf + "#H1#" + String(dhtH) + "\r\n";
#endif
buf = buf + "#W1#" + String(WindNarodmon, 2) + "\r\n";
buf = buf + "#D1#" + String(calDirection) + "\r\n";
buf = buf + "##\r\n"; // close packet
if (!client.connect("narodmon.com", 8283)) // try connect
{
Serial.println("connection failed");
return false; // fail;
} else {
client.print(buf); // sending data
Serial.println(buf);
while (client.available()) {
String line = client.readStringUntil('\r'); // redirect answer to serial port
Serial.println(line);
}
}
return true; //done
}
bool SendToNarodmonGet() { // sHTTP GET на http(s)://narodmon.com/get)
WiFiClient client;
HTTPClient http; //must be declared after WiFiClient for correct destruction order, because used by http.begin(client,...)
String getData, Link;
unsigned long time;
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
Link = "http://narodmon.com/get?";
//http://narodmon.com/get?ID=MAC&mac1=value1&...&macN=valueN
getData = "ID=" + WiFi.macAddress() + "&W1=" + String(WindNarodmon, 2) + "&D1=" + String(calDirection);
#ifdef DHTPIN
if (!isnan(dhtT)) getData = getData + "&T1=" + String(dhtT);
if (!isnan(dhtH)) getData = getData + "&H1=" + String(dhtH);
#endif
Serial.println(Link + getData);
http.begin(client, Link + getData); //Specify request destination
int httpCode = http.GET(); //Send the request
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(payload); //Print the response payload
if (mqttClient.connected() && (payload != "OK"))
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug",payload).set_retain().set_qos(1));
mqttClient.publish("debug", payload.c_str());
}
http.end(); //Close connection
} else {
Serial.println("wi-fi connection failed");
return false; // fail;
}
return true; //done
}
bool SendToWindguru() { // send info to windguru.cz
WiFiClient client;
HTTPClient http; //must be declared after WiFiClient for correct destruction order, because used by http.begin(client,...)
String getData = "", Link;
unsigned long time;
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
Link = "http://www.windguru.cz/upload/api.php?";
time = millis();
//--------------------------md5------------------------------------------------
MD5Builder md5;
md5.begin();
md5.add(String(time) + String(windguru_uid) + String(windguru_pass));
md5.calculate();
//Serial.println(md5.toString()); // can be getChars() to getBytes() too. (16 chars) .. see above
//--------------------------md5------------------------------------------------
//wind speed during interval (knots)
if (meterWind > 0)
getData = "uid=" + String(windguru_uid) + "&salt=" + String(time) + "&hash=" + md5.toString() + "&interval=" + String(meterWind * windPeriodSec) + "&wind_min=" + String(WindMin * kKnots, 2) + "&wind_avg=" + String(WindAvr * kKnots/meterWind, 2) + "&wind_max=" + String(WindMax * kKnots, 2);
//wind_direction wind direction as degrees (0 = north, 90 east etc...)
getData = getData + "&wind_direction=" + String(calDirection);
#ifdef DHTPIN
if (!isnan(dhtT)) getData = getData + "&temperature=" + String(dhtT);
if (!isnan(dhtH)) getData = getData + "&rh=" + String(dhtH);
#endif
Serial.println(Link + getData);
http.begin(client, Link + getData); //Specify request destination
int httpCode = http.GET(); //Send the request
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(payload); //Print the response payload
if (mqttClient.connected() && (payload != "OK"))
//mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/debug",payload).set_retain().set_qos(1));
mqttClient.publish("debug", payload.c_str());
}
http.end(); //Close connection
} else {
Serial.println("wi-fi connection failed");
return false; // fail;
}
return true; //done
}
//https://stations.windy.com/pws/update/XXX-API-KEY-XXX?winddir=230&windspeedmph=12&windgustmph=12&tempf=70&rainin=0&baromin=29.1&dewptf=68.2&humidity=90
//We will be displaying data in 5 minutes steps. So, it's not nessary send us data every minute, 5 minutes will be fine.
//https://community.windy.com/topic/8168/report-your-weather-station-data-to-windy
bool SendToWindyCom() { // send info to http://stations.windy.com/stations
WiFiClient client;
HTTPClient http; //must be declared after WiFiClient for correct destruction order, because used by http.begin(client,...)
String getData, Link;
unsigned long time;
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
Link = "http://stations.windy.com/pws/update/" + String(WindyComApiKey) + "?name=" + String(WindyComName) + "&";
//wind speed during interval (knots)
if (meterWind > 0)
getData = "winddir=" + String(calDirection) + "&wind=" + String(WindAvr/meterWind, 2) + "&gust=" + String(WindMax, 2);
#ifdef DHTPIN
if (!isnan(dhtT)) getData = getData + "&temp=" + String(dhtT);
if (!isnan(dhtH)) getData = getData + "&rh=" + String(dhtH);
#endif
Serial.println(Link + getData);
http.begin(client, Link + getData); //Specify request destination
int httpCode = http.GET(); //Send the request
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(payload); //Print the response payload
if (mqttClient.connected() && (payload.indexOf("SUCCESS") == -1))
mqttClient.publish("debug", payload.c_str());
}
http.end(); //Close connection
} else {
Serial.println("wi-fi connection failed");
return false; // fail;
}
return true; //done
}
//https://windyapp.co/apiV9.php?method=addCustomMeteostation&secret=WindyAPPSecret&d5=123&a=11&m=10&g=15&i=test1
//d5* - direction from 0 to 1024. direction in degrees is equal = (d5/1024)*360
//a* - average wind per sending interval. for m/c - divide by 10
//m* - minimal wind per sending interval. for m/c - divide by 10
//g* - maximum wind per sending interval. for m/c - divide by 10
//i* - device number
bool SendToWindyApp() { // send info to http://windy.app/
const char* host = "windyapp.co"; // only google.com not https://google.com
String getData= "", Link;
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
Link = "/apiV9.php?method=addCustomMeteostation&secret=" + String(WindyAppSecret) + "&i=" + String(WindyAppID) +"&";
if (meterWind > 0)
getData = "d5=" + String(map(calDirection, 0, 359, 1, 1024)) + "&m=" + String(WindMin *10, 0) + "&a=" + String(WindAvr/meterWind *10, 0) + "&g=" + String(WindMax *10, 0);
#ifdef DHTPIN
if (!isnan(dhtT)) getData = getData + "&t2=" + String(dhtT);
if (!isnan(dhtH)) getData = getData + "&h=" + String(dhtH);
#endif
getData.replace(" ", "");
// Use WiFiClient class to create TCP connections
WiFiClientSecure httpsClient;
const int httpPort = 443; // 80 is for HTTP / 443 is for HTTPS!
httpsClient.setInsecure(); // this is the magical line that makes everything work
if (!httpsClient.connect(host, httpPort)) { //works!
Serial.println("https connection failed");
if (mqttClient.connected())
mqttClient.publish("debug", "windyapp.co https connection failed");
return false;
}
// We now create a URI for the request
String url = Link + getData;
// This will send the request to the server
Serial.println("request sent: " + url);
httpsClient.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
while (httpsClient.connected()) {
String line = httpsClient.readStringUntil('\n');
if (line == "\r") {
Serial.println("headers received");