forked from fliphess/esp8266_p1meter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
esp8266_p1meter.ino
663 lines (550 loc) · 19.3 KB
/
esp8266_p1meter.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
#include <FS.h>
#include <EEPROM.h>
// * #include <DNSServer.h>
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <WiFiManager.h>
#include <ESP8266mDNS.h>
// * #include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <PubSubClient.h>
#include <SoftwareSerial.h>
// * Include settings
#include "settings.h"
// * Initiate led blinker library
Ticker ticker;
// * Initiate WIFI client
WiFiClient espClient;
// * Initiate MQTT client
PubSubClient mqtt_client(espClient);
// * Initiate Software Serial
SoftwareSerial p1_serial(P1_SERIAL_RX, -1, true); // (RX, TX. inverted)
// **********************************
// * WIFI *
// **********************************
// * Gets called when WiFiManager enters configuration mode
void configModeCallback(WiFiManager *myWiFiManager)
{
Serial.println(F("Entered config mode"));
Serial.println(WiFi.softAPIP());
// * If you used auto generated SSID, print it
Serial.println(myWiFiManager->getConfigPortalSSID());
// * Entered config mode, make led toggle faster
ticker.attach(0.2, tick);
}
// **********************************
// * Ticker (System LED Blinker) *
// **********************************
// * Blink on-board Led
void tick()
{
// * Toggle state
int state = digitalRead(LED_BUILTIN); // * Get the current state of GPIO1 pin
digitalWrite(LED_BUILTIN, !state); // * Set pin to the opposite state
}
// **********************************
// * MQTT *
// **********************************
// * Send a message to a broker topic
void send_mqtt_message(const char *topic, char *payload)
{
Serial.printf("MQTT Outgoing on %s: ", topic);
Serial.println(payload);
bool result = mqtt_client.publish(topic, payload, false);
if (!result)
{
Serial.printf("MQTT publish to topic %s failed\n", topic);
}
}
// * Reconnect to MQTT server and subscribe to in and out topics
bool mqtt_reconnect()
{
// * Loop until we're reconnected
int MQTT_RECONNECT_RETRIES = 0;
while (!mqtt_client.connected() && MQTT_RECONNECT_RETRIES < MQTT_MAX_RECONNECT_TRIES)
{
MQTT_RECONNECT_RETRIES++;
Serial.printf("MQTT connection attempt %d / %d ...\n", MQTT_RECONNECT_RETRIES, MQTT_MAX_RECONNECT_TRIES);
// * Attempt to connect
if (mqtt_client.connect(HOSTNAME, MQTT_USER, MQTT_PASS))
{
Serial.println(F("MQTT connected!"));
// * Once connected, publish an announcement...
char *message = new char[16 + strlen(HOSTNAME) + 1];
strcpy(message, "p1 meter alive: ");
strcat(message, HOSTNAME);
mqtt_client.publish("hass/status", message);
Serial.printf("MQTT root topic: %s\n", MQTT_ROOT_TOPIC);
}
else
{
Serial.print(F("MQTT Connection failed: rc="));
Serial.println(mqtt_client.state());
Serial.println(F(" Retrying in 5 seconds"));
Serial.println("");
// * Wait 5 seconds before retrying
delay(5000);
}
}
if (MQTT_RECONNECT_RETRIES >= MQTT_MAX_RECONNECT_TRIES)
{
Serial.printf("*** MQTT connection failed, giving up after %d tries ...\n", MQTT_RECONNECT_RETRIES);
return false;
}
return true;
}
void send_metric(String name, long metric)
{
Serial.print(F("Sending metric to broker: "));
Serial.print(name);
Serial.print(F("="));
Serial.println(metric);
char output[10];
ltoa(metric, output, sizeof(output));
String topic = String(MQTT_ROOT_TOPIC) + "/" + name;
send_mqtt_message(topic.c_str(), output);
}
void send_data_to_broker()
{
send_metric("consumption_low_tarif", CONSUMPTION_LOW_TARIF);
send_metric("delivery_low_tarif", DELIVERY_LOW_TARIF);
send_metric("consumption_high_tarif", CONSUMPTION_HIGH_TARIF);
send_metric("delivery_high_tarif", DELIVERY_HIGH_TARIF);
send_metric("actual_consumption", ACTUAL_CONSUMPTION);
send_metric("actual_delivery", ACTUAL_DELIVERY);
send_metric("instant_power_usage", INSTANT_POWER_USAGE);
send_metric("l1_instant_power_current", L1_INSTANT_POWER_CURRENT);
send_metric("l2_instant_power_current", L2_INSTANT_POWER_CURRENT);
send_metric("l3_instant_power_current", L3_INSTANT_POWER_CURRENT);
send_metric("gas_meter_m3", GAS_METER_M3);
send_metric("l1_voltage", L1_VOLTAGE);
send_metric("l2_voltage", L2_VOLTAGE);
send_metric("l3_voltage", L3_VOLTAGE);
send_metric("actual_tarif_group", ACTUAL_TARIF);
send_metric("short_power_outages", SHORT_POWER_OUTAGES);
send_metric("long_power_outages", LONG_POWER_OUTAGES);
send_metric("short_power_drops", SHORT_POWER_DROPS);
send_metric("short_power_peaks", SHORT_POWER_PEAKS);
}
// **********************************
// * P1 *
// **********************************
unsigned int CRC16(unsigned int crc, unsigned char *buf, int len)
{
for (int pos = 0; pos < len; pos++)
{
crc ^= (unsigned int)buf[pos]; // * XOR byte into least sig. byte of crc
// * Loop over each bit
for (int i = 8; i != 0; i--)
{
// * If the LSB is set
if ((crc & 0x0001) != 0)
{
// * Shift right and XOR 0xA001
crc >>= 1;
crc ^= 0xA001;
}
// * Else LSB is not set
else
// * Just shift right
crc >>= 1;
}
}
return crc;
}
bool isNumber(char *res, int len)
{
for (int i = 0; i < len; i++)
{
if (((res[i] < '0') || (res[i] > '9')) && (res[i] != '.' && res[i] != 0))
return false;
}
return true;
}
int FindCharInArrayRev(char array[], char c, int len)
{
for (int i = len - 1; i >= 0; i--)
{
if (array[i] == c)
return i;
}
return -1;
}
long getValue(char *buffer, int maxlen, char startchar, char endchar)
{
int s = FindCharInArrayRev(buffer, startchar, maxlen - 2);
int l = FindCharInArrayRev(buffer, endchar, maxlen - 2) - s - 1;
char res[16];
memset(res, 0, sizeof(res));
if (strncpy(res, buffer + s + 1, l))
{
if (endchar == '*')
{
if (isNumber(res, l))
// * Lazy convert float to long
return (1000 * atof(res));
}
else if (endchar == ')')
{
if (isNumber(res, l))
return atof(res);
}
}
return 0;
}
bool decode_telegram(int len)
{
int startChar = FindCharInArrayRev(telegram, '/', len);
int endChar = FindCharInArrayRev(telegram, '!', len);
bool validCRCFound = false;
for (int cnt = 0; cnt < len; cnt++)
Serial.print(telegram[cnt]);
if (startChar >= 0)
{
// * Start found. Reset CRC calculation
currentCRC = CRC16(0x0000,(unsigned char *) telegram+startChar, len-startChar);
}
else if (endChar >= 0)
{
// * Add to crc calc
currentCRC = CRC16(currentCRC,(unsigned char*)telegram+endChar, 1);
char messageCRC[5];
strncpy(messageCRC, telegram + endChar + 1, 4);
messageCRC[4] = 0; // * Thanks to HarmOtten (issue 5)
validCRCFound = (strtol(messageCRC, NULL, 16) == currentCRC);
if (validCRCFound)
Serial.println(F("CRC Valid!"));
else
Serial.println(F("CRC Invalid!"));
currentCRC = 0;
}
else
{
currentCRC = CRC16(currentCRC, (unsigned char*) telegram, len);
}
// 1-0:1.8.1(000992.992*kWh)
// 1-0:1.8.1 = Elektra verbruik laag tarief (DSMR v4.0)
// 1-0:2.8.1 = Elektra opbrengst laag tarief (DSMR v4.0)
if (strncmp(telegram, "1-0:1.8.1", strlen("1-0:1.8.1")) == 0)
{
CONSUMPTION_LOW_TARIF = getValue(telegram, len, '(', '*');
}
if (strncmp(telegram, "1-0:2.8.1", strlen("1-0:2.8.1")) == 0)
{
DELIVERY_LOW_TARIF = getValue(telegram, len, '(', '*');
}
// 1-0:1.8.2(000560.157*kWh)
// 1-0:1.8.2 = Elektra verbruik hoog tarief (DSMR v4.0)
// 1-0:2.8.2 = Elektra opbrengst hoog tarief (DSMR v4.0)
if (strncmp(telegram, "1-0:1.8.2", strlen("1-0:1.8.2")) == 0)
{
CONSUMPTION_HIGH_TARIF = getValue(telegram, len, '(', '*');
}
if (strncmp(telegram, "1-0:2.8.2", strlen("1-0:2.8.2")) == 0)
{
DELIVERY_HIGH_TARIF = getValue(telegram, len, '(', '*');
}
// 1-0:1.7.0(00.424*kW) Actueel verbruik
// 1-0:2.7.0(00.000*kW) Actuele teruglevering
// 1-0:1.7.x = Electricity consumption actual usage (DSMR v4.0)
if (strncmp(telegram, "1-0:1.7.0", strlen("1-0:1.7.0")) == 0)
{
ACTUAL_CONSUMPTION = getValue(telegram, len, '(', '*');
}
if (strncmp(telegram, "1-0:2.7.0", strlen("1-0:2.7.0")) == 0)
{
ACTUAL_DELIVERY = getValue(telegram, len, '(', '*');
}
// 1-0:21.7.0(00.378*kW)
// 1-0:21.7.0 = Instantaan vermogen Elektriciteit levering
if (strncmp(telegram, "1-0:21.7.0", strlen("1-0:21.7.0")) == 0)
{
INSTANT_POWER_USAGE = getValue(telegram, len, '(', '*');
}
// 1-0:31.7.0(002*A)
// 1-0:31.7.0 = Instantane stroom Elektriciteit L1
if (strncmp(telegram, "1-0:31.7.0", strlen("1-0:31.7.0")) == 0)
{
L1_INSTANT_POWER_CURRENT = getValue(telegram, len, '(', '*');
}
// 1-0:51.7.0(002*A)
// 1-0:51.7.0 = Instantane stroom Elektriciteit L2
if (strncmp(telegram, "1-0:51.7.0", strlen("1-0:51.7.0")) == 0)
{
L2_INSTANT_POWER_CURRENT = getValue(telegram, len, '(', '*');
}
// 1-0:71.7.0(002*A)
// 1-0:71.7.0 = Instantane stroom Elektriciteit L3
if (strncmp(telegram, "1-0:71.7.0", strlen("1-0:71.7.0")) == 0)
{
L3_INSTANT_POWER_CURRENT = getValue(telegram, len, '(', '*');
}
// 0-1:24.2.1(150531200000S)(00811.923*m3)
// 0-1:24.2.1 = Gas (DSMR v4.0) on Kaifa MA105 meter
if (strncmp(telegram, "0-1:24.2.1", strlen("0-1:24.2.1")) == 0)
{
GAS_METER_M3 = getValue(telegram, len, '(', '*');
}
// 1-0:32.7.0(229.0*V)
// 1-0:32.7.0 = L1 Voltage
if (strncmp(telegram, "1-0:32.7.0", strlen("1-0:32.7.0")) == 0)
{
L1_VOLTAGE = getValue(telegram, len, '(', ')');
}
// 1-0:52.7.0(226.0*V)
// 1-0:52.7.0 = L2 Voltage
if (strncmp(telegram, "1-0:52.7.0", strlen("1-0:52.7.0")) == 0)
{
L2_VOLTAGE = getValue(telegram, len, '(', ')');
}
// 1-0:72.7.0(229.0*V)
// 1-0:72.7.0 = L3 Voltage
if (strncmp(telegram, "1-0:72.7.0", strlen("1-0:72.7.0")) == 0)
{
L3_VOLTAGE = getValue(telegram, len, '(', ')');
}
// 0-0:96.14.0(0001)
// 0-0:96.14.0 = Actual Tarif
if (strncmp(telegram, "0-0:96.14.0", strlen("0-0:96.14.0")) == 0)
{
ACTUAL_TARIF = getValue(telegram, len, '(', ')');
}
// 0-0:96.7.21(00003)
// 0-0:96.7.21 = Aantal onderbrekingen Elektriciteit
if (strncmp(telegram, "0-0:96.7.21", strlen("0-0:96.7.21")) == 0)
{
SHORT_POWER_OUTAGES = getValue(telegram, len, '(', ')');
}
// 0-0:96.7.9(00001)
// 0-0:96.7.9 = Aantal lange onderbrekingen Elektriciteit
if (strncmp(telegram, "0-0:96.7.9", strlen("0-0:96.7.9")) == 0)
{
LONG_POWER_OUTAGES = getValue(telegram, len, '(', ')');
}
// 1-0:32.32.0(00000)
// 1-0:32.32.0 = Aantal korte spanningsdalingen Elektriciteit in fase 1
if (strncmp(telegram, "1-0:32.32.0", strlen("1-0:32.32.0")) == 0)
{
SHORT_POWER_DROPS = getValue(telegram, len, '(', ')');
}
// 1-0:32.36.0(00000)
// 1-0:32.36.0 = Aantal korte spanningsstijgingen Elektriciteit in fase 1
if (strncmp(telegram, "1-0:32.36.0", strlen("1-0:32.36.0")) == 0)
{
SHORT_POWER_PEAKS = getValue(telegram, len, '(', ')');
}
return validCRCFound;
}
void read_p1_serial()
{
if (p1_serial.available())
{
memset(telegram, 0, sizeof(telegram));
while (p1_serial.available())
{
ESP.wdtDisable();
int len = p1_serial.readBytesUntil('\n', telegram, P1_MAXLINELENGTH);
ESP.wdtEnable(1);
telegram[len] = '\n';
telegram[len + 1] = 0;
yield();
bool result = decode_telegram(len + 1);
if (result)
send_data_to_broker();
}
}
}
// **********************************
// * EEPROM helpers *
// **********************************
String read_eeprom(int offset, int len)
{
Serial.print(F("read_eeprom()"));
String res = "";
for (int i = 0; i < len; ++i)
{
res += char(EEPROM.read(i + offset));
}
return res;
}
void write_eeprom(int offset, int len, String value)
{
Serial.println(F("write_eeprom()"));
for (int i = 0; i < len; ++i)
{
if ((unsigned)i < value.length())
{
EEPROM.write(i + offset, value[i]);
}
else
{
EEPROM.write(i + offset, 0);
}
}
}
// ******************************************
// * Callback for saving WIFI config *
// ******************************************
bool shouldSaveConfig = false;
// * Callback notifying us of the need to save config
void save_wifi_config_callback ()
{
Serial.println(F("Should save config"));
shouldSaveConfig = true;
}
// **********************************
// * Setup OTA *
// **********************************
void setup_ota()
{
Serial.println(F("Arduino OTA activated."));
// * Port defaults to 8266
ArduinoOTA.setPort(8266);
// * Set hostname for OTA
ArduinoOTA.setHostname(HOSTNAME);
ArduinoOTA.setPassword(OTA_PASSWORD);
ArduinoOTA.onStart([]()
{
Serial.println(F("Arduino OTA: Start"));
});
ArduinoOTA.onEnd([]()
{
Serial.println(F("Arduino OTA: End (Running reboot)"));
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total)
{
Serial.printf("Arduino OTA Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error)
{
Serial.printf("Arduino OTA Error[%u]: ", error);
if (error == OTA_AUTH_ERROR)
Serial.println(F("Arduino OTA: Auth Failed"));
else if (error == OTA_BEGIN_ERROR)
Serial.println(F("Arduino OTA: Begin Failed"));
else if (error == OTA_CONNECT_ERROR)
Serial.println(F("Arduino OTA: Connect Failed"));
else if (error == OTA_RECEIVE_ERROR)
Serial.println(F("Arduino OTA: Receive Failed"));
else if (error == OTA_END_ERROR)
Serial.println(F("Arduino OTA: End Failed"));
});
ArduinoOTA.begin();
Serial.println(F("Arduino OTA finished"));
}
// **********************************
// * Setup MDNS discovery service *
// **********************************
void setup_mdns()
{
Serial.println(F("Starting MDNS responder service"));
bool mdns_result = MDNS.begin(HOSTNAME);
if (mdns_result)
{
MDNS.addService("http", "tcp", 80);
}
}
// **********************************
// * Setup Main *
// **********************************
void setup()
{
// * Configure Serial and EEPROM
Serial.begin(BAUD_RATE);
EEPROM.begin(512);
// * Set led pin as output
pinMode(LED_BUILTIN, OUTPUT);
// * Start ticker with 0.5 because we start in AP mode and try to connect
ticker.attach(0.6, tick);
// * Start software serial for p1 meter
p1_serial.begin(BAUD_RATE);
// * Get MQTT Server settings
String settings_available = read_eeprom(134, 1);
if (settings_available == "1")
{
read_eeprom(0, 64).toCharArray(MQTT_HOST, 64); // * 0-63
read_eeprom(64, 6).toCharArray(MQTT_PORT, 6); // * 64-69
read_eeprom(70, 32).toCharArray(MQTT_USER, 32); // * 70-101
read_eeprom(102, 32).toCharArray(MQTT_PASS, 32); // * 102-133
}
WiFiManagerParameter CUSTOM_MQTT_HOST("host", "MQTT hostname", MQTT_HOST, 64);
WiFiManagerParameter CUSTOM_MQTT_PORT("port", "MQTT port", MQTT_PORT, 6);
WiFiManagerParameter CUSTOM_MQTT_USER("user", "MQTT user", MQTT_USER, 32);
WiFiManagerParameter CUSTOM_MQTT_PASS("pass", "MQTT pass", MQTT_PASS, 32);
// * WiFiManager local initialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
// * Reset settings - uncomment for testing
// wifiManager.resetSettings();
// * Set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
wifiManager.setAPCallback(configModeCallback);
// * Set timeout
wifiManager.setConfigPortalTimeout(WIFI_TIMEOUT);
// * Set save config callback
wifiManager.setSaveConfigCallback(save_wifi_config_callback);
// * Add all your parameters here
wifiManager.addParameter(&CUSTOM_MQTT_HOST);
wifiManager.addParameter(&CUSTOM_MQTT_PORT);
wifiManager.addParameter(&CUSTOM_MQTT_USER);
wifiManager.addParameter(&CUSTOM_MQTT_PASS);
// * Fetches SSID and pass and tries to connect
// * Reset when no connection after 10 seconds
if (!wifiManager.autoConnect())
{
Serial.println(F("Failed to connect to WIFI and hit timeout"));
// * Reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(WIFI_TIMEOUT);
}
// * Read updated parameters
strcpy(MQTT_HOST, CUSTOM_MQTT_HOST.getValue());
strcpy(MQTT_PORT, CUSTOM_MQTT_PORT.getValue());
strcpy(MQTT_USER, CUSTOM_MQTT_USER.getValue());
strcpy(MQTT_PASS, CUSTOM_MQTT_PASS.getValue());
// * Save the custom parameters to FS
if (shouldSaveConfig)
{
Serial.println(F("Saving WiFiManager config"));
write_eeprom(0, 64, MQTT_HOST); // * 0-63
write_eeprom(64, 6, MQTT_PORT); // * 64-69
write_eeprom(70, 32, MQTT_USER); // * 70-101
write_eeprom(102, 32, MQTT_PASS); // * 102-133
write_eeprom(134, 1, "1"); // * 134 --> always "1"
EEPROM.commit();
}
// * If you get here you have connected to the WiFi
Serial.println(F("Connected to WIFI..."));
// * Keep LED on
ticker.detach();
digitalWrite(LED_BUILTIN, LOW);
// * Configure OTA
setup_ota();
// * Startup MDNS Service
setup_mdns();
// * Setup MQTT
Serial.printf("MQTT connecting to: %s:%s\n", MQTT_HOST, MQTT_PORT);
mqtt_client.setServer(MQTT_HOST, atoi(MQTT_PORT));
}
// **********************************
// * Loop *
// **********************************
void loop()
{
ArduinoOTA.handle();
if (!mqtt_client.connected())
{
long now = millis();
if (now - LAST_RECONNECT_ATTEMPT > 5000)
{
LAST_RECONNECT_ATTEMPT = now;
if (mqtt_reconnect())
{
LAST_RECONNECT_ATTEMPT = 0;
}
}
}
else
{
mqtt_client.loop();
}
read_p1_serial();
}