freifunkmanager/webroot/js/socket.js

78 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-05-16 16:00:32 +02:00
/* exported socket */
2017-05-16 19:18:35 +02:00
/* globals notify,gui,store,config*/
let socket = {'readyState': 0};
2017-05-08 19:13:29 +02:00
2017-05-16 19:18:35 +02:00
(function init () {
'use strict';
2017-05-08 19:13:29 +02:00
2017-05-16 19:18:35 +02:00
const RECONNECT_AFTER = 5000;
2017-05-16 19:18:35 +02:00
function onerror (err) {
console.warn(err);
// eslint-disable-next-line no-magic-numbers
if (socket.readyState !== 3) {
notify.send('error', 'Es gibt Übertragungsprobleme!');
gui.render();
}
}
2017-05-08 19:13:29 +02:00
2017-05-16 19:18:35 +02:00
function onopen () {
gui.render();
}
2017-05-08 19:13:29 +02:00
2017-05-16 19:18:35 +02:00
function onmessage (raw) {
const msg = JSON.parse(raw.data);
2017-05-16 19:18:35 +02:00
switch (msg.type) {
case 'system':
2017-05-16 19:18:35 +02:00
store.updateNode(msg.node, true);
break;
case 'current':
2017-05-16 19:18:35 +02:00
store.updateNode(msg.node);
break;
case 'stats':
if (msg.body) {
store.stats = msg.body;
}
break;
default:
notify.send('warn', `unable to identify message: ${raw}`);
break;
}
gui.render();
}
2017-05-16 19:18:35 +02:00
function onclose () {
console.log('socket closed by server');
notify.send('warn', 'Es besteht ein Verbindungsproblem!');
gui.render();
// eslint-disable-next-line no-use-before-define
window.setTimeout(connect, RECONNECT_AFTER);
}
2017-05-16 19:18:35 +02:00
function sendnode (node) {
const notifyMsg = `Einstellungen für '${node.node_id}' gespeichert.`,
socketMsg = JSON.stringify({
'node': node,
'type': 'system'
2017-05-16 19:18:35 +02:00
});
socket.send(socketMsg);
notify.send('success', notifyMsg);
}
function connect () {
socket = new window.WebSocket(config.backend);
socket.onopen = onopen;
socket.onerror = onerror;
socket.onmessage = onmessage;
socket.onclose = onclose;
socket.sendnode = sendnode;
}
connect();
2017-05-08 19:13:29 +02:00
})();