| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- const net = require('net');
- var clients = {};
- function Client(sock) {
- var _this = this;
- this.id = sock.remoteAddress;
- this.name = this.id;
- this.sock = sock;
- this.active = true;
- this.volumeControl = true;
- this.sock.on('data', (data) => {
- var dataStr = data.toString("utf-8");
- dataStr.split(/[\r\n]/).forEach(i => i.length ? _this.onData(i) : i);
- });
- this.sock.on('close', () => {
- if (this.active) {
- delete clients[this.id];
- require("./outputs.js").unregisterOutput(this.id);
- }
- });
- this.radios = {};
- var allRadios = require("./config.js").RADIOS;
- for (var i in allRadios)
- this.radios[i] = {
- address: allRadios[i],
- state: false
- };
- this.sendInputStates();
- }
- Client.prototype.onData = function(data) {
- if (data.startsWith("HELO"))
- this.name = data.replace(/^HELO\s+/, "") +" (" +this.sock.remoteAddress +")";
- }
- Client.prototype.getName = function() {
- return this.name;
- }
- Client.prototype.kill = function() {
- this.sock.destroy();
- this.active = false;
- }
- Client.prototype.getInputs = function() {
- var result = {};
- for (var i in this.radios)
- result[i] = this.radios[i].state;
- return result;
- }
- Client.prototype.sendInputStates = function() {
- this.sock.write(JSON.stringify(this.radios) +"\n");
- }
- Client.prototype.setState = function(inputId, state) {
- if (!this.radios[inputId])
- return false;
- if (this.radios[inputId].state !== !!state) {
- this.radios[inputId].state = !!state;
- this.sendInputStates();
- }
- return true;
- }
- function onClientConnection(sock) {
- var cli = new Client(sock);
- if (clients[cli.id])
- clients[cli.id].kill();
- clients[cli.id] = cli;
- require("./outputs.js").registerOutput(cli.id, cli);
- }
- module.exports.init = function() {
- net.createServer(onClientConnection).listen(require('./config.js').TCP_PORT, require('./config.js').TCP_LISTEN);
- }
|