diff --git a/main.js b/main.js index 194cd3b7d91845d5f20fad35c6ea23183eacaca3..77edf689f7882aca8d391c8b83b871f56067cd4a 100644 --- a/main.js +++ b/main.js @@ -9,6 +9,7 @@ require('console-stamp')(console); class DoorInfo { state = null; opener = null; + lastChange = null; } const web_host = process.env.HTTP_BIND; @@ -49,6 +50,8 @@ const update_door_state = (door, state) => { return; } + const oldState = doors[door].state; + switch (state) { case "ON": console.log(`Door ${door} opened!`); @@ -62,7 +65,12 @@ const update_door_state = (door, state) => { default: console.log(`Unknown message received for door ${door}`); - break; + return; + } + + // Only update lastChange if the state actually changed + if (oldState !== doors[door].state) { + doors[door].lastChange = new Date().toISOString(); } }; @@ -225,6 +233,39 @@ const server = http.createServer((req, res) => { return send_file(res, 200, './static/darkmode.js', 'text/javascript'); } + if (req.url === '/state/ucc/lastchange') { + if (doors['ucc-door'].lastChange === null) { + return send_json(res, 500, null); + } + + return send_json(res, 200, { + lastChange: doors['ucc-door'].lastChange, + state: doors['ucc-door'].state + }); + } + + if (req.url === '/state/unisfa/lastchange') { + if (doors['unisfa-door'].lastChange === null) { + return send_json(res, 500, null); + } + + return send_json(res, 200, { + lastChange: doors['unisfa-door'].lastChange, + state: doors['unisfa-door'].state + }); + } + + if (req.url === '/state/uwaes/lastchange') { + if (doors['uwaes-door'].lastChange === null) { + return send_json(res, 500, null); + } + + return send_json(res, 200, { + lastChange: doors['uwaes-door'].lastChange, + state: doors['uwaes-door'].state + }); + } + return send_error(res, 404); });