remoteOutput.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const net = require('net');
  2. var clients = {};
  3. function Client(sock) {
  4. var _this = this;
  5. this.id = sock.remoteAddress;
  6. this.name = this.id;
  7. this.sock = sock;
  8. this.active = true;
  9. this.volumeControl = true;
  10. this.sock.on('data', (data) => {
  11. var dataStr = data.toString("utf-8");
  12. dataStr.split(/[\r\n]/).forEach(i => i.length ? _this.onData(i) : i);
  13. });
  14. this.sock.on('close', () => {
  15. if (this.active) {
  16. delete clients[this.id];
  17. require("./outputs.js").unregisterOutput(this.id);
  18. }
  19. });
  20. this.radios = {};
  21. var allRadios = require("./config.js").RADIOS;
  22. for (var i in allRadios)
  23. this.radios[i] = {
  24. address: allRadios[i],
  25. state: false
  26. };
  27. this.sendInputStates();
  28. }
  29. Client.prototype.onData = function(data) {
  30. if (data.startsWith("HELO"))
  31. this.name = data.replace(/^HELO\s+/, "") +" (" +this.sock.remoteAddress +")";
  32. }
  33. Client.prototype.getName = function() {
  34. return this.name;
  35. }
  36. Client.prototype.kill = function() {
  37. this.sock.destroy();
  38. this.active = false;
  39. }
  40. Client.prototype.getInputs = function() {
  41. var result = {};
  42. for (var i in this.radios)
  43. result[i] = this.radios[i].state;
  44. return result;
  45. }
  46. Client.prototype.sendInputStates = function() {
  47. this.sock.write(JSON.stringify(this.radios) +"\n");
  48. }
  49. Client.prototype.setState = function(inputId, state) {
  50. if (!this.radios[inputId])
  51. return false;
  52. if (this.radios[inputId].state !== !!state) {
  53. this.radios[inputId].state = !!state;
  54. this.sendInputStates();
  55. }
  56. return true;
  57. }
  58. function onClientConnection(sock) {
  59. var cli = new Client(sock);
  60. if (clients[cli.id])
  61. clients[cli.id].kill();
  62. clients[cli.id] = cli;
  63. require("./outputs.js").registerOutput(cli.id, cli);
  64. }
  65. module.exports.init = function() {
  66. net.createServer(onClientConnection).listen(require('./config.js').TCP_PORT, require('./config.js').TCP_LISTEN);
  67. }