-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
717 lines (585 loc) · 24.3 KB
/
index.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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
var http = require('http');
var fetch = require('node-fetch');
var stores = require('./store.js');
var Accessory, Service, Characteristic, UUIDGen;
var host = "https://www.tih.tw"
module.exports = function(homebridge) {
console.log("homebridge API version: " + homebridge.version);
// Accessory must be created from PlatformAccessory Constructor
Accessory = homebridge.platformAccessory;
// Service and Characteristic are from hap-nodejs
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
UUIDGen = homebridge.hap.uuid;
// For platform plugin to be considered as dynamic platform plugin,
// registerPlatform(pluginName, platformName, constructor, dynamic), dynamic must be true
homebridge.registerPlatform("homebridge-maid-white", "Maid White", SamplePlatform, true);
}
// Platform constructor
// config may be null
// api may be null if launched from old homebridge version
function SamplePlatform(log, config, api) {
log("SamplePlatform Init: with comfig:", config);
// platform.log("config:", config);
var platform = this;
this.log = log;
this.config = config;
this.accessories = [];
this.deviceCache = {}
log("Config: " + JSON.stringify(config))
if (api) {
// Save the API object as plugin needs to register new accessory via this object
this.api = api;
// Listen to event "didFinishLaunching", this means homebridge already finished loading cached accessories.
// Platform Plugin should only register new accessory that doesn't exist in homebridge after this event.
// Or start discover new accessories.
this.api.on('didFinishLaunching', function() {
platform.log("DidFinishLaunching");
this.DiscoveryDevices()
}.bind(this));
}else{
log("Error: old homebridge version")
}
}
SamplePlatform.prototype.DiscoveryDevices = function() {
const config = this.config
const platform = this
fetch(host + "/2/driver-info")
.then(res => res.json())
.then(json => {
this.driverInfo = json;
// log("driver-info", json)
// log("config", config)
if (config.accessToken == '') {
const username = config['username']
const password = config['password']
fetch(host + "/2/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: "username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password) + "&client_id=homebridge",
})
.then(res => res.json())
.then(json => {
platform.log("get access token:", json)
if (typeof(json['access_token']) != "undefined") {
config['password'] = ""
config['accessToken'] = json['access_token']
platform.log("replace confige with", config)
this.config = config
}
})
} else {
this.accessToken = config["accessToken"]
if (config['password'] && config['password'] != "") {
platform.log("warn, password should be removed")
}
platform.log("access token:", this.accessToken);
fetch(host + "/2/homes", {
method: "GET",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "bearer " + this.accessToken,
},
})
.then(res => res.json())
.then(json => {
platform.log("get homes: ", json)
// this.removeAccessory()
const homes = json["homes"]
// devices.forEach(dev => {
// this.AddMaidWhiteDevice(dev)
platform.homeId = ""
for (var i = 0; i < homes.length; i++) {
const home = homes[i]
if (home['id'] == platform.config["homeId"]) {
platform.homeId = platform.config["homeId"]
break
}
if (home['display_name'] == platform.config['homeName']) {
platform.homeId = home["id"]
break
}
}
if (platform.homeId == "") {
platform.log("warn:, setting home not found, will display all devices")
}
fetch(host + "/2/devices", {
method: "GET",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "bearer " + this.accessToken,
},
})
.then(res => res.json())
.then(json => {
// log("get devices: ", json)
// this.removeAccessory()
const devices = json["devices"]
devices.forEach(dev => {
if (platform.homeId == "" || dev['home_id'] == platform.homeId) {
this.AddMaidWhiteDevice(dev)
}
})
})
})
}
})
}
SamplePlatform.prototype.AddMaidWhiteDevice = function(device) {
const driverInfo = this.driverInfo[device['driver_name']]
this.log("found Maid White device:", device["display_name"], driverInfo['screen_type'])
// if(this.driverInfo[] ==)
var platform = this;
var uuid;
uuid = UUIDGen.generate("" + device["id"]);
var found = false
this.log("platform len:", (this.accessories.length))
this.accessories.forEach(acc => {
if (acc.UUID == uuid) {
found = true
return
}
})
this.log("found :", found)
if (found) {
return
}
var newAccessory = new Accessory(device["display_name"], uuid);
newAccessory.context = {
id: device["id"],
driverName: device["driver_name"],
screenType: driverInfo["screen_type"],
}
// newAccessory.on('identify', function(paired, callback) {
// platform.log(newAccessory.displayName, "Identify!!!");
// callback();
// });
// Plugin can save context on accessory to help restore accessory in configureAccessory()
// newAccessory.context.something = "Something"
// Make sure you provided a name for service, otherwise it may not visible in some HomeKit apps
var isSupported = false
switch (newAccessory.context.screenType) {
case "thermostat":
isSupported = true
newAccessory.addService(Service.Thermostat, device["display_name"])
break;
case "smartplug":
isSupported = true
newAccessory.addService(Service.Switch, device["display_name"])
break;
default:
switch (newAccessory.context.driverName){
case "tw.tih.infrared.general_remote_controller.button":
// TODO: Add config for expouse button
isSupported = true
newAccessory.addService(Service.Switch, device["display_name"])
break;
}
break;
}
this.configureAccessory(newAccessory)
if (isSupported) {
this.api.registerPlatformAccessories("homebridge-maid-white", "Maid White", [newAccessory])
}
// this.accessories.push(newAccessory);
}
// Function invoked when homebridge tries to restore cached accessory.
// Developer can configure accessory at here (like setup event handler).
// Update current value.
SamplePlatform.prototype.configureAccessory = function(accessory) {
this.log(accessory.displayName, "Configure Accessory");
var platform = this;
var isSupported = false
switch (accessory.context.screenType) {
case 'thermostat':
this.ConfigureMaidWhiteThermostat(accessory)
isSupported = true
break
case 'smartplug':
this.ConfigureMaidWhiteSmartplug(accessory)
isSupported = true
break
default:
switch (accessory.context.driverName){
case "tw.tih.infrared.general_remote_controller.button":
// TODO: Add config for expouse button
this.ConfiguraMaidWhiteInfraredButton(accessory)
isSupported = true
break
}
break
}
if (isSupported){
this.accessories.push(accessory)
}
return
// Set the accessory to reachable if plugin can currently process the accessory,
// otherwise set to false and update the reachability later by invoking
// accessory.updateReachability()
accessory.reachable = true;
accessory.on('identify', function(paired, callback) {
platform.log(accessory.displayName, "Identify!!!");
callback();
});
if (accessory.getService(Service.Lightbulb)) {
accessory.getService(Service.Lightbulb)
.getCharacteristic(Characteristic.On)
.on('set', function(value, callback) {
platform.log(accessory.displayName, "Light -> " + value);
callback();
});
} else {
}
// this.api.unregisterPlatformAccessories("homebridge-maid-white", "Maid White", [accessory]);
this.accessories.push(accessory);
}
SamplePlatform.prototype.ConfigureMaidWhiteThermostat = function(accessory) {
this.log(accessory.displayName, "Configure Maid White Thermostat");
var platform = this;
const service = accessory.getService(Service.Thermostat)
const onChar = service.getCharacteristic(Characteristic.On)
onChar.on('set', function(value, callback) {
platform.log(accessory.displayName, "Thermostat on -> " + value);
if (value == 0) {
// turn off
body = "power_status=false"
} else {
// turn on
body = "power_status=true"
}
platform.setDevice(accessory, body, _ => {
callback();
});
});
onChar.on('change', function(oldValue, newValue) {
platform.log(accessory.displayName, "Thermostat on " + oldValue + " -> " + newValue);
})
onChar.on('get', function(callback) {
platform.log(accessory.displayName, "Thermostat on get:");
callback(null, 0)
})
const modeChar = service.getCharacteristic(Characteristic.TargetHeatingCoolingState)
modeChar.on('set', function(value, callback) {
platform.log(accessory.displayName, "Thermostat mode -> " + value);
body = ""
if (value == 0) {
body = "power_status=false"
} else {
if (value == 2) {
body = "power_status=true&mode=cool"
} else if (value == 1) {
body = "power_status=true&mode=heat"
} else {
body = "power_status=true"
}
}
platform.setDevice(accessory, body, _ => {
callback();
})
});
modeChar.on('change', function(oldValue, newValue) {
platform.log(accessory.displayName, "Thermostat mode " + oldValue + " -> " + newValue);
})
modeChar.on('get', function(callback) {
platform.log(accessory.displayName, "Thermostat mode get:");
platform.fetchDeviceWithCache(accessory, data => {
platform.log("got cached data: ", data)
if (data["power_status"] == false || data['power_status'] == 'false') {
callback(null, 0)
} else {
if (typeof(data["mode"]) != "undefined") {
switch (data["mode"]) {
case "cool":
callback(null, 2)
return;
case "heat":
callback(null, 1)
return;
case "auto":
callback(null, 3)
return;
}
callback(new Error("unknown mode: " + data["mode"]), 0)
} else {
callback(new Error("unknown mode"), 0)
}
}
})
})
const targetChar = service.getCharacteristic(Characteristic.TargetTemperature)
targetChar.on('set', function(value, callback) {
platform.log(accessory.displayName, "Thermostat target temp -> " + value);
platform.setDevice(accessory, "target_temperature_range=" + value, _ => {
callback();
})
});
targetChar.on('change', function(oldValue, newValue) {
platform.log(accessory.displayName, "Thermostat target temp " + oldValue + " -> " + newValue);
})
targetChar.on('get', function(callback) {
platform.log(accessory.displayName, "Thermostat target temp get:");
platform.log("token", platform.accessToken)
platform.fetchDeviceWithCache(accessory, data => {
if (typeof(data["error_description"]) != 'undefined') {
callback(new Error(data["error_description"]), null)
return
}
if (typeof(data["target_temperature_range"]) == 'undefined') {
callback(new Error("no target temperature"), null)
return
}
callback(null, data["target_temperature_range"][0])
})
})
const currentTempChar = service.getCharacteristic(Characteristic.CurrentTemperature)
currentTempChar.on('change', function(oldValue, newValue) {
platform.log(accessory.displayName, "Thermostat current temp " + oldValue + " -> " + newValue);
})
currentTempChar.on('get', function(callback) {
platform.log(accessory.displayName, "Thermostat current temp get ", accessory.context);
platform.log("token", platform.accessToken)
platform.fetchDeviceWithCache(accessory, data => {
if (typeof(data["error_description"]) != 'undefined') {
callback(new Error(data["error_description"]))
return
}
if (typeof(data["ambient_temperature"]) == 'undefined') {
callback(new Error("no ambient temperature"))
return
}
callback(null, data["ambient_temperature"])
})
// platform.fetchDevice(accessory, data => {
// })
})
}
SamplePlatform.prototype.ConfigureMaidWhiteSmartplug = function(accessory) {
this.log(accessory.displayName, "Configure Maid White Smartplug");
var platform = this;
const service = accessory.getService(Service.Switch)
const onChar = service.getCharacteristic(Characteristic.On)
onChar.on('set', function(value, callback) {
platform.log(accessory.displayName, "Smartplug on -> " + value);
if (value == 0) {
// turn off
body = "power_status=false"
} else {
// turn on
body = "power_status=true"
}
platform.setDevice(accessory, body, _ => {
callback();
});
});
onChar.on('change', function(oldValue, newValue) {
platform.log(accessory.displayName, "Smartplug on " + oldValue + " -> " + newValue);
})
onChar.on('get', function(callback) {
platform.log(accessory.displayName, "Smartplug on get:");
platform.fetchDeviceWithCache(accessory, data => {
platform.log("got cached data: ", data)
if (data["online"] == false || data["online"] == 'false') {
accessory.updateReachability(false);
return;
}
accessory.updateReachability(true);
if (data["power_status"] == false || data['power_status'] == 'false') {
callback(null, 0)
} else {
callback(null, 1)
}
})
})
}
SamplePlatform.prototype.ConfiguraMaidWhiteInfraredButton = function(accessory) {
this.log(accessory.displayName, "Configure Maid White Smartplug");
var platform = this;
const service = accessory.getService(Service.Switch)
const onChar = service.getCharacteristic(Characteristic.On)
onChar.on('set', function(value, callback) {
platform.log(accessory.displayName, "Button on -> " + value);
body = "power_status=true"
platform.setDevice(accessory, body, _ => {
callback();
});
});
onChar.on('change', function(oldValue, newValue) {
platform.log(accessory.displayName, "Button on " + oldValue + " -> " + newValue);
})
onChar.on('get', function(callback) {
platform.log(accessory.displayName, "Button on get:")
callback(null, 0)
platform.fetchDeviceWithCache(accessory, data => {
platform.log("got cached data: ", data)
if (data["online"] == false || data["online"] == 'false') {
accessory.updateReachability(false);
return;
}
accessory.updateReachability(true);
})
})
}
SamplePlatform.prototype.fetchDeviceWithCache = function(accessory, callback) {
const platform = this
if (typeof(platform.deviceCache[accessory.context.id]) != 'undefined') {
callback(platform.deviceCache[accessory.context.id])
platform.fetchDevice(accessory, _ => {})
return
}
platform.fetchDevice(accessory, callback)
}
SamplePlatform.prototype.fetchDevice = function(accessory, callback) {
const platform = this
fetch(host + "/2/devices/" + accessory.context.id, {
headers: {
"Authorization": "bearer " + platform.accessToken,
}
})
.then(res => res.json())
.then(json => {
platform.log(accessory.displayName, "Thermostat current temp get data ", json);
if (json["online"] != 'undefined') {
if (json["online"]) {
platform.log(accessory.displayName, "Thermostat notify online");
accessory.updateReachability(true);
} else {
platform.log(accessory.displayName, "Thermostat notify offline");
accessory.updateReachability(false);
}
}
platform.deviceCache[accessory.context.id] = json
callback(json)
})
}
SamplePlatform.prototype.setDevice = function(accessory, body, callback) {
const platform = this
fetch(host + "/2/devices/" + accessory.context.id, {
method: "POST",
headers: {
"Authorization": "bearer " + platform.accessToken,
"Content-Type": "application/x-www-form-urlencoded",
},
body: body,
})
.then(res => res.json())
.then(json => {
platform.log(accessory.displayName, "post maid white data got:", json);
if (json["online"] != 'undefined') {
if (json["online"]) {
accessory.updateReachability(true);
} else {
accessory.updateReachability(false);
}
}
callback(json)
})
}
// Handler will be invoked when user try to config your plugin.
// Callback can be cached and invoke when necessary.
SamplePlatform.prototype.configurationRequestHandler = function(context, request, callback) {
this.log("Context: ", JSON.stringify(context));
this.log("Request: ", JSON.stringify(request));
// Check the request response
if (request && request.response && request.response.inputs && request.response.inputs.name) {
this.addAccessory(request.response.inputs.name);
// Invoke callback with config will let homebridge save the new config into config.json
// Callback = function(response, type, replace, config)
// set "type" to platform if the plugin is trying to modify platforms section
// set "replace" to true will let homebridge replace existing config in config.json
// "config" is the data platform trying to save
callback(null, "Maid White", true, {
"platform": "Maid White",
"otherConfig": "SomeData"
});
return;
}
// - UI Type: Input
// Can be used to request input from user
// User response can be retrieved from request.response.inputs next time
// when configurationRequestHandler being invoked
var respDict = {
"type": "Interface",
"interface": "input",
"title": "Add Accessory",
"items": [{
"id": "name",
"title": "Name",
"placeholder": "Fancy Light"
} //,
// {
// "id": "pw",
// "title": "Password",
// "secure": true
// }
]
}
// - UI Type: List
// Can be used to ask user to select something from the list
// User response can be retrieved from request.response.selections next time
// when configurationRequestHandler being invoked
// var respDict = {
// "type": "Interface",
// "interface": "list",
// "title": "Select Something",
// "allowMultipleSelection": true,
// "items": [
// "A","B","C"
// ]
// }
// - UI Type: Instruction
// Can be used to ask user to do something (other than text input)
// Hero image is base64 encoded image data. Not really sure the maximum length HomeKit allows.
// var respDict = {
// "type": "Interface",
// "interface": "instruction",
// "title": "Almost There",
// "detail": "Please press the button on the bridge to finish the setup.",
// "heroImage": "base64 image data",
// "showActivityIndicator": true,
// "showNextButton": true,
// "buttonText": "Login in browser",
// "actionURL": "https://google.com"
// }
// Plugin can set context to allow it track setup process
context.ts = "Hello";
// Invoke callback to update setup UI
callback(respDict);
}
// Sample function to show how developer can add accessory dynamically from outside event
SamplePlatform.prototype.addAccessory = function(accessoryName) {
this.log("Add Accessory");
var platform = this;
var uuid;
uuid = UUIDGen.generate(accessoryName);
var newAccessory = new Accessory(accessoryName, uuid);
newAccessory.on('identify', function(paired, callback) {
platform.log(newAccessory.displayName, "Identify!!!");
callback();
});
// Plugin can save context on accessory to help restore accessory in configureAccessory()
// newAccessory.context.something = "Something"
// Make sure you provided a name for service, otherwise it may not visible in some HomeKit apps
newAccessory.addService(Service.Lightbulb, "Test Light")
.getCharacteristic(Characteristic.On)
.on('set', function(value, callback) {
platform.log(newAccessory.displayName, "Light -> " + value);
callback();
});
this.accessories.push(newAccessory);
this.api.registerPlatformAccessories("homebridge-maid-white", "Maid White", [newAccessory]);
}
SamplePlatform.prototype.updateAccessoriesReachability = function() {
this.log("Update Reachability");
for (var index in this.accessories) {
var accessory = this.accessories[index];
accessory.updateReachability(false);
}
}
// Sample function to show how developer can remove accessory dynamically from outside event
SamplePlatform.prototype.removeAccessory = function() {
this.log("Remove Accessory");
this.api.unregisterPlatformAccessories("homebridge-maid-white", "Maid White", this.accessories);
this.accessories = [];
}