-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (60 loc) · 1.74 KB
/
index.js
File metadata and controls
76 lines (60 loc) · 1.74 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const { connect } = require('mqtt');
const { Unifi } = require('./unifi');
const { config } = require('./config');
const { version } = require('./package');
const topics = {
state: () => `${config.mqtt.path}/state`,
update: ({ siteDescription, name }) => `${config.mqtt.path}/${siteDescription}/${name}`,
};
const format = (type, args) => [
`[${type.toUpperCase()}]`,
...args,
].join(' ');
const log = (type, ...args) => console.log(format(type, args));
const error = (type, ...args) => console.error(format(type, args));
const mqtt = connect(config.mqtt.host, {
username: config.mqtt.username,
password: config.mqtt.password,
clientId: config.mqtt.id,
will: {
topic: topics.state(),
payload: JSON.stringify({ online: false }),
retain: true,
},
});
const unifi = new Unifi(config.unifi);
unifi.on('error', (e) => {
error('unifi', 'connection error');
error('unifi', ` > ${e.toString()}`);
// exiting in case of error so
// supervisor can restart it
process.exit(1);
});
unifi.on('connect', () => {
error('unifi', `connected to ${config.unifi.host}`);
mqtt.publish(topics.state(), JSON.stringify({
online: true,
version,
}), { retain: true });
});
unifi.on('update', (site, client, state) => {
const topic = topics.update({
siteName: site.name,
siteDescription: site.desc,
name: client.name,
mac: client.mac,
});
log('unifi', `update for ${topic}`);
log('unifi', ` > ${JSON.stringify(state)}`);
mqtt.publish(topic, JSON.stringify(state), {
retain: true,
});
});
mqtt.on('connect', () => log('mqtt', `connected to ${config.mqtt.host}`));
mqtt.on('error', (e) => {
error('mqtt', 'connection error');
error('mqtt', ` > ${e.toString()}`);
// exiting in case of error so
// supervisor can restart it
process.exit(1);
});