-
Notifications
You must be signed in to change notification settings - Fork 5
/
lights-api.ts
93 lines (79 loc) · 2.61 KB
/
lights-api.ts
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
const https = require('https');
const SUCCESS = null;
const deviceMap = new Map<number, boolean>();
class DweloLight {
constructor(private readonly api, public readonly id) {
}
get = (callback) => {
this.api.getStatus(this.id)
.then(isOn => callback(SUCCESS, isOn))
.catch(callback);
}
set = (state, callback) => {
this.api.toggleLight(state, this.id)
.then(() => callback(SUCCESS))
.catch(callback);
}
}
export class DweloApi {
constructor(private readonly home, private readonly token) {
}
createLight(id) {
return new DweloLight(this, id);
}
makeRequest(path) {
const _headers = {
'Authorization': "Token " + this.token
};
let _content = undefined;
const makeRequest = (method) => {
return new Promise<{[key: string]: any}>((resolve) => {
const request = https.request({
host: 'api.dwelo.com',
path: path,
port: 443,
method: method,
headers: _headers
}, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("->::"+chunk);
resolve(JSON.parse(chunk));
});
});
_content && request.write(_content);
request.end();
});
}
return {
POST: (content) => {
_headers['Content-Type'] = 'application/json;charset=UTF-8';
_headers['Content-Length'] = Buffer.byteLength(content);
_content = content;
return makeRequest('POST');
},
GET: () => {
return makeRequest('GET');
}
}
}
toggleLight(on: boolean, id: number) {
const command = `{"command":"${on ? 'on' : 'off'}"}`;
const path = `/v3/device/${id}/command/`;
deviceMap.set(id, on);
return this.makeRequest(path).POST(command);
}
getStatus(deviceId: number) {
return new Promise<boolean>((resolve) => {
return resolve(!!deviceMap.get(deviceId));
});
// return this.makeRequest(`/v3/sensor/gateway/${this.home}/`).GET().then(r => {
// const device = r.results.find(s => s.deviceId == deviceId);
// if (!device) {
// return false;
// } else {
// return device.value == 'on';
// }
// });
}
}