From 64d186e4a5b938951cf4deb1f4629d784a040086 Mon Sep 17 00:00:00 2001 From: Martin Donnelly Date: Mon, 25 Apr 2016 10:35:39 +0100 Subject: [PATCH] some extra automation and other things, now controls the big room --- app.js | 46 +++++++++++++---------- app/index.html | 14 +++---- app/js/app.js | 41 ++++++++++++++------- lib/mqtt/mqttConnect.js | 67 +++++++++++++++++----------------- lib/office/officeController.js | 11 +++++- routes/heating_v1.js | 2 +- routes/lighting_v1.js | 67 ++++++++++++++++++---------------- routes/projector_v1.js | 2 +- 8 files changed, 142 insertions(+), 108 deletions(-) diff --git a/app.js b/app.js index 32bc92a..5539ecb 100644 --- a/app.js +++ b/app.js @@ -1,7 +1,7 @@ /** * Created by Martin on 08/02/2016. */ -"use strict"; +'use strict'; var express = require('express'); var path = require('path'); var http = require('http'); @@ -47,15 +47,15 @@ app.use(methodoverride()); app.use(bodyparser.urlencoded({extended: false})); -// parse application/json +// Parse application/json app.use(bodyparser.json()); app.use(function(req, res, next) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "X-Requested-With"); + res.header('Access-Control-Allow-Origin', '*'); + res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }); -// app.use(app.router); +// App.use(app.router); app.use(express.static(path.join(__dirname, 'app'))); app.use(errorhandler({dumpExceptions: true, showStack: true})); @@ -65,29 +65,38 @@ projector_v1.use(mqttConnect); // Calendar handler +busEmitter.on('lightingOn', lighting_v1.doLightsOn); +busEmitter.on('lightingOff', lighting_v1.doLightsOff); + +busEmitter.on('heatingOn', mqttConnect.heatingOn); +busEmitter.on('heatingOff', mqttConnect.heatingOff); +busEmitter.on('projectorOn', mqttConnect.projectorOn); +busEmitter.on('projectorOff', mqttConnect.projectorOff); + + cal.startController(busEmitter); -app.get("/stop", function (request, response) { +app.get('/stop', function(request, response) { cal.stopController(); -}); + }); -app.get("/start", function (request, response) { +app.get('/start', function(request, response) { cal.startController(); -}); + }); -app.get("/api/calendar", function (req, res) { +app.get('/api/calendar', function(req, res) { var calJson = cal.returnCalendar(); console.log(calJson); res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(calJson)); -}); + }); app.post('/api/calendar/extend', function(req, res) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({})); -}); + }); @@ -127,7 +136,7 @@ var wsServer = new WebSocketServer({ }); function originIsAllowed(origin) { - // put logic here to detect whether the specified origin is allowed. + // Put logic here to detect whether the specified origin is allowed. return true; } @@ -144,9 +153,9 @@ wsServer.on('request', function(request) { console.log((new Date()) + ' Connection accepted.'); var sendSocketHandler = (obj) => { - // logger.info('sendSocket: ' , JSON.stringify(obj)); - connection.sendUTF(JSON.stringify(obj)); - }; + // Logger.info('sendSocket: ' , JSON.stringify(obj)); + connection.sendUTF(JSON.stringify(obj)); + }; busEmitter.on('sendSocket', sendSocketHandler); @@ -154,8 +163,7 @@ wsServer.on('request', function(request) { if (message.type === 'utf8') { console.log('Received Message: ' + message.utf8Data); connection.sendUTF(message.utf8Data); - } - else if (message.type === 'binary') { + } else if (message.type === 'binary') { console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); connection.sendBytes(message.binaryData); } @@ -171,7 +179,7 @@ mqttConnect.connectWS(function() { console.log('Ready to plug in sockets...'); }); -/*app.get('/', function( req, res) { +/*App.get('/', function( req, res) { res.render('index'); });*/ diff --git a/app/index.html b/app/index.html index ae96538..fedd386 100644 --- a/app/index.html +++ b/app/index.html @@ -101,26 +101,26 @@ -
+
diff --git a/app/js/app.js b/app/js/app.js index 18c82e7..c69c259 100644 --- a/app/js/app.js +++ b/app/js/app.js @@ -5,10 +5,17 @@ var wsUrl = 'ws://ec2-52-50-147-81.eu-west-1.compute.amazonaws.com:8080'; var path = 'http://ec2-52-50-147-81.eu-west-1.compute.amazonaws.com/'; var skycons = new Skycons({color: '#e5f7fd'}); +/* var lights = { off: ['frontLightOff', 'middleLightOff', 'backLightOff'], on: ['frontLightOn', 'middleLightOn', 'backLightOn'] }; +*/ + +var lights = { + off: ['frontLightOff', 'backLightOff'], + on: ['frontLightOn', 'backLightOn'] + }; //Var tempColours = chroma.scale(['blue','yellow','red']).colors(36); //console.log(tempColours); @@ -253,7 +260,7 @@ function updateDateTime() { function turnOnLights(id) { - +console.log(id); $.post(path + 'api/v1/lighting/on', {light: id}, function() {}); } @@ -294,7 +301,8 @@ $('#heatingOff').on('click', function() { }); $('#frontLightOn').on('click', function() { - turnOnLights(1); + //turnOnLights(1); + turnOnLights('o'); }); $('#middleLightOn').on('click', function() { @@ -302,11 +310,13 @@ $('#middleLightOn').on('click', function() { }); $('#backLightOn').on('click', function() { - turnOnLights(3); + //turnOnLights(3); + turnOnLights('n'); }); $('#frontLightOff').on('click', function() { - turnOffLights('a'); + //turnOffLights('a'); + turnOffLights('f'); }); $('#middleLightOff').on('click', function() { @@ -314,7 +324,7 @@ $('#middleLightOff').on('click', function() { }); $('#backLightOff').on('click', function() { - turnOffLights('c'); + turnOffLights('g'); }); function rgb(cv) { @@ -370,15 +380,18 @@ var SOWEBSOCKET = function() { this.toggleLighting = function(id) { 'use strict'; - var _id, $show, $hide; - _id = ['a', 'b', 'c'].indexOf(id); + var _id, _off = ['f', 'g'], _on = ['o', 'n'], $show, $hide; + _id = _off.indexOf(id); + + console.log(id,_id); if (_id > -1) { // Lights are being turnd off $hide = ['#', lights.off[_id]].join(''); $show = ['#', lights.on[_id]].join(''); } else { - _id = parseInt(id) - 1; + _id = _on.indexOf(id); + console.log('>', id,_id); $show = ['#', lights.off[_id]].join(''); $hide = ['#', lights.on[_id]].join(''); @@ -407,6 +420,7 @@ var SOWEBSOCKET = function() { this.toggleProjector = function(status) { 'use strict'; var $show, $hide; + console.log('toggle projector', status); if (status) { $hide = $('#projectorOn'); $show = $('#projectorOff'); @@ -467,7 +481,7 @@ var SOWEBSOCKET = function() { }; this.handleData = function(d) { - +console.log(d.id); switch (d.id) { case 'LightingDataReceived': @@ -482,13 +496,14 @@ var SOWEBSOCKET = function() { case 'calendar': updateCalendar(d); break; - case 'LightingISP15': + case 'Lighting': + console.log('+++ Lighting'); this.toggleLighting(d.device); break; - case 'HeatingISP15': + case 'Heating': this.toggleHeating(d.status); break; - case 'ProjectorISP15': + case 'Projector': this.toggleProjector(d.status); break; @@ -591,7 +606,6 @@ var show_weather = function(position) { -/* (function() { path = 'http://localhost:3000/'; wsUrl = 'ws://localhost:3001'; @@ -605,7 +619,6 @@ var show_weather = function(position) { get_weather(); var soWebSocket = new SOWEBSOCKET(); })(); -*/ document.addEventListener('deviceready', onDeviceReady, false); diff --git a/lib/mqtt/mqttConnect.js b/lib/mqtt/mqttConnect.js index 4320be3..5aea07e 100644 --- a/lib/mqtt/mqttConnect.js +++ b/lib/mqtt/mqttConnect.js @@ -19,13 +19,19 @@ function randomString(length) { return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1); } +/* + Projector: 'ProjectorISP15', + lighting: 'LightingISP15', + heating: 'HeatingISP15', + + */ module.exports = { sockets: null, watches: {}, client: null, - projector: 'ProjectorISP15', - lighting: 'LightingISP15', - heating: 'HeatingISP15', + projector: 'Projector', + lighting: 'Lighting', + heating: 'Heating', myID: 0, connected: false, options: { @@ -53,11 +59,11 @@ module.exports = { }); this.client.on('disconnect', function(e) { - logger.error('mqttConnect - doConnection - disconnet'); + logger.error('mqttConnect - doConnection - disconnect'); logger.error(e); }); this.client.on('error', function(e) { - logger.error('mqttConnect - doConnection - disconnet'); + logger.error('mqttConnect - doConnection - disconnect'); logger.error(e); }); @@ -82,7 +88,7 @@ module.exports = { } var destinationName = mqttConfig.prefix + this.projector + '/cmd/' + 'ON' + '/fmt/json'; this.client.publish(destinationName, 'ON', _callback); - this.emitter.emit('sendSocket',{id: this.projector, status: true}); + this.emitter.emit('sendSocket',{id: this.projector, status: true}); }, projectorOff: function(callback) { var _callback = callback || {}; @@ -91,7 +97,7 @@ module.exports = { } var destinationName = mqttConfig.prefix + this.projector + '/cmd/' + 'OFF' + '/fmt/json'; this.client.publish(destinationName, 'OFF', _callback); - this.emitter.emit('sendSocket',{id: this.projector, status: false}); + this.emitter.emit('sendSocket',{id: this.projector, status: false}); }, heatingOn: function(callback) { console.log('Turn heating on...'); @@ -101,7 +107,7 @@ module.exports = { } var destinationName = mqttConfig.prefix + this.heating + '/cmd/' + 'on' + '/fmt/json'; this.client.publish(destinationName, 'ON', _callback); - this.emitter.emit('sendSocket',{id: this.heating, status: true}); + this.emitter.emit('sendSocket',{id: this.heating, status: true}); }, heatingOff: function(callback) { var _callback = callback || {}; @@ -110,7 +116,7 @@ module.exports = { } var destinationName = mqttConfig.prefix + this.heating + '/cmd/' + 'off' + '/fmt/json'; this.client.publish(destinationName, 'OFF', _callback); - this.emitter.emit('sendSocket',{id: this.heating, status: false}); + this.emitter.emit('sendSocket',{id: this.heating, status: false}); }, lightingOn: function(id, callback) { console.log('lightingOn:' + id); @@ -120,7 +126,7 @@ module.exports = { } var destinationName = mqttConfig.prefix + this.lighting + '/cmd/' + id + '/fmt/json'; this.client.publish(destinationName, 'ON', _callback); - this.emitter.emit('sendSocket',{id: this.lighting, device: id, status: true}); + this.emitter.emit('sendSocket',{id: this.lighting, device: id, status: true}); }, lightingOff: function(id, callback) { var _callback = callback || null; @@ -131,6 +137,14 @@ module.exports = { this.client.publish(destinationName, 'OFF', _callback); this.emitter.emit('sendSocket',{id: this.lighting, device: id, status: false}); }, + setupEvents: function() { + this.emitter.on('lightingOn', this.lightingOn); + this.emitter.on('lightingOff', this.lightingOff); + this.emitter.on('heatingOn', this.heatingOn); + this.emitter.on('heatingOff', this.heatingOff); + this.emitter.on('projectorOn', this.projectorOn); + this.emitter.on('projectorOff', this.projectorOff); + }, connectWS: function(connectCB) { @@ -148,37 +162,24 @@ module.exports = { var watches = {}; wsClient.onMessageArrived = function(msg) { - logger.info("Message from :" + msg.destinationName); - // Console.log("Message from :" + msg.destinationName); + //Logger.info("Message from :" + msg.destinationName); clientStatus.deviceConnected = true; - // $rootScope.$broadcast("clientStatusUpdated", clientStatus); - //logger.debug("clientStatusUpdated", clientStatus); sensorData = JSON.parse(msg.payloadString); + logger.debug(sensorData); var temp = msg.destinationName.split('/'); - //Console.log(temp[4]); - //console.log(sensorData); if (self.watches.hasOwnProperty(temp[4])) { // Logger.info('Emit: ' + JSON.stringify({id:self.watches[temp[4]],sensorData:sensorData})); self.emitter.emit('sendSocket',{id: self.watches[temp[4]],sensorData: sensorData}); } - /* If (temp[4] == lighting) { - // $rootScope.$broadcast("LightingDataReceived", sensorData); - } - if (temp[4] == projector) { - // $rootScope.$broadcast("ProjectorDataReceived", sensorData); - } - if (temp[4] == heating) { - // $rootScope.$broadcast("HeatingISP15DataReceived", sensorData); - }*/ }; - wsClient.onConnectionLost = function(e) { - logger.error('+ onConnectionLost'); - logger.error(e); - logger.error('- onConnectionLost'); - } + wsClient.onConnectionLost = function(e) { + logger.error('+ onConnectionLost'); + logger.error(e); + logger.error('- onConnectionLost'); + } var connectOptions = {}; connectOptions.keepAliveInterval = 3600; @@ -214,7 +215,7 @@ module.exports = { var subscribeOptions = { qos: 0, onSuccess: function() { - console.log('subscribed to ' + subscribeTopic); + logger.info('subscribed to ' + subscribeTopic); clientStatus.subscribed = true; // $rootScope.$broadcast("clientStatusUpdated", clientStatus); @@ -222,8 +223,8 @@ module.exports = { self.watches[deviceId] = emitterId; }, onFailure: function() { - console.error('Failed to subscribe to ' + subscribeTopic); - console.error('As messages are not available, visualization is not possible'); + logger.error('Failed to subscribe to ' + subscribeTopic); + logger.error('As messages are not available, visualization is not possible'); } }; diff --git a/lib/office/officeController.js b/lib/office/officeController.js index f0a4c23..9517a49 100644 --- a/lib/office/officeController.js +++ b/lib/office/officeController.js @@ -59,7 +59,7 @@ var officeController = function(neweventbus) { this.cloneObject(this.todaysList.current, curMeeting); curMeeting.cronJobs = {}; - eventBus.emit('sendSocket', {id:'calendar',current:curMeeting}); + eventBus.emit('sendSocket', {id: 'calendar',current: curMeeting}); }.bind(this)); this.task = cron.schedule('*/5 * * * *', function() { @@ -111,7 +111,11 @@ officeController.prototype.createMeeting = function(obj,delayStart) { self.cloneObject(self.schedule[key], curMeeting); curMeeting.cronJOBS = null; - eventBus.emit('sendSocket', {id:'calendar',current:curMeeting}); + // Lets turn on some lights! + eventBus.emit('lightingOn','o'); + eventBus.emit('lightingOn','n'); + + eventBus.emit('sendSocket', {id: 'calendar',current: curMeeting}); }, true); @@ -122,6 +126,9 @@ officeController.prototype.createMeeting = function(obj,delayStart) { newMeeting.cronJOBS.start = null; newMeeting.cronJOBS.stop = null; + eventBus.emit('lightingOn','f'); + eventBus.emit('lightingOn','g'); + logger.debug(newMeeting.cronJOBS); eventBus.emit('cleanUp',newMeeting.uid); diff --git a/routes/heating_v1.js b/routes/heating_v1.js index c6de590..8719101 100644 --- a/routes/heating_v1.js +++ b/routes/heating_v1.js @@ -52,7 +52,7 @@ module.exports = { }, subscribe: function (socket) { - this.socket.subscribe('HeatingISP15','HeatingDataReceived'); + this.socket.subscribe('Heating','HeatingDataReceived'); } }; diff --git a/routes/lighting_v1.js b/routes/lighting_v1.js index 3c4106b..869811b 100644 --- a/routes/lighting_v1.js +++ b/routes/lighting_v1.js @@ -1,75 +1,80 @@ -"use strict"; +'use strict'; /** * Created by Martin on 09/02/2016. */ -/*var mqttConnect = require("../lib/mqtt/mqttConnect"); +/*Var mqttConnect = require("../lib/mqtt/mqttConnect"); mqttConnect.doConnection();*/ var mqttConnect; + function doLightsOn(id) { - mqttConnect.doConnection().lightingOn(id); + mqttConnect.doConnection().lightingOn(id); } function doLightsOff(id) { - mqttConnect.doConnection().lightingOff(id); + mqttConnect.doConnection().lightingOff(id); } function setUseRef(ref) { - mqttConnect = ref; + mqttConnect = ref; } module.exports = { - mqttConnect:null, - socket:null, - use: function (ref) { + mqttConnect: null, + socket: null, + use: function(ref) { setUseRef(ref); - }, - turnoff: function (req, res) { + }, + turnoff: function(req, res) { if (!req.body.light) { - res.status(400).send({ status: 'error', error: 'missing required parameter' }); - return; + res.status(400).send({ status: 'error', error: 'missing required parameter' }); + return; } console.log(req.body.light); - if (req.body.hasOwnProperty('light')) - { - var light = req.body.light; - doLightsOff(light); + if (req.body.hasOwnProperty('light')) { + var light = req.body.light; + doLightsOff(light); } res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({})); - }, - turnon: function (req, res) { + }, + turnon: function(req, res) { if (!req.body.light) { - res.status(400).send({ status: 'error', error: 'missing required parameter' }); - return; + res.status(400).send({ status: 'error', error: 'missing required parameter' }); + return; } console.log(req.body.light); - if (req.body.hasOwnProperty('light')) - { - var light = req.body.light; - doLightsOn(light); + if (req.body.hasOwnProperty('light')) { + var light = req.body.light; + doLightsOn(light); } res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({})); - }, - setsocket: function (socket) { + }, + setsocket: function(socket) { this.socket = socket; return this; - }, - subscribe: function (socket) { + }, + subscribe: function(socket) { - this.socket.subscribe('LightingISP15','LightingDataReceived'); - } -}; + this.socket.subscribe('Lighting','LightingDataReceived'); + }, + doLightsOn: function(id) { + doLightsOn(id); + }, + doLightsOff: function(id) { + doLightsOff(id); + } + }; diff --git a/routes/projector_v1.js b/routes/projector_v1.js index cd8a9e9..e6e43e0 100644 --- a/routes/projector_v1.js +++ b/routes/projector_v1.js @@ -47,7 +47,7 @@ module.exports = { }, subscribe: function (socket) { - this.socket.subscribe('ProjectorISP15','ProjectorDataReceived'); + this.socket.subscribe('Projector','ProjectorDataReceived'); } };