-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (56 loc) · 1.53 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
const rawr = require('rawr');
const config = require('./config');
const { apiFetch } = require('./lib/fetch');
const mqtt = require('mqtt');
async function fetchCards() {
try {
const cards = await apiFetch('/cards/active');
return cards;
} catch (e) {
console.log('error retrieving card db', e);
}
}
async function run() {
if (!config.jwt) {
try {
const resp = await apiFetch('/auth', {method: 'POST', body: { email: config.username, password: config.password }});
console.log('logged in', resp);
config.jwt = resp.token;
} catch (e) {
console.log('error authenticating', e);
process.exit(1);
}
}
if (!config.cards) {
config.cards = await fetchCards();
console.log();
}
console.log('connecting to', config.mqttUrl);
const con = mqtt.connect(config.mqttUrl, {password: config.jwt, username: 'jwt'});
con.on('error', (e) => {
console.log('mqtt error', e);
});
con.on('close', (e, f) => {
console.log('mqtt close', e, f);
});
con.on('disconnect', (e) => {
console.log('mqtt disconnect', e);
});
con.on('reconnect', (e, f) => {
console.log('mqtt reconnect', e, f);
});
con.on('connect', (e) => {
console.log('mqtt connect', e);
con.subscribe('presence', function (err) {
if (!err) {
con.publish('presence', 'Hello mqtt')
}
});
});
con.on('message', (topic, message) => {
// message is Buffer
console.log(topic, message.toString());
// TODO, listen for door requests and updates
});
}
run();