-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.js
346 lines (292 loc) · 10.8 KB
/
main.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
/* jshint -W097 */// jshint strict:false
/*jslint node: true */
"use strict";
// you have to require the utils module and call adapter function
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const jsonPath = require('jsonpath');
const trigger_poll_state = 'trigger_poll'; // state for triggering a poll
// you have to call the adapter function and pass a options object
// name has to be set and has to be equal to adapters folder name and main file name excluding extension
// adapter will be restarted automatically every time as the configuration changed, e.g system.adapter.gardena.0
let adapter;
function startAdapter(options) {
options = options || {};
Object.assign(options, {
name: "gardena",
install: adapter_install,
unload: adapter_unload,
objectChange: adapter_objectChange,
stateChange: adapter_stateChange,
ready: adapter_ready,
message: adapter_message
});
adapter = new utils.Adapter(options);
return adapter;
}
const gardenaCloudConnector = require(__dirname + '/lib/gardenaCloudConnector');
const gardenaDBConnector = require(__dirname + '/lib/gardenaDBConnector');
// triggered when the adapter is installed
const adapter_install = function () {};
// is called when the adapter shuts down - callback has to be called under any circumstances!
const adapter_unload = function (callback) {
try {
adapter.log.info('cleaned everything up...');
callback();
} catch (e) {
callback();
}
};
// is called if a subscribed object changes
const adapter_objectChange = function (id, obj) {
// Warning, obj can be null if it was deleted
adapter.log.debug('objectChange ' + id + ' ' + JSON.stringify(obj));
};
// is called if a subscribed state changes
const adapter_stateChange = function (id, state) {
// Warning, state can be null if it was deleted
adapter.log.debug('stateChange ' + id + ' ' + JSON.stringify(state));
// connection related state change
if(id && state && id === state.from.split('.')[2] + '.' + state.from.split('.')[3] + '.' + 'info.connection') {
adapter.log.debug('Change in connection detected, setup polling if true.');
if (state.val === true) {
// got connection
gardenaCloudConnector.setupPolling();
} else {
gardenaCloudConnector.reconnect();
}
}
// a poll was manually triggered
if(id && state && id === 'gardena.' + adapter.instance + '.' + trigger_poll_state && state.val === true) {
gardenaCloudConnector.poll(function (err) {
if(err) adapter.log.error(err);
adapter.setState(trigger_poll_state, false, false); // reset trigger state
adapter.log.debug('A poll has been triggered manually.');
});
}
// helper function for autopolling
function check_autopoll() {
let gardena_conf = gardenaCloudConnector.get_gardena_config();
// autopoll after trigger?
if (gardena_conf.gardena_autopoll) {
setTimeout(
function () {
gardenaCloudConnector.poll(function (err) {
if(err) {
adapter.log.error(err);
} else {
adapter.log.debug('A poll has been triggered by a triggered event.');
}
})},
Number(gardena_conf.gardena_autopoll_delay) * 1000
);
}
}
// you can use the ack flag to detect if it is status (true) or command (false)
if (state && state.val && !state.ack && id.split('.')[id.split('.').length-1] === 'trigger') {
triggeredEvent(id, function (err) {
if(err) adapter.log.error('An error occurred during trigger!');
adapter.setState(id, false, false); // reset trigger
check_autopoll();
});
}
if (state && state.val && !state.ack && id.split('.')[id.split('.').length-1] === 'smart_trigger') {
triggeredSmartEvent(id, function (err) {
if(err) adapter.log.error('An error occurred during smart trigger!');
adapter.setState(id, false, false); // reset trigger
check_autopoll();
});
}
};
// is called when databases are connected and adapter received configuration.
const adapter_ready = function () {
// start main function
main();
};
// messages
const adapter_message = function (obj) {
let wait = false;
let credentials;
let msg;
if (obj) {
switch (obj.command) {
case 'checkConnection':
credentials = obj.message;
function sub_connect() {
gardenaCloudConnector.connect(
credentials.baseURI, credentials.gardena_username, credentials.gardena_password, function (err) {
if (!err) {
adapter.sendTo(obj.from, obj.command, true, obj.callback);
} else {
adapter.sendTo(obj.from, obj.command, false, obj.callback);
}
});
}
// is there already a connection?
if(!gardenaCloudConnector.is_connected()) {
gardenaCloudConnector.disconnect(function(err) {
sub_connect();
});
} else {
sub_connect();
}
wait = true;
break;
case 'connect':
credentials = obj.message;
// check if already connected (do not care about the credentials)
if(!gardenaCloudConnector.is_connected()) {
gardenaCloudConnector.connect(
credentials.baseURI, credentials.gardena_username, credentials.gardena_password, function (err, auth_data) {
if (!err) {
adapter.sendTo(obj.from, obj.command, auth_data, obj.callback);
} else {
adapter.sendTo(obj.from, obj.command, false, obj.callback);
}
});
} else {
adapter.sendTo(obj.from, obj.command, gardenaCloudConnector.get_auth(), obj.callback);
}
wait = true;
break;
case 'retrieveLocations':
msg = obj.message;
gardenaCloudConnector.retrieveLocations(msg.token, msg.user_id, function (err, locations) {
if(!err) {
adapter.sendTo(obj.from, obj.command, locations, obj.callback);
} else {
adapter.sendTo(obj.from, obj.command, false, obj.callback);
}
});
wait = true;
break;
case 'retrieveDevices':
msg = obj.message;
gardenaCloudConnector.retrieveDevicesFromLocation(msg.token, msg.location_id, function (err, devices) {
if(!err) {
adapter.sendTo(obj.from, obj.command, devices, obj.callback);
} else {
adapter.sendTo(obj.from, obj.command, false, obj.callback);
}
});
wait = true;
break;
default:
adapter.log.warn("Unknown command: " + obj.command);
break;
}
}
if (!wait && obj.callback) {
adapter.sendTo(obj.from, obj.command, obj.message, obj.callback);
}
return true;
};
// main function
function main() {
adapter.log.info('Starting gardena smart system adapter');
gardenaDBConnector.setAdapter(adapter); // set adapter instance in the DBConnector
gardenaCloudConnector.setAdapter(adapter); // set adapter instance in the DBConnector
// connect to gardena smart system service and start polling
// we need a connection for syncing the states
gardenaCloudConnector.connect(null, null, null, function(err, auth_data) {
if(err) {
adapter.log.error(err);
} else {
gardenaCloudConnector.poll(function (err) {
syncConfig(gardenaCloudConnector.get_cloud_data()); // sync database with config
});
}
});
// gardena subscribes to all state changes
adapter.subscribeStates('datapoints.*.trigger');
adapter.subscribeStates('datapoints.*.smart_trigger');
adapter.subscribeStates('info.connection');
adapter.subscribeStates(trigger_poll_state)
}
// a command has been triggered
function triggeredEvent(id, callback) {
let locationid = id.split('.').slice(3, 4);
let deviceid = id.split('.')[4];
// get the name of the trigger state (this is equal to the command)
adapter.getObject(id, function(err, obj) {
let cmd = obj.common.name;
// collect parameters
// get property states
adapter.getStates(id.split('.').slice(0, -1).join('.') + '.parameters.*', function(err, states) {
// build the json for the http put command
let json = {
"name": cmd,
"parameters": {}
};
for(let cstate in states) {
json.parameters[cstate.split('.').slice(-1)[0]] = states[cstate].val;
}
let names = getNamesFromIDs(id.split('.'));
let gardena_conf = gardenaCloudConnector.get_gardena_config();
let uri = gardena_conf.baseURI + gardena_conf.devicesURI + '/' + deviceid + '/' + names.slice(5, -2).join('/');
uri = uri + '?locationId=' + locationid;
gardenaCloudConnector.http_post(uri, json, function(err) {
if(callback) callback(err);
});
});
});
}
// a smart command has been triggered
function triggeredSmartEvent(id, callback) {
let locationid = id.split('.')[3];
let deviceid = id.split('.')[4];
// get the name of the trigger state (this is equal to the command)
adapter.getObject(id, function(err, obj) {
let cmd = obj.common.name;
// get property states
adapter.getStates(id.split('.').slice(0, -1).join('.') + '.properties.*', function(err, states) {
// build the json for the http put command
let json = {
"properties": {
"name": cmd,
"value": {}
}
};
for(let cstate in states) {
json.properties.value[cstate.split('.').slice(-1)[0]] = states[cstate].val;
}
let names = getNamesFromIDs(id.split('.'));
let gardena_conf = gardenaCloudConnector.get_gardena_config();
let uri = gardena_conf.baseURI + gardena_conf.devicesURI + '/' + deviceid + '/' + names.slice(5, -2).join('/') + '/properties/' + names.slice(-2, -1);
uri = uri + '?locationId=' + locationid;
gardenaCloudConnector.http_put(uri, json, function(err) {
if(callback) callback(err);
});
});
});
}
// synchronize config
function syncConfig(cloud_data) {
// compare gardena datapoints with objects, anything changed?
// create locations inside the datapoints structure
gardenaDBConnector.syncDBDatapoints(cloud_data, function(err) {
// do we have to create commands for devices?
gardenaDBConnector.createHTTPPostDatapointsInDB(cloud_data);
});
}
// this helper function returns the names from an array of ids
function getNamesFromIDs(ids) {
let cloud_data = gardenaCloudConnector.get_cloud_data();
let names = [];
for(let i=0;i<ids.length;i++) {
// can we find the id?
let res = jsonPath.query(cloud_data, '$..[?(@.id=="' + ids[i] + '")]');
if(!res || !Array.isArray(res) || res.length === 0) {
names.push(ids[i]);
} else {
names.push(res[0].name);
}
}
return names;
}
// If started as allInOne/compact mode => return function to create instance
if (module && module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}