/** * Created by Martin on 08/02/2016. */ const express = require('express'); const path = require('path'); const server = require('http').createServer(); let ejs = require('ejs'); const morgan = require('morgan'); const cookieparser = require('cookie-parser'); let session = require('express-session'); const sessionLW = require('express-session-lw'); const methodoverride = require('method-override'); const bodyparser = require('body-parser'); const errorhandler = require('errorhandler'); const log4js = require('log4js'); const logger = log4js.getLogger(); let authentication = require('basic-authentication'); const Wemo = require('wemo-client'); const Events = require('events'); const busEmitter = new Events.EventEmitter(); const WebSocketServer = require('ws').Server; const wss = new WebSocketServer({server: server}); const SocketHandler = require('./lib/wshandlerv2'); let webSocket = new SocketHandler(busEmitter, wss); let mqttClient = require('./lib/mqtt/mqttClient'); //Var mqttConnect = require('./lib/mqtt/mqttConnect'); let wemoClient = null; let wemo = new Wemo(); wemo.discover(function(deviceInfo) { logger.info('Wemo Device Found: %j', deviceInfo); // Get the client for the found device wemoClient = wemo.client(deviceInfo); // Handle BinaryState events wemoClient.on('binaryState', function(value) { logger.debug('Binary State changed to: %s', value); // mqttClient.updateGlobal(value); }); // Turn the switch on wemoClient.setBinaryState(0); }); busEmitter.on('changeState', function(mode) { logger.info('Changing state..'); if (wemoClient !== null) { wemoClient.setBinaryState(mode); // let newState = wemoClient.getBinaryState(); // busEmitter.emit('updateState', newState); } else { console.error('No wemoClient'); } }); /* setInterval(function() { let newState = wemoClient.getBinaryState(); busEmitter.emit('updateState', newState); }, 30000);*/ let mqtt = new mqttClient.mqttClient(busEmitter); require('sugar-date'); let isProduction = false; process.env.NODE_ENV = process.env.NODE_ENV || 'development'; if (process.env.NODE_ENV === 'production') { isProduction = true; } logger.warn('isProduction:', isProduction); const heartBeat = function() { this.pingTimer = 0; this.count = 0; this.rate = 90000; this.setupPing = function() { logger.warn('Starting heartbeat...'); this.pingTimer = setTimeout(function() { this.ping(); }.bind(this), 10000); }; this.ping = function() { const now = new Date; const mod = this.rate - (now.getTime() % this.rate); this.count++; if (this.count > 5) { this.count = 1; } const _newDots = ['.', '.', '.', '.', '.']; _newDots[this.count - 1] = 'O'; logger.info(_newDots.join('')); busEmitter.emit('sendSocket', {tick: new Date().getTime()}); this.pingTimer = setTimeout(function() { this.ping(); }.bind(this), mod); }; this.setupPing(); }; const app = express(); const port = (process.env.VCAP_APP_PORT || 3010); let host = (process.env.VCAP_APP_HOST || 'localhost'); app.set('port', port); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(morgan('combined')); app.use(cookieparser('your secret here')); /*App.use(session({ secret: '1234567890QWERTY', resave: false, saveUninitialized: false }));*/ app.use(sessionLW()); app.use(methodoverride()); app.use(bodyparser.urlencoded({extended: false})); // 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'); next(); }); // Run 'npm run production' to use dist const staticDir = isProduction ? 'dist' : 'app'; app.use(express.static(path.join(__dirname, staticDir))); app.use(errorhandler({dumpExceptions: true, showStack: true})); // Events and sockets function originIsAllowed(origin) { // Put logic here to detect whether the specified origin is allowed. return true; } // Glue routes //if (isProduction) { heartBeat(); //} app.get('*', function(req, res) { res.status(404).render('404',{delimiter: '^'}); }); server.on('request', app); server.listen(port, function() { logger.info('New server listening on ' + server.address().port) });