-
Notifications
You must be signed in to change notification settings - Fork 2
/
AmsToMqttBridge.cpp
2708 lines (2482 loc) · 91.1 KB
/
AmsToMqttBridge.cpp
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
/**
* Copyright (C) 2022 Gunnar Skjold
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @author Gunnar Skjold (@gskjold) gunnar.skjold@gmail.com
*
* @brief Program for ESP32 and ESP8266 to receive data from AMS electric meters and send to MQTT
*
* @details This program was created to receive data from AMS electric meters via M-Bus, decode
* and send to a MQTT broker. The data packet structure supported by this software is specific
* to Norwegian meters, but may also support data from electricity providers in other countries.
* EHorvat: Based on amsreader-firmware Release 2.2.17
*/
#include <Arduino.h>
#if defined(ESP8266)
ADC_MODE(ADC_VCC);
#endif
#if defined(ESP32)
#include <esp_task_wdt.h>
#endif
#define WDT_TIMEOUT 60
#if defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32C3)
#include <driver/uart.h>
#endif
#include "FirmwareVersion.h"
#include "AmsToMqttBridge.h"
#include "AmsStorage.h"
#include "AmsDataStorage.h"
#include "EnergyAccounting.h"
#include <MQTT.h>
#include <DNSServer.h>
#include <lwip/apps/sntp.h>
#include "hexutils.h"
#include "HwTools.h"
#include "EntsoeApi.h"
#include "AmsWebServer.h"
#include "AmsConfiguration.h"
#include "AmsMqttHandler.h"
#include "JsonMqttHandler.h"
#include "RawMqttHandler.h"
#include "DomoticzMqttHandler.h"
#include "HomeAssistantMqttHandler.h"
#include "Uptime.h"
#include "RemoteDebug.h"
#define debugV_P(x, ...) if (Debug.isActive(Debug.VERBOSE)) {Debug.printf_P(x, ##__VA_ARGS__);Debug.println();}
#define debugD_P(x, ...) if (Debug.isActive(Debug.DEBUG)) {Debug.printf_P(x, ##__VA_ARGS__);Debug.println();}
#define debugI_P(x, ...) if (Debug.isActive(Debug.INFO)) {Debug.printf_P(x, ##__VA_ARGS__);Debug.println();}
#define debugW_P(x, ...) if (Debug.isActive(Debug.WARNING)) {Debug.printf_P(x, ##__VA_ARGS__);Debug.println();}
#define debugE_P(x, ...) if (Debug.isActive(Debug.ERROR)) {Debug.printf_P(x, ##__VA_ARGS__);Debug.println();}
#define debugA_P(x, ...) if (Debug.isActive(Debug.ANY)) {Debug.printf_P(x, ##__VA_ARGS__);Debug.println();}
#define BUF_SIZE_COMMON (2048)
#define BUF_SIZE_HAN (1280)
#include "IEC6205621.h"
#include "IEC6205675.h"
#include "LNG.h"
#include "LNG2.h"
#include "DataParsers.h"
#include "Timezones.h"
#include "NES-MEP.h" // EHorvat NES-MEP added ********
#include "NES-MEP-Tools.h"// EHorvat NES-MEP added ********
uint8_t commonBuffer[BUF_SIZE_COMMON];
uint8_t hanBuffer[BUF_SIZE_HAN];
HwTools hw;
DNSServer* dnsServer = NULL;
AmsConfiguration config;
RemoteDebug Debug;
EntsoeApi* eapi = NULL;
Timezone* tz = NULL;
AmsWebServer ws(commonBuffer, &Debug, &hw);
MQTTClient *mqtt = NULL;
WiFiClient *mqttClient = NULL;
WiFiClientSecure *mqttSecureClient = NULL;
AmsMqttHandler* mqttHandler = NULL;
Stream *hanSerial;
SoftwareSerial *swSerial = NULL;
// HardwareSerial *hwSerial = NULL; // EHorvat NES-MEP disabled this line
size_t rxBufferSize = 128;
uint8_t rxBufferErrors = 0;
GpioConfig gpioConfig;
MeterConfig meterConfig;
bool mqttEnabled = false;
String topic = "ams";
AmsData meterState;
bool ntpEnabled = false;
bool mdnsEnabled = false;
AmsDataStorage ds(&Debug);
EnergyAccounting ea(&Debug);
uint8_t wifiReconnectCount = 0;
HDLCParser *hdlcParser = NULL;
MBUSParser *mbusParser = NULL;
GBTParser *gbtParser = NULL;
GCMParser *gcmParser = NULL;
LLCParser *llcParser = NULL;
DLMSParser *dlmsParser = NULL;
DSMRParser *dsmrParser = NULL;
void configFileParse();
void swapWifiMode();
void WiFi_connect();
void WiFi_post_connect();
void MQTT_connect();
void handleNtpChange();
void handleDataSuccess(AmsData* data);
// void handleTemperature(unsigned long now);
void handleSystem(unsigned long now);
void handleAutodetect(unsigned long now);
void handleButton(unsigned long now);
void handlePriceApi(unsigned long now);
void handleClear(unsigned long now);
void handleEnergyAccountingChanged();
bool readHanPort();
void setupHanPort(GpioConfig& gpioConfig, uint32_t baud, uint8_t parityOrdinal, bool invert);
void rxerr(int err);
int16_t unwrapData(uint8_t *buf, DataParserContext &context);
void errorBlink();
void printHanReadError(int pos);
void debugPrint(byte *buffer, int start, int length);
// ****************** EHorvat NES-MEP start ******************
void SerialEvent2();
AmsData ad;
//
extern ConsumptionDataStruct ConsumptionData;
extern MeterInfoStruct MeterInfo;
MEPQueueStruct MEPQueue[MaxMEPBuffer];
byte MEPQueueNextIndex = 0;
byte MEPQueueSendIndex = 0;
unsigned long LastSentMillis = 0;
unsigned long LastReceiveMillis = 0;
boolean SentAwaitingReply = false;
boolean FirstRequestOk = false;
boolean GetConfigurationRequestsSent = false;
long UserLoginSession = random(LONG_MAX);
long SecretLoginSession = random(LONG_MAX);
char mep_key[21] = "`!Vp3;,qDoU2BlLS8tZH"; // dummy MEP Basic Key in ASCII format
String RequestsBytesString;
String ReceiveBytesString;
uint32_t previousMillis;
byte InputBuffer[MaxMEPReplyLength];
unsigned long InputBufferLength = 0;
unsigned long mep_LastSentMillis = 0;
unsigned long mep_Last_ok_millis = 0;
bool mep_data_ready = false;
bool mep_data_ready_to_send = false;
long mep_alivecounter = 0;
long mep_alivecounter_last = 0;
long summ_60minplot = 0;
long hour_plot_avg = 0;
byte index_60minplot = 0;
unsigned long Last_hourplot_millis = 0;
unsigned long Last_APClient_millis =millis();
//
// ++++++++++++ EHorvat NES-MEP End ++++++++++
void setup() {
Serial.begin(115200);
Serial2.begin(9600, SERIAL_8N1); //EHorvat NES-MEP
config.hasConfig(); // Need to run this to make sure all configuration have been migrated before we load GPIO config
if(!config.getGpioConfig(gpioConfig)) {
config.clearGpio(gpioConfig);
}
delay(1);
config.loadTempSensors();
hw.setup(&gpioConfig, &config);
if(gpioConfig.apPin >= 0) {
pinMode(gpioConfig.apPin, INPUT_PULLUP);
if(!hw.ledOn(LED_GREEN)) {
hw.ledOn(LED_INTERNAL);
}
delay(1000);
if(digitalRead(gpioConfig.apPin) == LOW) {
if(!hw.ledOn(LED_RED)) {
hw.ledBlink(LED_INTERNAL, 4);
}
delay(2000);
if(digitalRead(gpioConfig.apPin) == LOW) {
if(!hw.ledOff(LED_GREEN)) {
hw.ledOn(LED_INTERNAL);
}
delay(2000);
if(digitalRead(gpioConfig.apPin) == HIGH) {
config.clear();
if(!hw.ledBlink(LED_RED, 6)) {
hw.ledBlink(LED_INTERNAL, 6);
}
}
}
}
}
hw.ledBlink(LED_INTERNAL, 1);
hw.ledBlink(LED_RED, 1);
hw.ledBlink(LED_YELLOW, 1);
hw.ledBlink(LED_GREEN, 1);
hw.ledBlink(LED_BLUE, 1);
EntsoeConfig entsoe;
if(config.getEntsoeConfig(entsoe) && entsoe.enabled && strlen(entsoe.area) > 0) {
eapi = new EntsoeApi(&Debug);
eapi->setup(entsoe);
ws.setEntsoeApi(eapi);
}
ws.setPriceSettings(entsoe.area, entsoe.currency);
ea.setFixedPrice(entsoe.fixedPrice / 1000.0, entsoe.currency);
ea.setFixedRefund(entsoe.fixedRefund / 1000.0, entsoe.currency); // EHorvat new fixed income price / refund
ea.setLast_Counter_Value(entsoe.last_counter_value); // EHorvat new last_counter_value
ea.setLast_Counter_Info(entsoe.last_counter_info); // EHorvat new last_counter_value
ea.setLast_expCounter_Value(entsoe.last_expcounter_value); // EHorvat new last_counter_value
ea.setLast_expCounter_Info(entsoe.last_expcounter_info); // EHorvat new last_counter_value
bool shared = false;
config.getMeterConfig(meterConfig);
Serial.flush();
Serial.end();
if(gpioConfig.hanPin == 3) {
shared = true;
#if defined(ESP8266)
SerialConfig serialConfig;
#elif defined(ESP32)
uint32_t serialConfig;
#endif
switch(meterConfig.parity) {
case 2:
serialConfig = SERIAL_7N1;
break;
case 3:
serialConfig = SERIAL_8N1;
break;
case 10:
serialConfig = SERIAL_7E1;
break;
default:
serialConfig = SERIAL_8E1;
break;
}
#if defined(ESP32)
Serial.begin(meterConfig.baud == 0 ? 2400 : meterConfig.baud, serialConfig, -1, -1, meterConfig.invert);
#else
Serial.begin(meterConfig.baud == 0 ? 2400 : meterConfig.baud, serialConfig, SERIAL_FULL, 1, meterConfig.invert);
#endif
}
if(!shared) {
Serial.begin(115200);
}
Debug.setSerialEnabled(true);
yield();
float vcc = hw.getVcc();
if (Debug.isActive(RemoteDebug::INFO)) {
debugI_P(PSTR("AMS bridge started"));
debugI_P(PSTR("Voltage: %.2fV"), vcc);
}
float vccBootLimit = gpioConfig.vccBootLimit == 0 ? 0 : min(3.29, gpioConfig.vccBootLimit / 10.0); // Make sure it is never above 3.3v
/* EHorvat NES-MEP disable checking supply voltages **********
if(vccBootLimit > 2.5 && vccBootLimit < 3.3 && (gpioConfig.apPin == 0xFF || digitalRead(gpioConfig.apPin) == HIGH)) { // Skip if user is holding AP button while booting (HIGH = button is released)
if (vcc < vccBootLimit) {
if(Debug.isActive(RemoteDebug::INFO)) {
Debug.printf_P(PSTR("(setup) Voltage is too low (%.2f < %.2f), sleeping\n"), vcc, vccBootLimit);
Serial.flush();
}
ESP.deepSleep(10000000); //Deep sleep to allow output cap to charge up
}
}
EHorvat NES-MEP disable checking supply voltages ********** End */
WiFi.disconnect(true);
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_OFF);
bool hasFs = false;
#if defined(ESP32)
debugD_P(PSTR("ESP32 LittleFS"));
hasFs = LittleFS.begin(true);
debugD_P(PSTR(" size: %d"), LittleFS.totalBytes());
#else
debugD_P(PSTR("ESP8266 LittleFS"));
hasFs = LittleFS.begin();
#endif
yield();
if(hasFs) {
#if defined(ESP8266)
LittleFS.gc();
if(!LittleFS.check()) {
debugW_P(PSTR("LittleFS filesystem error"));
if(!LittleFS.format()) {
debugE_P(PSTR("Unable to format broken filesystem"));
}
}
#endif
bool flashed = false;
if(LittleFS.exists(FILE_FIRMWARE)) {
if (!config.hasConfig()) {
debugI_P(PSTR("Device has no config, yet a firmware file exists, deleting file."));
} else if (gpioConfig.apPin == 0xFF || digitalRead(gpioConfig.apPin) == HIGH) {
if(Debug.isActive(RemoteDebug::INFO)) debugI_P(PSTR("Found firmware"));
#if defined(ESP8266)
WiFi.setSleepMode(WIFI_LIGHT_SLEEP);
WiFi.forceSleepBegin();
#endif
int i = 0;
/* EHorvat NES-MEP ********** disable checking supply voltages
while(hw.getVcc() > 1.0 && hw.getVcc() < 3.2 && i < 3) {
if(Debug.isActive(RemoteDebug::INFO)) debugI_P(PSTR(" vcc not optimal, light sleep 10s"));
#if defined(ESP8266)
delay(10000);
#elif defined(ESP32)
esp_sleep_enable_timer_wakeup(10000000);
esp_light_sleep_start();
#endif
i++;
}
EHorvat NES-MEP disable checking supply voltages End */
debugI_P(PSTR(" flashing"));
File firmwareFile = LittleFS.open(FILE_FIRMWARE, (char*) "r");
debugD_P(PSTR(" firmware size: %d"), firmwareFile.size());
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
debugD_P(PSTR(" available: %d"), maxSketchSpace);
if (!Update.begin(maxSketchSpace, U_FLASH)) {
if(Debug.isActive(RemoteDebug::ERROR)) {
debugE_P(PSTR("Unable to start firmware update"));
Update.printError(Serial);
}
} else {
while (firmwareFile.available()) {
uint8_t ibuffer[128];
firmwareFile.read((uint8_t *)ibuffer, 128);
Update.write(ibuffer, sizeof(ibuffer));
}
flashed = Update.end(true);
}
config.setUpgradeInformation(flashed ? 2 : 0, 0xFF, FirmwareVersion::VersionString, "");
firmwareFile.close();
} else {
debugW_P(PSTR("AP button pressed, skipping firmware update and deleting firmware file."));
}
LittleFS.remove(FILE_FIRMWARE);
} else if(LittleFS.exists(FILE_CFG)) {
if(Debug.isActive(RemoteDebug::INFO)) debugI_P(PSTR("Found config"));
configFileParse();
flashed = true;
}
if(flashed) {
LittleFS.end();
if(Debug.isActive(RemoteDebug::INFO)) {
debugI_P(PSTR("Firmware update complete, restarting"));
Debug.flush();
}
delay(250);
ESP.restart();
return;
}
}
LittleFS.end();
yield();
if(config.hasConfig()) {
if(Debug.isActive(RemoteDebug::INFO)) config.print(&Debug);
WiFi_connect();
NtpConfig ntp;
if(config.getNtpConfig(ntp)) {
tz = resolveTimezone(ntp.timezone);
ws.setTimezone(tz);
ds.setTimezone(tz);
ea.setTimezone(tz);
}
ds.load();
} else {
if(Debug.isActive(RemoteDebug::INFO)) {
debugI_P(PSTR("No configuration, booting AP"));
}
swapWifiMode();
}
EnergyAccountingConfig *eac = new EnergyAccountingConfig();
if(!config.getEnergyAccountingConfig(*eac)) {
config.clearEnergyAccountingConfig(*eac);
config.setEnergyAccountingConfig(*eac);
config.ackEnergyAccountingChange();
}
ea.setup(&ds, eac);
ea.load();
ea.setEapi(eapi);
ws.setup(&config, &gpioConfig, &meterConfig, &meterState, &ds, &ea);
#if defined(ESP32)
esp_task_wdt_init(WDT_TIMEOUT, true);
esp_task_wdt_add(NULL);
#elif defined(ESP8266)
ESP.wdtEnable(WDT_TIMEOUT * 1000);
#endif
//EHorvat NES-MEP start ***********
// Wait for connection
previousMillis = millis();
// RS3232Enable(true); // EHorvat disabled this function (was turning on power to MAX3232 in dabbler.dk software)
// delay(1000); // EHorvat disabled this function
MEPEnable(true);
delay(500); // EHorvat was 1000
SerialEvent2();
InputBufferLength = 0;
// Get started by requesting the UTC Clock
queueRequest("300034",mep_key,MEPQueue,&MEPQueueNextIndex,None); // BT52: UTC Clock
//EHorvat NES-MEP end *******
} // ********** void setup END
//EHorvat NES-MEP SerialEvent2 start ***********
void SerialEvent2() {
while(Serial2.available() && InputBufferLength < MaxMEPReplyLength) {
InputBuffer[InputBufferLength] = (byte)Serial2.read();
InputBufferLength++;
LastReceiveMillis = millis();
}
} //EHorvat NES-MEP SerialEvent2 end *******
int buttonTimer = 0;
bool buttonActive = false;
unsigned long longPressTime = 2500; //EHorvat was 5000
bool longPressActive = false;
bool wifiConnected = false;
//unsigned long lastTemperatureRead = 0;
unsigned long lastSysupdate = 0;
unsigned long lastErrorBlink = 0;
int lastError = 0;
unsigned long lastMEPinfo = 0; //EHorvat new
bool meterAutodetect = false;
unsigned long meterAutodetectLastChange = 0;
uint8_t meterAutoIndex = 0;
uint32_t bauds[] = { 2400, 2400, 115200, 115200 };
uint8_t parities[] = { 11, 3, 3, 3 };
bool inverts[] = { false, false, false, true };
void loop() {
byte mep_keyByteArray[16] = {0}; //EHorvat for testing ASCII Key
unsigned long mep_keyByteArrayLen = 0; //EHorvat for testing ASCII Key
unsigned long now = millis();
unsigned long start = now;
Debug.handle();
unsigned long end = millis();
if(end - start > 1000) {
debugW_P(PSTR("Used %dms to handle debug"), millis()-start);
}
handleButton(now);
if(now > 10000 && now - lastErrorBlink > 3000) {
errorBlink();
}
/* EHorvat disabled this check
if(hwSerial != NULL) {
#if defined ESP8266
if(hwSerial->hasRxError()) {
debugE_P(PSTR("Serial RX error"));
meterState.setLastError(METER_ERROR_RX);
}
if(hwSerial->hasOverrun()) {
rxerr(2);
}
#endif
} else if(swSerial != NULL) {
if(swSerial->overflow()) {
rxerr(2);
}
}
*/ // EHorvat end
// Only do normal stuff if we're not booted as AP
if (WiFi.getMode() != WIFI_AP) {
if (WiFi.status() != WL_CONNECTED) {
wifiConnected = false;
Debug.stop();
WiFi_connect();
} else {
wifiReconnectCount = 0;
if(!wifiConnected) {
WiFi_post_connect();
}
if(config.isNtpChanged()) {
handleNtpChange();
}
#if defined ESP8266
if(mdnsEnabled) {
start = millis();
MDNS.update();
end = millis();
if(end - start > 1000) {
debugW_P(PSTR("Used %dms to update mDNS"), millis()-start);
}
}
#endif
if (mqttEnabled || config.isMqttChanged()) {
if(mqtt == NULL || !mqtt->connected() || config.isMqttChanged()) {
MQTT_connect();
config.ackMqttChange();
}
} else if(mqtt != NULL && mqtt->connected()) {
mqttClient->stop();
mqtt->disconnect();
}
try {
handlePriceApi(now);
} catch(const std::exception& e) {
debugE_P(PSTR("Exception in ENTSO-E loop (%s)"), e.what());
}
start = millis();
ws.loop();
end = millis();
if(end - start > 1000) {
debugW_P(PSTR("Used %dms to handle web"), millis()-start);
}
}
if(mqtt != NULL) {
start = millis();
mqtt->loop();
delay(10); // Needed to preserve power. After adding this, the voltage is super smooth on a HAN powered device
end = millis();
if(end - start > 1000) {
debugW_P(PSTR("Used %dms to handle mqtt"), millis()-start);
}
}
} else {
if(dnsServer != NULL) {
dnsServer->processNextRequest();
}
// Continously flash the LED when AP mode
if (now / 50 % 64 == 0) {
if(!hw.ledBlink(LED_YELLOW, 1)) {
hw.ledBlink(LED_INTERNAL, 1);
}
}
ws.loop();
}
if(config.isMeterChanged()) {
config.getMeterConfig(meterConfig);
setupHanPort(gpioConfig, meterConfig.baud, meterConfig.parity, meterConfig.invert);
config.ackMeterChanged();
if(gcmParser != NULL) {
delete gcmParser;
gcmParser = NULL;
}
}
if(config.isEnergyAccountingChanged()) {
handleEnergyAccountingChanged();
}
try {
//EHorvat (mep key stuff) start
if(now - lastMEPinfo > 30000) { //Show mep Key every 30 sec if debug is >= INFO
lastMEPinfo = now;
for(int i = 0; i < 20; i++) mep_key[i] = meterConfig.encryptionKey[i]; //EHorvat just copy hex key from cofig to mep_key
hexStringToBytes(ASCIIString2HexString(mep_key).substring(0,32), mep_keyByteArray, &mep_keyByteArrayLen); //EHorvat new
if(Debug.isActive(RemoteDebug::INFO)) //EHorvat send mep_key Info only at 1st send attemp
debugI("---- MEP key (only relevant first 16 positions in HEX) = %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X", //EHorvat new
mep_keyByteArray[0],mep_keyByteArray[1],mep_keyByteArray[2],mep_keyByteArray[3],mep_keyByteArray[4],
mep_keyByteArray[5],mep_keyByteArray[6],mep_keyByteArray[7],mep_keyByteArray[8],mep_keyByteArray[9],
mep_keyByteArray[10],mep_keyByteArray[11],mep_keyByteArray[12],mep_keyByteArray[13],mep_keyByteArray[14],
mep_keyByteArray[15]);
//EHorvat (mep key stuff) end
}
if (mep_data_ready_to_send) { //EHorvat NES-MEP added to check if it is time to get NES data via MEPport by running readHanPort()
mep_data_ready_to_send = false; //EHorvat NES-MEP
start = millis();
if(readHanPort() || now - meterState.getLastUpdateMillis() > 30000) {
end = millis();
if(end - start > 1000) {
debugW_P(PSTR("Used %dms to read HAN port (true)"), millis()-start);
}
// handleTemperature(now);
handleSystem(now);
} else {
end = millis();
if(end - start > 1000) {
debugW_P(PSTR("Used %dms to read HAN port (false)"), millis()-start);
}
}
// if(now - lastTemperatureRead > 15000) {
// unsigned long start = millis();
// if(hw.updateTemperatures()) {
// lastTemperatureRead = now;
//
// if(mqtt != NULL && mqttHandler != NULL && WiFi.getMode() != WIFI_AP && WiFi.status() == WL_CONNECTED && mqtt->connected() && !topic.isEmpty()) {
// mqttHandler->publishTemperatures(&config, &hw);
// }
// debugD("Used %ld ms to update temperature", millis()-start);
// }
// }
if(now - lastSysupdate > 20000) { //EHorvat was 60000
if(mqtt != NULL && mqttHandler != NULL && WiFi.getMode() != WIFI_AP && WiFi.status() == WL_CONNECTED && mqtt->connected() && !topic.isEmpty()) {
mqttHandler->publishSystem(&hw, eapi, &ea);
}
lastSysupdate = now;
}
} //EHorvat NES-MEP added
if(millis() - meterState.getLastUpdateMillis() > 1800000 && !ds.isHappy()) {
handleClear(now);
}
} catch(const std::exception& e) {
debugE_P(PSTR("Exception in readHanPort (%s)"), e.what());
meterState.setLastError(METER_ERROR_EXCEPTION);
}
try {
handleAutodetect(now);
} catch(const std::exception& e) {
debugE_P(PSTR("Exception in meter autodetect (%s)"), e.what());
meterState.setLastError(METER_ERROR_AUTODETECT);
}
delay(10); // Needed for auto modem sleep
start = millis();
#if defined(ESP32)
esp_task_wdt_reset();
#elif defined(ESP8266)
ESP.wdtFeed();
#endif
// yield(); // EHorvat disabled line
end = millis();
if(end-start > 1000) {
debugW_P(PSTR("Used %dms to feed WDT"), end-start);
}
if(end-now > 2000) {
debugW_P(PSTR("loop() used %dms"), end-now);
}
//
// EHorvat last_counter_value start
float price = ea.getPriceForHour(0);
if (price < 0.01) {
price = 0.1;
}
float consumption_to_last;
float costs_to_last;
uint32_t ImportCounter;
ImportCounter = meterState.getActiveImportCounter();
if (ImportCounter < 0) {
ImportCounter = 1;
}
consumption_to_last = ImportCounter - ea.getLast_Counter_Value() ;
if (consumption_to_last < 0) {
consumption_to_last = 0;
}
//consumption_to_last = 12345.678;
ea.setLast_Counter_Diff(uint32_t(consumption_to_last));
costs_to_last = consumption_to_last * price;
ea.setCostsLastCounterValue(costs_to_last);
//
// for Export
float refund = ea.getIncomeRefundForHour(0);
if (refund < 0.01) {
refund = 0.1;
}
float export_to_last;
float income_to_last;
uint32_t ExportCounter;
ExportCounter = meterState.getActiveExportCounter();
if (ExportCounter < 0) {
ExportCounter = 1;
}
export_to_last = ExportCounter - ea.getLast_expCounter_Value() ;
if (export_to_last < 0) {
export_to_last = 0;
}
//export_to_last = 2345.678;
ea.setLast_expCounter_Diff(uint32_t(export_to_last));
income_to_last = export_to_last * refund;
ea.setCostsLastexpCounterValue(income_to_last);
//
// EHorvat last_counter_value end
//
// ****************** EHorvat NES-MEP added start ******************
byte j;
if(millis()- mep_LastSentMillis > 2000) { // NES-MEP ..... send data at a 2000ms rate
mep_LastSentMillis = millis();
mep_data_ready = mep_alivecounter > mep_alivecounter_last; // mep_alivecounter is increased in NESMEP.cpp line 543 and 615 receiving Table 23 or 28 data
mep_data_ready_to_send = mep_data_ready;
mep_alivecounter_last = mep_alivecounter;
summ_60minplot = summ_60minplot + (ConsumptionData.BT28_Fwd_W - ConsumptionData.BT28_Rev_W); //EHorvat
index_60minplot++;
if(Debug.isActive(RemoteDebug::INFO)) debugI("++++++ EHo +++ Stations connected to AP: %i",WiFi.softAPgetStationNum());
}
if (mep_data_ready) {
mep_Last_ok_millis = millis(); // Timestamp to be used for HAN/MEP port timeout error indication
}
if(millis()- Last_hourplot_millis > 29850) { // EHorvat set hour plot data update rate of app 30s rate
Last_hourplot_millis = millis();
if (index_60minplot > 0) {
hour_plot_avg = summ_60minplot / index_60minplot;
ds.updateHour(hour_plot_avg); //EHorvat put data to new 60 Minute Plot array
index_60minplot = 0;
summ_60minplot = 0;
if(Debug.isActive(RemoteDebug::INFO)) debugI("+++++ millis: %i LastSent: %i +++ Hour Plot updateHour was done with: %d Watt\r\n", millis(), LastSentMillis, hour_plot_avg); //EHorvat new
}
}
// Check if a Client is connected to the AP , if no Client connected for 90 Sec --> swapWifiMode() should try STA Wifi
WiFiConfig wifi;
if ((WiFi.softAPgetStationNum() > 0) && (WiFi.getMode() == WIFI_AP)) {
Last_APClient_millis = millis(); //update timeout value if any connection is on AP and in AP mode
}
if (WiFi.getMode() != WIFI_AP) { //do not swapWifiMode() if on STA or autoreboot flag from GUI is off without || !wifi.autoreboot
Last_APClient_millis = millis();
}
if((WiFi.getMode() == WIFI_AP) && (millis() - Last_APClient_millis > 90000)) { // EHorvat check if no Client did connect to the AP in last 90 sec
Last_APClient_millis = millis();
if(Debug.isActive(RemoteDebug::INFO)) debugI("++++-----+++++-----++++++ No Clients where connected to AP in last 90 Seconds .... do a swapWifiMode");
swapWifiMode();
}
// Receiving packages from meter
// Timeout waiting for answer from meter
if(millis() < LastSentMillis) {
LastSentMillis = millis();
}
if(SentAwaitingReply) {
if(millis() - LastSentMillis > 10000) {
MEPEnable(false);
// delay(1000); // EHorvat disabled this function
// RS3232Enable(false); // EHorvat disabled this function
// Serial.printf("RS3232 reset 1/2. Dropping buffer with this contents:\r\n"); // EHorvat disabled this function
dumpByteArray(InputBuffer,InputBufferLength);
InputBufferLength = 0;
SentAwaitingReply = false;
// delay(1000);
// RS3232Enable(true);
delay(500); // EHorvat was 1000
MEPEnable(true);
delay(500); // EHorvat was 1000
SerialEvent2();
if(Debug.isActive(RemoteDebug::INFO)) debugI("RS3232 reset 2/2. Dropping buffer with this contents:");
// Serial.printf("RS3232 reset 2/2. Dropping buffer with this contents:\r\n"); //Disabled
dumpByteArray(InputBuffer,InputBufferLength);
InputBufferLength = 0;
}
}
SerialEvent2();
if(InputBufferLength > 0) {
if(PackageIsValid(InputBuffer,InputBufferLength)) {
HandleAlertSequence(InputBuffer,&InputBufferLength,mep_key,MEPQueue,&MEPQueueNextIndex);
if(InputBufferLength >= MaxMEPReplyLength) {
queueResponseWithNoRequest(InputBuffer,InputBufferLength,MEPQueue,&MEPQueueNextIndex);
// Serial.printf("Error: Input buffer overflow. InputBufferLength: %i Dropping buffer with this contents:\r\n",InputBufferLength); //EHorvat disabled
if(Debug.isActive(RemoteDebug::INFO)) debugI("Error: Input buffer overflow. InputBufferLength: %i Dropping buffer with this contents:",InputBufferLength); //EHorvat new
dumpByteArray(InputBuffer,InputBufferLength);
InputBufferLength = 0;
}
if(InputBufferLength > 0) {
if(!SentAwaitingReply) {
queueResponseWithNoRequest(InputBuffer,InputBufferLength,MEPQueue,&MEPQueueNextIndex);
// Serial.printf("Error: InputBufferLength: %i, got this reply from the meter, but did not expect one:\r\n",InputBufferLength); //EHorvat disabled
if(Debug.isActive(RemoteDebug::INFO)) debugI("Error: InputBufferLength: %i, got this reply from the meter, but did not expect one:",InputBufferLength); //EHorvat new
dumpByteArray(InputBuffer,InputBufferLength);
InputBufferLength = 0;
}
else {
if(Debug.isActive(RemoteDebug::INFO)) debugI("Received: %i, Bytes of Input",InputBufferLength); //EHorvat new test
ReceiveBytesString = bytesToHexString(InputBuffer,InputBufferLength,true); //EHorvat new
if(Debug.isActive(RemoteDebug::VERBOSE)) debugD("Received this in hex: %s \r\n", ReceiveBytesString.c_str()); //EHorvat new
MEPQueue[MEPQueueSendIndex].ReplyLength = GetPackageLength(InputBuffer);
memcpy(MEPQueue[MEPQueueSendIndex].Reply,InputBuffer,MEPQueue[MEPQueueSendIndex].ReplyLength);
memcpy(InputBuffer,InputBuffer+MEPQueue[MEPQueueSendIndex].ReplyLength,InputBufferLength-MEPQueue[MEPQueueSendIndex].ReplyLength);
InputBufferLength -= MEPQueue[MEPQueueSendIndex].ReplyLength;
HandleInvalidSequenceNumber(mep_key,MEPQueue,MEPQueueSendIndex,&MEPQueueNextIndex);
// Serial.printf("Saved request response at index %i\r\n",MEPQueueSendIndex); //EHorvat disabled
if(Debug.isActive(RemoteDebug::INFO)) debugI("Saved request response at index %i",MEPQueueSendIndex); //EHorvat new
if(!GetConfigurationRequestsSent) {
if(!FirstRequestOk) {// Read UTC clock is first request (queued in Setup)
FirstRequestOk = (MEPQueue[MEPQueueSendIndex].Reply[2] == 0x00);
if(Debug.isActive(RemoteDebug::VERBOSE)) debugD("Request response at index %i - Reply#0 to 2= %i %i %i ",
MEPQueueSendIndex, MEPQueue[MEPQueueSendIndex].Reply[0], MEPQueue[MEPQueueSendIndex].Reply[1], MEPQueue[MEPQueueSendIndex].Reply[2]); //EHorvat new
}
if(FirstRequestOk) {
// Read the meter configs we need to decode other requests
queueRequest("300001",mep_key,MEPQueue,&MEPQueueNextIndex,None); // BT01: General Manufacturer Information
queueRequest("300034",mep_key,MEPQueue,&MEPQueueNextIndex,None); // BT52: UTC Clock +++ EHorvat added
queueRequest("300015",mep_key,MEPQueue,&MEPQueueNextIndex,None); // BT21: Actual Register
queueRequest("300803",mep_key,MEPQueue,&MEPQueueNextIndex,None); // ET03: Utility Information
queueRequest("30080B",mep_key,MEPQueue,&MEPQueueNextIndex,None); // ET11: MFG Dimension Table
queueRequest("30080D",mep_key,MEPQueue,&MEPQueueNextIndex,None); // ET13: MEP/M-Bus Device Configuration
queueRequest("300832",mep_key,MEPQueue,&MEPQueueNextIndex,None); // ET50: MEP Inbound Data Space
GetConfigurationRequestsSent = true;
}
}
if(FirstRequestOk) ReplyData2String(MEPQueue,MEPQueueSendIndex,true);
HandleNextAction(mep_key,MEPQueue,MEPQueueSendIndex,&MEPQueueNextIndex);
SentAwaitingReply = false;
IncreaseMEPQueueIndex(&MEPQueueSendIndex);
}
}
}
else {
if((!SentAwaitingReply) && (millis()-LastReceiveMillis > 100)) {
// Serial.printf("Error: InputBufferLength: %i, got this garbage from the meter, but did not expect a package:\r\n",InputBufferLength); //EHorvat disabled
if(Debug.isActive(RemoteDebug::INFO)) debugI("Error: InputBufferLength: %i, got this garbage from the meter, but did not expect a package:",InputBufferLength); //EHorvat new
dumpByteArray(InputBuffer,InputBufferLength);
InputBufferLength = 0;
}
}
}
// Sending packages to meter
if(!SentAwaitingReply) {
j = 0;
while((MEPQueue[MEPQueueSendIndex].ReplyLength > 0) && (j <= MaxMEPBuffer)) { // (MEPQueue[MEPQueueSendIndex].RequestLength == 0) &&
IncreaseMEPQueueIndex(&MEPQueueSendIndex);
j++;
}
if((MEPQueue[MEPQueueSendIndex].RequestLength > 0) && (MEPQueue[MEPQueueSendIndex].ReplyLength == 0)) {
if(MEPQueue[MEPQueueSendIndex].SendAttempts >= MaxSendAttempts) {
// Serial.printf("Giving up on reqest at index %i - too may retries\r\n"); //EHorvat disabled
if(Debug.isActive(RemoteDebug::INFO)) debugI("Giving up on reqest at index %i - too may retries"); //EHorvat new
IncreaseMEPQueueIndex(&MEPQueueSendIndex);
}
else {
MEPQueue[MEPQueueSendIndex].SendAttempts++;
// Serial.printf("Transmitting request at index %i (attempt %i)\r\n",MEPQueueSendIndex,MEPQueue[MEPQueueSendIndex].SendAttempts);//EHorvat disabled
if(Debug.isActive(RemoteDebug::INFO)) debugI("Sending now request at index %i , this is attempt %i with a length of %i bytes",MEPQueueSendIndex,MEPQueue[MEPQueueSendIndex].SendAttempts,MEPQueue[MEPQueueSendIndex].RequestLength); //EHorvat new
for(unsigned long i = 0; i < MEPQueue[MEPQueueSendIndex].RequestLength; i++) { //EHorvat new
// if(Debug.isActive(RemoteDebug::VERBOSE)) debugD("This Requests bytes: %i %X",MEPQueue[MEPQueueSendIndex].Request[i],MEPQueue[MEPQueueSendIndex].Request[i]); //EHorvat new
}
RequestsBytesString = bytesToHexString(MEPQueue[MEPQueueSendIndex].Request,MEPQueue[MEPQueueSendIndex].RequestLength,true);
if(Debug.isActive(RemoteDebug::VERBOSE)) debugD("This Request in hex: %s \r\n", RequestsBytesString.c_str()); //EHorvat new
if(Debug.isActive(RemoteDebug::VERBOSE)) debugD(" \r\n"); //EHorvat new
for(unsigned long i = 0; i < MEPQueue[MEPQueueSendIndex].RequestLength; i++) {
Serial2.write((byte)MEPQueue[MEPQueueSendIndex].Request[i]);
}
LastSentMillis = millis();
SentAwaitingReply = true;
}
}
else {
if(millis()-LastSentMillis > 2000) { //EHorvat Nes-MEP was 5000
// Update consumption data
queueRequest("3F0017000000000D", mep_key, MEPQueue, &MEPQueueNextIndex, None); //EHorvat ... Fix table read BT23 for Gen4 meters....thanks to makerspace-reinach.ch
// for details check discussion here: https://github.com/orgs/OSGP-Alliance-MEP-and-Optical/discussions/18
// queueRequest("300017" + MaxMEPReplyLengthAsHex(),mep_key,MEPQueue,&MEPQueueNextIndex,None); //EHorvat ... this was Rev2.6 version ....changed now...seee above 2 lines
queueRequest("30001C" + MaxMEPReplyLengthAsHex(),mep_key,MEPQueue,&MEPQueueNextIndex,None);
// queueRequest("300803",mep_key,MEPQueue,&MEPQueueNextIndex,None); // ET03: Utility Information EHorvat added for testing
// queueRequest("300034",mep_key,MEPQueue,&MEPQueueNextIndex,None); // BT52: UTC Clock EHorvat added
// if(Debug.isActive(RemoteDebug::INFO)) debugI("---++++---- mep_key = %s", mep_key);
// hexStringToBytes(ASCIIString2HexString(mep_key).substring(0,32), mep_keyByteArray, &mep_keyByteArrayLen);
// if(Debug.isActive(RemoteDebug::INFO)) debugI("---- mep_key ByteArray (int) = %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d",
// mep_keyByteArray[0],mep_keyByteArray[1],mep_keyByteArray[2],mep_keyByteArray[3],mep_keyByteArray[4],
// mep_keyByteArray[5],mep_keyByteArray[6],mep_keyByteArray[7],mep_keyByteArray[8],mep_keyByteArray[9],
// mep_keyByteArray[10],mep_keyByteArray[11],mep_keyByteArray[12],mep_keyByteArray[13],mep_keyByteArray[14],
// mep_keyByteArray[15]);
// if(Debug.isActive(RemoteDebug::INFO)) debugI("---- mep_key ByteArray (hex) = %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X",
// mep_keyByteArray[0],mep_keyByteArray[1],mep_keyByteArray[2],mep_keyByteArray[3],mep_keyByteArray[4],
// mep_keyByteArray[5],mep_keyByteArray[6],mep_keyByteArray[7],mep_keyByteArray[8],mep_keyByteArray[9],
// mep_keyByteArray[10],mep_keyByteArray[11],mep_keyByteArray[12],mep_keyByteArray[13],mep_keyByteArray[14],
// mep_keyByteArray[15]);
if(Debug.isActive(RemoteDebug::INFO)) debugI("---- Read MEP Port ---- ++++++ actual Import Power: %d Watt", ConsumptionData.BT28_Fwd_W); // EHorvat NES-MEP
ds.updateMinute((ConsumptionData.BT28_Fwd_W - ConsumptionData.BT28_Rev_W)); //EHorvat put data to new Minute Plot array
}
}
}
ad.setfromNESMEP_0(mep_data_ready,mep_alivecounter);
//
ad.setfromNESMEP_1(ConsumptionData.BT28_Fwd_W,
ConsumptionData.BT23_Fwd_Act_Wh/1000.0,
ConsumptionData.BT28_Rev_W,
ConsumptionData.BT23_Rev_Act_Wh/1000.0,
ConsumptionData.BT28_Fwd_VA,
ConsumptionData.BT28_Rev_VA,
ConsumptionData.BT23_Fwd_React_Wh/1000.0,
ConsumptionData.BT23_Rev_React_Wh/1000.0,
ConsumptionData.BT28_Pwr_Factor_L1/1000.0,
ConsumptionData.BT28_Pwr_Factor_L2/1000.0,
ConsumptionData.BT28_Pwr_Factor_L3/1000.0,
ConsumptionData.BT28_VA_L1L2L3,
ConsumptionData.BT28_ReactivePower_Q1,
ConsumptionData.BT28_ReactivePower_Q2,
ConsumptionData.BT28_ReactivePower_Q3,
ConsumptionData.BT28_ReactivePower_Q4,
ConsumptionData.BT28_Freq_mHz/1000.0,
ConsumptionData.BT28_RMS_mV_L1/1000.0,
ConsumptionData.BT28_RMS_mV_L2/1000.0,
ConsumptionData.BT28_RMS_mV_L3/1000.0,
ConsumptionData.BT28_RMS_mA_L1/1000.0,
ConsumptionData.BT28_RMS_mA_L2/1000.0,
ConsumptionData.BT28_RMS_mA_L3/1000.0);
//
ad.setfromNESMEP_2(MeterInfo.BT01_Manufacturer,
MeterInfo.BT01_Model,
MeterInfo.BT01_MainHardwareVersionNumber,
MeterInfo.BT01_HardwareRevisionNumber,
MeterInfo.BT01_MainFirmwareVersionNumber,
MeterInfo.BT01_FirmwareRevisionNumber,
MeterInfo.ET03_UtilitySerialNumber);
//
// ****************** EHorvat NES-MEP end ******************
if(end-now > 1000) {
debugW_P(PSTR("loop() used %dms"), end-now);
}
} // ********* void loop() end *********^
void handleClear(unsigned long now) {
tmElements_t tm;
breakTime(time(nullptr), tm);
if(tm.Minute == 0) {
AmsData nullData;
debugI_P(PSTR("Clearing data that have not been updated"));
ds.update(&nullData);
}
}