fancy socket handling stuff

This commit is contained in:
Martin Donnelly 2016-04-21 16:15:11 +01:00
parent 295bf56587
commit 8fbf67c393
5 changed files with 242 additions and 165 deletions

2
app.js
View File

@ -56,7 +56,7 @@ app.use(function(req, res, next) {
next();
});
// app.use(app.router);
app.use(express.static(path.join(__dirname, 'dist')));
app.use(express.static(path.join(__dirname, 'app')));
app.use(errorhandler({dumpExceptions: true, showStack: true}));
lighting_v1.use(mqttConnect);

View File

@ -4,7 +4,8 @@ body {
}
#weatherIcon {
margin-left:15px;
margin-left:25%;
margin-right:25%;
height:70px;
width:70px;

View File

@ -195,6 +195,7 @@
</div>
</div>-->
</div>
<script src="cordova.js"></script>
<!-- build:vendor -->
<script src="lib/mui.js"></script>
<script src="lib/jquery.js" integrity="sha256-laXWtGydpwqJ8JA+X9x2miwmaiKhn8tVmOVEigRNtP4=" crossorigin="anonymous"></script>

View File

@ -1,8 +1,9 @@
var bus = {};
MicroEvent.mixin(bus);
var path = '';
var skycons = new Skycons({"color": "#e5f7fd"});
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'],
@ -213,14 +214,14 @@ var tempColours = [
}
];
var prevDate, prevTime;
var prevDate, prevTime, weatherTimer = 0;
function updateCalendar(d) {
'use strict';
var $calendar = $('#calendar');
if (d.current !== null && d.current.hasOwnProperty('dtstart')) {
var calString = `<div class="mui--text-subhead">${d.current.summary}</div>`;
var calString = ['<div class="mui--text-subhead">',d.current.summary,'</div>'].join('');
$('#caltext').html(calString);
$calendar.slideDown();
} else {
@ -252,64 +253,28 @@ function updateDateTime() {
function turnOnLights(id) {
var _id = parseInt(id) - 1;
var $lightsOff = ['#', lights.off[_id]].join('');
var $lightsOn = ['#', lights.on[_id]].join('');
$.post(path + 'api/v1/lighting/on', {light: id}, function(res) {
$($lightsOff).show();
$($lightsOn).hide();
});
$.post(path + 'api/v1/lighting/on', {light: id}, function() {});
}
function turnOffLights(id) {
var _id = ['a', 'b', 'c'].indexOf(id);
var $lightsOff = ['#', lights.off[_id]].join('');
var $lightsOn = ['#', lights.on[_id]].join('');
$.post(path + 'api/v1/lighting/off', {light: id}, function(res) {
$($lightsOff).hide();
$($lightsOn).show();
});
$.post(path + 'api/v1/lighting/off', {light: id}, function() {});
}
function turnOnHeating() {
var $heatingOn = $('#heatingOn');
var $heatingOff = $('#heatingOff');
$.post(path + 'api/v1/heating/on', {}, function(repsonse) {
$($heatingOff).show();
$($heatingOn).hide();
});
$.post(path + 'api/v1/heating/on', {}, function() {});
}
function turnOffHeating() {
var $heatingOn = $('#heatingOn');
var $heatingOff = $('#heatingOff');
$.post(path + 'api/v1/heating/off', {}, function(repsonse) {
$($heatingOn).show();
$($heatingOff).hide();
});
$.post(path + 'api/v1/heating/off', {}, function() {});
}
function turnOnProjector() {
var $projectorOn = $('#projectorOn');
var $projectorOff = $('#projectorOff');
$.post(path + 'api/v1/projector/on', {}, function(repsonse) {
$($projectorOff).show();
$($projectorOn).hide();
});
$.post(path + 'api/v1/projector/on', {}, function() {});
}
function turnOffProjector() {
var $projectorOn = $('#projectorOn');
var $projectorOff = $('#projectorOff');
$.post(path + 'api/v1/projector/off', {}, function(repsonse) {
$($projectorOff).hide();
$($projectorOn).show();
});
$.post(path + 'api/v1/projector/off', {}, function() {});
}
$('#projectorOn').on('click', function() {
@ -376,9 +341,8 @@ var SOWEBSOCKET = function() {
this.startWebSocket = function() {
'use strict';
console.log('Starting socket?');
//var url = 'ws://localhost:8080';
var url = 'ws://ec2-52-50-147-81.eu-west-1.compute.amazonaws.com:8080';
var url = wsUrl;
var wsCtor = window['MozWebSocket'] ? MozWebSocket : WebSocket;
this.socket = new wsCtor(url, 'stream');
@ -403,6 +367,59 @@ var SOWEBSOCKET = function() {
}
};
this.toggleLighting = function(id) {
'use strict';
var _id, $show, $hide;
_id = ['a', 'b', 'c'].indexOf(id);
if (_id > -1) {
// Lights are being turnd off
$hide = ['#', lights.off[_id]].join('');
$show = ['#', lights.on[_id]].join('');
} else {
_id = parseInt(id) - 1;
$show = ['#', lights.off[_id]].join('');
$hide = ['#', lights.on[_id]].join('');
}
$($show).show();
$($hide).hide();
};
this.toggleHeating = function(status) {
'use strict';
var $show, $hide;
if (status) {
$hide = $('#heatingOn');
$show = $('#heatingOff');
} else {
$show = $('#heatingOn');
$hide = $('#heatingOff');
}
$($show).show();
$($hide).hide();
};
this.toggleProjector = function(status) {
'use strict';
var $show, $hide;
if (status) {
$hide = $('#projectorOn');
$show = $('#projectorOff');
} else {
$show = $('#projectorOn');
$hide = $('#projectorOff');
}
$($show).show();
$($hide).hide();
};
this.updateLighting = function(obj) {
//Console.log(obj);
$('#lightR').text(obj.Red);
@ -423,8 +440,7 @@ var SOWEBSOCKET = function() {
2) + ('0' + parseInt(newG).toString(16)).substr(-2,
2) + ('0' + parseInt(newB).toString(16)).substr(-2, 2);
$('#lightW').text(w);
$('#lightW').css('background-color', w);
$('#lightW').text(w).css('background-color', w);
};
this.updateProj = function(obj) {
@ -447,8 +463,7 @@ var SOWEBSOCKET = function() {
2) + ('0' + parseInt(y).toString(16)).substr(-2, 2) + ('0' + parseInt(
y).toString(16)).substr(-2, 2);
$('#projW').text(w);
$('#projW').css('background-color', w);
$('#projW').text(w).css('background-color', w);
};
this.handleData = function(d) {
@ -467,6 +482,16 @@ var SOWEBSOCKET = function() {
case 'calendar':
updateCalendar(d);
break;
case 'LightingISP15':
this.toggleLighting(d.device);
break;
case 'HeatingISP15':
this.toggleHeating(d.status);
break;
case 'ProjectorISP15':
this.toggleProjector(d.status);
break;
default:
console.log(d);
break;
@ -516,15 +541,25 @@ var SOWEBSOCKET = function() {
};
var get_weather = function() {
navigator.geolocation.getCurrentPosition(show_weather,function(e){alert(e.code + ' / ' + e.message);});
navigator.geolocation.getCurrentPosition(show_weather,function(e) {alert(e.code + ' / ' + e.message);});
};
bus.bind('displayWeather', function(data) {
console.log(data);
console.log(data.currently);
$('#weatherText').html(parseInt(data.currently.temperature) + '&deg;c&nbsp;');
skycons.add("icon1", data.currently.icon);
skycons.add('icon1', data.currently.icon);
});
var weatherClock = function() {
'use strict';
get_weather();
var now = new Date;
var mod = 1800000 - (now.getTime() % 1800000);
weatherTimer = setTimeout(function() {weatherClock();},mod + 10);
}
var show_weather = function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
@ -556,7 +591,10 @@ var show_weather = function(position) {
/*
(function() {
path = 'http://localhost:3000/';
wsUrl = 'ws://localhost:3001';
var iOS = ['iPad', 'iPhone', 'iPod'].indexOf(navigator.platform) >= 0;
if (iOS) {
$('#iosTaskbar').show();
@ -567,3 +605,20 @@ var show_weather = function(position) {
get_weather();
var soWebSocket = new SOWEBSOCKET();
})();
*/
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
console.log('+++ device ready');
var iOS = ['iPad', 'iPhone', 'iPod'].indexOf(navigator.platform) >= 0;
if (iOS) {
$('#iosTaskbar').show();
// path = 'http://localhost:3000/';
}
clock();
weatherClock();
var soWebSocket = new SOWEBSOCKET();
}

View File

@ -1,10 +1,10 @@
/**
* Created by Martin on 08/02/2016.
*/
"use strict";
'use strict';
var mqtt = require('mqtt');
var Messaging = require("mqtt_over_websockets");
var Messaging = require('mqtt_over_websockets');
var log4js = require('log4js');
var logger = log4js.getLogger();
@ -13,15 +13,15 @@ var mqttConfig = {
userName: 'a-qz0da4-dfwwdkmkzr',
appKey: '9txJEf3Cjy7hkSOvkv',
prefix: 'iot-2/type/Ti-CC3200/id/'
};
};
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
module.exports = {
sockets : null,
watches : {},
sockets: null,
watches: {},
client: null,
projector: 'ProjectorISP15',
lighting: 'LightingISP15',
@ -34,132 +34,151 @@ module.exports = {
username: mqttConfig.userName,
password: new Buffer(mqttConfig.appKey)
},
setEmitter: function(newEmitter)
{
},
setEmitter: function(newEmitter) {
this.emitter = newEmitter;
},
doConnection: function (cb) {
doConnection: function(cb) {
console.log('Do connection');
var self = this;
if (this.client === null) {
this.client = mqtt.connect('mqtt://' + mqttConfig.orgId + '.messaging.internetofthings.ibmcloud.com', this.options);
this.client = mqtt.connect('mqtt://' + mqttConfig.orgId + '.messaging.internetofthings.ibmcloud.com', this.options);
this.client.on('connect', function () {
console.log('Connected to IBM');
self.connected = this.connected;
this.client.on('connect', function() {
logger.info('Connected to IBM');
self.connected = this.connected;
});
this.client.on('connected', function() {
logger.debug('mqttConnect - doConnection - Connected');
});
this.client.on('disconnect', function(e) {
logger.error('mqttConnect - doConnection - disconnet');
logger.error(e);
});
this.client.on('error', function(e) {
logger.error('mqttConnect - doConnection - disconnet');
logger.error(e);
});
}
return this;
},
isConnected: function () {
},
isConnected: function() {
return this.connected;
},
sendCommand: function (deviceID, command) {
},
sendCommand: function(deviceID, command) {
var payload = {
id: "d",
id: 'd',
text: command
};
},
projectorOn: function (callback) {
};
},
projectorOn: function(callback) {
var _callback = callback || {};
if (!this.client) {
return -1;
return -1;
}
var destinationName = mqttConfig.prefix + this.projector + "/cmd/" + 'ON' + "/fmt/json";
var destinationName = mqttConfig.prefix + this.projector + '/cmd/' + 'ON' + '/fmt/json';
this.client.publish(destinationName, 'ON', _callback);
},
projectorOff: function (callback) {
this.emitter.emit('sendSocket',{id: this.projector, status: true});
},
projectorOff: function(callback) {
var _callback = callback || {};
if (!this.client) {
return -1;
return -1;
}
var destinationName = mqttConfig.prefix + this.projector + "/cmd/" + 'OFF' + "/fmt/json";
var destinationName = mqttConfig.prefix + this.projector + '/cmd/' + 'OFF' + '/fmt/json';
this.client.publish(destinationName, 'OFF', _callback);
},
heatingOn: function (callback) {
this.emitter.emit('sendSocket',{id: this.projector, status: false});
},
heatingOn: function(callback) {
console.log('Turn heating on...');
var _callback = callback || null;
if (!this.client) {
return -1;
return -1;
}
var destinationName = mqttConfig.prefix + this.heating + "/cmd/" + 'on' + "/fmt/json";
var destinationName = mqttConfig.prefix + this.heating + '/cmd/' + 'on' + '/fmt/json';
this.client.publish(destinationName, 'ON', _callback);
},
heatingOff: function (callback) {
this.emitter.emit('sendSocket',{id: this.heating, status: true});
},
heatingOff: function(callback) {
var _callback = callback || {};
if (!this.client) {
return -1;
return -1;
}
var destinationName = mqttConfig.prefix + this.heating + "/cmd/" + 'off' + "/fmt/json";
var destinationName = mqttConfig.prefix + this.heating + '/cmd/' + 'off' + '/fmt/json';
this.client.publish(destinationName, 'OFF', _callback);
},
lightingOn: function (id, callback) {
this.emitter.emit('sendSocket',{id: this.heating, status: false});
},
lightingOn: function(id, callback) {
console.log('lightingOn:' + id);
var _callback = callback || null;
if (!this.client) {
return -1;
return -1;
}
var destinationName = mqttConfig.prefix + this.lighting + "/cmd/" + id + "/fmt/json";
var destinationName = mqttConfig.prefix + this.lighting + '/cmd/' + id + '/fmt/json';
this.client.publish(destinationName, 'ON', _callback);
},
lightingOff: function (id, callback) {
this.emitter.emit('sendSocket',{id: this.lighting, device: id, status: true});
},
lightingOff: function(id, callback) {
var _callback = callback || null;
if (!this.client) {
return -1;
return -1;
}
var destinationName = mqttConfig.prefix + this.lighting + "/cmd/" + id + "/fmt/json";
var destinationName = mqttConfig.prefix + this.lighting + '/cmd/' + id + '/fmt/json';
this.client.publish(destinationName, 'OFF', _callback);
this.emitter.emit('sendSocket',{id: this.lighting, device: id, status: false});
},
},
connectWS: function(connectCB) {
connectWS: function (connectCB) {
logger.debug("Going to connect WS");
logger.debug('Going to connect WS');
var self = this;
var hostname = "qz0da4" + ".messaging.internetofthings.ibmcloud.com";
var clientId = "a:" + "qz0da4" + ":" + Date.now();
var hostname = 'qz0da4' + '.messaging.internetofthings.ibmcloud.com';
var clientId = 'a:' + 'qz0da4' + ':' + Date.now();
var api_key = "a-qz0da4-dfwwdkmkzr";
var auth_token = "9txJEf3Cjy7hkSOvkv";
var api_key = 'a-qz0da4-dfwwdkmkzr';
var auth_token = '9txJEf3Cjy7hkSOvkv';
var wsClient = new Messaging.Client(hostname, 8883, clientId);
var clientStatus = {connected: false, subscribed: false, deviceConnected: false};
var sensorData = {};
var watches ={};
var watches = {};
wsClient.onMessageArrived = function (msg) {
// console.log("Message from :" + msg.destinationName);
clientStatus.deviceConnected = true;
// $rootScope.$broadcast("clientStatusUpdated", clientStatus);
//logger.debug("clientStatusUpdated", clientStatus);
sensorData = JSON.parse(msg.payloadString);
var temp = msg.destinationName.split("/");
//console.log(temp[4]);
//console.log(sensorData);
if (self.watches.hasOwnProperty(temp[4]))
{
wsClient.onMessageArrived = function(msg) {
logger.info("Message from :" + msg.destinationName);
// Console.log("Message from :" + msg.destinationName);
clientStatus.deviceConnected = true;
// $rootScope.$broadcast("clientStatusUpdated", clientStatus);
//logger.debug("clientStatusUpdated", clientStatus);
sensorData = JSON.parse(msg.payloadString);
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}));
// 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);
}*/
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');
}
var connectOptions = {};
connectOptions.keepAliveInterval = 3600;
@ -167,59 +186,60 @@ module.exports = {
connectOptions.userName = api_key;
connectOptions.password = auth_token;
connectOptions.onSuccess = function () {
connectOptions.onSuccess = function() {
clientStatus.connected = true;
logger.info("MQTT connected to host: " + wsClient.host + " port : " + wsClient.port + " at " + Date.now());
logger.info('MQTT connected to host: ' + wsClient.host + ' port : ' + wsClient.port + ' at ' + Date.now());
self.emitter.emit("clientStatusUpdated", clientStatus);
self.emitter.emit("clientConnected", self.sockets);
};
self.emitter.emit('clientStatusUpdated', clientStatus);
self.emitter.emit('clientConnected', self.sockets);
};
connectOptions.onFailure = function (e) {
logger.error("MQTT connection failed at " + Date.now() + "\nerror: " + e.errorCode + " : " + e.errorMessage);
};
connectOptions.onFailure = function(e) {
logger.error('MQTT connection failed at ' + Date.now() + '\nerror: ' + e.errorCode + ' : ' + e.errorMessage);
};
logger.debug("about to connect to " + wsClient.host);
logger.debug('about to connect to ' + wsClient.host);
wsClient.connect(connectOptions);
this.sockets = {
getClientStatus: function () {
getClientStatus: function() {
return clientStatus;
},
subscribe: function( deviceId, emitterId) {
logger.debug("trying to subscribe");
var subscribeTopic = "iot-2/type/Ti-CC3200/id/" + deviceId + "/evt/+/fmt/json";
},
subscribe: function(deviceId, emitterId) {
logger.debug('trying to subscribe');
var subscribeTopic = 'iot-2/type/Ti-CC3200/id/' + deviceId + '/evt/+/fmt/json';
logger.debug(subscribeTopic);
var subscribeOptions = {
qos: 0,
onSuccess: function () {
console.log("subscribed to " + subscribeTopic);
onSuccess: function() {
console.log('subscribed to ' + subscribeTopic);
clientStatus.subscribed = true;
// $rootScope.$broadcast("clientStatusUpdated", clientStatus);
// $rootScope.$broadcast("clientStatusUpdated", clientStatus);
self.emitter.emit("clientStatusUpdated", clientStatus);
self.emitter.emit('clientStatusUpdated', clientStatus);
self.watches[deviceId] = emitterId;
},
onFailure: function () {
console.log("Failed to subscribe to " + subscribeTopic);
console.log("As messages are not available, visualization is not possible");
}
};
},
onFailure: function() {
console.error('Failed to subscribe to ' + subscribeTopic);
console.error('As messages are not available, visualization is not possible');
}
};
/*if (IoTFconnector.prototype.clientStatus.subscribeTopic != "") {
/*If (IoTFconnector.prototype.clientStatus.subscribeTopic != "") {
console.log("Unsubscribing to " + subscribeTopic);
wsClient.unsubscribe(IoTFconnector.prototype.clientStatus.subscribeTopic);
};*/
wsClient.subscribe(subscribeTopic, subscribeOptions);
}
};
}
};
return this.sockets;
}
};
}
};