-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
67 lines (58 loc) · 2.18 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
var Service, Characteristic;
var request = require('request');
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-sonoff-tasmota-http", "SonoffTasmotaHTTP", SonoffTasmotaHTTPAccessory);
}
function SonoffTasmotaHTTPAccessory(log, config) {
this.log = log;
this.config = config;
this.name = config["name"]
this.relay = config["relay"] || ""
this.hostname = config["hostname"] || "sonoff"
this.password = config["password"] || "";
this.service = new Service.Outlet(this.name);
this.service
.getCharacteristic(Characteristic.On)
.on('get', this.getState.bind(this))
.on('set', this.setState.bind(this));
this.log("Sonoff Tasmota HTTP Initialized")
}
SonoffTasmotaHTTPAccessory.prototype.getState = function(callback) {
var that = this
request("http://" + that.hostname + "/cm?user=admin&password=" + that.password + "&cmnd=Power" + that.relay, function(error, response, body) {
if (error) return callback(error);
var sonoff_reply = JSON.parse(body); // {"POWER":"ON"}
that.log("Sonoff HTTP: " + that.hostname + ", Relay " + that.relay + ", Get State: " + JSON.stringify(sonoff_reply));
switch (sonoff_reply["POWER" + that.relay]) {
case "ON":
callback(null, 1);
break;
case "OFF":
callback(null, 0);
break;
}
})
}
SonoffTasmotaHTTPAccessory.prototype.setState = function(toggle, callback) {
var newstate = "%20Off"
if (toggle) newstate = "%20On"
var that = this
request("http://" + that.hostname + "/cm?user=admin&password=" + that.password + "&cmnd=Power" + that.relay + newstate, function(error, response, body) {
if (error) return callback(error);
var sonoff_reply = JSON.parse(body); // {"POWER":"ON"}
that.log("Sonoff HTTP: " + that.hostname + ", Relay " + that.relay + ", Set State: " + JSON.stringify(sonoff_reply));
switch (sonoff_reply["POWER" + that.relay]) {
case "ON":
callback();
break;
case "OFF":
callback();
break;
}
})
}
SonoffTasmotaHTTPAccessory.prototype.getServices = function() {
return [this.service];
}