diff --git a/main.js b/main.js index ce4f6054d57217e44d0746f40ca66a34deef2b90..8cb769adb9494a2227dadc21ae25fa57445fc401 100644 --- a/main.js +++ b/main.js @@ -25,10 +25,11 @@ const client = mqtt.connect(`mqtt://${mqtt_host}:${mqtt_port}`, options); client.on('connect', () => { console.log('Connected!'); // Subscribe to a topic - client.subscribe('door/ucc-door/state', () => {}); + client.subscribe('door/ucc-door/+', () => {}); }); -let doorStatus = null; +let doorState = null; +let doorOpener = null; // Receive messages client.on('message', (topic, message) => { @@ -36,12 +37,12 @@ client.on('message', (topic, message) => { switch (message.toString()) { case "ON": console.log("Door opened!"); - doorStatus = true; + doorState = true; break; case "OFF": console.log("Door closed!"); - doorStatus = false; + doorState = false; break; default: @@ -49,6 +50,12 @@ client.on('message', (topic, message) => { break; } } + else if (topic === 'door/ucc-door/opener') { + const opener = message.toString(); + if (opener) { + doorOpener = opener; + } + } }); const send_error = (res, code) => { @@ -58,7 +65,7 @@ const send_error = (res, code) => { const send_json = (res, code, data) => { res.writeHead(code, {'Content-Type': 'application/json'}); - res.end(String(data)); + res.end(JSON.stringify(data)); } const send_file = (res, code, fname, ctype) => { @@ -68,7 +75,7 @@ const send_file = (res, code, fname, ctype) => { res.end(data); } -// Serve status on http +// Serve state on http const server = http.createServer((req, res) => { console.log(`Serving request for ${req.url}`); @@ -77,20 +84,28 @@ const server = http.createServer((req, res) => { } if (req.url === '/') { - if (doorStatus === null) { + if (doorState === null) { return send_file(res, 500, './door_unavail.html', 'text/html'); } - const fname = doorStatus ? './door_open.html' : './door_closed.html'; + const fname = doorState ? './door_open.html' : './door_closed.html'; return send_file(res, 200, fname, 'text/html'); } - if (req.url === '/status') { - if (doorStatus === null) { + if (req.url === '/state') { + if (doorState === null) { + return send_json(res, 500, null); + } + + return send_json(res, 200, doorState); + } + + if (req.url === '/opener') { + if (doorOpener === null) { return send_json(res, 500, null); } - return send_json(res, 200, doorStatus); + return send_json(res, 200, doorOpener); } if (req.url === '/gary.jpg') {