/* * rhrdweb * * Copyright (C) 2016 Christian Pointner * * This file is part of rhrdweb. * * rhrdweb is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * rhrdweb 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with rhrdweb. If not, see . */ 'use strict'; function Rhctl() { this.draw_callbacks = $.Callbacks('unique'); this.state = 'NEW'; this.sock_onmessage = function(event) { var msg = JSON.parse(event.data); if (msg.RESPONSE_CODE != 200) { console.log("got error message: ", event.data) } else { switch(msg.TYPE) { case 'state': this.draw_callbacks.fireWith(window, [ msg.STATE ]); break; case 'ack': break; default: console.log("rhctl: got unexpected message type '" + msg.TYPE + "'") } } } this.addCallback = function(cb) { this.draw_callbacks.add(cb); } this.sock_onopen = function() { this.state = 'CONNECTED'; console.log('rhctl: ' + this.state) this.sock.onmessage = this.sock_onmessage.bind(this); this.sock.send(JSON.stringify({ COMMAND: 'subscribe', ARGS: [ 'state' ] })); this.sock.send(JSON.stringify({ COMMAND: 'state' })); } this.sock_onclose = function(event) { this.sock.close(); delete this.sock; setTimeout(this.connect.bind(this), 1000); this.state = 'RECONNECTING'; console.log('rhctl: ' + this.state) } this.connect = function() { this.sock = new WebSocket('wss://' + window.location.host + '/rhctl/socket'); this.sock.onopen = this.sock_onopen.bind(this); this.sock.onclose = this.sock_onclose.bind(this); this.state = 'CONNECTING'; console.log('rhctl: ' + this.state) } } var rhctl = new Rhctl(); function rhctl_init() { rhctl.connect(); $('#rhctl').text("loading..."); rhctl.addCallback(rhctl_draw_state); } function rhctl_draw_state(state) { console.log(state); $('#rhctl').text(JSON.stringify(state, null, '\t')); }