forked from homebridge/homebridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOpenhab.js
573 lines (457 loc) · 15.5 KB
/
Openhab.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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// OpenHAB 1 Platform Shim for HomeBridge
// Written by Tommaso Marchionni
// Based on many of the other HomeBridge platform modules
//
// Revisions:
//
// 17 October 2015 [tommasomarchionni]
// - Initial release
//
// 25 October 2015 [tommasomarchionni]
// - Added WS listener and new OOP structure
//
// Remember to add platform to config.json. Example:
// "platforms": [
// {
// "platform": "Openhab",
// "name": "Openhab",
// "server": "127.0.0.1",
// "port": "8080",
// "sitemap": "demo"
// }
// ],
//
// Example of sitemap in OpenHAB:
// sitemap homekit label="HomeKit" {
// Switch item=Light_1 label="Light 1"
// }
//
// Rollershutter is tested with this binding in OpenHAB:
// command=SWITCH_MULTILEVEL,invert_percent=true,invert_state=false"
// When you attempt to add a device, it will ask for a "PIN code".
// The default code for all HomeBridge accessories is 031-45-154.
//
//////// LIBS /////////
var WebSocket = require('ws');
var request = require("request");
var Service = require("hap-nodejs/lib/Service.js").Service;
var Characteristic = require("hap-nodejs").Characteristic;
var currentModule = this;
var util = require('core-util-is');
util.inherits = require('inherits');
//////// PLATFORM /////////
function OpenhabPlatform(log, config){
this.log = log;
this.user = config["user"];
this.password = config["password"];
this.server = config["server"];
this.port = config["port"];
this.protocol = "http";
this.sitemap = "demo";
if (typeof config["sitemap"] != 'undefined') {
this.sitemap = config["sitemap"];
}
}
OpenhabPlatform.prototype = {
accessories: function(callback) {
var that = this;
this.log("Platform - Fetching OpenHAB devices.");
var itemFactory = new ItemFactory(this);
url = itemFactory.sitemapUrl();
this.log("Platform - Connecting to " + url);
request.get({
url: url,
json: true
}, function(err, response, json) {
if (!err && response.statusCode == 200) {
callback(itemFactory.parseSitemap(json));
} else {
that.log("Platform - There was a problem connecting to OpenHAB.");
}
});
}
};
//////// END PLATFORM /////////
///////// ACCESSORY /////////
function OpenhabAccessory(widget,platform) {}
///////// ABSTRACT ITEM /////////
function AbstractItem(widget,platform){
AbstractItem.super_.call(this,widget,platform);
this.widget = widget;
this.label = widget.label;
this.name = widget.item.name;
this.url = widget.item.link;
this.state = widget.item.state;
this.platform = platform;
this.log = platform.log;
this.setInitialState = false;
this.setFromOpenHAB = false;
this.informationService = undefined;
this.otherService = undefined;
this.listener = undefined;
this.ws = undefined;
};
util.inherits(AbstractItem, OpenhabAccessory);
AbstractItem.prototype.getInformationServices = function() {
informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, "OpenHAB")
.setCharacteristic(Characteristic.Model, this.constructor.name)
.setCharacteristic(Characteristic.SerialNumber, "N/A")
.setCharacteristic(Characteristic.Name, this.name);
return informationService;
}
AbstractItem.prototype.checkListener = function() {
if (typeof this.listener == 'undefined' || typeof this.ws == 'undefined') {
this.ws = undefined;
this.listener = new WSListener(this, this.updateCharacteristics.bind(this));
this.listener.startListener();
}
};
///////// END ABSTRACT ITEM /////////
///////// SWITCH ITEM /////////
function SwitchItem(widget,platform){
SwitchItem.super_.call(this, widget,platform);
};
util.inherits(SwitchItem, AbstractItem);
SwitchItem.prototype.getServices = function() {
this.checkListener();
this.setInitialState = true;
this.informationService = this.getInformationServices();
this.otherService = new Service.Lightbulb();
this.otherService.getCharacteristic(Characteristic.On)
.on('set', this.setItem.bind(this))
.on('get', this.getItemPowerState.bind(this))
.setValue(this.state === 'ON');
return [this.informationService, this.otherService];
};
SwitchItem.prototype.updateCharacteristics = function(message) {
this.setFromOpenHAB = true;
this.otherService
.getCharacteristic(Characteristic.On)
.setValue(message === 'ON' ? true : false,
function() {
this.setFromOpenHAB = false;
}.bind(this)
);
};
SwitchItem.prototype.getItemPowerState = function(callback) {
var self = this;
this.checkListener();
this.log("iOS - request power state from " + this.name);
request(this.url + '/state?type=json', function (error, response, body) {
if (!error && response.statusCode == 200) {
self.log("OpenHAB HTTP - response from " + self.name + ": " + body);
callback(undefined,body == "ON" ? true : false);
} else {
self.log("OpenHAB HTTP - error from " + self.name + ": " + error);
}
})
};
SwitchItem.prototype.setItem = function(value, callback) {
var self = this;
this.checkListener();
if (this.setInitialState) {
this.setInitialState = false;
callback();
return;
}
if (this.setFromOpenHAB) {
callback();
return;
}
this.log("iOS - send message to " + this.name + ": " + value);
var command = value ? 'ON' : 'OFF';
request.post(
this.url,
{ body: command },
function (error, response, body) {
if (!error && response.statusCode == 201) {
self.log("OpenHAB HTTP - response from " + self.name + ": " + body);
} else {
self.log("OpenHAB HTTP - error from " + self.name + ": " + error);
}
callback();
}
);
};
///////// END SWITCH ITEM /////////
///////// DIMMER ITEM /////////
function DimmerItem(widget,platform){
DimmerItem.super_.call(this, widget,platform);
};
util.inherits(DimmerItem, AbstractItem);
DimmerItem.prototype.getServices = function() {
this.checkListener();
this.setInitialState = true;
this.informationService = this.getInformationServices();
this.otherService = new Service.Lightbulb();
this.otherService.getCharacteristic(Characteristic.On)
.on('set', this.setItem.bind(this))
.on('get', this.getItemPowerState.bind(this))
.setValue(+this.state > 0);
this.setInitialState = true;
this.otherService.addCharacteristic(Characteristic.Brightness)
.on('set', this.setItem.bind(this))
.on('get', this.getItemBrightnessState.bind(this))
.setValue(+this.state);
return [this.informationService, this.otherService];
};
DimmerItem.prototype.updateCharacteristics = function(message) {
this.setFromOpenHAB = true;
var brightness = +message;
var steps = 2;
if (brightness >= 0) {
this.otherService.getCharacteristic(Characteristic.Brightness)
.setValue(brightness,
function() {
steps--;
if (!steps) {
this.setFromOpenHAB = false;
}
}.bind(this));
this.otherService.getCharacteristic(Characteristic.On)
.setValue(brightness > 0 ? true : false,
function() {
steps--;
if (!steps) {
this.setFromOpenHAB = false;
}
}.bind(this));
}
}
DimmerItem.prototype.getItemPowerState = function(callback) {
var self = this;
this.checkListener();
this.log("iOS - request power state from " + this.name);
request(this.url + '/state?type=json', function (error, response, body) {
if (!error && response.statusCode == 200) {
self.log("OpenHAB HTTP - response from " + self.name + ": " + body);
callback(undefined,+body > 0 ? true : false);
} else {
self.log("OpenHAB HTTP - error from " + self.name + ": " + error);
}
})
};
DimmerItem.prototype.setItem = function(value, callback) {
var self = this;
this.checkListener();
if (this.setInitialState) {
this.setInitialState = false;
callback();
return;
}
if (this.setFromOpenHAB) {
callback();
return;
}
this.log("iOS - send message to " + this.name + ": " + value);
var command = 0;
if (typeof value === 'boolean') {
command = value ? '100' : '0';
} else {
command = "" + value;
}
request.post(
this.url,
{
body: command,
headers: {'Content-Type': 'text/plain'}
},
function (error, response, body) {
if (!error && response.statusCode == 201) {
self.log("OpenHAB HTTP - response from " + self.name + ": " + body);
} else {
self.log("OpenHAB HTTP - error from " + self.name + ": " + error);
}
callback();
}
);
};
DimmerItem.prototype.getItemBrightnessState = function(callback) {
var self = this;
this.log("iOS - request brightness state from " + this.name);
request(this.url + '/state?type=json', function (error, response, body) {
if (!error && response.statusCode == 200) {
self.log("OpenHAB HTTP - response from " + self.name + ": " + body);
callback(undefined,+body);
} else {
self.log("OpenHAB HTTP - error from " + self.name + ": " + error);
}
})
};
///////// END DIMMER ITEM /////////
///////// ROLLERSHUTTER ITEM /////////
function RollershutterItem(widget,platform){
RollershutterItem.super_.call(this, widget,platform);
this.positionState = Characteristic.PositionState.STOPPED;
this.currentPosition = 100;
this.targetPosition = 100;
this.startedPosition = 100;
};
util.inherits(RollershutterItem, AbstractItem);
RollershutterItem.prototype.getServices = function() {
this.checkListener();
this.informationService = this.getInformationServices();
this.otherService = new Service.WindowCovering();
this.otherService.getCharacteristic(Characteristic.CurrentPosition)
.on('get', this.getItemCurrentPosition.bind(this))
.setValue(this.currentPosition);
this.setInitialState = true;
this.otherService.getCharacteristic(Characteristic.TargetPosition)
.on('set', this.setItem.bind(this))
.on('get', this.getItemTargetPosition.bind(this))
.setValue(this.currentPosition);
this.otherService.getCharacteristic(Characteristic.PositionState)
.on('get', this.getItemPositionState.bind(this))
.setValue(this.positionState);
return [this.informationService, this.otherService];
};
RollershutterItem.prototype.updateCharacteristics = function(message) {
console.log(message);
console.log(this.targetPosition);
if (parseInt(message) == this.targetPosition) {
var ps = Characteristic.PositionState.STOPPED;
var cs = parseInt(message);
} else if (parseInt(message) > this.targetPosition){
var ps = Characteristic.PositionState.INCREASING;
var cs = this.startedPosition;
} else {
var ps = Characteristic.PositionState.DECREASING;
var cs = this.startedPosition;
}
this.otherService
.getCharacteristic(Characteristic.PositionState)
.setValue(ps);
this.otherService
.getCharacteristic(Characteristic.CurrentPosition)
.setValue(parseInt(cs));
this.currentPosition = parseInt(cs);
};
RollershutterItem.prototype.setItem = function(value, callback) {
var self = this;
this.checkListener();
if (this.setInitialState) {
this.setInitialState = false;
callback();
return;
}
this.startedPosition = this.currentPosition;
this.log("iOS - send message to " + this.name + ": " + value);
var command = 0;
if (typeof value === 'boolean') {
command = value ? '100' : '0';
} else {
command = "" + value;
}
request.post(
this.url,
{
body: command,
headers: {'Content-Type': 'text/plain'}
},
function (error, response, body) {
if (!error && response.statusCode == 201) {
self.log("OpenHAB HTTP - response from " + self.name + ": " + body);
self.targetPosition = parseInt(value);
} else {
self.log("OpenHAB HTTP - error from " + self.name + ": " + error);
}
callback();
}
);
};
RollershutterItem.prototype.getItemPositionState = function(callback) {
this.log("iOS - request position state from " + this.name);
this.log("Platform - response from " + this.name + ": " + this.positionState);
callback(undefined,this.positionState);
};
RollershutterItem.prototype.getItemTargetPosition = function(callback) {
this.log("iOS - get target position state from " + this.name);
this.log("Platform - response from " + this.name + ": " + this.targetPosition);
callback(undefined,this.targetPosition);
}
RollershutterItem.prototype.getItemCurrentPosition = function(callback) {
var self = this;
this.log("iOS - request current position state from " + this.name);
request(this.url + '/state?type=json', function (error, response, body) {
if (!error && response.statusCode == 200) {
self.log("OpenHAB HTTP - response from " + self.name + ": " +body);
self.currentPosition = parseInt(body);
callback(undefined,parseInt(body));
} else {
self.log("OpenHAB HTTP - error from " + self.name + ": " + error);
}
})
};
///////// END ROLLERSHUTTER ITEM /////////
///////// ITEM UTILITY /////////
function ItemFactory(openhabPlatform){
this.platform = openhabPlatform;
this.log = this.platform.log;
}
ItemFactory.prototype = {
sitemapUrl: function() {
var serverString = this.platform.server;
//TODO da verificare
if (this.platform.user && this.platform.password) {
serverString = this.platform.user + ":" + this.platform.password + "@" + serverString;
}
return this.platform.protocol + "://" + serverString + ":" + this.platform.port + "/rest/sitemaps/" + this.platform.sitemap + "?type=json";
},
parseSitemap: function(jsonSitemap) {
var widgets = [].concat(jsonSitemap.homepage.widget);
var result = [];
for (var i = 0; i < widgets.length; i++) {
var widget = widgets[i];
if (!widget.item) {
//TODO to handle frame
this.log("Platform - The widget '" + widget.label + "' is not an item.");
continue;
}
if (currentModule[widget.item.type] != undefined) {
var accessory = new currentModule[widget.item.type](widget,this.platform);
} else {
this.log("Platform - The widget '" + widget.label + "' of type "+widget.item.type+" is an item not handled.");
continue;
}
this.log("Platform - Accessory Found: " + widget.label);
result.push(accessory);
}
return result;
}
};
///////// END ITEM UTILITY /////////
///////// WS LISTENER /////////
function WSListener(item, callback){
this.item = item;
this.callback = callback;
}
WSListener.prototype = {
startListener: function() {
var self = this;
if (typeof this.item.ws == 'undefined') {
this.item.ws = new WebSocket(this.item.url.replace('http:', 'ws:') + '/state?type=json');
}
this.item.ws.on('open', function() {
self.item.log("OpenHAB WS - new connection for "+self.item.name);
});
this.item.ws.on('message', function(message) {
self.item.log("OpenHAB WS - message from " +self.item.name+": "+ message);
self.callback(message);
});
this.item.ws.on('close', function close() {
self.item.log("OpenHAB WS - closed connection for "+self.item.name);
self.item.listener = undefined;
self.item.ws = undefined;
});
}
};
///////// END WS LISTENER /////////
///////// SUPPORTED ITEMS /////////
module.exports.SwitchItem = SwitchItem;
module.exports.DimmerItem = DimmerItem;
module.exports.RollershutterItem = RollershutterItem;
///////// END SUPPORTED ITEMS /////////
module.exports.accessory = OpenhabAccessory;
module.exports.platform = OpenhabPlatform;