forked from MichMich/MMM-Toon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToonAPI.js
More file actions
349 lines (293 loc) · 10.8 KB
/
Copy pathToonAPI.js
File metadata and controls
349 lines (293 loc) · 10.8 KB
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
let http = require('http');
let https = require('https');
let querystring = require('querystring');
let extend = require('util')._extend;
let ToonAPI = (function () {
let self = this;
// Private Properties
let HOST = 'api.toon.eu';
let API = '/toon/v3/';
let PORT = 443;
let APIKEY = null;
let APISECRET = null;
let ACCESSTOKEN = null;
let X_COMMONNAME = null;
let X_AGREEMENT_ID = null;
let agreementSet = false;
let status = {updated: false};
/**
* makeRequest
* Makes a request to the Toon API server. It can be used for both the API requests as well as the oAuth requests.
* @param {Object} options request options.
*/
/**
* makeRequest
* Makes a request to the Toon API server. It can be used for both the API requests as well as the oAuth requests.
* @param {Object} options request options.
*/
function makeRequest(options) {
if (!APIKEY || !APISECRET) {
console.error('You haven\'t supplied the application with the needed APIKEY or APISECRET credentials');
process.exit(1);
}
let defaultOptions = {
host: HOST,
port: PORT,
path: '/',
method: 'GET', // GET | POST
parameters: {},
body: '',
callback: function () {
},
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + ACCESSTOKEN,
}
};
options = extend(defaultOptions, options);
console.log("Make request: " + options.path + " (" + options.method + ")");
// Update Content-Type header
options.headers = extend(options.headers, {
'Content-Type': options.contentType
});
// Update Header if agreement has been set
if (agreementSet === true) {
options.headers = extend(options.headers, {
'X-CommonName': X_COMMONNAME,
'X-Agreement-ID': X_AGREEMENT_ID
});
}
// Encode body if contentType is json.
if (options.contentType === 'application/json') {
options.body = JSON.stringify(options.body);
}
// Make changes to the request options headers if method is POST
if (options.method === 'POST') {
options.headers = extend(options.headers, {
'Content-Length': Buffer.byteLength(options.body),
});
}
let request = https.request(options, function (response) {
response.setEncoding('utf8');
let str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
if (response.statusCode === 200) {
if (str.length > 0) {
options.callback(JSON.parse(str));
} else {
options.callback({});
}
} else if (response.statusCode === 401) {
// Unauthorized
throw new Error("Error performing request: Unauthorized. Check your config file.");
} else if (response.statusCode === 500) {
// Interal server error. This might be caused because the agreement is not properly set.
// Let's reset it ...
throw new Error("Error performing request (500): " + str);
} else if (response.statusCode === 503) {
// Probably a message throttle issue ... lets wait a while before we contine...
console.log("Exceeded quota. Waiting for 5 seconds.");
setTimeout(function () {
options.callback();
}, 5000);
} else {
console.log("Error performing request: " + response.statusCode);
console.log(str);
options.callback();
}
});
response.on('error', function (e) {
console.log("Error performing request to endpoint: /" + endpoint);
options.callback();
});
});
if (options.method === 'POST') {
request.write(options.body);
}
request.end();
}
function makeApiRequest(options) {
if (!ACCESSTOKEN) {
throw new Error("No Access Token. Please check your config file.");
}
if (!agreementSet && options.path !== 'agreements') {
console.log("Agreement not set. Set it ...");
activateFirstAgreement(function () {
makeApiRequest(options);
});
return;
}
console.log("All good. Let's make a request ...");
if(!agreementSet) {
options = extend(options, {
path: API + options.path
});
}else{
options = extend(options, {
path: API + X_AGREEMENT_ID + "/" + options.path
})
}
makeRequest(options);
}
/**
* makeSimpleApiRequest
* @param {string} endpoint The endpoint of the API.
* @param {Function} callback The callback after completion.
*/
function makeSimpleApiRequest(endpoint, callback) {
callback = callback || function () {
};
makeApiRequest({path: endpoint, callback: callback});
}
/**
* activateFirstAgreement
* Activates the first agreement for the current user.
* @param {Function} callback Callback after the agreement is activted.
*/
function activateFirstAgreement(callback) {
self.getAgreements(function (agreements) {
if (agreements && agreements.length > 0) {
self.setAgreement(agreements[0].agreementId, agreements[0].displayCommonName, callback);
} else {
// No agreements or request failed.
console.log("Agreements request failed.");
callback();
}
});
}
/// Public Methods
/**
* setApiKeySecret
* Set the API Key and Secret.
* @param {string} k API Key.
* @param {string} s API Secret.
* @param {string} a Access Token
*/
self.setApiKeySecret = function (k, s, a) {
ACCESSTOKEN = a;
APIKEY = k;
APISECRET = s;
};
// Agreements
/**
* getAgreements
* Get the all the agreements for the current user.
* @param {Function} callback The callback after the agreements are received.
*/
self.getAgreements = function (callback) {
makeSimpleApiRequest('agreements', callback);
};
/**
* setAgreement
* Set an agreement as the active agreement.
* @param {string} agreementId The agreementId for the desired active agreement.
* @param {string} displayCommonName the x-CommonName for the desired active agreement
* @param {Function} callback The callback after the agreement is activated.
*/
self.setAgreement = function (agreementId, displayCommonName, callback) {
console.log('Set agreementID: ' + agreementId + " CommonName: " + displayCommonName);
// makeApiRequest({
// path: 'agreements',
// method: 'POST',
// headers: {"X-Agreement-ID": agreementId, "X-CommonName": displayCommonName, authorization: "bearer" + APIKEY},
// callback: function() {
// console.log("Agreement set: " + agreementId + ", X-CommonName set: " + displayCommonName);
// agreementSet = true;
// callback();
// }
// });
// Update headers for agreement
X_AGREEMENT_ID = agreementId;
X_COMMONNAME = displayCommonName;
console.log("Agreement set: " + agreementId + ", X-CommonName set: " + displayCommonName);
agreementSet = true;
callback();
};
// Consumption
/**
* getConsumptionElectricityFlows
* Request the consumption electricity flows.
* @param {Function} callback The callback after the data is received.
*/
self.getConsumptionElectricityFlows = function (callback) {
makeSimpleApiRequest('consumption/electricity/flows', callback);
};
/**
* getConsumptionElectricityData
* Request the consumption electricity data.
* @param {Function} callback The callback after the data is received.
*/
self.getConsumptionElectricityData = function (callback) {
makeSimpleApiRequest('consumption/electricity/data', callback);
};
/**
* getConsumptionDistrictheatData
* Request the consumption district heat data.
* @param {Function} callback The callback after the data is received.
*/
self.getConsumptionDistrictheatData = function (callback) {
makeSimpleApiRequest('consumption/districtheat/data', callback);
};
/**
* getConsumptionGasFlows
* Request the consumption gas flows.
* @param {Function} callback The callback after the data is received.
*/
self.getConsumptionGasFlows = function (callback) {
makeSimpleApiRequest('consumption/gas/flows', callback);
};
/**
* getConsumptionGasData
* Request the consumption gas data.
* @param {Function} callback The callback after the data is received.
*/
self.getConsumptionGasData = function (callback) {
makeSimpleApiRequest('consumption/gas/data', callback);
};
// Temperature
/**
* getTemperatureStates
* Request the temperature states.
* @param {Function} callback The callback after the data is received.
*/
self.getTemperatureStates = function (callback) {
makeSimpleApiRequest('temperature/states', callback);
};
/**
* getTemperaturePrograms
* Request the temperature programs.
* @param {Function} callback The callback after the data is received.
*/
self.getTemperaturePrograms = function (callback) {
makeSimpleApiRequest('temperature/programs', callback);
};
// Status
/**
* getStatus
* Request the current status.
* @param {Function} callback The callback after the data is received.
*/
self.getStatus = function (callback) {
makeSimpleApiRequest('status', function (data) {
if (!data) {
console.log("Error while fetching new status.");
callback(status);
return;
}
if (Object.keys(data).length !== 0) {
status = extend(status, data);
status.updated = true;
} else {
status.updated = false;
}
callback(status);
});
};
return self;
})();
module.exports = ToonAPI;