UNPKG

domotz-remote-pawn

Version:

Domotz Agent

97 lines (84 loc) 3.3 kB
/** This file is part of Domotz Agent. * Copyright (C) 2016 Domotz Ltd * * Domotz Agent is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Domotz Agent is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Domotz Agent. If not, see <http://www.gnu.org/licenses/>. * * Created by Andrea Azzarà <a.azzara@domotz.com> on 13/12/18 */ 'use strict'; function wsServer(resourceLocator) { var myConsole = resourceLocator.log.decorateLogs(); var webapp = resourceLocator.webapp; var wss = null; function create() { if (wss) { return; } var port = webapp.get('port'); var server = webapp.get('server'); myConsole.info('WS_SERVER ON %s', port); var webSocket = resourceLocator.ws; wss = new webSocket.Server({ server: server }); wss.on('connection', function connection(session) { myConsole.info('connection'); var handleMessage = function (data) { var message; try { message = JSON.parse(data); } catch (err) { myConsole.warn('%s - error parsing command %s', err); return; } if (message.command !== 'LIVE_PING') { myConsole.warn('%s - unrecognized command', message.command); return; } if (!resourceLocator.netPing) { myConsole.warn('netping module not available'); return; } var sessionId = message.session_id; var startTime = new Date(); resourceLocator.networkTools.rtd.livePing( { interval_ms: message.interval_ms || 1000, timeout_ms: message.timeout_ms || 1000, count: message.count || 20, destination: message.destination, }, function (res) { session.send( JSON.stringify({ session_id: sessionId, sample: res, elapsed: new Date() - startTime, }), function (err) { if (err) { myConsole.warn('websocket send error'); } } ); } ); myConsole.debug('Received command %s', data); }; session.on('message', handleMessage); }); } return { create: create, }; } module.exports.wsServer = wsServer;