-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
53 lines (46 loc) · 1.51 KB
/
Copy pathindex.js
File metadata and controls
53 lines (46 loc) · 1.51 KB
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
const http = require('http');
const Doorbell = require('./Doorbell');
class HTTPDoorbell {
constructor(log, config, api) {
this.log = log;
const { hap } = api || {};
const {
Service,
Characteristic
} = hap || {};
const {
doorbells: doorbellsConfig,
port = 9090
} = config || {};
this.accessoriesArray = doorbellsConfig.map((d, i) => new Doorbell(d, i, Service, Characteristic, log));
this.doorbells = this.accessoriesArray.reduce((acc, curr) => ({...acc, [curr.id]: curr}), {});
this.server = http.createServer((req, res) => {
const { url } = req || {};
const [, bellId] = url.match(/\/([a-zA-Z0-9]+)/) || [];
const isOK = this.handleRequest(bellId);
const response = { success: isOK };
if (isOK) {
res.end(JSON.stringify(response));
} else {
res.statusCode = 404;
res.end(JSON.stringify(response));
}
});
this.server.listen(port, () => {
this.log(`Doorbells server is listening to port ${port}`);
});
}
handleRequest(bellId) {
const { [bellId]: bell } = this.doorbells || {};
if (bell) {
return bell.ring();
}
return false;
}
accessories(callback) {
callback(this.accessoriesArray);
}
}
module.exports = api => {
api.registerPlatform('http-doorbell-v3', HTTPDoorbell);
};