From 914d60ca25def8805b7fb2dafcab17474e08cc87 Mon Sep 17 00:00:00 2001 From: James Barnett Date: Fri, 30 Mar 2018 22:02:12 +0100 Subject: Poll for realtime usage updates --- routes/energy-usage.js | 24 ++++++++++++++++++++++++ routes/index.js | 29 ++++++----------------------- 2 files changed, 30 insertions(+), 23 deletions(-) create mode 100644 routes/energy-usage.js (limited to 'routes') diff --git a/routes/energy-usage.js b/routes/energy-usage.js new file mode 100644 index 0000000..847248d --- /dev/null +++ b/routes/energy-usage.js @@ -0,0 +1,24 @@ +const express = require('express'); +const router = express.Router(); + +const deviceManager = require('../services/device-manager'); + +router.get('/:deviceId/realtime', function(req, res, next) { + + let deviceId = req.params.deviceId; + + let realtimeUsage = {}; + // TODO - cache results with a short TTL so we don't hammer the plug if multiple clients are requesting data + deviceManager.getDevice(deviceId).emeter.getRealtime().then(response => { + + // Voltage seems to be reported as its peak to peak voltage, not RMS. + // Show the RMS value since thats what would you expect to see. + // i.e. 220v not 310v (in the U.K) + response.voltage = response.voltage / Math.sqrt(2); + + res.json(response); + }); + +}); + +module.exports = router; \ No newline at end of file diff --git a/routes/index.js b/routes/index.js index d1d0519..1dba277 100644 --- a/routes/index.js +++ b/routes/index.js @@ -1,30 +1,13 @@ -var express = require('express'); -var router = express.Router(); +const express = require('express'); +const router = express.Router(); -const { Client } = require('tplink-smarthome-api'); - -const client = new Client(); -var devices = []; - -client.startDiscovery({deviceTypes: ['plug']}).on('plug-new', plug => { - console.log('Found device: ' + plug.alias + ' [' + plug.deviceId + ']'); - devices.push(plug); -}) +const deviceManager = require('../services/device-manager'); router.get('/', function(req, res, next) { - let realtimeUsage = {}; - devices[0].emeter.getRealtime().then(response => { - - realtimeUsage.power = Math.round(response.power); - realtimeUsage.current = response.current.toFixed(2); - realtimeUsage.voltage = Math.round(response.voltage); - - res.render('index',{ - device: devices[0], - devices: devices, - realtimeUsage: realtimeUsage - }); + res.render('index', { + device: deviceManager.getDevice(), + devices: deviceManager.getAllDevices() }); }); -- cgit v1.2.3