forked from dubocr/homebridge-tahoma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
overkiz-api.js
331 lines (299 loc) · 10 KB
/
overkiz-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
var request = require("request").defaults({ jar: true })
var pollingtoevent = require('polling-to-event');
Command = function(name) {
this.type = 1;
this.name = name;
this.parameters = [];
}
Execution = function(name, deviceURL, command) {
this.label = name;
this.metadata = null;
this.actions = [{
deviceURL: deviceURL,
commands: [command]
}];
}
ExecutionState = {
INITIALIZED: 'INITIALIZED',
IN_PROGRESS: 'IN_PROGRESS',
COMPLETED: 'COMPLETED',
FAILED: 'FAILED'
};
State = {
STATE_MANUFACTURER: "core:ManufacturerState",
STATE_MODEL: "core:ModelState",
STATE_CLOSURE: "core:ClosureState",
STATE_OPEN_CLOSED: "core:OpenClosedState",
STATE_OPEN_CLOSED_PEDESTRIAN: "core:OpenClosedPedestrianState",
STATE_LOCKED_UNLOCKED: "core:LockedUnlockedState",
STATE_PRIORITY_LOCK: "core:PriorityLockLevelState",
STATE_ACTIVE_ZONES: "core:ActiveZonesState",
STATE_TARGET_TEMP: "core:TargetTemperatureState",
STATE_HEATING_ON_OFF: "core:HeatingOnOffState",
STATE_OPEN_CLOSED_UNKNOWN: 'core:OpenClosedUnknownState',
STATE_RSSI: 'core:RSSILevelState',
STATE_ON_OFF: 'core:OnOffState',
STATE_INTENSITY: 'core:IntensityState'
};
Server = {
'Cozytouch': 'ha110-1.overkiz.com',
'TaHoma': 'tahomalink.com'
}
module.exports = {
Command: Command,
Execution: Execution,
ExecutionState: ExecutionState,
State: State,
Api: OverkizApi
}
function OverkizApi(log, config) {
this.log = log;
// Default values
this.pollingPeriod = config['pollingPeriod'] || 2; // Poll for events every 2 seconds by default
this.refreshPeriod = config['refreshPeriod'] || (60 * 10); // Refresh device states every 10 minutes by default
this.service = config['service'] || 'TaHoma';
this.user = config['user'];
this.password = config['password'];
this.server = Server[this.service];
if (!this.user || !this.password) throw new Error("You must provide credentials ('user'/'password')");
if (!this.server) throw new Error("Invalid service name '"+this.service+"'");
this.isLoggedIn = false;
this.listenerId = null;
this.executionCallback = [];
this.platformAccessories = [];
this.stateChangedEventListener = null;
var that = this;
this.eventpoll = pollingtoevent(function(done) {
if (that.listenerId != null) {
that.post({
url: that.urlForQuery("/events/" + that.listenerId + "/fetch"),
json: true
}, function(error, data) {
done(error, data);
});
} else {
done(null, []);
}
}, {
longpolling: true,
interval: (1000 * this.pollingPeriod)
});
this.eventpoll.on("longpoll", function(data) {
for (event of data) {
if (event.name == 'DeviceStateChangedEvent') {
if (that.stateChangedEventListener != null)
that.stateChangedEventListener.onStatesChange(event.deviceURL, event.deviceStates);
} else if (event.name == 'ExecutionStateChangedEvent') {
var cb = that.executionCallback[event.execId];
if (cb != null) {
cb(event.newState, event.failureType == undefined ? null : event.failureType);
if (event.timeToNextState == -1) { // No more state expected for this execution
delete that.executionCallback[event.execId];
if(Object.keys(that.executionCallback).length == 0) { // Unregister listener when no more execution running
that.unregisterListener();
}
}
}
}
}
});
this.eventpoll.on("error", function(error) {
that.listenerId = null;
});
var refreshpoll = pollingtoevent(function(done) {
that.refreshStates(function(error, data) {
setTimeout(function() {
that.getDevices(function(error, data) {
if (!error) {
for (device of data) {
if (that.stateChangedEventListener != null) {
that.stateChangedEventListener.onStatesChange(device.deviceURL, device.states);
}
}
}
});
}, 10 * 1000); // Read devices states after 10s
done(error, data);
});
}, {
longpolling: true,
interval: (1000 * this.refreshPeriod)
});
refreshpoll.on("error", function(error) {
that.log(error);
});
}
OverkizApi.prototype = {
urlForQuery: function(query) {
return "https://" + this.server + "/enduser-mobile-web/enduserAPI" + query;
},
post: function(options, callback) {
var fct = request.post.bind(request, options);
this.requestWithLogin(fct, callback);
},
get: function(options, callback) {
var fct = request.get.bind(request, options);
this.requestWithLogin(fct, callback);
},
put: function(options, callback) {
var fct = request.put.bind(request, options);
this.requestWithLogin(fct, callback);
},
delete: function(options, callback) {
var fct = request.delete.bind(request, options);
this.requestWithLogin(fct, callback);
},
getDevices(callback) {
this.get({
url: this.urlForQuery("/setup/devices"),
json: true
}, function(error, json) {
callback(error, json);
});
},
getActionGroups(callback) {
this.get({
url: this.urlForQuery("/actionGroups"),
json: true
}, function(error, json) {
callback(error, json);
});
},
requestWithLogin: function(myRequest, callback) {
var that = this;
var authCallback = function(err, response, json) {
if (response != undefined && response.statusCode == 401) { // Reauthenticated
that.isLoggedIn = false;
//that.log(json.error);
that.requestWithLogin(myRequest, callback);
} else if (err) {
that.log("There was a problem requesting to Overkiz : " + err);
callback(err);
} else if (response != undefined && (response.statusCode < 200 || response.statusCode >= 300)) {
var msg = 'Error ' + response.statusCode;
if(json.error != null)
msg += ' ' + json.error;
if(json.errorCode != null)
msg += ' (' + json.errorCode + ')';
that.log(msg);
callback(msg);
} else {
callback(null, json);
}
};
if (this.isLoggedIn) {
myRequest(authCallback);
} else {
this.log.debug("Connecting " + this.service + " server...");
var that = this;
request.post({
url: this.urlForQuery("/login"),
form: {
'userId': this.user,
'userPassword': this.password
},
json: true
}, function(err, response, json) {
if (err) {
that.log.warn("Unable to login: " + err);
} else if (json.success) {
that.isLoggedIn = true;
myRequest(authCallback);
} else if (json.error) {
that.log.warn("Loggin fail: " + json.error);
} else {
that.log.error("Unable to login");
}
});
}
},
registerListener: function() {
var that = this;
if(this.listenerId == null) {
this.log.debug('Register listener');
this.post({
url: that.urlForQuery("/events/register"),
json: true
}, function(error, data) {
if(!error) {
that.listenerId = data.id;
}
});
}
},
unregisterListener: function() {
var that = this;
if(this.listenerId != null) {
this.log.debug('Unregister listener');
this.post({
url: that.urlForQuery("/events/" + this.listenerId + "/unregister"),
json: true
}, function(error, data) {
if(!error) {
that.listenerId = null;
}
});
}
},
refreshStates: function(callback) {
this.put({
url: this.urlForQuery("/setup/devices/states/refresh"),
json: true
}, function(error, data) {
callback(error, data);
});
},
requestState: function(deviceURL, state, callback) {
var that = this;
this.get({
url: this.urlForQuery("/setup/devices/" + encodeURIComponent(deviceURL) + "/states/" + encodeURIComponent(state)),
json: true
}, function(error, data) {
//that.log(data);
callback(error, data.value);
});
},
cancelCommand: function(execId, callback) {
var that = this;
this.delete({
url: this.urlForQuery("/exec/current/setup/" + execId),
json: true
}, function(error, json) {
callback();
});
},
/*
cmdName: The command to execute
params: Parameter of the command
callback: Callback function executed when command sended
refresh: Callback function executed when command succeed
*/
executeCommand: function(execution, callback) {
this.execute('apply', execution, callback);
},
/*
oid: The command OID or 'apply' if immediate execution
execution: Body parameters
callback: Callback function executed when command sended
*/
execute: function(oid, execution, callback) {
var that = this;
//this.log(command);
this.post({
url: that.urlForQuery('/exec/'+oid),
body: execution,
json: true
}, function(error, json) {
if (error == null) {
callback(ExecutionState.INITIALIZED, null, json); // Init OK
that.executionCallback[json.execId] = callback;
that.registerListener();
} else {
callback(ExecutionState.INITIALIZED, error);
}
});
},
setDeviceStateChangedEventListener: function(listener) {
this.stateChangedEventListener = listener;
}
}