-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathAurora-Web-Invert-Monitor.ino
2462 lines (1941 loc) · 71.2 KB
/
Aurora-Web-Invert-Monitor.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
/*
* This work is licensed under the
* Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Italy License.
* To view a copy of this license, visit
* http://creativecommons.org/licenses/by-nc-nd/3.0/it/
* or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
*
* Renzo Mischianti <www.mischianti.org>
*
* https://www.mischianti.org/category/project/web-monitoring-station-for-abb-aurora-inverter-ex-power-one-now-fimer/
*
*/
#include "Arduino.h"
#include <Aurora.h>
#include <SD.h>
#define FS_NO_GLOBALS
#include "FS.h"
#include <Thread.h>
#include <ESP8266WiFi.h>
#include <TimeLib.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ESP8266mDNS.h> // Include the mDNS library
#include <ESP8266WebServer.h>
#include <ESP8266WebServerSecure.h>
#include <ArduinoJson.h>
#include <WiFiManager.h>
#include <SPI.h>
#define SEND_EMAIL
//#define FORCE_SEND_ERROR_MESSAGE
#ifdef SEND_EMAIL
#include <EMailSender.h>
#endif
#define WRITE_SETTINGS_IF_EXIST
// SD
#define SD_WRONG_WRITE_NUMBER_ALERT 10
#define CS_PIN D8
#include <Timezone.h> // https://github.com/JChristensen/Timezone
#define WS_ACTIVE
#ifdef WS_ACTIVE
#include <WebSocketsServer.h>
#endif
#define WS_PORT 8081
#ifdef WS_ACTIVE
WebSocketsServer webSocket = WebSocketsServer(WS_PORT);
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length);
#endif
// HEAP file
#define CONFIG_FILE_HEAP 4096
#define BATTERY_STATE_HEAP 4096
#define ALARM_IN_A_DAY 4096
#define INVERTER_INFO_HEAP 4096
#define PRODUCTION_AND_CUMULATED_HEAP 8192+8192
#define CUMULATED_VALUES_HEAP 2048
#define CUMULATED_VALUES_TOT_HEAP 4096
// Battery voltage resistance
#define BAT_RES_VALUE_GND 20.0
#define BAT_RES_VALUE_VCC 10.0
// Uncomment to enable server ftp.
//#define SERVER_FTP
//#define SERVER_HTTPS
#define HARDWARE_SERIAL
#ifdef SERVER_FTP
#include <ESP8266FtpServer.h>
#endif
#ifdef SERVER_HTTPS
#include <ESP8266WebServerSecure.h>
#endif
// Uncomment to enable printing out nice debug messages.
#define AURORA_SERVER_DEBUG
// Define where debug output will be printed.
#define DEBUG_PRINTER Serial1
// Setup debug printing macros.
#ifdef AURORA_SERVER_DEBUG
#define DEBUG_PRINT(...) { DEBUG_PRINTER.print(__VA_ARGS__); }
#define DEBUG_PRINTLN(...) { DEBUG_PRINTER.println(__VA_ARGS__); }
#else
#define DEBUG_PRINT(...) {}
#define DEBUG_PRINTLN(...) {}
#endif
char hostname[] = "InverterCentraline";
// Interval get data
#define REALTIME_INTERVAL 5
#define DAILY_INTERVAL 10
#define CUMULATIVE_INTERVAL 10
#define CUMULATIVE_TOTAL_INTERVAL 10
#define STATE_INTERVAL 10
#define STATE_STORE_INTERVAL 10
#define BATTERY_INTERVAL 20
#define STATIC_DATA_INTERVAL 6 * 60
// LED
#ifdef HARDWARE_SERIAL
#define ERROR_PIN D3
#else
#define ERROR_PIN D1
#endif
#define INVERTER_COMMUNICATION_CONTROL_PIN D0
// Inverte inizialization
#ifdef HARDWARE_SERIAL
Aurora inverter = Aurora(2, &Serial, INVERTER_COMMUNICATION_CONTROL_PIN);
#else
Aurora inverter = Aurora(2, D2, D3, INVERTER_COMMUNICATION_CONTROL_PIN);
#endif
void manageStaticDataCallback ();
void leggiProduzioneCallback();
void realtimeDataCallbak();
void leggiStatoInverterCallback();
void leggiStatoBatteriaCallback();
void updateLocalTimeWithNTPCallback();
float getBatteryVoltage();
Timezone getTimezoneData(const String code);
time_t getLocalTime(void);
bool isFileSaveOK = true;
bool saveJSonToAFile(DynamicJsonDocument *doc, String filename);
JsonObject getJSonFromFile(DynamicJsonDocument *doc, String filename, bool forceCleanONJsonError = true);
void errorLed(bool flag);
Thread RealtimeData = Thread();
Thread ManageStaticData = Thread();
Thread LeggiStatoInverter = Thread();
Thread LeggiStatoBatteria = Thread();
Thread LeggiProduzione = Thread();
#define HTTP_REST_PORT 8080
ESP8266WebServer httpRestServer(HTTP_REST_PORT);
#ifdef SERVER_HTTPS
static const char serverCert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDDjCCAfagAwIBAgIQNqQC531UdrtOiCvz8JHQTDANBgkqhkiG9w0BAQsFADAU
MRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMTgwOTMwMjAwMDQ1WhcNMzgwOTMwMjAx
MDQ0WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IB
DwAwggEKAoIBAQCrY932OMWnQynPBqtOOm/4dR6aQaSXdeLAUcRjlDy+AEl8C0Xe
sBbwi1dpBatqyFpnYnoWkfduLOCJM4x8J1aoufMHO/XkNP19b8tViFpsmEiwtQnQ
uSKQy8tGtlehYHBEqSqv1E5OkgTAlgYtAEJcY1Ih8DG1vWhMJ73CJcR5fkSQ1OMR
6AUaJORxLyKk0pgmKHmXeue2jP9aiuf1gHJQE9BcIRLpX9jElEA9rTvH5f9yLieg
gP8r1x6BmB/gsyIQ0mnft6aJpyEaJ2XLL4ggnqpHOjrVUZ5AKzk2GQrnQlaZnnZ2
xiiY2R9rp6U6lDWivPgOpaQUZ1c8jGvaV/2hAgMBAAGjXDBaMA4GA1UdDwEB/wQE
AwIFoDAUBgNVHREEDTALgglsb2NhbGhvc3QwEwYDVR0lBAwwCgYIKwYBBQUHAwEw
HQYDVR0OBBYEFOtRfncRTORMIF/wndrep6DmLsZUMA0GCSqGSIb3DQEBCwUAA4IB
AQABwfZ54kRSMGSHXQkIkSJaI8DRByMCro+WCjZnWawfaqJOpihbVC5riZ1oQuyD
gNe8sMoqI2R/xKthUaYsrXb50yVlZ2QLiW9MzOHnd6DkivDNGVBMsu0pKG7nLEiZ
1wnoMxzIrkSYakHLBPhmMMeCl7ahRC29xRMlup46okxcH5xTirM27TUl3Oy8mZcY
UpT+QiqXdcWVFAsTKZfJRzCa1+Su480clKeUuFTYSnuyQ1CNCcnoj3RtR7p8TAzk
Ht6qiI8BQ8kcPiRcYCdWK5g2SBs5QpaAB3/S3IxN8CAu5+CiTkPjmdcCijUJ1VoL
/VxlMAt54NKKnN1MfCgVh4Gb
-----END CERTIFICATE-----
)EOF";
static const char serverKey[] PROGMEM = R"EOF(
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAq2Pd9jjFp0MpzwarTjpv+HUemkGkl3XiwFHEY5Q8vgBJfAtF
3rAW8ItXaQWrashaZ2J6FpH3bizgiTOMfCdWqLnzBzv15DT9fW/LVYhabJhIsLUJ
0LkikMvLRrZXoWBwRKkqr9ROTpIEwJYGLQBCXGNSIfAxtb1oTCe9wiXEeX5EkNTj
EegFGiTkcS8ipNKYJih5l3rntoz/Worn9YByUBPQXCES6V/YxJRAPa07x+X/ci4n
oID/K9cegZgf4LMiENJp37emiachGidlyy+IIJ6qRzo61VGeQCs5NhkK50JWmZ52
dsYomNkfa6elOpQ1orz4DqWkFGdXPIxr2lf9oQIDAQABAoIBAB/Y9NvV/NRx5Ij1
wktNDJVsnf0oCX+jhjkaeJXQa+EaiI0mQxt4OSsFmX6IcSvsgvAHGoyrHwE4EZkt
HQPNA4ti0kgb2jtHpXrzlSMVrUfUnF1JpsNEQ6oIVIOVSn9QPkxj6uy1VL/A3mUy
+37NN4eXZSGtUm9k/MZ59AbpobK5eAXmCxvgss4ZPDW3QGnXqVT8bu6RXaF7Ph64
KMUajkrGEyU9ff8MRzykb3kBit0nchOBvtETRg39L2MtXpnJoLzElZPr5ZbcwHk2
Xp4iuL8D6hoiA0r0jAeYNYZkTW96u4u0eysyUV4xbVuOmozFHCiE/zOa0uW7xjrp
hzPiE2kCgYEA1CnXyUCWiaIN29T//PfuZRiAHFWxG3RaiR7VprMZGsebx7aEVRsP
EPgw0PILAOvNQIWwJWClCoKIWSf0grgDp+QhKAtyk5AaEspr7fXCXf8IK6xh+tDz
OxlRbvQlYwWOFsXLZ3cu1vPuIAUEL4ez/EKeYQ1GC/W86cRBcM6r0mMCgYEAzs1c
r34Tv7Asrec+BxZKrPbq1gaLG4ivVoiZTpo+6MOIGI236tKZIWouy2GklknoE36N
rxz2KrPAFwg6V8N7q1CG/yNn5WJbasPLnb7ygauZ6yiyC4bqaXSKjrZJ2P4UYVOX
t66K/Qr7Ud5gvDfStXPFdun0dUEgfDZqovpS7SsCgYBi5yqft8s1V+UsAIxhCdcJ
K7W0/8FzMfduioBAmKbwU/Lr08q2vcl1OK3RCbRVdpcVJ/0oP3hQgO882KJkOZIC
txc5yrRb08ZD0jckE/fKx7OwYEjAmp14hGHw3kF7esB1Hzml/upH7Ciqpov/+DvQ
MeIRDhYER0cMlp+HDeENTwKBgEXSYlvCForewYcJjxC3fwj86PbQCMGIGaL+xbwb
KehOtDGOD62R4y+7+Qaj9fzkAR4r2UxpW9e5Dr74ATLGhoelzZ5w5tA0sCbQ6ntd
D+Wl+XbDK7HmoFhwh6N9eltwFZNytMPIg5bB0W6nxUNnGZY3+1CV1vqLvZsSiFh0
afE3AoGBAMDHbH2YCshMkDJ5RqZs3gVFQX5jXbUh1+j8/bJrWyW49TErGqWOFKxy
0hJbrLFftgnNuABWQw2Ve11rdboXGqIGhLNksRDFPHOYhgrzvw41DCllI7d3n5ij
sYyW+iXYsiV5NCrE9KvlKkjxA5FJMdb8qiq5uZ03PxxtNTyVhfy+
-----END RSA PRIVATE KEY-----
)EOF";
#define SECURE_HTTP_PORT 443
BearSSL::ESP8266WebServerSecure httpServer(SECURE_HTTP_PORT);
#else
#define HTTP_PORT 80
ESP8266WebServer httpServer(HTTP_PORT);
#endif
void restServerRouting();
void serverRouting();
WiFiUDP ntpUDP;
// By default 'pool.ntp.org' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 0*60*60, 60*60*1000);
Thread UpdateLocalTimeWithNTP = Thread();
bool fixedTime = false;
bool sdStarted = false;
bool wifiConnected = false;
float setPrecision(float val, byte precision);
#define DSP_GRID_POWER_ALL_FILENAME F("power.jso") /* Global */
#define DSP_GRID_CURRENT_ALL_FILENAME F("current.jso")
#define DSP_GRID_VOLTAGE_ALL_FILENAME F("voltage.jso")
#define BATTERY_RT F("bat_rt") /* Global */
#define WIFI_SIGNAL_STRENGHT_RT F("wifi_rt") /* Global */
#define DSP_GRID_POWER_ALL_TYPE_RT F("power_rt") /* Global */
#define DSP_GRID_POWER_ALL_TYPE F("power") /* Global */
#define DSP_GRID_CURRENT_ALL_TYPE F("current")
#define DSP_GRID_VOLTAGE_ALL_TYPE F("voltage")
#define CUMULATED_ENERGY_TYPE F("cumulated")
#define ERROR_TYPE F("error")
#define ERROR_INVERTER_TYPE F("error_inverter")
#ifdef SEND_EMAIL
EMailSender emailSend("", "");
#endif
#ifdef SERVER_FTP
FtpServer ftpSrv; //set #define FTP_DEBUG in ESP8266FtpServer.h to see ftp verbose on serial
#endif
int timeOffset = 0;
String codeDST = "GTM";
void setup() {
pinMode(A0, INPUT);
pinMode(ERROR_PIN, OUTPUT);
digitalWrite(ERROR_PIN, HIGH);
#ifdef AURORA_SERVER_DEBUG
// Inizilization of serial debug
Serial1.begin(19200);
Serial1.setTimeout(500);
// Wait to finish inizialization
delay(600);
#endif
DEBUG_PRINT(F("Inizializing FS..."));
if (SPIFFS.begin()){
DEBUG_PRINTLN(F("done."));
}else{
DEBUG_PRINTLN(F("fail."));
}
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
// wifiManager.setConfigPortalTimeout(10);
WiFi.hostname(hostname);
wifi_station_set_hostname(hostname);
DEBUG_PRINT(F("Open config file..."));
fs::File configFile = SPIFFS.open(F("/mc/config.txt"), "r");
if (configFile) {
// while (configFile.available())
// {
// Serial1.write(configFile.read());
// }
//
DEBUG_PRINTLN(F("done."));
DynamicJsonDocument doc(CONFIG_FILE_HEAP);
ArduinoJson::DeserializationError error = deserializeJson(doc, configFile);
// close the file:
configFile.close();
if (error){
// if the file didn't open, print an error:
DEBUG_PRINT(F("Error parsing JSON "));
DEBUG_PRINTLN(error.c_str());
}else{
JsonObject rootObj = doc.as<JsonObject>();
JsonObject preferences = rootObj[F("preferences")];
bool isGTM = preferences.containsKey(F("GTM"));
if (isGTM){
JsonObject GTM = preferences[F("GTM")];
bool isValue = GTM.containsKey(F("value"));
if (isValue){
int value = GTM[F("value")];
DEBUG_PRINT(F("Impostazione GTM+"))
DEBUG_PRINTLN(value)
// timeClient.setTimeOffset(value*60*60);
timeOffset = value*60*60;
}
}
bool isDST = preferences.containsKey(F("DST"));
if (isDST){
JsonObject DST = preferences[F("DST")];
bool isCode = DST.containsKey(F("code"));
if (isCode){
const String code = DST[F("code")];
// const String desc = DST[F("description")];
codeDST = code;
DEBUG_PRINT(F("Impostazione DST "))
DEBUG_PRINTLN(code)
// DEBUG_PRINT(F("Description DST "))
// DEBUG_PRINTLN(desc)
// timeClient.setTimeOffset(value*60*60);
// timeOffset = value*60*60;
}
}else{
codeDST = "GTM";
}
JsonObject serverConfig = rootObj[F("server")];
bool isStatic = serverConfig[F("isStatic")];
if (isStatic==true){
const char* address = serverConfig[F("address")];
const char* gatway = serverConfig[F("gatway")];
const char* netMask = serverConfig[F("netMask")];
const char* dns1 = serverConfig[F("dns1")];
const char* dns2 = serverConfig[F("dns2")];
const char* _hostname = serverConfig[F("hostname")];
//start-block2
IPAddress _ip;
bool parseSuccess;
parseSuccess = _ip.fromString(address);
if (parseSuccess) {
DEBUG_PRINTLN(F("Address correctly parsed!"));
}
IPAddress _gw;
parseSuccess = _gw.fromString(gatway);
if (parseSuccess) {
DEBUG_PRINTLN(F("Gatway correctly parsed!"));
}
IPAddress _sn;
parseSuccess = _sn.fromString(netMask);
if (parseSuccess) {
DEBUG_PRINTLN(F("Subnet correctly parsed!"));
}
IPAddress _dns1;
IPAddress _dns2;
bool isDNS = false;
if (dns1 && sizeof(_dns1) > 7 && dns2 && sizeof(_dns2) > 7 ){
parseSuccess = _dns1.fromString(dns1);
if (parseSuccess) {
DEBUG_PRINTLN(F("DNS 1 correctly parsed!"));
isDNS = true;
}
parseSuccess = _dns2.fromString(dns2);
if (parseSuccess) {
DEBUG_PRINTLN(F("DNS 2 correctly parsed!"));
}
//end-block2
}
DEBUG_PRINT(F("Set static data..."));
if (isDNS){
wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn, _dns1, _dns2);
}else{
wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
}
if (_hostname && sizeof(_hostname)>1){
strcpy(hostname, _hostname);
}
// IPAddress(85, 37, 17, 12), IPAddress(8, 8, 8, 8)
//
// emailSend.setEMailLogin("smtp.mischianti@gmail.com");
DEBUG_PRINTLN(F("done."));
}
}
}else{
DEBUG_PRINTLN(F("fail."));
}
//reset saved settings
// wifiManager.resetSettings();
//set custom ip for portal
//wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
//fetches ssid and pass from eeprom and tries to connect
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
wifiManager.autoConnect("InverterCentralineConfiguration");
//or use this for auto generated name ESP + ChipID
//wifiManager.autoConnect();
//if you get here you have connected to the WiFi
DEBUG_PRINTLN(F("WIFIManager connected!"));
DEBUG_PRINT(F("IP --> "));
DEBUG_PRINTLN(WiFi.localIP());
DEBUG_PRINT(F("GW --> "));
DEBUG_PRINTLN(WiFi.gatewayIP());
DEBUG_PRINT(F("SM --> "));
DEBUG_PRINTLN(WiFi.subnetMask());
DEBUG_PRINT(F("DNS 1 --> "));
DEBUG_PRINTLN(WiFi.dnsIP(0));
DEBUG_PRINT(F("DNS 2 --> "));
DEBUG_PRINTLN(WiFi.dnsIP(1));
#ifndef WRITE_SETTINGS_IF_EXIST
if (!SPIFFS.exists(F("/settings.json"))){
#endif
DEBUG_PRINT(F("Recreate settings file..."));
fs::File settingsFile = SPIFFS.open(F("/settings.json"), "w");
if (!settingsFile) {
DEBUG_PRINTLN(F("fail."));
}else{
DEBUG_PRINTLN(F("done."));
DynamicJsonDocument doc(2048);
JsonObject postObj = doc.to<JsonObject>();
// postObj[F("localIP")] = WiFi.localIP().toString();
postObj[F("localRestPort")] = HTTP_REST_PORT;
postObj[F("localWSPort")] = WS_PORT;
String buf;
serializeJson(postObj, buf);
settingsFile.print(F("var settings = "));
settingsFile.print(buf);
settingsFile.print(";");
settingsFile.close();
// serializeJson(doc, settingsFile);
DEBUG_PRINTLN(F("success."));
}
#ifndef WRITE_SETTINGS_IF_EXIST
}
#endif
// Start inverter serial
DEBUG_PRINT(F("Initializing Inverter serial..."));
inverter.begin();
DEBUG_PRINTLN(F("initialization done."));
// Start inizialization of SD cart
DEBUG_PRINT(F("Initializing SD card..."));
// Initialize SD library
while (!SD.begin(CS_PIN)) {
Serial.println(F("Failed to initialize SD library"));
delay(1000);
sdStarted = false;
}
sdStarted = true;
// if (!SD.begin(CS_PIN, SPI_HALF_SPEED)) {
// DEBUG_PRINTLN(F("initialization failed!"));
// sdStarted = false;
// // return to stop all
// return;
// }else{
// sdStarted = true;
//
// }
DEBUG_PRINTLN(F("Inizialization done."));
ManageStaticData.onRun(manageStaticDataCallback);
ManageStaticData.setInterval(STATIC_DATA_INTERVAL * 60 * 1000);
// Start thread, and set it every 1 minutes
LeggiStatoInverter.onRun(leggiStatoInverterCallback);
LeggiStatoInverter.setInterval(STATE_INTERVAL * 60 * 1000);
// Start thread, and set it every 60
LeggiStatoBatteria.onRun(leggiStatoBatteriaCallback);
LeggiStatoBatteria.setInterval(BATTERY_INTERVAL * 60 * 1000);
// Start thread, and set it every 1 minutes
LeggiProduzione.onRun(leggiProduzioneCallback);
LeggiProduzione.setInterval(60 * 1000);
RealtimeData.onRun(realtimeDataCallbak);
RealtimeData.setInterval(1000 * REALTIME_INTERVAL);
int timeToRetry = 10;
while ( WiFi.status() != WL_CONNECTED && timeToRetry>0 ) {
delay ( 500 );
DEBUG_PRINT ( "." );
timeToRetry--;
}
wifiConnected = true;
//#ifndef SERVER_FTP
timeClient.begin();
updateLocalTimeWithNTPCallback();
UpdateLocalTimeWithNTP.onRun(updateLocalTimeWithNTPCallback);
UpdateLocalTimeWithNTP.setInterval(60*60 * 1000);
restServerRouting();
httpRestServer.begin();
DEBUG_PRINTLN(F("HTTP REST Server Started"));
#ifdef SERVER_HTTPS
httpServer.setRSACert(new BearSSLX509List(serverCert), new BearSSLPrivateKey(serverKey));
#endif
serverRouting();
httpServer.begin();
#ifdef SERVER_HTTPS
DEBUG_PRINTLN(F("HTTPS Server Started"));
#else
DEBUG_PRINTLN(F("HTTP Server Started"));
#endif
#ifdef SERVER_FTP
// SPIFFS.format();
ftpSrv.begin(F("aurora"),F("aurora")); //username, password for ftp. set ports in ESP8266FtpServer.h (default 21, 50009 for PASV)
DEBUG_PRINTLN(F("FTP Server Started"));
#endif
if (!MDNS.begin(hostname)) { // Start the mDNS responder for esp8266.local
DEBUG_PRINTLN(F("Error setting up mDNS responder!"));
}
DEBUG_PRINT(hostname);
DEBUG_PRINTLN(F(" --> mDNS responder started"));
DEBUG_PRINT(F("ERROR --> "));
DEBUG_PRINTLN(!(fixedTime && sdStarted&& wifiConnected));
#ifdef WS_ACTIVE
webSocket.begin();
webSocket.onEvent(webSocketEvent);
DEBUG_PRINTLN(F("WS Server Started"));
#endif
errorLed(!(fixedTime && sdStarted&& wifiConnected && isFileSaveOK));
// digitalWrite(ERROR_PIN, !(fixedTime && sdStarted&& wifiConnected && isFileSaveOK));
if (fixedTime && sdStarted){
DEBUG_PRINTLN(F("FIRST LOAD..."))
leggiStatoInverterCallback();
leggiStatoBatteriaCallback();
manageStaticDataCallback();
leggiProduzioneCallback();
}
}
void loop() {
//#ifndef SERVER_FTP
// Activate thread
if (fixedTime && LeggiProduzione.shouldRun()) {
LeggiProduzione.run();
}
if (fixedTime && RealtimeData.shouldRun()) {
RealtimeData.run();
}
if (fixedTime && sdStarted && LeggiStatoInverter.shouldRun()) {
LeggiStatoInverter.run();
}
if (fixedTime && sdStarted && LeggiStatoBatteria.shouldRun()) {
LeggiStatoBatteria.run();
}
if (fixedTime && sdStarted && ManageStaticData.shouldRun()) {
ManageStaticData.run();
}
if (UpdateLocalTimeWithNTP.shouldRun()) {
UpdateLocalTimeWithNTP.run();
}
#ifdef WS_ACTIVE
webSocket.loop();
#endif
httpRestServer.handleClient();
httpServer.handleClient();
timeClient.update();
//#endif
#ifdef SERVER_FTP
ftpSrv.handleFTP(); //make sure in loop you call handleFTP()!!
#endif
}
// We can read/write a file at time in the SD card
File myFileSDCart; // @suppress("Ambiguous problem")
void leggiStatoBatteriaCallback() {
DEBUG_PRINT(F("Thread call (leggiStatoBatteriaCallback) --> "));
DEBUG_PRINT(getEpochStringByParams(getLocalTime()));
DEBUG_PRINT(F(" MEM --> "));
DEBUG_PRINTLN(ESP.getFreeHeap())
float bv = getBatteryVoltage();
DEBUG_PRINT(F(" BATTERY --> "));
DEBUG_PRINTLN(bv);
DEBUG_PRINTLN(bv>2);
DEBUG_PRINTLN(bv>1);
if (bv>1) {
String scopeDirectory = F("battery");
if (!SD.exists(scopeDirectory)) {
SD.mkdir(scopeDirectory);
}
String filename = scopeDirectory +"/"+ getEpochStringByParams(getLocalTime(), (char*) "%Y%m%d") + F(".jso");
DynamicJsonDocument doc(BATTERY_STATE_HEAP);
JsonObject obj;
obj = getJSonFromFile(&doc, filename);
obj[F("lastUpdate")] = getEpochStringByParams(getLocalTime());
JsonObject data;
if (!obj.containsKey(F("data"))) {
data = obj.createNestedObject(F("data"));
} else {
data = obj[F("data")];
}
data[getEpochStringByParams(getLocalTime(),(char*) "%H%M")]=bv;
DEBUG_PRINTLN(F("done."));
isFileSaveOK = saveJSonToAFile(&doc, filename);
}
}
int lastAlarm = 0;
bool saveInverterStats(String scopeDirectory, Aurora::DataState dataState){
if (!SD.exists(scopeDirectory)) {
SD.mkdir(scopeDirectory);
}
String filename = scopeDirectory + F("/alarStat.jso");
DynamicJsonDocument doc(2048);
JsonObject rootObj = doc.to<JsonObject>();
rootObj[F("lastUpdate")] = getEpochStringByParams(getLocalTime());
rootObj[F("alarmStateParam")] = dataState.alarmState;
rootObj[F("alarmState")] = dataState.getAlarmState();
rootObj[F("channel1StateParam")] = dataState.channel1State;
rootObj[F("channel1State")] = dataState.getDcDcChannel1State();
rootObj[F("channel2StateParam")] = dataState.channel2State;
rootObj[F("channel2State")] = dataState.getDcDcChannel2State();
rootObj[F("inverterStateParam")] = dataState.inverterState;
rootObj[F("inverterState")] = dataState.getInverterState();
DEBUG_PRINTLN(F("done."));
isFileSaveOK = saveJSonToAFile(&doc, filename);
return isFileSaveOK;
}
struct LastDataState {
byte asp;
byte c1sp;
byte c2sp;
byte isp;
bool variationFromPrevious = false;
bool inverterProblem = false;
bool firstElement = true;
bool needNotify = false;
};
LastDataState manageLastDataState(String scopeDirectory, Aurora::DataState dataState){
LastDataState lds;
String dayDirectory = getEpochStringByParams(getLocalTime(), (char*) "%Y%m%d");
String filenameAL = scopeDirectory + '/' + dayDirectory + F("/alarms.jso");
DynamicJsonDocument docAS(ALARM_IN_A_DAY);
JsonObject obj;
obj = getJSonFromFile(&docAS, filenameAL);
obj[F("lastUpdate")] = getEpochStringByParams(getLocalTime());
JsonArray data;
if (!obj.containsKey(F("data"))) {
data = obj.createNestedArray(F("data"));
} else {
data = obj[F("data")];
}
bool inverterProblem = dataState.alarmState > 0 || (dataState.inverterState != 2 && dataState.inverterState != 1);
lds.inverterProblem = inverterProblem;
bool firstElement = data.size() == 0;
lds.firstElement = firstElement;
if (inverterProblem || !firstElement) {
JsonObject lastData;
if (data.size() > 0) {
lastData = data[data.size() - 1];
lds.asp = lastData[F("asp")];
lds.c1sp = lastData[F("c1sp")];
lds.c2sp = lastData[F("c2sp")];
lds.isp = lastData[F("isp")];
}
bool variationFromPrevious = (data.size() > 0
&& (lastData[F("asp")] != dataState.alarmState
|| lastData[F("c1sp")] != dataState.channel1State
|| lastData[F("c2sp")] != dataState.channel2State
|| lastData[F("isp")] != dataState.inverterState));
lds.variationFromPrevious = variationFromPrevious;
byte ldState = lastData[F("isp")];
DEBUG_PRINT(F("Last data state --> "));
DEBUG_PRINTLN(ldState);
DEBUG_PRINT(F("Data state --> "));
DEBUG_PRINTLN(dataState.inverterState);
DEBUG_PRINT(F("Last data vs data state is different --> "));
DEBUG_PRINTLN(lastData[F("isp")] != dataState.inverterState);
DEBUG_PRINT(F("Inverter problem --> "));
DEBUG_PRINTLN(inverterProblem);
DEBUG_PRINT(F("firstElement --> "));
DEBUG_PRINTLN(firstElement);
DEBUG_PRINT(F("Variation From Previous --> "));
DEBUG_PRINTLN(variationFromPrevious);
lds.needNotify = false;
if ((inverterProblem && firstElement)
|| (!firstElement && variationFromPrevious)) {
lds.needNotify = true;
if (docAS.memoryUsage()>(ALARM_IN_A_DAY-1024)){
DEBUG_PRINTLN(F("Too much data in a day, removed 4 elements"));
data.remove(0);
data.remove(1);
data.remove(2);
data.remove(3);
// for (int i = 0; i<4; i++){
// data.remove[(const char*)i];
// }
}
JsonObject objArrayData = data.createNestedObject();
objArrayData[F("h")] = getEpochStringByParams(getLocalTime(),
(char*) "%H%M");
objArrayData[F("asp")] = dataState.alarmState;
// objArrayData[F("as")] = dataState.getAlarmState();
objArrayData[F("c1sp")] = dataState.channel1State;
// objArrayData[F("c1s")] = dataState.getDcDcChannel1State();
objArrayData[F("c2sp")] = dataState.channel2State;
// objArrayData[F("c2s")] = dataState.getDcDcChannel2State();
objArrayData[F("isp")] = dataState.inverterState;
// objArrayData["is"] = dataState.getInverterState();
DEBUG_PRINTLN(F("Store alarms --> "));
// serializeJson(doc, Serial);
DEBUG_PRINT(docAS.memoryUsage());
DEBUG_PRINTLN();
if (!SD.exists(scopeDirectory + '/' + dayDirectory)) {
SD.mkdir(scopeDirectory + '/' + dayDirectory);
}
isFileSaveOK = saveJSonToAFile(&docAS, filenameAL);
}
}
return lds;
}
#ifdef WS_ACTIVE
void sendWSMessageAlarm(Aurora::DataState dataState, bool inverterProblem, bool variationFromPrevious){
if (inverterProblem || variationFromPrevious){
DEBUG_PRINT(F(" MEM Condition --> "));
DEBUG_PRINTLN(ESP.getFreeHeap())
DynamicJsonDocument docws(512);
JsonObject objws = docws.to<JsonObject>();
String dateFormatted = getEpochStringByParams(getLocalTime());
objws[F("type")] = ERROR_INVERTER_TYPE;
objws[F("date")] = dateFormatted;
JsonObject objValue = objws.createNestedObject(F("value"));
objValue[F("inverterProblem")] = inverterProblem;
objValue[F("asp")] = dataState.alarmState;
objValue[F("c1sp")] = dataState.channel1State;
objValue[F("c2sp")] = dataState.channel2State;
objValue[F("isp")] = dataState.inverterState;
objValue[F("alarm")] = dataState.getAlarmState();
objValue[F("ch1state")] = dataState.getDcDcChannel1State();
objValue[F("ch2state")] = dataState.getDcDcChannel2State();
objValue[F("state")] = dataState.getInverterState();
String buf;
serializeJson(objws, buf);
webSocket.broadcastTXT(buf);
}
}
#endif
void leggiStatoInverterCallback() {
DEBUG_PRINT(F("Thread call (LeggiStatoInverterCallback) --> "));
DEBUG_PRINT(getEpochStringByParams(getLocalTime()));
DEBUG_PRINT(F(" MEM --> "));
DEBUG_PRINTLN(ESP.getFreeHeap())
Aurora::DataState dataState = inverter.readState();
#ifdef FORCE_SEND_ERROR_MESSAGE
if (lastAlarm==0){
dataState.alarmState = 2;
lastAlarm = 2;
}else{
dataState.alarmState = 0;
lastAlarm = 0;
}
dataState.state.readState = 1;
#endif
DEBUG_PRINT(F("Read state --> "));
DEBUG_PRINTLN(dataState.state.readState);
if (dataState.state.readState == 1) {
DEBUG_PRINTLN(F("done."));
DEBUG_PRINT(F("Create json..."));
String scopeDirectory = F("alarms");
saveInverterStats(scopeDirectory, dataState);
LastDataState lds = manageLastDataState(scopeDirectory, dataState);
sendWSMessageAlarm(dataState, lds.inverterProblem, lds.variationFromPrevious);
#ifdef SEND_EMAIL
DEBUG_PRINT(F("MEM "));
DEBUG_PRINTLN(ESP.getFreeHeap());
if (lds.needNotify){
DEBUG_PRINT(F("Open config file..."));
fs::File configFile = SPIFFS.open(F("/mc/config.txt"), "r");
if (configFile) {
DEBUG_PRINTLN(F("done."));
DynamicJsonDocument doc(CONFIG_FILE_HEAP);
DeserializationError error = deserializeJson(doc, configFile);
if (error) {
// if the file didn't open, print an error:
DEBUG_PRINT(F("Error parsing JSON "));
DEBUG_PRINTLN(error.c_str());
}
// close the file:
configFile.close();
DEBUG_PRINT(F("MEM "));
DEBUG_PRINTLN(ESP.getFreeHeap());
JsonObject rootObj = doc.as<JsonObject>();
DEBUG_PRINT(F("After read config check serverSMTP and emailNotification "));
DEBUG_PRINTLN(rootObj.containsKey(F("serverSMTP")) && rootObj.containsKey(F("emailNotification")));
if (rootObj.containsKey(F("serverSMTP")) && rootObj.containsKey(F("emailNotification"))){
// JsonObject serverConfig = rootObj["server"];
JsonObject serverSMTP = rootObj[F("serverSMTP")];
JsonObject emailNotification = rootObj[F("emailNotification")];
bool isNotificationEnabled = (emailNotification.containsKey(F("isNotificationEnabled")))?emailNotification[F("isNotificationEnabled")]:false;
DEBUG_PRINT(F("isNotificationEnabled "));
DEBUG_PRINTLN(isNotificationEnabled);
if (isNotificationEnabled){
const char* serverSMTPAddr = serverSMTP[F("server")];
emailSend.setSMTPServer(serverSMTPAddr);
uint16_t portSMTP = serverSMTP[F("port")];
emailSend.setSMTPPort(portSMTP);
const char* loginSMTP = serverSMTP[F("login")];
emailSend.setEMailLogin(loginSMTP);
const char* passwordSMTP = serverSMTP[F("password")];
emailSend.setEMailPassword(passwordSMTP);
const char* fromSMTP = serverSMTP[F("from")];
emailSend.setEMailFrom(fromSMTP);
DEBUG_PRINT(F("server "));
DEBUG_PRINTLN(serverSMTPAddr);
DEBUG_PRINT(F("port "));
DEBUG_PRINTLN(portSMTP);
DEBUG_PRINT(F("login "));
DEBUG_PRINTLN(loginSMTP);
DEBUG_PRINT(F("password "));
DEBUG_PRINTLN(passwordSMTP);
DEBUG_PRINT(F("from "));
DEBUG_PRINTLN(fromSMTP);
EMailSender::EMailMessage message;
const String sub = emailNotification[F("subject")];
message.subject = sub;
JsonArray emailList = emailNotification[F("emailList")];
DEBUG_PRINT(F("Email list "));
for (uint8_t i=0; i<emailList.size(); i++){
JsonObject emailElem = emailList[i];
// byte asp = lastData[F("asp")];
// byte c1sp = lastData[F("c1sp")];
// byte c2sp = lastData[F("c2sp")];
// byte isp = lastData[F("isp")];
const String alarm = emailElem[F("alarm")];
const String ch1 = emailElem[F("ch1")];
const String ch2 = emailElem[F("ch2")];
const String state = emailElem[F("state")];
DEBUG_PRINT(F("State value "));
DEBUG_PRINTLN(state);
DEBUG_PRINT(F("State value on_problem comparison "));
DEBUG_PRINTLN(state==F("on_problem"));
DEBUG_PRINT(F("Alarm value "));
DEBUG_PRINTLN(alarm);