/
readDSMR-logger.ino
395 lines (326 loc) · 11.7 KB
/
readDSMR-logger.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
/*
***************************************************************************
** Program : readDSMR-logger (DSMRloggerAPI)
**
** This program call's the DSMR-logger "actual" restAPI
** and presents the value of the fields.
*/
#define _FW_VERSION "v2.0 (20-09-2020)"
/*
** Copyright (c) 2020 Willem Aandewiel
**
** TERMS OF USE: MIT License. See bottom of file.
***************************************************************************
*/
//======= define type of board ===========
//==== only define one (1) board type ====
// #define _IS_ARDUINO_MEGA
// #define _IS_ESP8266
// #define _IS_ESP32
//========================================
//==== edit setup.h ======================
#include "setup.h"
//======= leave the rest unchanged =======
#if !defined(_IS_ARDUINO_MEGA) && !defined(_IS_ESP8266) && !defined(_IS_ESP32)
#error Select one (and only one) board -- abort
#endif
#ifdef _IS_ARDUINO_MEGA
#include <ArduinoHttpClient.h> // tested with version 0.4.0
#include <Ethernet.h>
#include <SPI.h>
#endif
#ifdef _IS_ESP8266
#include <ESP8266WiFi.h>
const char *ssid = _WIFI_SSID;
const char *password = _WIFI_PASSWRD;
#endif
#ifdef _IS_ESP32
#include <WiFi.h>
#include <HTTPClient.h>
const char *ssid = _WIFI_SSID;
const char *password = _WIFI_PASSWRD;
#endif
#include <Arduino_JSON.h> // install with Library Manager
#define _READINTERVAL 60000
const char *DSMRprotocol = "http://";
const char *DSMRserverIP = _DSMR_IP_ADDRESS;
const char *DSMRrestAPI = "/api/v1/sm/actual";
String payload;
int httpResponseCode;
uint32_t lastRead = 0;
//--- catch specific fields for further processing -------
//--- these are just an example! see readDsmrLogger() ----
String timeStamp;
int voltageL1, currentL1;
float pwrDelivered, pwrReturned;
#ifdef _IS_ARDUINO_MEGA
//--------------------------------------------------------------------------
// Include in the main program:
// #include <ArduinoHttpClient.h> // version 0.4.0
// #include <Ethernet.h>
// #include <SPI.h>
//
// and in Setup() do something like:
// // Initialize Ethernet library
// byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
//
// if (!Ethernet.begin(mac)) {
// Serial.println("Failed to configure Ethernet");
// return;
// }
// delay(1000);
//
//--------------------------------------------------------------------------
bool dsmrGETrequest()
{
EthernetClient ETHclient;
HttpClient DSMRclient = HttpClient(ETHclient, DSMRserverIP, 80);
payload = "";
Serial.println(F("making GET request"));
DSMRclient.get(DSMRrestAPI);
// read the response code and body of the response
httpResponseCode = DSMRclient.responseStatusCode();
Serial.print(F("http Response Code: "));
Serial.println(httpResponseCode);
if (httpResponseCode <= 0)
{
return false;
}
payload = DSMRclient.responseBody();
//--debug-Serial.print(F("payload: "));
//--debug-Serial.println(payload);
// Free resources
DSMRclient.stop();
return true;
} // dsmrGETrequest()
#endif
#ifdef _IS_ESP8266
//--------------------------------------------------------------------------
// Include in the main program:
// #include <ESP8266WiFi.h>
//--------------------------------------------------------------------------
bool dsmrGETrequest()
{
WiFiClient DSMRclient;
payload = "";
Serial.print("DSMRclient.connect("); Serial.print(DSMRserverIP);
Serial.println(", 80)");
if (!DSMRclient.connect(DSMRserverIP, 80))
{
Serial.println(F("error connecting to DSMRlogger "));
payload = "{\"actual\":[{\"name\":\"httpresponse\", \"value\":\"error connecting\"}]}";
return false;
}
//-- normal operation
DSMRclient.print(F("GET "));
DSMRclient.print(DSMRrestAPI);
DSMRclient.println(" HTTP/1.1");
DSMRclient.print(F("Host: "));
DSMRclient.println(DSMRserverIP);
DSMRclient.println(F("Connection: close"));
DSMRclient.println();
DSMRclient.setTimeout(1000);
//--debug-Serial.println("find(HTTP/1.1)..");
DSMRclient.find("HTTP/1.1"); // skip everything up-until "HTTP/1.1"
//--debug-Serial.print("DSMRclient.parseInt() ==> ");
httpResponseCode = DSMRclient.parseInt(); // parse status code
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
if (httpResponseCode <= 0)
{
payload = "{\"actual\":[{\"name\":\"httpresponse\", \"value\": "+String(httpResponseCode)+"}]}";
return false;
}
// Skip HTTP headers
if (!DSMRclient.find("\r\n\r\n"))
{
Serial.println(F("Invalid response"));
payload = "{\"actual\":[{\"name\":\"httpresponse\", \"value\": "+String(httpResponseCode)+"}]}";
return false;
}
while(DSMRclient.connected())
{
if (DSMRclient.available())
{
// read an incoming lines from the server:
String line = DSMRclient.readStringUntil('\r');
line.replace("\n", "");
if ( (line[0] == '{') || (line[0] == ',')
|| (line[0] == '[') || (line[0] == ']') )
{
//--debug-Serial.print(line);
payload += line;
}
}
}
//--debug-Serial.println();
// Free resources
DSMRclient.stop();
return true;
} // dsmrGETrequest()
#endif
#ifdef _IS_ESP32
//--------------------------------------------------------------------------
// Include in the main program:
// #include <WiFi.h>
// #include <HTTPClient.h>
//--------------------------------------------------------------------------
bool dsmrGETrequest()
{
HTTPClient DSMRclient;
// Your IP address with path or Domain name with URL path
DSMRclient.begin(String(DSMRprotocol) + String(DSMRserverIP)+String(DSMRrestAPI));
// Send HTTP GET request
httpResponseCode = DSMRclient.GET();
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = "";
if (httpResponseCode > 0)
{
payload = DSMRclient.getString();
}
else
{
payload = "{\"actual\":[{\"name\":\"httpresponse\", \"value\": "+String(httpResponseCode)+"}]}";
// Free resources
DSMRclient.end();
return false;
}
// Free resources
DSMRclient.end();
return true;
} // dsmrGETrequest()
#endif
//--------------------------------------------------------------------------
void readDsmrLogger()
{
int fieldNr = 0;
dsmrGETrequest();
Serial.println();
Serial.println(F("==== Start parsing payload ======================="));
// This is how the "actual" JSON object looks like:
// {"actual":[
// {"name":"timestamp","value":"200911140716S"}
// ,{"name":"energy_delivered_tariff1","value":3433.297,"unit":"kWh"}
// ,{"name":"energy_delivered_tariff2","value":4453.041,"unit":"kWh"}
// ,{"name":"energy_returned_tariff1","value":678.953,"unit":"kWh"}
// ...
// ,{"name":"power_delivered_l2","value":0.071,"unit":"kW"}
// ,{"name":"power_delivered_l3","value":0,"unit":"kW"}
// ,{"name":"power_returned_l1","value":0,"unit":"kW"}
// ,{"name":"power_returned_l2","value":0,"unit":"kW"}
// ,{"name":"power_returned_l3","value":0.722,"unit":"kW"}
// ,{"name":"gas_delivered","value":2915.08,"unit":"m3"}
// ]}
//--debug-Serial.print(F("payload: "));
//--debug-Serial.println(payload);
JSONVar dsmrJsonObject = JSON.parse(payload);
// JSON.typeof(jsonVar) can be used to get the type of the var
if (JSON.typeof(dsmrJsonObject) == "undefined")
{
Serial.println(F("Parsing failed!"));
return;
}
//--debug-Serial.print("JSON.typeof(dsmrJsonObject) = ");
//--debug-Serial.println(JSON.typeof(dsmrJsonObject)); // prints: array
JSONVar dsmrJsonField = dsmrJsonObject["actual"];
// dsmrJsonField.length() can be used to get the length of the array
//--debug-Serial.print("dsmrJsonField.length() = ");
//--debug-Serial.println(dsmrJsonField.length());
//--debug-Serial.println();
for (int i = 0; i < dsmrJsonField.length(); i++)
{
fieldNr++;
//--debug-Serial.print(dsmrJsonField[i]);
String sName = (const char *)dsmrJsonField[i]["name"];
String sValue = (const char *)dsmrJsonField[i]["value"];
if (sValue == "") sValue = String((double)dsmrJsonField[i]["value"]);
String sUnit = (const char *)dsmrJsonField[i]["unit"];
//---- list all fields and values ----
Serial.print(sName); Serial.print(" \t");
Serial.print(sValue); Serial.print(" ");
Serial.print(sUnit);
Serial.println();
//--- now catch some fields of interrest for further
//--- processing
//--- you need to declare the fields to be captured global
if (sName == "timestamp") timeStamp = sValue;
if (sName == "voltage_l1") voltageL1 = sValue.toInt();
if (sName == "current_l1") currentL1 = sValue.toInt();
if (sName == "power_delivered") pwrDelivered = sValue.toFloat();
if (sName == "power_returned") pwrReturned = sValue.toFloat();
}
Serial.println(F("=================================================="));
Serial.print(F("Parsed [")); Serial.print(fieldNr); Serial.println(F("] fields"));
} // readDsmrLogger()
//--------------------------------------------------------------------------
void setup()
{
Serial.begin(115200);
while(!Serial) { /* wait a bit */ }
Serial.println("");
Serial.println(F("And then it all begins ..."));
#ifdef _IS_ARDUINO_MEGA
// Initialize Ethernet library
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
if (!Ethernet.begin(mac))
{
Serial.println(F("Failed to configure Ethernet"));
return;
}
delay(1000);
#endif
#if defined(_IS_ESP8266) || defined(_IS_ESP32)
WiFi.begin(ssid, password);
Serial.println(F("Connecting"));
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print(F("Connected to WiFi network with IP Address: "));
Serial.println(WiFi.localIP());
#endif
lastRead = millis() + _READINTERVAL;
Serial.println(F("\r\nStart reading ..."));
} // setup()
//--------------------------------------------------------------------------
void loop()
{
if ((millis() - lastRead) > _READINTERVAL)
{
lastRead = millis();
Serial.println(F("\r\nread API from DSMR-logger..."));
readDsmrLogger();
Serial.println(F("\r\nCaptured fields .."));
Serial.print(F("timestamp : \t")); Serial.println(timeStamp);
Serial.print(F("voltage L1 : \t")); Serial.println(voltageL1);
Serial.print(F("current L1 : \t")); Serial.println(currentL1);
Serial.print(F("pwrDelivered : \t")); Serial.println(pwrDelivered);
Serial.print(F("pwrReturned : \t")); Serial.println(pwrReturned);
}
} // loop()
/*
****************************************************************************
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
****************************************************************************
*/