From b151acf98f9687c7f1313a8a7d82c23f5d2e8ca9 Mon Sep 17 00:00:00 2001 From: jean-emmanuel Date: Fri, 25 May 2018 09:03:38 +0200 Subject: [PATCH] osc: implement tcp support (#298) --- CHANGELOG.md | 5 + app/main/osc.js | 227 ---------------------------- app/main/osc/index.js | 236 ++++++++++++++++++++++++++++++ app/main/osc/tcp.js | 122 +++++++++++++++ app/main/osc/udp.js | 22 +++ app/main/settings.js | 18 +++ app/package.json | 4 +- package.json | 24 +-- resources/docs/getting-started.md | 2 + 9 files changed, 419 insertions(+), 241 deletions(-) delete mode 100644 app/main/osc.js create mode 100644 app/main/osc/index.js create mode 100644 app/main/osc/tcp.js create mode 100644 app/main/osc/udp.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cd88319..ab5de8f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 0.32.0 + +- main + - add tcp support + ## 0.31.0 - bug fixes diff --git a/app/main/osc.js b/app/main/osc.js deleted file mode 100644 index 30930743..00000000 --- a/app/main/osc.js +++ /dev/null @@ -1,227 +0,0 @@ -// destroy serialport module -// (electron-rebuild breaks it for node-only mode) -require('vmodule')('serialport', {}, {global: true}) - -var osc = require('osc'), - ipc = require('./server').ipc, - settings = require('./settings'), - zeroconf = require('./zeroconf'), - oscInPort = settings.read('oscInPort') || settings.read('httpPort'), - debug = settings.read('debug'), - vm = require('vm'), - fs = require('fs'), - midi = settings.read('midi') ? require('./midi') : false - -var oscServer = new osc.UDPPort({ - localAddress: "0.0.0.0", - localPort: oscInPort, - metadata: true, - broadcast: true -}) - -zeroconf.publish({ - name: settings.read('appName') + (settings.read('instanceName') ? ' (' + settings.read('instanceName') + ')' : ''), - protocol: 'udp', - type: 'osc', - port: oscInPort -}).on('error', (e)=>{ - console.error(`Error: Zeroconf: ${e.message}`) -}) - -var parseType = function(type){ - var t = type[0].match(/[bhtdscrmifTFNI]/) - - if (t!==null) { - return t[0] - } else { - return 's' - } - -} - -var parseArg = function(arg, precision){ - if (arg==null) return null - switch (typeof arg) { - case 'number': - var typeTagMatch = typeof precision == 'string' ? precision.match(/[0-9]+([a-zA-Z]{1})/) : null, - typeTag = typeTagMatch === null ? precision == 0 ? 'i' : 'f' : typeTagMatch[1], - precisionValue = parseFloat(precision) || 0 - - return {type: typeTag, value: parseFloat(arg.toFixed(precisionValue))} - case 'boolean': - return {type: arg ? 'T' : 'F', value: arg} - case 'object': - if (arg.type) { - return {type: parseType(arg.type), value: arg.value} - } else { - return {type: 's', value:JSON.stringify(arg)} - } - case 'string': - return {type: 's', value:arg} - default: - return {type: 's', value:JSON.stringify(arg)} - } -} - -var sendOsc = function(data){ - - if (!data) return - - if (data.host == 'midi') { - - if (midi) midi.send(data) - - } else { - - if (typeof data.address !== 'string' || data.address[0] !== '/') { - console.error('OSC error: malformed address: "' + data.address + "") - return - } - - oscServer.send({ - address: data.address, - args: data.args - }, data.host, data.port) - - if (debug) console.log('OSC sent: ',{address:data.address, args: data.args}, 'To : ' + data.host + ':' + data.port) - - } - - -} - -// var receiveOscQueue = [] - -var receiveOsc = function(data, info){ - - if (!data) return - - for (i in data.args) { - data.args[i] = data.args[i].value - } - - if (data.args.length==1) data.args = data.args[0] - - // receiveOscQueue.push(data) - - ipc.send('receiveOsc',data) - - if (debug) console.log('OSC received: ', {address:data.address, args: data.args}, 'From : ' + data.host + ':' + data.port) - -} - -// setInterval(()=>{ -// -// if (receiveOscQueue.length > 0) { -// ipc.send('bundle',receiveOscQueue) -// receiveOscQueue = [] -// } -// -// }, 5) - - -var customModule = (function(){ - - if (!settings.read('customModule')) return false - - var file = (function(){ - try { - return fs.readFileSync(settings.read('customModule'),'utf8') - } catch(err) { - console.log('CustomModule Error: File not found: ' + settings.read('customModule')) - return false - } - })(), - mod, - context = { - console, - sendOsc, - receiveOsc, - setTimeout, - clearTimeout, - setInterval, - clearInterval, - settings - } - - try { - mod = vm.runInContext(file, vm.createContext(context)) - } catch(err) { - console.log(err) - return false - } - - return mod - -})() - - -var oscInFilter = function(data){ - if (customModule.oscInFilter) { - return customModule.oscInFilter(data) - } else { - return data - } -} -var oscOutFilter = function(data){ - if (customModule.oscOutFilter) { - return customModule.oscOutFilter(data) - } else { - return data - } -} - -var oscInHandler = function(msg, timetag, info){ - var data = oscInFilter({address: msg.address, args: msg.args, host: info.address, port: info.port}) - if (!data) return - receiveOsc(data) -} - -oscServer.on('message', function (msg, timetag, info) { - var delay = timetag? Math.max(0,timetag.native - Date.now()) : 0 - if (delay) { - setTimeout(()=>{ - oscInHandler(msg, timetag, info) - }, delay) - } else { - oscInHandler(msg, timetag, info) - } -}) - -oscServer.on('error', function (error) { - console.log(error) -}) - -oscServer.open() - -if (customModule.init) { - customModule.init() -} - -if (midi) midi.init((data)=>{ - var data = oscInFilter({address: data.address, args: data.args, host: data.host, port: data.port}) - if (!data) return - receiveOsc(data) -}) - -module.exports = { - - send: function(host,port,address,args,precision) { - - var message = [] - - if (!Array.isArray(args)) args = [args] - if (typeof args=='object' && args!==null) { - for (var i in args) { - var arg = parseArg(args[i],precision) - if (arg!=null) message.push(arg) - } - } - - var data = oscOutFilter({address:address, args: message, host: host, port: port}) - - sendOsc(data) - - }, - midi:midi -} diff --git a/app/main/osc/index.js b/app/main/osc/index.js new file mode 100644 index 00000000..45110cae --- /dev/null +++ b/app/main/osc/index.js @@ -0,0 +1,236 @@ +// destroy serialport module +// (electron-rebuild breaks it for node-only mode) +require('vmodule')('serialport', {}, {global: true}) + +var osc = require('osc'), + ipc = require('../server').ipc, + settings = require('../settings'), + zeroconf = require('../zeroconf'), + oscInPort = settings.read('oscInPort') || settings.read('httpPort'), + tcpInPort = settings.read('tcpInPort'), + debug = settings.read('debug'), + vm = require('vm'), + fs = require('fs'), + midi = settings.read('midi') ? require('../midi') : false, + oscUDPServer = require('./udp'), + oscTCPServer = require('./tcp') + +class OscServer { + + constructor(){ + + this.customModule = (()=>{ + + if (!settings.read('customModule')) return false + + var file = (()=>{ + try { + return fs.readFileSync(settings.read('customModule'),'utf8') + } catch(err) { + console.log('CustomModule Error: File not found: ' + settings.read('customModule')) + return false + } + })(), + mod, + context = { + console, + sendOsc: this.sendOsc.bind(this), + receiveOsc: this.receiveOsc.bind(this), + setTimeout, + clearTimeout, + setInterval, + clearInterval, + settings + } + + try { + mod = vm.runInContext(file, vm.createContext(context)) + } catch(err) { + console.log(err) + return false + } + + return mod + + })() + + + } + + parseType(type){ + var t = type[0].match(/[bhtdscrmifTFNI]/) + + if (t!==null) { + return t[0] + } else { + return 's' + } + + } + + parseArg(arg, precision){ + if (arg==null) return null + switch (typeof arg) { + case 'number': + var typeTagMatch = typeof precision == 'string' ? precision.match(/[0-9]+([a-zA-Z]{1})/) : null, + typeTag = typeTagMatch === null ? precision == 0 ? 'i' : 'f' : typeTagMatch[1], + precisionValue = parseFloat(precision) || 0 + + return {type: typeTag, value: parseFloat(arg.toFixed(precisionValue))} + case 'boolean': + return {type: arg ? 'T' : 'F', value: arg} + case 'object': + if (arg.type) { + return {type: parseType(arg.type), value: arg.value} + } else { + return {type: 's', value:JSON.stringify(arg)} + } + case 'string': + return {type: 's', value:arg} + default: + return {type: 's', value:JSON.stringify(arg)} + } + } + + sendOsc(data){ + + if (!data) return + + if (data.host == 'midi') { + + if (midi) midi.send(data) + + } else { + + if (typeof data.address !== 'string' || data.address[0] !== '/') { + console.error('OSC error: malformed address: "' + data.address + "") + return + } + + oscUDPServer.send({ + address: data.address, + args: data.args + }, data.host, data.port) + + if (tcpInPort && oscTCPServer.clients[data.host + ':' + data.port]) { + oscTCPServer.clients[data.host + ':' + data.port].send({ + address: data.address, + args: data.args + }) + } + + if (debug) console.log('OSC sent: ',{address:data.address, args: data.args}, 'To : ' + data.host + ':' + data.port) + + } + + + } + + receiveOsc(data, info){ + + if (!data) return + + for (i in data.args) { + data.args[i] = data.args[i].value + } + + if (data.args.length==1) data.args = data.args[0] + + ipc.send('receiveOsc',data) + + if (debug) console.log('OSC received: ', {address:data.address, args: data.args}, 'From : ' + data.host + ':' + data.port) + + } + + + oscInFilter(data){ + if (this.customModule.oscInFilter) { + return this.customModule.oscInFilter(data) + } else { + return data + } + } + oscOutFilter(data){ + if (this.customModule.oscOutFilter) { + return this.customModule.oscOutFilter(data) + } else { + return data + } + } + + oscInHandler(msg, timetag, info){ + var data = this.oscInFilter({address: msg.address, args: msg.args, host: info.address, port: info.port}) + if (!data) return + this.receiveOsc(data) + } + + oscInHandlerWrapper(msg, timetag, info) { + var delay = timetag? Math.max(0,timetag.native - Date.now()) : 0 + if (delay) { + setTimeout(()=>{ + this.oscInHandler(msg, timetag, info) + }, delay) + } else { + this.oscInHandler(msg, timetag, info) + } + } + + + + init(){ + + if (midi) midi.init((data)=>{ + + var data = this.oscInFilter({address: data.address, args: data.args, host: data.host, port: data.port}) + + if (!data) return + + this.receiveOsc(data) + + }) + + oscUDPServer.on('message', this.oscInHandlerWrapper.bind(this)) + oscTCPServer.on('message', this.oscInHandlerWrapper.bind(this)) + + oscUDPServer.on('error', function(error) { + console.error(error) + }) + + oscUDPServer.open() + + if (settings.read('tcpInPort')) oscTCPServer.open() + + if (this.customModule.init) { + this.customModule.init() + } + + } + + +} + + +var oscServer = new OscServer() +oscServer.init() + +module.exports = { + + send: function(host,port,address,args,precision) { + + var message = [] + + if (!Array.isArray(args)) args = [args] + if (typeof args=='object' && args!==null) { + for (var i in args) { + var arg = oscServer.parseArg(args[i],precision) + if (arg!=null) message.push(arg) + } + } + + var data = oscServer.oscOutFilter({address:address, args: message, host: host, port: port}) + + oscServer.sendOsc(data) + + }, + midi:midi +} diff --git a/app/main/osc/tcp.js b/app/main/osc/tcp.js new file mode 100644 index 00000000..bc44929b --- /dev/null +++ b/app/main/osc/tcp.js @@ -0,0 +1,122 @@ +var osc = require('osc'), + EventEmitter = require('events').EventEmitter + settings = require('../settings'), + zeroconf = require('../zeroconf'), + tcpInPort = settings.read('tcpInPort'), + tcpTargets = settings.read('tcpTargets'), + net = require('net') + +class OscTCPClient extends EventEmitter { + + constructor(options) { + + super() + + this.options = options + this.remoteAddress = options.address + this.remotePort = options.port + this.name = this.remoteAddress + ':' + this.remotePort + + this.open() + + } + + open() { + + this.port = new osc.TCPSocketPort(this.options) + + this.port.on('error', (err)=>{ + console.error(err) + }) + + this.port.on('close', (hadErr)=>{ + if (!this.options.socket) { + this.reconnect() + } else { + this.emit('die') + } + }) + + this.port.on('message', (msg, timetag)=>{ + this.emit('message', msg, timetag, {address: this.remoteAddress, port: this.remotePort}) + }) + + if (!this.options.socket) this.port.open() + + } + + reconnect() { + + setTimeout(()=>{ + this.open() + }, 5000) + + } + + send(msg) { + + this.port.send(msg) + + } + + + +} + +class OscTCPServer extends EventEmitter { + + constructor() { + + super() + + this.clients = {} + + } + + bindSocket(socket) { + + this.addClient(new OscTCPClient({ + metadata: true, + socket: socket, + address: socket.remoteAddress.indexOf('::ffff:') === 0 ? socket.remoteAddress.replace('::ffff:', '') : socket.remoteAddress, + port: socket.remotePort + })) + + } + + addClient(client) { + + this.clients[client.name] = client + + client.on('message', (msg, timetag, info)=>{ + this.emit('message', msg, timetag, info) + }) + + client.on('die', (hadError)=>{ + delete this.clients[client.name] + }) + + } + + + open() { + + this.server = net.createServer(this.bindSocket.bind(this)) + this.server.listen({port: tcpInPort}) + + for (var i in tcpTargets) { + + this.addClient(new OscTCPClient({ + metadata: true, + address: tcpTargets[i].split(':')[0], + port: tcpTargets[i].split(':')[1] + })) + + } + + } +} + +var oscTCPServer = new OscTCPServer() + +module.exports = oscTCPServer diff --git a/app/main/osc/udp.js b/app/main/osc/udp.js new file mode 100644 index 00000000..cce0ce67 --- /dev/null +++ b/app/main/osc/udp.js @@ -0,0 +1,22 @@ +var osc = require('osc'), + settings = require('../settings'), + zeroconf = require('../zeroconf'), + oscInPort = settings.read('oscInPort') || settings.read('httpPort') + +var oscUDPServer = new osc.UDPPort({ + localAddress: "0.0.0.0", + localPort: oscInPort, + metadata: true, + broadcast: true +}) + +zeroconf.publish({ + name: settings.read('appName') + (settings.read('instanceName') ? ' (' + settings.read('instanceName') + ')' : ''), + protocol: 'udp', + type: 'osc', + port: oscInPort +}).on('error', (e)=>{ + console.error(`Error: Zeroconf: ${e.message}`) +}) + +module.exports = oscUDPServer diff --git a/app/main/settings.js b/app/main/settings.js index 92f7aa8d..1ba22165 100644 --- a/app/main/settings.js +++ b/app/main/settings.js @@ -35,6 +35,21 @@ var options = { true : 'Port must be an integer >= 1024' } }, + 'tcp-port':{type:'number', describe:'TCP server input port', + check: (t, argv)=>{ + var h = argv.p || 8080 + if (t===h) return 'TCP input port must different from --port' + return (!isNaN(t) && t > 1023 && parseInt(t)===t) ? + true : 'Port must be an integer >= 1024' + } + }, + 'tcp-targets':{type:'array',describe:'TCP servers to connect to (ip:port pairs), does not susbtitute for --send', + check: (s, argv)=>{ + if (!argv['tcp-port']) return '--tcp-port must be set' + return s.some(item => !item.match('^[^:\s\"\']*:[0-9]{4,5}[\s\"\']*$')) ? + 'Targets must be ip:port pairs & port must be >= 1024' : true + } + }, 'm':{alias:'midi',type:'array',describe:'midi router settings'}, 'd':{alias:'debug',type:'boolean',describe:'log received osc messages in the console'}, 'n':{alias:'no-gui',type:'boolean',describe:'disable default gui', @@ -116,6 +131,9 @@ var makeDefaultConfig = function(argv){ targets: argv.s || argv.sync || false, oscInPort: argv.o || 0, httpPort: argv.p || 8080, + httpPort: argv.p || 8080, + tcpInPort: argv['tcp-port'] || false, + tcpTargets: argv['tcp-targets'] || [], debug: argv.d || false, sessionFile: argv.l || false, newSession: argv.b || false, diff --git a/app/package.json b/app/package.json index 83bbe9fd..d8c037df 100644 --- a/app/package.json +++ b/app/package.json @@ -25,10 +25,10 @@ "chokidar": "2.0.3", "electron-localshortcut": "3.1.0", "express": "4.16.3", - "osc": "2.2.1", + "osc": "2.2.2", "python-shell": "0.5.0", "vmodule": "1.0.1", - "ws": "^5.1.1", + "ws": "^5.2.0", "yargs": "11.0.0" }, "scripts": { diff --git a/package.json b/package.json index 9a9a9024..a93cf825 100644 --- a/package.json +++ b/package.json @@ -20,34 +20,34 @@ "license": "GPL-3.0", "dependencies": { "autolayout": "0.7.0", - "babel-core": "^6.26.0", + "babel-core": "^6.26.3", "babel-plugin-transform-object-rest-spread": "6.26.0", - "babel-preset-env": "*", + "babel-preset-env": "^1.7.0", "babelify": "8.0.0", - "browserify": "16.1.1", + "browserify": "16.2.2", "cardinal-spline-js": "2.3.6", - "deep-extend": "^0.5.0", - "electron": "~1.8.4", - "electron-packager": "12.0.0", + "deep-extend": "^0.6.0", + "electron": "~2.0.2", + "electron-packager": "12.1.0", "electron-packager-plugin-non-proprietary-codecs-ffmpeg": "^1.0.1", "exorcist": "1.0.1", "file-saver": "1.3.8", "jquery": "3.3.1", "json5": "1.0.1", - "keyboardjs": "jean-emmanuel/KeyboardJS", + "keyboardjs": "github:jean-emmanuel/KeyboardJS", "kiwi.js": "1.0.2", "licensify": "3.1.3", - "mathjs": "^4.1.0", + "mathjs": "^4.3.0", "minimatch": "^3.0.4", "nanomorph": "^5.1.3", - "node-sass": "4.8.3", - "nodemon": "1.17.3", - "scope-css": "^1.0.5", + "node-sass": "4.9.0", + "nodemon": "1.17.5", + "scope-css": "^1.1.0", "screenfull": "3.3.2", "shortid": "2.2.8", "stacktrace-js": "^2.0.0", "through": "^2.3.8", - "uglifyify": "4.0.5", + "uglifyify": "5.0.0", "wolfy87-eventemitter": "^5.2.4" }, "optionalDependencies": { diff --git a/resources/docs/getting-started.md b/resources/docs/getting-started.md index b374437e..ac4fba36 100644 --- a/resources/docs/getting-started.md +++ b/resources/docs/getting-started.md @@ -19,6 +19,8 @@ Below are the available command-line options. Note that when running without any | `-c` | `--custom-module` | custom module file to load | | `-p` | `--port` | http port of the server (default to 8080) | | `-o` | `--osc-port` | osc input port (default to --port) | +| | `--tcp-port` | tcp server input port | +| | `--osc-targets` | tcp servers to connect to (ip:port pairs), does not susbtitute for --send | | `-m` | `--midi` | midi router settings | | `-d` | `--debug` | log received osc messages in the console | | `-n` | `--no-gui` | disable default gui |