-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
80 lines (69 loc) · 2.05 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
const request = require('request-promise-native');
let Service, Characteristic;
const BASE_URL = 'https://api.nature.global';
module.exports = homebridge => {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory(
'homebridge-nature-remo-lights',
'NatureRemoLightDevice',
NatureRemoLightDevice
);
};
class NatureRemoLightDevice {
constructor(log, config, api) {
this.log = log;
this.config = config;
if (api) {
this.api = api;
this.api.on('didFinishLaunching', () => {
this.log('DidFinishLaunching');
});
}
}
getServices() {
const informationService = new Service.AccessoryInformation()
.setCharacteristic(Characteristic.Manufacturer, 'Nature, Inc.')
.setCharacteristic(Characteristic.Model, 'NatureRemo')
.setCharacteristic(Characteristic.SerialNumber, 'nature-remo');
const lightBulb = new Service.Lightbulb(this.config.name);
lightBulb
.getCharacteristic(Characteristic.On)
.on('get', this.getOnCharacteristicHandler.bind(this))
.on('set', this.setOnCharacteristicHandler.bind(this));
return [informationService, lightBulb];
}
async getOnCharacteristicHandler(callback) {
const options = {
url: `${BASE_URL}/1/appliances`,
headers: {
Authorization: `Bearer ${this.config.accessToken}`,
},
};
let state = false;
try {
const responses = await request(options);
const device = JSON.parse(responses).filter(
res => res.id === this.config.id
)[0];
state = device.light.state.power === 'on';
} catch (e) {
this.log(e);
}
callback(null, state);
}
async setOnCharacteristicHandler(value, callback) {
const options = {
method: 'POST',
url: `${BASE_URL}/1/appliances/${this.config.id}/light`,
form: {
button: value ? 'on' : 'off',
},
headers: {
Authorization: `Bearer ${this.config.accessToken}`,
},
};
await request(options);
callback(null);
}
}