-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
104 lines (78 loc) · 2.79 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
"use strict";
var Service, Characteristic;
var crypto = require("crypto");
var Client = require('node-rest-client').Client;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-api-switch", "APISwitch", APISwitch);
}
function APISwitch(log, config) {
this.log = log;
this.service = config.service;
this.name = config.name;
this.url = config.url;
if (config.sn){
this.sn = config.sn;
} else {
var shasum = crypto.createHash('sha1');
shasum.update(this.name);
this.sn = shasum.digest('base64');
this.log('Computed SN ' + this.sn);
}
this.client = new Client();
}
function parseBool(val) {
return val === true || val === "true"
}
APISwitch.prototype = {
getPowerState: function (callback) {
var requestUrl = this.url + "/status"
this.log("Invoking " + requestUrl)
this.client.get(requestUrl, function (data, response) {
this.log("Got state from server:")
//this.log(data)
//this.log(data.status)
//this.log(data.status.power)
var currentState = false
if (data && data.status && data.status.power) {
this.log('Parsing bool from ' + data.status.power)
currentState = parseBool(data.status.power)
}
this.log('Setting current state: ' + currentState)
callback(null, currentState);
}.bind(this));
},
setPowerState: function(powerOn, callback) {
this.log("Setting NAD power to " + powerOn);
var method = "/power_" + (powerOn ? "on" : "off")
var requestUrl = this.url + method
this.log("Invoking " + requestUrl)
var args = {
data: { power: powerOn },
headers: { "Content-Type": "application/json" }
}
this.client.post(requestUrl, args, function (data, response) {
this.log("Got response from server:" + data);
callback();
}.bind(this));
},
identify: function (callback) {
this.log("Identify requested!");
callback(); // success
},
getServices: function () {
this.log("Configuring services");
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, "PianosaLab")
.setCharacteristic(Characteristic.Model, "APISwitch")
.setCharacteristic(Characteristic.SerialNumber, this.sn);
this.service = new Service.Switch(this.name);
this.service
.getCharacteristic(Characteristic.On)
.on('get', this.getPowerState.bind(this))
.on('set', this.setPowerState.bind(this));
return [this.service];
}
}