forked from Adeptive/Smappee-NodeJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmappee-api.js
472 lines (414 loc) · 15.7 KB
/
smappee-api.js
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
var http = require('http');
var request = require('request');
var querystring = require('querystring');
var moment = require('moment');
const fs = require('node:fs');
const mqtt = require('async-mqtt');
function SmappeeAPI(settings) {
var clientId = settings.clientId;
var clientSecret = settings.clientSecret;
var username = settings.username;
var password = settings.password;
var mqtt_server = settings.mqtt_server;
var mqtt_port = settings.mqtt_port;
var mqtt_baseTopic = settings.mqtt_baseTopic;
var mqtt_clientID = settings.mqtt_clientID || "smappee2pqtt" ;
var mqtt_protocol = settings.mqtt_protocol || "mqtt" ;
mqtt_protocol
this.noAPIcall = settings.noAPIcall || false;
this.debug = settings.debug || false;
var thisObject = this;
var accessToken = undefined;
this.AGGREGATION_TYPES = {
MINUTES: 1,
HOURLY: 2,
DAILY: 3,
MONTHLY: 4,
QUARTERLY: 5
};
// PUBLIC METHODS ++++++++++++++++++++++++++++++++++++++++
/**
* Get a list of all houses/installations on this account.
*
* See https://smappee.atlassian.net/wiki/display/DEVAPI/Get+Servicelocations
*
* @param handler function that will be called when request is completed.
*/
this.getServiceLocations = function(handler) {
_get('https://app1pub.smappee.net/dev/v3/servicelocation', {}, handler);
};
/**
* Get the details about 1 service location (list of appliances, list of actuators, ...).
*
* See https://smappee.atlassian.net/wiki/display/DEVAPI/Get+Servicelocation+Info
*
* @param serviceLocationId one of the ids from the getServiceLocations() request.
* @param handler function that will be called when request is completed.
*/
this.getServiceLocationInfo = function(serviceLocationId, handler) {
var url = 'https://app1pub.smappee.net/dev/v3/servicelocation/' + serviceLocationId + '/info';
_get(url, {}, handler);
};
/**
* Get a list of all consumptions for the specified period and interval.
*
* see https://smappee.atlassian.net/wiki/display/DEVAPI/Get+Consumption
*
* @param serviceLocationId serviceLocationId one of the ids from the getServiceLocations() request.
* @param aggregation one of the AGGREGATION TYPES to specify the periodically of the consumptions to return.
* @param from date in UTC milliseconds to start from
* @param to date in UTC milliseconds to end with
* @param handler function that will be called when request is completed.
*/
this.getConsumptions = function(serviceLocationId, aggregation, from, to, handler) {
var url = 'https://app1pub.smappee.net/dev/v3/servicelocation/' + serviceLocationId + '/consumption';
var fields = {
aggregation: aggregation,
from: from,
to: to
};
//_get(url, fields, handler);
_get(url, fields, function(output) {
try {
var strOutput = JSON.stringify(output);
if (thisObject.debug) {
console.log("getConsumptions output : "+ strOutput);
}
if (strOutput.length>0) {
if (thisObject.debug) {
console.log("publishing getConsumptions output to mqtt");
}
_publishMQTT(mqtt_baseTopic+"consumptions",JSON.stringify(output));
handler(output);
} else {
if (thisObject.debug) {
console.log("getConsumptions output null");
}
_publishMQTT(mqtt_baseTopic+"consumptions","no consumptions");
handler(undefined);
}
} catch (e) {
if (thisObject.debug) {
console.log("getConsumptions output null");
}
_publishMQTT(mqtt_baseTopic+"consumptions","no consumptions");
handler(undefined);
}
});
};
this.getLatestConsumption = function(serviceLocationId, handler) {
var url = 'https://app1pub.smappee.net/dev/v3/servicelocation/' + serviceLocationId + '/consumption';
var fields = {
aggregation: this.AGGREGATION_TYPES.MINUTES,
from: moment().subtract(20, 'minutes').utc().valueOf(),
to: moment().add(5, 'minutes').utc().valueOf()
};
_get(url, fields, function(output) {
try {
var strOutput = JSON.stringify(output.consumptions[output.consumptions.length - 1]);
if (thisObject.debug) {
console.log("getConsumptions output 1 : "+ JSON.stringify(output));
}
if (strOutput.length > 0) {
if (thisObject.debug) {
console.log("publishing getConsumptions output to mqtt");
}
_publishMQTT(mqtt_baseTopic+"consumptions",strOutput);
handler(output.consumptions[output.consumptions.length - 1]);
} else {
if (thisObject.debug) {
console.log("getConsumptions output is null");
}
console.log("getConsumptions avant publish ");
_publishMQTT(mqtt_baseTopic+"consumptions","no consumptions");
handler(undefined);
}
} catch (e) {
if (thisObject.debug) {
console.log("getConsumptions output null");
}
_publishMQTT(mqtt_baseTopic+"consumptions","no consumptions");
handler(undefined);
}
});
};
this.getMonthlyConsumptionsForLastYear = function(serviceLocationId, handler) {
var url = 'https://app1pub.smappee.net/dev/v3/servicelocation/' + serviceLocationId + '/consumption';
var fields = {
aggregation: this.AGGREGATION_TYPES.MONTHLY,
from: moment().subtract(1, 'year').utc().valueOf(),
to: moment().utc().valueOf()
};
_get(url, fields, handler);
};
this.getEvents = function(serviceLocationId, applianceId, from, to, maxNumber, handler) {
var url = 'https://app1pub.smappee.net/dev/v3/servicelocation/' + serviceLocationId + '/events';
var fields = {
applienceId: applianceId,
from: from,
to: to,
maxNumber: maxNumber || 10
};
_get(url, fields, handler);
};
this.turnActuatorOn = function(serviceLocationId, actuatorId, duration, handler) {
var url = 'https://app1pub.smappee.net/dev/v3/servicelocation/' + serviceLocationId + '/actuator/' + actuatorId + '/on';
_post(url, "{'duration': " + duration + "}", handler);
};
this.turnActuatorOff = function(serviceLocationId, actuatorId, duration, handler) {
var url = 'https://app1pub.smappee.net/dev/v3/servicelocation/' + serviceLocationId + '/actuator/' + actuatorId + '/off';
_post(url, "{'duration': " + duration + "}", handler);
};
this.getCurrentChargingSession = function(chargingStationSN, handler) {
var url = 'https://app1pub.smappee.net/dev/v3/chargingstations/' + chargingStationSN + '/sessions';
if (thisObject.debug) {
console.log("getCurrentChargingSession url : "+ url);
}
var fields = {
active: true,
range:"1635721200000"
};
_get(url, fields, function(output) {
try {
var strOutput = JSON.stringify(output);
if (strOutput.length>0 && strOutput!="[]") {
var apiResponse = strOutput;
if (apiResponse.startsWith("[")){
apiResponse = apiResponse.substring(1, apiResponse.length-1);//remove invalid [ ] around response
}
let timestampNow = Date.now();
var timestampNowSeconds = timestampNow/1000;
apiResponse=apiResponse.substring(0, apiResponse.length-1);
apiResponse+=",\"timestamp\":"+timestampNowSeconds.toString()+"}";
if (thisObject.debug) {
console.log("apiResponse with timestamp : "+ apiResponse);
}
_publishMQTT(mqtt_baseTopic+"currentChargingSession",apiResponse);
handler(apiResponse);
} else {
_publishMQTT(mqtt_baseTopic+"currentChargingSession","{\"id\":-1}");
handler(undefined);
}
} catch (e) {
_publishMQTT(mqtt_baseTopic+"currentChargingSession","{\"id\":-1}");
handler(undefined);
}
});
};
// HELPER METHODS ++++++++++++++++++++++++++++++++++++++++
var _getAccessToken = function(handler) {
var tokenFile = null;
var existingToken = null;
let timestampNow = Date.now();
var timestampNowSeconds = timestampNow/1000;
//Try to read Access token from file
if (fs.existsSync('./token.json') && fs.existsSync('./tokenBirth.txt')) {
tokenFile=fs.readFileSync('./token.json');
existingToken = JSON.parse(tokenFile);
if (thisObject.debug) {
console.log("Existing Token found : "+tokenFile);
}
var tokenBirth=fs.readFileSync('./tokenBirth.txt');
var tokenDeath = Number(tokenBirth)+existingToken.expires_in-60; //token death with 60sec threshold
if (tokenDeath<timestampNowSeconds){
//Token expired or less than 60 secs remaining; try to Refresh Token
if (thisObject.debug) {
console.log("Token expired : "+tokenDeath);
console.log("Time is now : "+timestampNowSeconds);
console.log("Making oAuth call with refresh token : "+existingToken.refresh_token);
}
var body = {
client_id: clientId,
client_secret: clientSecret,
refresh_token: existingToken.refresh_token,
grant_type: 'refresh_token'
};
var options = {
url: 'https://app1pub.smappee.net/dev/v3/oauth2/token',
headers: {
'Host': 'app1pub.smappee.net'
},
form: body
};
request.post(options, function (err, httpResponse, body) {
if (err) {
return console.error('Request failed:', err);
}
if (thisObject.debug) {
//console.log('Server responded with:', body);
}
accessToken = JSON.parse(body);
fs.writeFileSync('./token.json', body, err => {
if (err) {
console.error('Could not save token to file', err);
}
});
fs.writeFileSync('./tokenBirth.txt', timestampNowSeconds.toString(), err => {
if (err) {
console.error('Could not save token birth to file', err);
}
});
});
} else {
//Using existing Token from file
accessToken=existingToken;
}
}
if (accessToken==null){
//Still got no Token, requesting a new one
var body = {
client_id: clientId,
client_secret: clientSecret,
username: username,
password: password,
grant_type: 'password'
};
if (thisObject.debug) {
console.log("Making oAuth call...");
}
var options = {
url: 'https://app1pub.smappee.net/dev/v3/oauth2/token',
headers: {
'Host': 'app1pub.smappee.net'
},
form: body
};
request.post(options, function (err, httpResponse, body) {
if (err) {
return console.error('Request failed:', err);
}
if (thisObject.debug) {
//console.log('Server responded with:', body);
}
accessToken = JSON.parse(body);
fs.writeFileSync('./token.json', body, err => {
if (err) {
console.error('Could not save token to file', err);
}
});
fs.writeFileSync('./tokenBirth.txt', timestampNowSeconds.toString(), err => {
if (err) {
console.error('Could not save token birth to file', err);
}
});
});
}
if (accessToken!=null){
handler(accessToken);
} else {
return console.error('Could not get valid token');
}
};
var _post = function(url, fields, handler) {
_getAccessToken(function(accessToken) {
if (thisObject.debug) {
console.log("Request to " + url);
console.log("With parameters: " + fields);
}
var options = {
url: url,
headers: {
'Authorization': 'Bearer ' + accessToken.access_token
},
body: fields
};
request.post(options, function (err, httpResponse, body) {
if (err) {
return console.error('Request failed:', err);
}
if (thisObject.debug) {
//console.log('Server responded with:', body);
}
handler({status: 'OK'});
}); //end of POST request
}); //end of access token request
};
var _get = function(url, fields, handler) {
if (thisObject.noAPIcall){
console.log('Did not call API as noAPIcall is true');
handler();
} else {
_getAccessToken(function(accessToken) {
var query = querystring.stringify(fields);
if (thisObject.debug) {
console.log("Request to " + url);
console.log("With parameters: " + query);
}
var options = {
url: url + "?" + query,
headers: {
'Authorization': 'Bearer ' + accessToken.access_token
}
};
request.get(options, function (err, httpResponse, body) {
if (err) {
return console.error('Request failed:', err);
}
if (thisObject.debug) {
//console.log('Server responded with:', body);
}
var output = JSON.parse(body);
handler(output);
}); //end of GET request
}); //end of access token request
}
};
//var _publishMQTT = function(topic, value){
async function _publishMQTT(topic, value){
const options = {
protocol: mqtt_protocol,
host: mqtt_server,
port: mqtt_port,
clientId: mqtt_clientID
};
if (thisObject.debug) {
console.log('Connecting to mqtt : ',mqtt_server,":",mqtt_port);
}
try {
//const client = mqtt.connect(options);
const client = await mqtt.connect(options);
if (thisObject.debug) {
console.log('After connection attempt ',client.connected);
}
client.on('offline', () => {
console.log('Client is offline');
});
client.on('reconnect', () => {
console.log('Reconnecting to MQTT broker');
});
client.on('close', () => {
console.log('Client MQTT received closed event');
});
client.on('disconnect', () => {
console.log('Client MQTT received closed event');
});
client.on('error', (err) => {
console.log('MQTT error: ',err);
});
client.on('end', () => {
console.log('Connection to MQTT broker ended');
process.exit();
});
console.log('Connected to MQTT broker');
await client.publish(topic, value, { retain: true }, (err) => {
if (thisObject.debug) {
console.log('Publishing to mqtt');
}
if (err) {
console.error('Failed to publish message: ', err);
} else {
if (thisObject.debug) {
console.log('Message published with retain flag set to true');
}
client.end();
}
});
client.end();
} catch (e){
// Do something about it!
console.log(e.stack);
process.exit();
}
}
}
module.exports = SmappeeAPI;