Mercurial > hg > beaglert
changeset 271:fb9c28a4676b prerelease
Added osc example project and node script for testing
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/osc/render.cpp Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,63 @@ +#include <BeagleRT.h> +#include <OSCServer.h> +#include <OSCClient.h> + +OSCServer oscServer; +OSCClient oscClient; + +// this example is designed to be run alongside resources/osc/osc.js + +// parse messages recieved by OSC Server +// msg is Message class of oscpkt: http://gruntthepeon.free.fr/oscpkt/ +void parseMessage(oscpkt::Message msg){ + + rt_printf("recieved message to: %s\n", msg.addressPattern().c_str()); + + int intArg; + float floatArg; + if (msg.match("/osc-test").popInt32(intArg).popFloat(floatArg).isOkNoMoreArgs()){ + rt_printf("recieved int %i and float %f\n", intArg, floatArg); + } + +} + +bool setup(BeagleRTContext *context, void *userData) +{ + // setup the OSC server to recieve on port 7562 + oscServer.setup(7562); + // setup the OSC client to send on port 7563 + oscClient.setup(7563); + + // the following code sends an OSC message to address /osc-setup + // then waits 1 second for a reply on /osc-setup-reply + bool handshakeRecieved = false; + oscClient.sendMessageNow(oscClient.newMessage.to("/osc-setup").end()); + oscServer.recieveMessageNow(1000); + while (oscServer.messageWaiting()){ + if (oscServer.popMessage().match("/osc-setup-reply")){ + handshakeRecieved = true; + } + } + + if (handshakeRecieved){ + rt_printf("handshake recieved!\n"); + } else { + rt_printf("timeout!\n"); + } + + return true; +} + +void render(BeagleRTContext *context, void *userData) +{ + // recieve OSC messages, parse them, and send back an acknowledgment + while (oscServer.messageWaiting()){ + parseMessage(oscServer.popMessage()); + oscClient.queueMessage(oscClient.newMessage.to("/osc-acknowledge").add(5).add(4.2f).add(std::string("OSC message recieved")).end()); + } +} + +void cleanup(BeagleRTContext *context, void *userData) +{ + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/binpack/.npmignore Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,4 @@ +build/ +binpack.node +node_modules +.lock-wscript
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/binpack/.travis.yml Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,7 @@ +language: node_js +node_js: + - 0.8 + - 0.10 +branches: + only: + - master \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/binpack/COPYING Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,14 @@ +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/binpack/changes.md Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,6 @@ +# Changelog + +## 0.0.3 + Switched "repositories" to "repository" in package.json. +## 0.0.2 + Updated documentation \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/binpack/index.js Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,92 @@ +// t is a binpack typename +var sizeOfType = function(t) { + // unsigned are the same length as signed + if(t[0] === 'U') { + t = t.slice(1); + } + + return { + 'Float32' : 4, + 'Float64' : 8, + 'Int8' : 1, + 'Int16' : 2, + 'Int32' : 4, + 'Int64' : 8 + }[t]; +}; + +var endianConv = function(e, t) { + // node doesn't define 8 bit endianness + if(t[t.length - 1] === '8') + return ''; + + if(e === 'big') { + return 'BE'; + } + return 'LE'; +}; + +var addBindings = function(binpackTypename, nodeTypename){ + if(!(typeof nodeTypename !== "undefined" && nodeTypename !== null)) { + nodeTypename = binpackTypename; + } + module.exports['pack' + binpackTypename] = function(num, endian){ + b = new Buffer(sizeOfType(binpackTypename)); + b['write' + nodeTypename + endianConv(endian, binpackTypename)](num, 0, true); + return b; + } + + module.exports['unpack' + binpackTypename] = function(buff, endian){ + return buff['read' + nodeTypename + endianConv(endian, binpackTypename)](0); + } +} + +var addIntBindings = function(n) { + addBindings("Int" + n); + addBindings("UInt" + n); +} + +addIntBindings(8); +addIntBindings(16); +addIntBindings(32); + +twoToThe32 = Math.pow(2, 32); + +// 64 bit bindings require special care +var read64 = function(unsigned){return function(buff, endian){ + var e = endianConv(endian, ''); + var u = unsigned ? 'U' : ''; + var low, high; + if(e === 'LE') { + low = buff.readUInt32LE(0); + high = buff['read' + u + 'Int32LE'](4); + } else { + low = buff.readUInt32BE(4); + high = buff['read' + u + 'Int32BE'](0); + } + return high * twoToThe32 + low; +};}; + +var write64 = function(unsigned){return function(num, endian){ + var e = endianConv(endian, ''); + var u = unsigned ? 'U' : ''; + var b = new Buffer(8); + var high = Math.floor(num / twoToThe32); + var low = Math.floor(num - high * twoToThe32); + if(e == 'LE') { + b.writeUInt32LE(low, 0, true); + b['write' + u + 'Int32LE'](high, 4, true); + } else { + b.writeUInt32BE(low, 4, true); + b['write' + u + 'Int32BE'](high, 0, true); + } + return b; +};}; + +module.exports.unpackInt64 = read64(false); +module.exports.unpackUInt64 = read64(true); +module.exports.packInt64 = write64(false); +module.exports.packUInt64 = write64(true); + +addBindings("Float32", "Float"); +addBindings("Float64", "Double");
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/binpack/package.json Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,78 @@ +{ + "_args": [ + [ + "binpack@~0", + "/Users/liam/Documents/Bela/osc-node/node_modules/osc-min" + ] + ], + "_from": "binpack@>=0.0.0 <1.0.0", + "_id": "binpack@0.1.0", + "_inCache": true, + "_installable": true, + "_location": "/binpack", + "_npmUser": { + "email": "russell.mcclellan@gmail.com", + "name": "ghostfact" + }, + "_npmVersion": "1.3.21", + "_phantomChildren": {}, + "_requested": { + "name": "binpack", + "raw": "binpack@~0", + "rawSpec": "~0", + "scope": null, + "spec": ">=0.0.0 <1.0.0", + "type": "range" + }, + "_requiredBy": [ + "/osc-min" + ], + "_resolved": "https://registry.npmjs.org/binpack/-/binpack-0.1.0.tgz", + "_shasum": "bd3d0974c3f2a0446e17df4f60b55a72a205a97e", + "_shrinkwrap": null, + "_spec": "binpack@~0", + "_where": "/Users/liam/Documents/Bela/osc-node/node_modules/osc-min", + "author": { + "email": "russell.mcclellan@gmail.com", + "name": "Russell McClellan", + "url": "http://www.russellmcc.com" + }, + "bugs": { + "url": "https://github.com/russellmcc/node-binpack/issues" + }, + "dependencies": {}, + "description": "Minimalist numeric binary packing utilities for node.js", + "devDependencies": { + "coffee-script": "<1.7.0", + "vows": "*" + }, + "directories": {}, + "dist": { + "shasum": "bd3d0974c3f2a0446e17df4f60b55a72a205a97e", + "tarball": "http://registry.npmjs.org/binpack/-/binpack-0.1.0.tgz" + }, + "homepage": "https://github.com/russellmcc/node-binpack", + "keywords": [ + "binary", + "pack", + "unpack" + ], + "main": "index", + "maintainers": [ + { + "email": "russell.mcclellan@gmail.com", + "name": "ghostfact" + } + ], + "name": "binpack", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/russellmcc/node-binpack.git" + }, + "scripts": { + "test": "vows tests/*" + }, + "version": "0.1.0" +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/binpack/readme.md Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,29 @@ +[![build status](https://secure.travis-ci.org/russellmcc/node-binpack.png)](http://travis-ci.org/russellmcc/node-binpack) +# binpack + +_Deprecated binary packing utilities for node.js_ + +## What's all this? + +node now actually contains native code for packing binary buffers so this module is no longer needed. do not use in new code. + +see the included COPYING file for licensing. + +the core of the module is the set of `pack`/`unpack` pair functions. The meaning should be clear from the name - for example, `packInt32` packs a given javascript number into a 32-bit int inside a 4-byte node.js Buffer, while `unpackFloat32` unpacks a 4-byte node.js Buffer containing a native floating point number into a javascript number. + +The following types are available for both pack and unpack: + + Float32 + Float64 + Int8 + Int16 + Int32 + UInt8 + UInt16 + UInt32 + +Each `pack*` function takes a javascript number and outputs a node.js Buffer. + +Each `unpack*` function takes a node.js Buffer and outputs a javascript number. + +Both types of functions take an optional second argument. If this argument is `"big"`, the output is put in big endian format. If the argument is `"little"`, the output is put in little endian format. If the argument is anything else or non-existent, we default to "little" endian [THIS IS NEW BEHAVIOR IN 0.0.15 - previous version would default to the native encoding.].
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/binpack/tests/test-binpack.coffee Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,64 @@ +vows = require "vows" +assert = require "assert" +binpack = require "../index" + +# do a round trip +okayForOptions = (num, options) -> + return false if options.size? and Math.abs(num) > options.size? + return false if num < 0 and options.unsigned + true + +roundTrip = (type, options) -> + works : (num) -> + return null if not okayForOptions(num, options) + assert.strictEqual (binpack["unpack" + type] binpack["pack" + type] num), num + + "fails plus 1.1" : (num) -> + return null if not okayForOptions(num, options) + assert.notStrictEqual (binpack["unpack" + type] binpack["pack" + type] num + 1.1), num + + "works little endian" : (num) -> + return null if options.onebyte + return null if not okayForOptions(num, options) + assert.strictEqual (binpack["unpack" + type] (binpack["pack" + type] num, "little"), "little"), num + + "works big endian" : (num) -> + return null if options.onebyte + return null if not okayForOptions(num, options) + assert.strictEqual (binpack["unpack" + type] (binpack["pack" + type] num, "big"), "big"), num + + "fails mismatched" : (num) -> + return null if not okayForOptions(num, options) + return null if num is 0 + return null if options.onebyte + assert.notStrictEqual (binpack["unpack" + type] (binpack["pack" + type] num, "little"), "big"), num + +types = + "Float32" : {} + "Float64" : {} + "Int8" : {onebyte : true, size : 128} + "Int16" : {size : 32768} + "Int32" : {} + "Int64" : {} + "UInt8" : {unsigned : true, onebyte : true, size:255} + "UInt16" : {unsigned : true, size : 65535} + "UInt32" : {unsigned : true} + "UInt64" : {unsigned : true} + +# round trip testing makes up the core of the test. +roundTripTests = (num) -> + tests = {topic : num} + for type, options of types + tests[type + "round trip test"] = roundTrip type, options + tests + +vows.describe("binpack").addBatch( + # choose a bunch of random numbers + 'roundTrips for 0' : roundTripTests 0 + 'roundTrips for 12' : roundTripTests 12 + 'roundTrips for -18' : roundTripTests -18 + 'roundTrips for 129' : roundTripTests 129 + 'roundTrips for -400' : roundTripTests -400 + 'roundTrips for 60000' : roundTripTests 60000 + 'roundTrips for 1234567' : roundTripTests 1234567 +).export module
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/.npmignore Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,3 @@ +node_modules/ +build/ +coverage.html
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/.travis.yml Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.10 +after_script: + - npm run-script coveralls \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/COPYING Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,15 @@ +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgement in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/Cakefile Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,39 @@ +fs = require 'fs' +child = require 'child_process' + +task 'test', 'run tests (requires development install)', (options) -> + process.env['NODE_PATH'] = './lib/:$NODE_PATH' + test = child.spawn 'mocha', ['--compilers', 'coffee:coffee-script/register', '-u', 'tdd', 'test'] + test.stdout.pipe process.stdout + test.stderr.pipe process.stderr + test.on 'exit', (num) -> + return process.exit num + +spawnMochaCov = (reporter) -> + return child.spawn 'mocha', ['--compilers', 'coffee:coffee-script/register', '-r', 'blanket', '-R', reporter, '-u', 'tdd', 'test'] + +task 'coverage', 'run tests with coverage check (requires development install)', (options) -> + process.env['NODE_PATH'] = './lib/:$NODE_PATH' + test = spawnMochaCov 'html-cov' + file = fs.createWriteStream 'coverage.html' + test.stdout.pipe file + test.stderr.pipe process.stderr + test.on 'exit', (num) -> + child.exec 'open ./coverage.html' + +task 'coveralls', 'report coveralls to travis', (options) -> + process.env['NODE_PATH'] = './lib/:$NODE_PATH' + test = spawnMochaCov 'mocha-lcov-reporter' + report = child.spawn './node_modules/coveralls/bin/coveralls.js' + test.stdout.pipe report.stdin + test.stderr.pipe process.stderr + +task 'doc', 'create md and html doc files', (options) -> + child.exec 'coffee -b -c examples/*', -> + child.exec 'docket lib/* examples/* -m', -> + child.exec 'docket lib/* examples/* -d doc_html' + +task 'browserify', 'build for a browser', (options)-> + fs.mkdir './build', -> + child.exec './node_modules/browserify/bin/cmd.js ./lib/index.js --standalone osc -o ./build/osc-min.js', -> + child.exec './node_modules/uglify-js/bin/uglifyjs -o ./build/osc-min.min.js ./build/osc-min.js'
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/examples/osc-float-to-int.coffee Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,38 @@ +# This listens for osc messages and rebroadcasts them +# with all the floats converted to ints. + +osc = require 'osc-min' +udp = require "dgram" + +if process.argv[2]? + inport = parseInt process.argv[2] +else + inport = 41234 + +if process.argv[3]? + outport = parseInt process.argv[3] +else + outport = 41235 + +float_to_int = (message) -> + for arg in message.args + if arg.type is "float" + arg.type = "integer" + message + +sock = udp.createSocket "udp4", (msg, rinfo) -> + try + edited = osc.applyMessageTransform msg, (message) -> float_to_int message + sock.send( + edited, + 0, + edited.length, + outport, + "localhost" + ) + catch error + console.log "error redirecting: " + error +sock.bind inport + +console.log "OSC redirecter running at http://localhost:" + inport +console.log "translating messages to http://localhost:" + outport \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/examples/osc-float-to-int.js Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,49 @@ +// Generated by CoffeeScript 1.10.0 +var float_to_int, inport, osc, outport, sock, udp; + +osc = require('osc-min'); + +udp = require("dgram"); + +if (process.argv[2] != null) { + inport = parseInt(process.argv[2]); +} else { + inport = 41234; +} + +if (process.argv[3] != null) { + outport = parseInt(process.argv[3]); +} else { + outport = 41235; +} + +float_to_int = function(message) { + var arg, i, len, ref; + ref = message.args; + for (i = 0, len = ref.length; i < len; i++) { + arg = ref[i]; + if (arg.type === "float") { + arg.type = "integer"; + } + } + return message; +}; + +sock = udp.createSocket("udp4", function(msg, rinfo) { + var edited, error, error1; + try { + edited = osc.applyMessageTransform(msg, function(message) { + return float_to_int(message); + }); + return sock.send(edited, 0, edited.length, outport, "localhost"); + } catch (error1) { + error = error1; + return console.log("error redirecting: " + error); + } +}); + +sock.bind(inport); + +console.log("OSC redirecter running at http://localhost:" + inport); + +console.log("translating messages to http://localhost:" + outport);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/examples/osc-redirect.coffee Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,35 @@ +# This listens for osc messages and outputs them +# on a different port with all addresses redirected +# to /redirect + +osc = require 'osc-min' +udp = require "dgram" + +if process.argv[2]? + inport = parseInt process.argv[2] +else + inport = 41234 + +if process.argv[3]? + outport = parseInt process.argv[3] +else + outport = 41235 + +console.log "OSC redirecter running at http://localhost:" + inport +console.log "redirecting messages to http://localhost:" + outport + +`//~verbatim:examples[2]~ +//### A simple OSC redirecter` +sock = udp.createSocket "udp4", (msg, rinfo) -> + try + redirected = osc.applyAddressTransform msg, (address) -> "/redirect" + address + sock.send( + redirected, + 0, + redirected.length, + outport, + "localhost" + ) + catch error + console.log "error redirecting: " + error +sock.bind inport \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/examples/osc-redirect.js Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,40 @@ +// Generated by CoffeeScript 1.10.0 +var inport, osc, outport, sock, udp; + +osc = require('osc-min'); + +udp = require("dgram"); + +if (process.argv[2] != null) { + inport = parseInt(process.argv[2]); +} else { + inport = 41234; +} + +if (process.argv[3] != null) { + outport = parseInt(process.argv[3]); +} else { + outport = 41235; +} + +console.log("OSC redirecter running at http://localhost:" + inport); + +console.log("redirecting messages to http://localhost:" + outport); + +//~verbatim:examples[2]~ +//### A simple OSC redirecter; + +sock = udp.createSocket("udp4", function(msg, rinfo) { + var error, error1, redirected; + try { + redirected = osc.applyAddressTransform(msg, function(address) { + return "/redirect" + address; + }); + return sock.send(redirected, 0, redirected.length, outport, "localhost"); + } catch (error1) { + error = error1; + return console.log("error redirecting: " + error); + } +}); + +sock.bind(inport);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/examples/oscbundle_heartbeat.coffee Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,44 @@ +# Same thing as the oscheartbeat example but with oscbundles. + +osc = require 'osc-min' +dgram = require "dgram" + +udp = dgram.createSocket "udp4" + +if process.argv[2]? + outport = parseInt process.argv[2] +else + outport = 41234 + +# Get the unix timestamp in seconds +now = -> (new Date()).getTime() / 1000; + +sendHeartbeat = () -> + buf = osc.toBuffer( + timetag : now() + 0.05 # 0.05 seconds from now + elements : [ + { + address : "/p1" + args : new Buffer "beat" + } + { + address : "/p2" + args : "string" + } + { + timetag: now() + 1 # 1 second from now + elements : [ + { + address : "/p3" + args : 12 + } + ] + } + ] + ) + + udp.send buf, 0, buf.length, outport, "localhost" + +setInterval sendHeartbeat, 2000 + +console.log "sending heartbeat messages to http://localhost:" + outport
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/examples/oscbundle_heartbeat.js Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,47 @@ +// Generated by CoffeeScript 1.10.0 +var dgram, now, osc, outport, sendHeartbeat, udp; + +osc = require('osc-min'); + +dgram = require("dgram"); + +udp = dgram.createSocket("udp4"); + +if (process.argv[2] != null) { + outport = parseInt(process.argv[2]); +} else { + outport = 41234; +} + +now = function() { + return (new Date()).getTime() / 1000; +}; + +sendHeartbeat = function() { + var buf; + buf = osc.toBuffer({ + timetag: now() + 0.05, + elements: [ + { + address: "/p1", + args: new Buffer("beat") + }, { + address: "/p2", + args: "string" + }, { + timetag: now() + 1, + elements: [ + { + address: "/p3", + args: 12 + } + ] + } + ] + }); + return udp.send(buf, 0, buf.length, outport, "localhost"); +}; + +setInterval(sendHeartbeat, 2000); + +console.log("sending heartbeat messages to http://localhost:" + outport);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/examples/oscheartbeat.coffee Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,30 @@ +# This example simply sends a message with several parameter types +# every two seconds to port 41234 + +osc = require 'osc-min' +dgram = require "dgram" + +udp = dgram.createSocket "udp4" + +if process.argv[2]? + outport = parseInt process.argv[2] +else + outport = 41234 +console.log "sending heartbeat messages to http://localhost:" + outport + +`//~verbatim:examples[1]~ +//### Send a bunch of args every two seconds` +sendHeartbeat = () -> + buf = osc.toBuffer( + address : "/heartbeat" + args : [ + 12 + "sttttring" + new Buffer "beat" + {type : "integer", value : 7} + ] + ) + + udp.send buf, 0, buf.length, outport, "localhost" + +setInterval sendHeartbeat, 2000 \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/examples/oscheartbeat.js Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,35 @@ +// Generated by CoffeeScript 1.10.0 +var dgram, osc, outport, sendHeartbeat, udp; + +osc = require('osc-min'); + +dgram = require("dgram"); + +udp = dgram.createSocket("udp4"); + +if (process.argv[2] != null) { + outport = parseInt(process.argv[2]); +} else { + outport = 41234; +} + +console.log("sending heartbeat messages to http://localhost:" + outport); + +//~verbatim:examples[1]~ +//### Send a bunch of args every two seconds; + +sendHeartbeat = function() { + var buf; + buf = osc.toBuffer({ + address: "/heartbeat", + args: [ + 12, "sttttring", new Buffer("beat"), { + type: "integer", + value: 7 + } + ] + }); + return udp.send(buf, 0, buf.length, outport, "localhost"); +}; + +setInterval(sendHeartbeat, 2000);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/examples/printosc.coffee Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,18 @@ +osc = require 'osc-min' +udp = require "dgram" + +if process.argv[2]? + inport = parseInt process.argv[2] +else + inport = 41234 + +console.log "OSC listener running at http://localhost:" + inport + +`//~verbatim:examples[0]~ +//### A simple OSC printer` +sock = udp.createSocket "udp4", (msg, rinfo) -> + try + console.log osc.fromBuffer msg + catch error + console.log "invalid OSC packet" +sock.bind inport
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/examples/printosc.js Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,29 @@ +// Generated by CoffeeScript 1.10.0 +var inport, osc, sock, udp; + +osc = require('osc-min'); + +udp = require("dgram"); + +if (process.argv[2] != null) { + inport = parseInt(process.argv[2]); +} else { + inport = 41234; +} + +console.log("OSC listener running at http://localhost:" + inport); + +//~verbatim:examples[0]~ +//### A simple OSC printer; + +sock = udp.createSocket("udp4", function(msg, rinfo) { + var error, error1; + try { + return console.log(osc.fromBuffer(msg)); + } catch (error1) { + error = error1; + return console.log("invalid OSC packet"); + } +}); + +sock.bind(inport);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/lib/index.js Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,219 @@ +(function() { + +//~readme.out~ +//[![build status](https://secure.travis-ci.org/russellmcc/node-osc-min.png)](http://travis-ci.org/russellmcc/node-osc-min) [![Coverage Status](https://coveralls.io/repos/russellmcc/node-osc-min/badge.png?branch=master)](https://coveralls.io/r/russellmcc/node-osc-min?branch=master) [![dependencies](https://david-dm.org/russellmcc/node-osc-min.png)](https://david-dm.org/russellmcc/node-osc-min) +//# osc-min +// +// _simple utilities for open sound control in node.js_ +// +// This package provides some node.js utilities for working with +// [OSC](http://opensoundcontrol.org/), a format for sound and systems control. +// Here we implement the [OSC 1.1][spec11] specification. OSC is a transport-independent +// protocol, so we don't provide any server objects, as you should be able to +// use OSC over any transport you like. The most common is probably udp, but tcp +// is not unheard of. +// +// [spec11]: http://opensoundcontrol.org/spec-1_1 +// +//---- +//## Installation +//~installation~ +//---- +//## Examples +//~examples~ +// +// more examples are available in the `examples/` directory. +// +//---- +//~api~ +//---- +//~representation~ +//---- +//## License +// Licensed under the terms found in COPYING (zlib license) + +//~representation~ +//## Javascript representations of the OSC types. +// See the [spec][spec] for more information on the OSC types. +// +// + An _OSC Packet_ is an _OSC Message_ or an _OSC Bundle_. +// +// + An _OSC Message_: +// +// { +// oscType : "message" +// address : "/address/pattern/might/have/wildcards" +// args : [arg1,arg2] +// } +// +// Where args is an array of _OSC Arguments_. `oscType` is optional. +// `args` can be a single element. +// +// + An _OSC Argument_ is represented as a javascript object with the following layout: +// +// { +// type : "string" +// value : "value" +// } +// +// Where the `type` is one of the following: +// + `string` - string value +// + `float` - numeric value +// + `integer` - numeric value +// + `blob` - node.js Buffer value +// + `true` - value is boolean true +// + `false` - value is boolean false +// + `null` - no value +// + `bang` - no value (this is the `I` type tag) +// + `timetag` - numeric value +// + `array` - array of _OSC Arguments_ +// +// Note that `type` is always a string - i.e. `"true"` rather than `true`. +// +// The following non-standard types are also supported: +// + `double` - numeric value (encodes to a float64 value) +// +// +// For messages sent to the `toBuffer` function, `type` is optional. +// If the argument is not an object, it will be interpreted as either +// `string`, `float`, `array` or `blob`, depending on its javascript type +// (String, Number, Array, Buffer, respectively) +// +// + An _OSC Bundle_ is represented as a javascript object with the following fields: +// +// { +// oscType : "bundle" +// timetag : 7 +// elements : [element1, element] +// } +// +// `oscType` "bundle" +// +// `timetag` is one of: +// - `null` - meaning now, the current time. +// By the time the bundle is received it will too late and depending +// on the receiver may be discarded or you may be scolded for being late. +// - `number` - relative seconds from now with millisecond accuracy. +// - `Date` - a JavaScript Date object in your local time zone. +// OSC timetags use UTC timezone, so do not try to adjust for timezones, +// this is not needed. +// - `Array` - `[numberOfSecondsSince1900, fractionalSeconds]` +// Both values are `number`s. This gives full timing accuracy of 1/(2^32) seconds. +// +// `elements` is an `Array` of either _OSC Message_ or _OSC Bundle_ +// +// +// [spec]: http://opensoundcontrol.org/spec-1_0 + + var utils, coffee; + utils = require("./osc-utilities"); +// ~api~ +//## Exported functions +// +//------ +//### .fromBuffer(buffer, [strict]) +// takes a node.js Buffer of a complete _OSC Packet_ and +// outputs the javascript representation, or throws if the buffer is ill-formed. +// +// `strict` is an optional parameter that makes the function fail more often. + exports.fromBuffer = function(buffer, strict) { + if (buffer instanceof ArrayBuffer) { + buffer = new Buffer(new Uint8Array(buffer)); + } else if (buffer instanceof Uint8Array) { + buffer = new Buffer(buffer); + } + return utils.fromOscPacket(buffer, strict); + }; + +//~api~ +//---- +//### .toBuffer(object, [strict]) +// takes a _OSC packet_ javascript representation as defined below and returns +// a node.js Buffer, or throws if the representation is ill-formed. +// +// See "JavaScript representations of the OSC types" below. +// +//---- +//### .toBuffer(address, args[], [strict]) +// alternative syntax for above. Assumes this is an _OSC Message_ as defined below, +// and `args` is an array of _OSC Arguments_ or single _OSC Argument_ + exports.toBuffer = function(object, strict, opt) { + if(typeof object === "string") + return utils.toOscPacket({'address' : object, 'args' : strict}, opt); + return utils.toOscPacket(object, strict); + }; + +//~api~ +//---- +//### .applyAddressTransform(buffer, transform) +// takes a callback that takes a string and outputs a string, +// and applies that to the address of the message encoded in the buffer, +// and outputs an encoded buffer. +// +// If the buffer encodes an _OSC Bundle_, this applies the function to each address +// in the bundle. +// +// There's two subtle reasons you'd want to use this function rather than +// composing `fromBuffer` and `toBuffer`: +// - Future-proofing - if the OSC message uses an argument typecode that +// we don't understand, calling `fromBuffer` will throw. The only time +// when `applyAddressTranform` might fail is if the address is malformed. +// - Accuracy - javascript represents numbers as 64-bit floats, so some +// OSC types will not be able to be represented accurately. If accuracy +// is important to you, then, you should never convert the OSC message to a +// javascript representation. + exports.applyAddressTransform = function(buffer, transform) { + return utils.applyTransform(buffer, utils.addressTransform(transform)); + }; + +//~api~ +//---- +//### .applyMessageTransform(buffer, transform) +// takes a function that takes and returns a javascript _OSC Message_ representation, +// and applies that to each message encoded in the buffer, +// and outputs a new buffer with the new address. +// +// If the buffer encodes an osc-bundle, this applies the function to each message +// in the bundle. +// +// See notes above for applyAddressTransform for why you might want to use this. +// While this does parse and re-pack the messages, the bundle timetags are left +// in their accurate and prestine state. + exports.applyMessageTransform = function(buffer, transform) { + return utils.applyTransform(buffer, utils.messageTransform(transform)); + }; + + +//~api~ +//---- +//### .timetagToDate(ntpTimeTag) +// Convert a timetag array to a JavaScript Date object in your local timezone. +// +// Received OSC bundles converted with `fromBuffer` will have a timetag array: +// [secondsSince1970, fractionalSeconds] +// This utility is useful for logging. Accuracy is reduced to milliseconds. + exports.timetagToDate = utils.timetagToDate; + +//~api~ +//---- +//### .dateToTimetag(date) +// Convert a JavaScript Date to a NTP timetag array [secondsSince1970, fractionalSeconds]. +// +// `toBuffer` already accepts Dates for timetags so you might not need this function. If you need to schedule bundles with finer than millisecond accuracy then you could use this to help assemble the NTP array. + exports.dateToTimetag = utils.dateToTimetag; + +//~api~ +//---- +//### .timetagToTimestamp(timeTag) +// Convert a timetag array to the number of seconds since the UNIX epoch. +// + exports.timetagToTimestamp = utils.timetagToTimestamp; + +//~api~ +//---- +//### .timestampToTimetag(timeStamp) +// Convert a number of seconds since the UNIX epoch to a timetag array. +// + exports.timestampToTimetag = utils.timestampToTimetag; + +}).call(this);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/lib/install.md Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,31 @@ +~installation~ + +The easiest way to get osc-min is through [NPM](http://npmjs.org). +After install npm, you can install osc-min in the current directory with + +``` +npm install osc-min +``` + +If you'd rather get osc-min through github (for example, if you're forking +it), you still need npm to install dependencies, which you can do with + +``` +npm install --dev +``` + +Once you've got all the dependencies you should be able to run the unit +tests with + +``` +npm test +npm run-script coverage +``` + +### For the browser +If you want to use this library in a browser, you can build a browserified file (`build/osc-min.js`) with + +``` +npm install --dev +npm run-script browserify +``` \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/lib/osc-utilities.coffee Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,772 @@ +# # osc-utilities.coffee +# ## Intro +# This file contains some lower-level utilities for OSC handling. +# My guess is client code won't need this. If you do need this, you must +# require coffee first, then write: +# +# require("coffee-script/register"); +# osc-utils = require("osc/lib/osc-utilities"); +# +# See the comments in osc.coffee for more information about the structure of +# the objects we're dealing with here. +# + +# ## Dependencies +# require the minimal binary packing utilities +binpack = require "binpack" + +# ## Exported Functions + +# Utility for working with buffers. takes an array of buffers, +# output one buffer with all of the array concatenated +# +# This is really only exported for TDD, but maybe it'll be useful +# to someone else too. +exports.concat = (buffers) -> + if not IsArray buffers + throw new Error "concat must take an array of buffers" + + for buffer in buffers + if not Buffer.isBuffer(buffer) + throw new Error "concat must take an array of buffers" + + sumLength = 0 + sumLength += buffer.length for buffer in buffers + + destBuffer = new Buffer(sumLength) + + copyTo = 0 + for buffer in buffers + buffer.copy destBuffer, copyTo + copyTo += buffer.length + + destBuffer + +# +# Convert a javascript string into a node.js Buffer containing an OSC-String. +# +# str must not contain any \u0000 characters. +# +# `strict` is an optional boolean paramter that fails if the string is invalid +# (i.e. contains a \u0000 character) +exports.toOscString = (str, strict) -> + if not (typeof str == "string") + throw new Error "can't pack a non-string into an osc-string" + + # strip off any \u0000 characters. + nullIndex = str.indexOf("\u0000") + + # if we're being strict, we can't allow strings with null characters + if (nullIndex != -1 and strict) + throw StrictError "Can't pack an osc-string that contains NULL characters" + + str = str[0...nullIndex] if nullIndex != -1 + + # osc-strings must have length divisible by 4 and end with at least one zero. + for i in [0...(padding str)] + str += "\u0000" + + # create a new buffer from the string. + new Buffer(str) + +# +# Try to split a buffer into a leading osc-string and the rest of the buffer, +# with the following layout: +# { string : "blah" rest : <Buffer>}. +# +# `strict`, as above, is an optional boolean parameter that defaults to false - +# if it is true, then an invalid buffer will always return null. +# +exports.splitOscString = (buffer, strict) -> + if not Buffer.isBuffer buffer + throw StrictError "Can't split something that isn't a buffer" + + # extract the string + rawStr = buffer.toString "utf8" + nullIndex = rawStr.indexOf "\u0000" + + # the rest of the code doesn't apply if there's no null character. + if nullIndex == -1 + throw new Error "All osc-strings must contain a null character" if strict + return {string:rawStr, rest:(new Buffer 0)} + + # extract the string. + str = rawStr[0...nullIndex] + + # find the length of the string's buffer + splitPoint = Buffer.byteLength(str) + padding(str) + + # in strict mode, don't succeed if there's not enough padding. + if strict and splitPoint > buffer.length + throw StrictError "Not enough padding for osc-string" + + # if we're in strict mode, check that all the padding is null + if strict + for i in [Buffer.byteLength(str)...splitPoint] + if buffer[i] != 0 + throw StrictError "Not enough or incorrect padding for osc-string" + + # return a split + rest = buffer[splitPoint...(buffer.length)] + + {string: str, rest: rest} + +# This has similar semantics to splitOscString but works with integers instead. +# bytes is the number of bytes in the integer, defaults to 4. +exports.splitInteger = (buffer, type) -> + type = "Int32" if not type? + bytes = (binpack["pack" + type] 0).length + + if buffer.length < bytes + throw new Error "buffer is not big enough for integer type" + + num = 0 + + # integers are stored in big endian format. + value = binpack["unpack" + type] buffer[0...bytes], "big" + + rest = buffer[bytes...(buffer.length)] + + return {integer : value, rest : rest} + +# Split off an OSC timetag from buffer +# returning {timetag: [seconds, fractionalSeconds], rest: restOfBuffer} +exports.splitTimetag = (buffer) -> + type = "Int32" + bytes = (binpack["pack" + type] 0).length + + if buffer.length < (bytes * 2) + throw new Error "buffer is not big enough to contain a timetag" + + # integers are stored in big endian format. + a = 0 + b = bytes + seconds = binpack["unpack" + type] buffer[a...b], "big" + c = bytes + d = bytes + bytes + fractional = binpack["unpack" + type] buffer[c...d], "big" + rest = buffer[d...(buffer.length)] + + return {timetag: [seconds, fractional], rest: rest} + +UNIX_EPOCH = 2208988800 +TWO_POW_32 = 4294967296 + +# Convert a JavaScript Date to a NTP timetag array. +# Time zone of the Date object is respected, as the NTP +# timetag uses UTC. +exports.dateToTimetag = (date) -> + return exports.timestampToTimetag(date.getTime() / 1000) + +# Convert a unix timestamp (seconds since jan 1 1970 UTC) +# to NTP timestamp array +exports.timestampToTimetag = (secs) -> + wholeSecs = Math.floor(secs) + fracSeconds = secs - wholeSecs + return makeTimetag(wholeSecs, fracSeconds) + +# Convert a timetag to unix timestamp (seconds since unix epoch) +exports.timetagToTimestamp = (timetag) -> + seconds = timetag[0] + exports.ntpToFractionalSeconds(timetag[1]) + return seconds - UNIX_EPOCH + +makeTimetag = (unixseconds, fracSeconds) -> + # NTP epoch is 1900, JavaScript Date is unix 1970 + ntpSecs = unixseconds + UNIX_EPOCH + ntpFracs = Math.round(TWO_POW_32 * fracSeconds) + return [ntpSecs, ntpFracs] + +# Convert NTP timestamp array to a JavaScript Date +# in your systems local time zone. +exports.timetagToDate = (timetag) -> + [seconds, fractional] = timetag + seconds = seconds - UNIX_EPOCH + fracs = exports.ntpToFractionalSeconds(fractional) + date = new Date() + # Sets date to UTC/GMT + date.setTime((seconds * 1000) + (fracs * 1000)) + # Create a local timezone date + dd = new Date() + dd.setUTCFullYear(date.getUTCFullYear()) + dd.setUTCMonth(date.getUTCMonth()) + dd.setUTCDate(date.getUTCDate()) + dd.setUTCHours(date.getUTCHours()) + dd.setUTCMinutes(date.getUTCMinutes()) + dd.setUTCSeconds(date.getUTCSeconds()) + dd.setUTCMilliseconds(fracs * 1000) + return dd + +# Make NTP timestamp array for relative future: now + seconds +# Accuracy of 'now' limited to milliseconds but 'seconds' may be a full 32 bit float +exports.deltaTimetag = (seconds, now) -> + n = (now ? new Date()) / 1000 + return exports.timestampToTimetag(n + seconds) + +# Convert 32 bit int for NTP fractional seconds +# to a 32 bit float +exports.ntpToFractionalSeconds = (fracSeconds) -> + return parseFloat(fracSeconds) / TWO_POW_32 + +# Encodes a timetag of type null|Number|Array|Date +# as a Buffer for adding to an OSC bundle. +exports.toTimetagBuffer = (timetag) -> + if typeof timetag is "number" + timetag = exports.timestampToTimetag(timetag) + else if typeof timetag is "object" and ("getTime" of timetag) + # quacks like a Date + timetag = exports.dateToTimetag(timetag) + else if timetag.length != 2 + throw new Error("Invalid timetag" + timetag) + type = "Int32" + high = binpack["pack" + type] timetag[0], "big" + low = binpack["pack" + type] timetag[1], "big" + return exports.concat([high, low]) + +exports.toIntegerBuffer = (number, type) -> + type = "Int32" if not type? + if typeof number isnt "number" + throw new Error "cannot pack a non-number into an integer buffer" + binpack["pack" + type] number, "big" + +# This mapping contains three fields for each type: +# - representation : the javascript string representation of this type. +# - split : a function to split a buffer into a decoded value and +# the rest of the buffer. +# - toArg : a function that takes the representation of the type and +# outputs a buffer. +oscTypeCodes = + s : { + representation : "string" + split : (buffer, strict) -> + # just pass it through to splitOscString + split = exports.splitOscString buffer, strict + {value : split.string, rest : split.rest} + toArg : (value, strict) -> + throw new Error "expected string" if typeof value isnt "string" + exports.toOscString value, strict + } + i : { + representation : "integer" + split : (buffer, strict) -> + split = exports.splitInteger buffer + {value : split.integer, rest : split.rest} + toArg : (value, strict) -> + throw new Error "expected number" if typeof value isnt "number" + exports.toIntegerBuffer value + } + t : { + representation : "timetag" + split : (buffer, strict) -> + split = exports.splitTimetag buffer + {value: split.timetag, rest: split.rest} + toArg : (value, strict) -> + exports.toTimetagBuffer value + } + f : { + representation : "float" + split : (buffer, strict) -> + value : (binpack.unpackFloat32 buffer[0...4], "big") + rest : buffer[4...(buffer.length)] + toArg : (value, strict) -> + throw new Error "expected number" if typeof value isnt "number" + binpack.packFloat32 value, "big" + } + d : { + representation : "double" + split : (buffer, strict) -> + value : (binpack.unpackFloat64 buffer[0...8], "big") + rest : buffer[8...(buffer.length)] + toArg : (value, strict) -> + throw new Error "expected number" if typeof value isnt "number" + binpack.packFloat64 value, "big" + } + b : { + representation : "blob" + split : (buffer, strict) -> + # not much to do here, first grab an 4 byte int from the buffer + {integer : length, rest : buffer} = exports.splitInteger buffer + {value : buffer[0...length], rest : buffer[length...(buffer.length)]} + toArg : (value, strict) -> + throw new Error "expected node.js Buffer" if not Buffer.isBuffer value + size = exports.toIntegerBuffer value.length + exports.concat [size, value] + } + T : { + representation : "true" + split : (buffer, strict) -> + rest : buffer + value : true + toArg : (value, strict) -> + throw new Error "true must be true" if not value and strict + new Buffer 0 + } + F : { + representation : "false" + split : (buffer, strict) -> + rest : buffer + value : false + toArg : (value, strict) -> + throw new Error "false must be false" if value and strict + new Buffer 0 + } + N : { + representation : "null" + split : (buffer, strict) -> + rest : buffer + value : null + toArg : (value, strict) -> + throw new Error "null must be false" if value and strict + new Buffer 0 + } + I : { + representation : "bang" + split : (buffer, strict) -> + rest : buffer + value : "bang" + toArg : (value, strict) -> + new Buffer 0 + } + +# simple function that converts a type code into it's javascript +# string representation. +exports.oscTypeCodeToTypeString = (code) -> + oscTypeCodes[code]?.representation + +# simple function that converts a javascript string representation +# into its OSC type code. +exports.typeStringToOscTypeCode = (rep) -> + for own code, {representation : str} of oscTypeCodes + return code if str is rep + return null + +exports.argToTypeCode = (arg, strict) -> + # if there's an explicit type annotation, back-translate that. + if arg?.type? and + (typeof arg.type is 'string') and + (code = exports.typeStringToOscTypeCode arg.type)? + return code + + value = if arg?.value? then arg.value else arg + + # now, we try to guess the type. + throw new Error 'Argument has no value' if strict and not value? + + # if it's a string, use 's' + if typeof value is 'string' + return 's' + + # if it's a number, use 'f' by default. + if typeof value is 'number' + return 'f' + + # if it's a buffer, use 'b' + if Buffer.isBuffer(value) + return 'b' + + #### These are 1.1 specific types. + + # if it's a boolean, use 'T' or 'F' + if typeof value is 'boolean' + if value then return 'T' else return 'F' + + # if it's null, use 'N' + if value is null + return 'N' + + throw new Error "I don't know what type this is supposed to be." + +# Splits out an argument from buffer. Same thing as splitOscString but +# works for all argument types. +exports.splitOscArgument = (buffer, type, strict) -> + osctype = exports.typeStringToOscTypeCode type + if osctype? + oscTypeCodes[osctype].split buffer, strict + else + throw new Error "I don't understand how I'm supposed to unpack #{type}" + +# Create a buffer with the given javascript type +exports.toOscArgument = (value, type, strict) -> + osctype = exports.typeStringToOscTypeCode type + if osctype? + oscTypeCodes[osctype].toArg value, strict + else + throw new Error "I don't know how to pack #{type}" + +# +# translates an OSC message into a javascript representation. +# +exports.fromOscMessage = (buffer, strict) -> + # break off the address + { string : address, rest : buffer} = exports.splitOscString buffer, strict + + # technically, addresses have to start with '/'. + if strict and address[0] isnt '/' + throw StrictError 'addresses must start with /' + + # if there's no type string, this is technically illegal, but + # the specification says we should accept this until all + # implementations that send message without a type string are fixed. + # this will never happen, so we should accept this, even in + # strict mode. + return {address : address, args : []} if not buffer.length + + # if there's more data but no type string, we can't parse the arguments. + {string : types, rest : buffer} = exports.splitOscString buffer, strict + + # if the first letter isn't a ',' this isn't a valid type so we can't + # parse the arguments. + if types[0] isnt ',' + throw StrictError 'Argument lists must begin with ,' if strict + return {address : address, args : []} + + # we don't need the comma anymore + types = types[1..(types.length)] + + args = [] + + # we use this to build up array arguments. + # arrayStack[-1] is always the currently contructing + # array. + arrayStack = [args] + + # grab each argument. + for type in types + # special case: we're beginning construction of an array. + if type is '[' + arrayStack.push([]) + continue + + # special case: we've just finished constructing an array. + if type is ']' + if arrayStack.length <= 1 + throw new StrictError "Mismatched ']' character." if strict + else + built = arrayStack.pop() + arrayStack[arrayStack.length-1].push( + type: 'array' + value: built + ) + continue + + # by the standard, we have to ignore the whole message + # if we don't understand an argument + typeString = exports.oscTypeCodeToTypeString type + if not typeString? + throw new Error "I don't understand the argument code #{type}" + + arg = exports.splitOscArgument buffer, typeString, strict + + # consume the argument from the buffer + buffer = arg.rest if arg? + + # add it to the list. + arrayStack[arrayStack.length-1].push( + type : typeString + value : arg?.value + ) + + if arrayStack.length isnt 1 and strict + throw new StrictError "Mismatched '[' character" + {address : address, args : args, oscType : "message"} + +# +# Try to parse an OSC bundle into a javascript object. +# +exports.fromOscBundle = (buffer, strict) -> + # break off the bundletag + { string : bundleTag, rest : buffer} = exports.splitOscString buffer, strict + + # bundles have to start with "#bundle". + if bundleTag isnt "\#bundle" + throw new Error "osc-bundles must begin with \#bundle" + + # grab the 8 byte timetag + {timetag: timetag, rest: buffer} = exports.splitTimetag buffer + + # convert each element. + convertedElems = mapBundleList buffer, (buffer) -> + exports.fromOscPacket buffer, strict + + return {timetag : timetag, elements : convertedElems, oscType : "bundle"} + +# +# convert the buffer into a bundle or a message, depending on the first string +# +exports.fromOscPacket = (buffer, strict) -> + if isOscBundleBuffer buffer, strict + exports.fromOscBundle buffer, strict + else + exports.fromOscMessage buffer, strict + +# helper - is it an argument that represents an array? +getArrayArg = (arg) -> + if IsArray arg + arg + else if (arg?.type is "array") and (IsArray arg?.value) + arg.value + else if arg? and (not arg.type?) and (IsArray arg.value) + arg.value + else + null + +# helper - converts an argument list into a pair of a type string and a +# data buffer +# argList must be an array!!! +toOscTypeAndArgs = (argList, strict) -> + osctype = "" + oscargs = [] + for arg in argList + if (getArrayArg arg)? + [thisType, thisArgs] = toOscTypeAndArgs (getArrayArg arg), strict + osctype += "[" + thisType + "]" + oscargs = oscargs.concat thisArgs + continue + typeCode = exports.argToTypeCode arg, strict + if typeCode? + value = arg?.value + if value is undefined + value = arg + buff = exports.toOscArgument value, + (exports.oscTypeCodeToTypeString typeCode), strict + if buff? + oscargs.push buff + osctype += typeCode + [osctype, oscargs] + +# +# convert a javascript format message into an osc buffer +# +exports.toOscMessage = (message, strict) -> + # the message must have addresses and arguments. + address = if message?.address? then message.address else message + if typeof address isnt "string" + throw new Error "message must contain an address" + + args = message?.args + + if args is undefined + args = [] + + # pack single args + if not IsArray args + old_arg = args + args = [] + args[0] = old_arg + + oscaddr = exports.toOscString address, strict + [osctype, oscargs] = toOscTypeAndArgs args, strict + osctype = "," + osctype + + # bundle everything together. + allArgs = exports.concat oscargs + + # convert the type tag into an oscString. + osctype = exports.toOscString osctype + + exports.concat [oscaddr, osctype, allArgs] + +# +# convert a javascript format bundle into an osc buffer +# +exports.toOscBundle = (bundle, strict) -> + # the bundle must have timetag and elements. + if strict and not bundle?.timetag? + throw StrictError "bundles must have timetags." + timetag = bundle?.timetag ? new Date() + elements = bundle?.elements ? [] + if not IsArray elements + elemstr = elements + elements = [] + elements.push elemstr + + oscBundleTag = exports.toOscString "\#bundle" + oscTimeTag = exports.toTimetagBuffer timetag + + oscElems = [] + for elem in elements + try + # try to convert this sub-element into a buffer + buff = exports.toOscPacket elem, strict + + # okay, pack in the size. + size = exports.toIntegerBuffer buff.length + oscElems.push exports.concat [size, buff] + catch e + null + + allElems = exports.concat oscElems + exports.concat [oscBundleTag, oscTimeTag, allElems] + +# convert a javascript format bundle or message into a buffer +exports.toOscPacket = (bundleOrMessage, strict) -> + # first, determine whether or not this is a bundle. + if bundleOrMessage?.oscType? + if bundleOrMessage.oscType is "bundle" + return exports.toOscBundle bundleOrMessage, strict + return exports.toOscMessage bundleOrMessage, strict + + # bundles have "timetags" and "elements" + if bundleOrMessage?.timetag? or bundleOrMessage?.elements? + return exports.toOscBundle bundleOrMessage, strict + + exports.toOscMessage bundleOrMessage, strict + +# +# Helper function for transforming all messages in a bundle with a given message +# transform. +# +exports.applyMessageTranformerToBundle = (transform) -> (buffer) -> + + # parse out the bundle-id and the tag, we don't want to change these + { string, rest : buffer} = exports.splitOscString buffer + + # bundles have to start with "#bundle". + if string isnt "\#bundle" + throw new Error "osc-bundles must begin with \#bundle" + + bundleTagBuffer = exports.toOscString string + + # we know that the timetag is 8 bytes, we don't want to mess with it, + # so grab it as a buffer. There is some subtle loss of precision with + # the round trip from int64 to float64. + timetagBuffer = buffer[0...8] + buffer = buffer[8...buffer.length] + + # convert each element. + elems = mapBundleList buffer, (buffer) -> + exports.applyTransform( + buffer, + transform, + exports.applyMessageTranformerToBundle transform + ) + + totalLength = bundleTagBuffer.length + timetagBuffer.length + totalLength += 4 + elem.length for elem in elems + + # okay, now we have to reconcatenate everything. + outBuffer = new Buffer totalLength + bundleTagBuffer.copy outBuffer, 0 + timetagBuffer.copy outBuffer, bundleTagBuffer.length + copyIndex = bundleTagBuffer.length + timetagBuffer.length + for elem in elems + lengthBuff = exports.toIntegerBuffer elem.length + lengthBuff.copy outBuffer, copyIndex + copyIndex += 4 + elem.copy outBuffer, copyIndex + copyIndex += elem.length + outBuffer + +# +# Applies a transformation function (that is, a function from buffers +# to buffers) to each element of given osc-bundle or message. +# +# `buffer` is the buffer to transform, which must be a buffer of a full packet. +# `messageTransform` is function from message buffers to message buffers +# `bundleTransform` is an optional parameter for functions from bundle buffers +# to bundle buffers. +# if `bundleTransform` is not set, it defaults to just applying the +# `messageTransform` to each message in the bundle. +# +exports.applyTransform = (buffer, mTransform, bundleTransform) -> + if not bundleTransform? + bundleTransform = exports.applyMessageTranformerToBundle mTransform + + if isOscBundleBuffer buffer + bundleTransform buffer + else + mTransform buffer + +# Converts a javascript function from string to string to a function +# from message buffer to message buffer, applying the function to the +# parsed strings. +# +# We pre-curry this because we expect to use this with `applyMessageTransform` +# above +# +exports.addressTransform = (transform) -> (buffer) -> + # parse out the address + {string, rest} = exports.splitOscString buffer + + # apply the function + string = transform string + + # re-concatenate + exports.concat [ + exports.toOscString string + rest + ] + +# +# Take a function that transform a javascript _OSC Message_ and +# convert it to a function that transforms osc-buffers. +# +exports.messageTransform = (transform) -> (buffer) -> + message = exports.fromOscMessage buffer + exports.toOscMessage transform message + +## Private utilities + +# +# is it an array? +# +IsArray = Array.isArray + +# +# An error that only throws when we're in strict mode. +# +StrictError = (str) -> + new Error "Strict Error: " + str + +# this private utility finds the amount of padding for a given string. +padding = (str) -> + bufflength = Buffer.byteLength(str) + 4 - (bufflength % 4) + +# +# Internal function to check if this is a message or bundle. +# +isOscBundleBuffer = (buffer, strict) -> + # both formats begin with strings, so we should just grab the front but not + # consume it. + {string} = exports.splitOscString buffer, strict + + return string is "\#bundle" + +# +# Does something for each element in an array of osc-message-or-bundles, +# each prefixed by a length (such as appears in osc-messages), then +# return the result as an array. +# +# This is not exported because it doesn't validate the format and it's +# not really a generally useful function. +# +# If a function throws on an element, we discard that element in the map +# but we don't give up completely. +# +mapBundleList = (buffer, func) -> + elems = while buffer.length + # the length of the element is stored in an integer + {integer : size, rest : buffer} = exports.splitInteger buffer + + # if the size is bigger than the packet, something's messed up, so give up. + if size > buffer.length + throw new Error( + "Invalid bundle list: size of element is bigger than buffer") + + thisElemBuffer = buffer[0...size] + + # move the buffer to after the element we're just parsing. + buffer = buffer[size...buffer.length] + + # record this element + try + func thisElemBuffer + catch e + null + + # remove all null from elements + nonNullElems = [] + for elem in elems + (nonNullElems.push elem) if elem? + + nonNullElems
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/lib/osc-utilities.js Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,741 @@ +// Generated by CoffeeScript 1.10.0 +(function() { + var IsArray, StrictError, TWO_POW_32, UNIX_EPOCH, binpack, getArrayArg, isOscBundleBuffer, makeTimetag, mapBundleList, oscTypeCodes, padding, toOscTypeAndArgs, + hasProp = {}.hasOwnProperty; + + binpack = require("binpack"); + + exports.concat = function(buffers) { + var buffer, copyTo, destBuffer, j, k, l, len, len1, len2, sumLength; + if (!IsArray(buffers)) { + throw new Error("concat must take an array of buffers"); + } + for (j = 0, len = buffers.length; j < len; j++) { + buffer = buffers[j]; + if (!Buffer.isBuffer(buffer)) { + throw new Error("concat must take an array of buffers"); + } + } + sumLength = 0; + for (k = 0, len1 = buffers.length; k < len1; k++) { + buffer = buffers[k]; + sumLength += buffer.length; + } + destBuffer = new Buffer(sumLength); + copyTo = 0; + for (l = 0, len2 = buffers.length; l < len2; l++) { + buffer = buffers[l]; + buffer.copy(destBuffer, copyTo); + copyTo += buffer.length; + } + return destBuffer; + }; + + exports.toOscString = function(str, strict) { + var i, j, nullIndex, ref; + if (!(typeof str === "string")) { + throw new Error("can't pack a non-string into an osc-string"); + } + nullIndex = str.indexOf("\u0000"); + if (nullIndex !== -1 && strict) { + throw StrictError("Can't pack an osc-string that contains NULL characters"); + } + if (nullIndex !== -1) { + str = str.slice(0, nullIndex); + } + for (i = j = 0, ref = padding(str); 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) { + str += "\u0000"; + } + return new Buffer(str); + }; + + exports.splitOscString = function(buffer, strict) { + var i, j, nullIndex, rawStr, ref, ref1, rest, splitPoint, str; + if (!Buffer.isBuffer(buffer)) { + throw StrictError("Can't split something that isn't a buffer"); + } + rawStr = buffer.toString("utf8"); + nullIndex = rawStr.indexOf("\u0000"); + if (nullIndex === -1) { + if (strict) { + throw new Error("All osc-strings must contain a null character"); + } + return { + string: rawStr, + rest: new Buffer(0) + }; + } + str = rawStr.slice(0, nullIndex); + splitPoint = Buffer.byteLength(str) + padding(str); + if (strict && splitPoint > buffer.length) { + throw StrictError("Not enough padding for osc-string"); + } + if (strict) { + for (i = j = ref = Buffer.byteLength(str), ref1 = splitPoint; ref <= ref1 ? j < ref1 : j > ref1; i = ref <= ref1 ? ++j : --j) { + if (buffer[i] !== 0) { + throw StrictError("Not enough or incorrect padding for osc-string"); + } + } + } + rest = buffer.slice(splitPoint, buffer.length); + return { + string: str, + rest: rest + }; + }; + + exports.splitInteger = function(buffer, type) { + var bytes, num, rest, value; + if (type == null) { + type = "Int32"; + } + bytes = (binpack["pack" + type](0)).length; + if (buffer.length < bytes) { + throw new Error("buffer is not big enough for integer type"); + } + num = 0; + value = binpack["unpack" + type](buffer.slice(0, bytes), "big"); + rest = buffer.slice(bytes, buffer.length); + return { + integer: value, + rest: rest + }; + }; + + exports.splitTimetag = function(buffer) { + var a, b, bytes, c, d, fractional, rest, seconds, type; + type = "Int32"; + bytes = (binpack["pack" + type](0)).length; + if (buffer.length < (bytes * 2)) { + throw new Error("buffer is not big enough to contain a timetag"); + } + a = 0; + b = bytes; + seconds = binpack["unpack" + type](buffer.slice(a, b), "big"); + c = bytes; + d = bytes + bytes; + fractional = binpack["unpack" + type](buffer.slice(c, d), "big"); + rest = buffer.slice(d, buffer.length); + return { + timetag: [seconds, fractional], + rest: rest + }; + }; + + UNIX_EPOCH = 2208988800; + + TWO_POW_32 = 4294967296; + + exports.dateToTimetag = function(date) { + return exports.timestampToTimetag(date.getTime() / 1000); + }; + + exports.timestampToTimetag = function(secs) { + var fracSeconds, wholeSecs; + wholeSecs = Math.floor(secs); + fracSeconds = secs - wholeSecs; + return makeTimetag(wholeSecs, fracSeconds); + }; + + exports.timetagToTimestamp = function(timetag) { + var seconds; + seconds = timetag[0] + exports.ntpToFractionalSeconds(timetag[1]); + return seconds - UNIX_EPOCH; + }; + + makeTimetag = function(unixseconds, fracSeconds) { + var ntpFracs, ntpSecs; + ntpSecs = unixseconds + UNIX_EPOCH; + ntpFracs = Math.round(TWO_POW_32 * fracSeconds); + return [ntpSecs, ntpFracs]; + }; + + exports.timetagToDate = function(timetag) { + var date, dd, fracs, fractional, seconds; + seconds = timetag[0], fractional = timetag[1]; + seconds = seconds - UNIX_EPOCH; + fracs = exports.ntpToFractionalSeconds(fractional); + date = new Date(); + date.setTime((seconds * 1000) + (fracs * 1000)); + dd = new Date(); + dd.setUTCFullYear(date.getUTCFullYear()); + dd.setUTCMonth(date.getUTCMonth()); + dd.setUTCDate(date.getUTCDate()); + dd.setUTCHours(date.getUTCHours()); + dd.setUTCMinutes(date.getUTCMinutes()); + dd.setUTCSeconds(date.getUTCSeconds()); + dd.setUTCMilliseconds(fracs * 1000); + return dd; + }; + + exports.deltaTimetag = function(seconds, now) { + var n; + n = (now != null ? now : new Date()) / 1000; + return exports.timestampToTimetag(n + seconds); + }; + + exports.ntpToFractionalSeconds = function(fracSeconds) { + return parseFloat(fracSeconds) / TWO_POW_32; + }; + + exports.toTimetagBuffer = function(timetag) { + var high, low, type; + if (typeof timetag === "number") { + timetag = exports.timestampToTimetag(timetag); + } else if (typeof timetag === "object" && ("getTime" in timetag)) { + timetag = exports.dateToTimetag(timetag); + } else if (timetag.length !== 2) { + throw new Error("Invalid timetag" + timetag); + } + type = "Int32"; + high = binpack["pack" + type](timetag[0], "big"); + low = binpack["pack" + type](timetag[1], "big"); + return exports.concat([high, low]); + }; + + exports.toIntegerBuffer = function(number, type) { + if (type == null) { + type = "Int32"; + } + if (typeof number !== "number") { + throw new Error("cannot pack a non-number into an integer buffer"); + } + return binpack["pack" + type](number, "big"); + }; + + oscTypeCodes = { + s: { + representation: "string", + split: function(buffer, strict) { + var split; + split = exports.splitOscString(buffer, strict); + return { + value: split.string, + rest: split.rest + }; + }, + toArg: function(value, strict) { + if (typeof value !== "string") { + throw new Error("expected string"); + } + return exports.toOscString(value, strict); + } + }, + i: { + representation: "integer", + split: function(buffer, strict) { + var split; + split = exports.splitInteger(buffer); + return { + value: split.integer, + rest: split.rest + }; + }, + toArg: function(value, strict) { + if (typeof value !== "number") { + throw new Error("expected number"); + } + return exports.toIntegerBuffer(value); + } + }, + t: { + representation: "timetag", + split: function(buffer, strict) { + var split; + split = exports.splitTimetag(buffer); + return { + value: split.timetag, + rest: split.rest + }; + }, + toArg: function(value, strict) { + return exports.toTimetagBuffer(value); + } + }, + f: { + representation: "float", + split: function(buffer, strict) { + return { + value: binpack.unpackFloat32(buffer.slice(0, 4), "big"), + rest: buffer.slice(4, buffer.length) + }; + }, + toArg: function(value, strict) { + if (typeof value !== "number") { + throw new Error("expected number"); + } + return binpack.packFloat32(value, "big"); + } + }, + d: { + representation: "double", + split: function(buffer, strict) { + return { + value: binpack.unpackFloat64(buffer.slice(0, 8), "big"), + rest: buffer.slice(8, buffer.length) + }; + }, + toArg: function(value, strict) { + if (typeof value !== "number") { + throw new Error("expected number"); + } + return binpack.packFloat64(value, "big"); + } + }, + b: { + representation: "blob", + split: function(buffer, strict) { + var length, ref; + ref = exports.splitInteger(buffer), length = ref.integer, buffer = ref.rest; + return { + value: buffer.slice(0, length), + rest: buffer.slice(length, buffer.length) + }; + }, + toArg: function(value, strict) { + var size; + if (!Buffer.isBuffer(value)) { + throw new Error("expected node.js Buffer"); + } + size = exports.toIntegerBuffer(value.length); + return exports.concat([size, value]); + } + }, + T: { + representation: "true", + split: function(buffer, strict) { + return { + rest: buffer, + value: true + }; + }, + toArg: function(value, strict) { + if (!value && strict) { + throw new Error("true must be true"); + } + return new Buffer(0); + } + }, + F: { + representation: "false", + split: function(buffer, strict) { + return { + rest: buffer, + value: false + }; + }, + toArg: function(value, strict) { + if (value && strict) { + throw new Error("false must be false"); + } + return new Buffer(0); + } + }, + N: { + representation: "null", + split: function(buffer, strict) { + return { + rest: buffer, + value: null + }; + }, + toArg: function(value, strict) { + if (value && strict) { + throw new Error("null must be false"); + } + return new Buffer(0); + } + }, + I: { + representation: "bang", + split: function(buffer, strict) { + return { + rest: buffer, + value: "bang" + }; + }, + toArg: function(value, strict) { + return new Buffer(0); + } + } + }; + + exports.oscTypeCodeToTypeString = function(code) { + var ref; + return (ref = oscTypeCodes[code]) != null ? ref.representation : void 0; + }; + + exports.typeStringToOscTypeCode = function(rep) { + var code, str; + for (code in oscTypeCodes) { + if (!hasProp.call(oscTypeCodes, code)) continue; + str = oscTypeCodes[code].representation; + if (str === rep) { + return code; + } + } + return null; + }; + + exports.argToTypeCode = function(arg, strict) { + var code, value; + if (((arg != null ? arg.type : void 0) != null) && (typeof arg.type === 'string') && ((code = exports.typeStringToOscTypeCode(arg.type)) != null)) { + return code; + } + value = (arg != null ? arg.value : void 0) != null ? arg.value : arg; + if (strict && (value == null)) { + throw new Error('Argument has no value'); + } + if (typeof value === 'string') { + return 's'; + } + if (typeof value === 'number') { + return 'f'; + } + if (Buffer.isBuffer(value)) { + return 'b'; + } + if (typeof value === 'boolean') { + if (value) { + return 'T'; + } else { + return 'F'; + } + } + if (value === null) { + return 'N'; + } + throw new Error("I don't know what type this is supposed to be."); + }; + + exports.splitOscArgument = function(buffer, type, strict) { + var osctype; + osctype = exports.typeStringToOscTypeCode(type); + if (osctype != null) { + return oscTypeCodes[osctype].split(buffer, strict); + } else { + throw new Error("I don't understand how I'm supposed to unpack " + type); + } + }; + + exports.toOscArgument = function(value, type, strict) { + var osctype; + osctype = exports.typeStringToOscTypeCode(type); + if (osctype != null) { + return oscTypeCodes[osctype].toArg(value, strict); + } else { + throw new Error("I don't know how to pack " + type); + } + }; + + exports.fromOscMessage = function(buffer, strict) { + var address, arg, args, arrayStack, built, j, len, ref, ref1, type, typeString, types; + ref = exports.splitOscString(buffer, strict), address = ref.string, buffer = ref.rest; + if (strict && address[0] !== '/') { + throw StrictError('addresses must start with /'); + } + if (!buffer.length) { + return { + address: address, + args: [] + }; + } + ref1 = exports.splitOscString(buffer, strict), types = ref1.string, buffer = ref1.rest; + if (types[0] !== ',') { + if (strict) { + throw StrictError('Argument lists must begin with ,'); + } + return { + address: address, + args: [] + }; + } + types = types.slice(1, +types.length + 1 || 9e9); + args = []; + arrayStack = [args]; + for (j = 0, len = types.length; j < len; j++) { + type = types[j]; + if (type === '[') { + arrayStack.push([]); + continue; + } + if (type === ']') { + if (arrayStack.length <= 1) { + if (strict) { + throw new StrictError("Mismatched ']' character."); + } + } else { + built = arrayStack.pop(); + arrayStack[arrayStack.length - 1].push({ + type: 'array', + value: built + }); + } + continue; + } + typeString = exports.oscTypeCodeToTypeString(type); + if (typeString == null) { + throw new Error("I don't understand the argument code " + type); + } + arg = exports.splitOscArgument(buffer, typeString, strict); + if (arg != null) { + buffer = arg.rest; + } + arrayStack[arrayStack.length - 1].push({ + type: typeString, + value: arg != null ? arg.value : void 0 + }); + } + if (arrayStack.length !== 1 && strict) { + throw new StrictError("Mismatched '[' character"); + } + return { + address: address, + args: args, + oscType: "message" + }; + }; + + exports.fromOscBundle = function(buffer, strict) { + var bundleTag, convertedElems, ref, ref1, timetag; + ref = exports.splitOscString(buffer, strict), bundleTag = ref.string, buffer = ref.rest; + if (bundleTag !== "\#bundle") { + throw new Error("osc-bundles must begin with \#bundle"); + } + ref1 = exports.splitTimetag(buffer), timetag = ref1.timetag, buffer = ref1.rest; + convertedElems = mapBundleList(buffer, function(buffer) { + return exports.fromOscPacket(buffer, strict); + }); + return { + timetag: timetag, + elements: convertedElems, + oscType: "bundle" + }; + }; + + exports.fromOscPacket = function(buffer, strict) { + if (isOscBundleBuffer(buffer, strict)) { + return exports.fromOscBundle(buffer, strict); + } else { + return exports.fromOscMessage(buffer, strict); + } + }; + + getArrayArg = function(arg) { + if (IsArray(arg)) { + return arg; + } else if (((arg != null ? arg.type : void 0) === "array") && (IsArray(arg != null ? arg.value : void 0))) { + return arg.value; + } else if ((arg != null) && (arg.type == null) && (IsArray(arg.value))) { + return arg.value; + } else { + return null; + } + }; + + toOscTypeAndArgs = function(argList, strict) { + var arg, buff, j, len, oscargs, osctype, ref, thisArgs, thisType, typeCode, value; + osctype = ""; + oscargs = []; + for (j = 0, len = argList.length; j < len; j++) { + arg = argList[j]; + if ((getArrayArg(arg)) != null) { + ref = toOscTypeAndArgs(getArrayArg(arg), strict), thisType = ref[0], thisArgs = ref[1]; + osctype += "[" + thisType + "]"; + oscargs = oscargs.concat(thisArgs); + continue; + } + typeCode = exports.argToTypeCode(arg, strict); + if (typeCode != null) { + value = arg != null ? arg.value : void 0; + if (value === void 0) { + value = arg; + } + buff = exports.toOscArgument(value, exports.oscTypeCodeToTypeString(typeCode), strict); + if (buff != null) { + oscargs.push(buff); + osctype += typeCode; + } + } + } + return [osctype, oscargs]; + }; + + exports.toOscMessage = function(message, strict) { + var address, allArgs, args, old_arg, oscaddr, oscargs, osctype, ref; + address = (message != null ? message.address : void 0) != null ? message.address : message; + if (typeof address !== "string") { + throw new Error("message must contain an address"); + } + args = message != null ? message.args : void 0; + if (args === void 0) { + args = []; + } + if (!IsArray(args)) { + old_arg = args; + args = []; + args[0] = old_arg; + } + oscaddr = exports.toOscString(address, strict); + ref = toOscTypeAndArgs(args, strict), osctype = ref[0], oscargs = ref[1]; + osctype = "," + osctype; + allArgs = exports.concat(oscargs); + osctype = exports.toOscString(osctype); + return exports.concat([oscaddr, osctype, allArgs]); + }; + + exports.toOscBundle = function(bundle, strict) { + var allElems, buff, e, elem, elements, elemstr, error, j, len, oscBundleTag, oscElems, oscTimeTag, ref, ref1, size, timetag; + if (strict && ((bundle != null ? bundle.timetag : void 0) == null)) { + throw StrictError("bundles must have timetags."); + } + timetag = (ref = bundle != null ? bundle.timetag : void 0) != null ? ref : new Date(); + elements = (ref1 = bundle != null ? bundle.elements : void 0) != null ? ref1 : []; + if (!IsArray(elements)) { + elemstr = elements; + elements = []; + elements.push(elemstr); + } + oscBundleTag = exports.toOscString("\#bundle"); + oscTimeTag = exports.toTimetagBuffer(timetag); + oscElems = []; + for (j = 0, len = elements.length; j < len; j++) { + elem = elements[j]; + try { + buff = exports.toOscPacket(elem, strict); + size = exports.toIntegerBuffer(buff.length); + oscElems.push(exports.concat([size, buff])); + } catch (error) { + e = error; + null; + } + } + allElems = exports.concat(oscElems); + return exports.concat([oscBundleTag, oscTimeTag, allElems]); + }; + + exports.toOscPacket = function(bundleOrMessage, strict) { + if ((bundleOrMessage != null ? bundleOrMessage.oscType : void 0) != null) { + if (bundleOrMessage.oscType === "bundle") { + return exports.toOscBundle(bundleOrMessage, strict); + } + return exports.toOscMessage(bundleOrMessage, strict); + } + if (((bundleOrMessage != null ? bundleOrMessage.timetag : void 0) != null) || ((bundleOrMessage != null ? bundleOrMessage.elements : void 0) != null)) { + return exports.toOscBundle(bundleOrMessage, strict); + } + return exports.toOscMessage(bundleOrMessage, strict); + }; + + exports.applyMessageTranformerToBundle = function(transform) { + return function(buffer) { + var bundleTagBuffer, copyIndex, elem, elems, j, k, len, len1, lengthBuff, outBuffer, ref, string, timetagBuffer, totalLength; + ref = exports.splitOscString(buffer), string = ref.string, buffer = ref.rest; + if (string !== "\#bundle") { + throw new Error("osc-bundles must begin with \#bundle"); + } + bundleTagBuffer = exports.toOscString(string); + timetagBuffer = buffer.slice(0, 8); + buffer = buffer.slice(8, buffer.length); + elems = mapBundleList(buffer, function(buffer) { + return exports.applyTransform(buffer, transform, exports.applyMessageTranformerToBundle(transform)); + }); + totalLength = bundleTagBuffer.length + timetagBuffer.length; + for (j = 0, len = elems.length; j < len; j++) { + elem = elems[j]; + totalLength += 4 + elem.length; + } + outBuffer = new Buffer(totalLength); + bundleTagBuffer.copy(outBuffer, 0); + timetagBuffer.copy(outBuffer, bundleTagBuffer.length); + copyIndex = bundleTagBuffer.length + timetagBuffer.length; + for (k = 0, len1 = elems.length; k < len1; k++) { + elem = elems[k]; + lengthBuff = exports.toIntegerBuffer(elem.length); + lengthBuff.copy(outBuffer, copyIndex); + copyIndex += 4; + elem.copy(outBuffer, copyIndex); + copyIndex += elem.length; + } + return outBuffer; + }; + }; + + exports.applyTransform = function(buffer, mTransform, bundleTransform) { + if (bundleTransform == null) { + bundleTransform = exports.applyMessageTranformerToBundle(mTransform); + } + if (isOscBundleBuffer(buffer)) { + return bundleTransform(buffer); + } else { + return mTransform(buffer); + } + }; + + exports.addressTransform = function(transform) { + return function(buffer) { + var ref, rest, string; + ref = exports.splitOscString(buffer), string = ref.string, rest = ref.rest; + string = transform(string); + return exports.concat([exports.toOscString(string), rest]); + }; + }; + + exports.messageTransform = function(transform) { + return function(buffer) { + var message; + message = exports.fromOscMessage(buffer); + return exports.toOscMessage(transform(message)); + }; + }; + + IsArray = Array.isArray; + + StrictError = function(str) { + return new Error("Strict Error: " + str); + }; + + padding = function(str) { + var bufflength; + bufflength = Buffer.byteLength(str); + return 4 - (bufflength % 4); + }; + + isOscBundleBuffer = function(buffer, strict) { + var string; + string = exports.splitOscString(buffer, strict).string; + return string === "\#bundle"; + }; + + mapBundleList = function(buffer, func) { + var e, elem, elems, j, len, nonNullElems, size, thisElemBuffer; + elems = (function() { + var error, ref, results; + results = []; + while (buffer.length) { + ref = exports.splitInteger(buffer), size = ref.integer, buffer = ref.rest; + if (size > buffer.length) { + throw new Error("Invalid bundle list: size of element is bigger than buffer"); + } + thisElemBuffer = buffer.slice(0, size); + buffer = buffer.slice(size, buffer.length); + try { + results.push(func(thisElemBuffer)); + } catch (error) { + e = error; + results.push(null); + } + } + return results; + })(); + nonNullElems = []; + for (j = 0, len = elems.length; j < len; j++) { + elem = elems[j]; + if (elem != null) { + nonNullElems.push(elem); + } + } + return nonNullElems; + }; + +}).call(this);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/package.json Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,108 @@ +{ + "_args": [ + [ + "osc-min", + "/Users/liam/Documents/Bela/osc-node" + ] + ], + "_from": "osc-min@latest", + "_id": "osc-min@1.1.1", + "_inCache": true, + "_installable": true, + "_location": "/osc-min", + "_nodeVersion": "5.2.0", + "_npmUser": { + "email": "russell.mcclellan@gmail.com", + "name": "ghostfact" + }, + "_npmVersion": "3.3.12", + "_phantomChildren": {}, + "_requested": { + "name": "osc-min", + "raw": "osc-min", + "rawSpec": "", + "scope": null, + "spec": "latest", + "type": "tag" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/osc-min/-/osc-min-1.1.1.tgz", + "_shasum": "8580443a3abb02f73254f5a286340dcbe3cf3f07", + "_shrinkwrap": null, + "_spec": "osc-min", + "_where": "/Users/liam/Documents/Bela/osc-node", + "author": { + "email": "russell.mcclellan@gmail.com", + "name": "Russell McClellan", + "url": "http://www.russellmcc.com" + }, + "bugs": { + "url": "https://github.com/russellmcc/node-osc-min/issues" + }, + "config": { + "blanket": { + "data-cover-never": "node_modules", + "loader": "./node-loaders/coffee-script", + "pattern": "lib" + } + }, + "dependencies": { + "binpack": "~0" + }, + "description": "Simple utilities for open sound control in node.js", + "devDependencies": { + "blanket": "*", + "browserify": "^6.1.0", + "coffee-script": ">=1.7.1 <2.0.0", + "coveralls": "*", + "docket": "0.0.5", + "mocha": "*", + "mocha-lcov-reporter": "*", + "uglify-js": "^2.4.15" + }, + "directories": { + "examples": "examples", + "lib": "lib" + }, + "dist": { + "shasum": "8580443a3abb02f73254f5a286340dcbe3cf3f07", + "tarball": "https://registry.npmjs.org/osc-min/-/osc-min-1.1.1.tgz" + }, + "engines": { + "node": ">=0.10.0" + }, + "gitHead": "579ef44bd99ab4fb6f180ec4c29ff223f48e64a8", + "homepage": "https://github.com/russellmcc/node-osc-min#readme", + "keywords": [ + "open sound control", + "OSC", + "music control", + "NIME" + ], + "license": "Zlib", + "main": "lib/index", + "maintainers": [ + { + "email": "russell.mcclellan@gmail.com", + "name": "ghostfact" + } + ], + "name": "osc-min", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/russellmcc/node-osc-min.git" + }, + "scripts": { + "browserify": "cake browserify", + "coverage": "cake coverage", + "coveralls": "cake coveralls", + "doc": "cake doc", + "prepublish": "cake doc; coffee -c lib/osc-utilities.coffee", + "test": "cake test" + }, + "version": "1.1.1" +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/readme.md Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,262 @@ +[![build status](https://secure.travis-ci.org/russellmcc/node-osc-min.png)](http://travis-ci.org/russellmcc/node-osc-min) [![Coverage Status](https://coveralls.io/repos/russellmcc/node-osc-min/badge.png?branch=master)](https://coveralls.io/r/russellmcc/node-osc-min?branch=master) [![dependencies](https://david-dm.org/russellmcc/node-osc-min.png)](https://david-dm.org/russellmcc/node-osc-min) +# osc-min + +_simple utilities for open sound control in node.js_ + +This package provides some node.js utilities for working with +[OSC](http://opensoundcontrol.org/), a format for sound and systems control. +Here we implement the [OSC 1.1][spec11] specification. OSC is a transport-independent +protocol, so we don't provide any server objects, as you should be able to +use OSC over any transport you like. The most common is probably udp, but tcp +is not unheard of. + +[spec11]: http://opensoundcontrol.org/spec-1_1 + +---- +## Installation + +The easiest way to get osc-min is through [NPM](http://npmjs.org). +After install npm, you can install osc-min in the current directory with + +``` +npm install osc-min +``` + +If you'd rather get osc-min through github (for example, if you're forking +it), you still need npm to install dependencies, which you can do with + +``` +npm install --dev +``` + +Once you've got all the dependencies you should be able to run the unit +tests with + +``` +npm test +npm run-script coverage +``` + +### For the browser +If you want to use this library in a browser, you can build a browserified file (`build/osc-min.js`) with + +``` +npm install --dev +npm run-script browserify +``` + +---- +## Examples +### A simple OSC printer; +```javascript + +sock = udp.createSocket("udp4", function(msg, rinfo) { + var error, error1; + try { + return console.log(osc.fromBuffer(msg)); + } catch (error1) { + error = error1; + return console.log("invalid OSC packet"); + } +}); + +sock.bind(inport); + +``` +### Send a bunch of args every two seconds; +```javascript + +sendHeartbeat = function() { + var buf; + buf = osc.toBuffer({ + address: "/heartbeat", + args: [ + 12, "sttttring", new Buffer("beat"), { + type: "integer", + value: 7 + } + ] + }); + return udp.send(buf, 0, buf.length, outport, "localhost"); +}; + +setInterval(sendHeartbeat, 2000); + +``` +### A simple OSC redirecter; +```javascript + +sock = udp.createSocket("udp4", function(msg, rinfo) { + var error, error1, redirected; + try { + redirected = osc.applyAddressTransform(msg, function(address) { + return "/redirect" + address; + }); + return sock.send(redirected, 0, redirected.length, outport, "localhost"); + } catch (error1) { + error = error1; + return console.log("error redirecting: " + error); + } +}); + +sock.bind(inport); + +``` + + +more examples are available in the `examples/` directory. + +---- +## Exported functions + +------ +### .fromBuffer(buffer, [strict]) +takes a node.js Buffer of a complete _OSC Packet_ and +outputs the javascript representation, or throws if the buffer is ill-formed. + +`strict` is an optional parameter that makes the function fail more often. + +---- +### .toBuffer(object, [strict]) +takes a _OSC packet_ javascript representation as defined below and returns +a node.js Buffer, or throws if the representation is ill-formed. + +See "JavaScript representations of the OSC types" below. + +---- +### .toBuffer(address, args[], [strict]) +alternative syntax for above. Assumes this is an _OSC Message_ as defined below, +and `args` is an array of _OSC Arguments_ or single _OSC Argument_ + +---- +### .applyAddressTransform(buffer, transform) +takes a callback that takes a string and outputs a string, +and applies that to the address of the message encoded in the buffer, +and outputs an encoded buffer. + +If the buffer encodes an _OSC Bundle_, this applies the function to each address +in the bundle. + +There's two subtle reasons you'd want to use this function rather than +composing `fromBuffer` and `toBuffer`: + - Future-proofing - if the OSC message uses an argument typecode that + we don't understand, calling `fromBuffer` will throw. The only time + when `applyAddressTranform` might fail is if the address is malformed. + - Accuracy - javascript represents numbers as 64-bit floats, so some + OSC types will not be able to be represented accurately. If accuracy + is important to you, then, you should never convert the OSC message to a + javascript representation. + +---- +### .applyMessageTransform(buffer, transform) +takes a function that takes and returns a javascript _OSC Message_ representation, +and applies that to each message encoded in the buffer, +and outputs a new buffer with the new address. + +If the buffer encodes an osc-bundle, this applies the function to each message +in the bundle. + +See notes above for applyAddressTransform for why you might want to use this. +While this does parse and re-pack the messages, the bundle timetags are left +in their accurate and prestine state. + +---- +### .timetagToDate(ntpTimeTag) +Convert a timetag array to a JavaScript Date object in your local timezone. + +Received OSC bundles converted with `fromBuffer` will have a timetag array: +[secondsSince1970, fractionalSeconds] +This utility is useful for logging. Accuracy is reduced to milliseconds. + +---- +### .dateToTimetag(date) +Convert a JavaScript Date to a NTP timetag array [secondsSince1970, fractionalSeconds]. + +`toBuffer` already accepts Dates for timetags so you might not need this function. If you need to schedule bundles with finer than millisecond accuracy then you could use this to help assemble the NTP array. + +---- +### .timetagToTimestamp(timeTag) +Convert a timetag array to the number of seconds since the UNIX epoch. + + +---- +### .timestampToTimetag(timeStamp) +Convert a number of seconds since the UNIX epoch to a timetag array. + + +---- +## Javascript representations of the OSC types. +See the [spec][spec] for more information on the OSC types. + ++ An _OSC Packet_ is an _OSC Message_ or an _OSC Bundle_. + ++ An _OSC Message_: + + { + oscType : "message" + address : "/address/pattern/might/have/wildcards" + args : [arg1,arg2] + } + + Where args is an array of _OSC Arguments_. `oscType` is optional. + `args` can be a single element. + ++ An _OSC Argument_ is represented as a javascript object with the following layout: + + { + type : "string" + value : "value" + } + + Where the `type` is one of the following: + + `string` - string value + + `float` - numeric value + + `integer` - numeric value + + `blob` - node.js Buffer value + + `true` - value is boolean true + + `false` - value is boolean false + + `null` - no value + + `bang` - no value (this is the `I` type tag) + + `timetag` - numeric value + + `array` - array of _OSC Arguments_ + + Note that `type` is always a string - i.e. `"true"` rather than `true`. + + The following non-standard types are also supported: + + `double` - numeric value (encodes to a float64 value) + + + For messages sent to the `toBuffer` function, `type` is optional. + If the argument is not an object, it will be interpreted as either + `string`, `float`, `array` or `blob`, depending on its javascript type + (String, Number, Array, Buffer, respectively) + ++ An _OSC Bundle_ is represented as a javascript object with the following fields: + + { + oscType : "bundle" + timetag : 7 + elements : [element1, element] + } + + `oscType` "bundle" + + `timetag` is one of: + - `null` - meaning now, the current time. + By the time the bundle is received it will too late and depending + on the receiver may be discarded or you may be scolded for being late. + - `number` - relative seconds from now with millisecond accuracy. + - `Date` - a JavaScript Date object in your local time zone. + OSC timetags use UTC timezone, so do not try to adjust for timezones, + this is not needed. + - `Array` - `[numberOfSecondsSince1900, fractionalSeconds]` + Both values are `number`s. This gives full timing accuracy of 1/(2^32) seconds. + + `elements` is an `Array` of either _OSC Message_ or _OSC Bundle_ + + +[spec]: http://opensoundcontrol.org/spec-1_0 + +---- +## License +Licensed under the terms found in COPYING (zlib license)
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/osc-min/test/test-osc-utilities.coffee Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,794 @@ +# +# This file was used for TDD and as such probably has limited utility as +# actual unit tests. +# +try + osc = require '../lib-cov/osc-utilities' +catch e + osc = require '../lib/osc-utilities' + +assert = require "assert" + +# Basic string tests. + +testString = (str, expected_len) -> + str : str + len : expected_len + +testData = [ + testString("abc", 4) + testString("abcd", 8) + testString("abcde", 8) + testString("abcdef", 8) + testString("abcdefg", 8) +] + +testStringLength = (str, expected_len) -> + oscstr = osc.toOscString(str) + assert.strictEqual(oscstr.length, expected_len) + +test 'basic strings length', -> + for data in testData + testStringLength data.str, data.len + + +testStringRoundTrip = (str, strict) -> + oscstr = osc.toOscString(str) + str2 = osc.splitOscString(oscstr, strict)?.string + assert.strictEqual(str, str2) + +test 'basic strings round trip', -> + for data in testData + testStringRoundTrip data.str + + +test 'non strings fail toOscString', -> + assert.throws -> osc.toOscString(7) + + +test 'strings with null characters don\'t fail toOscString by default', -> + assert.notEqual(osc.toOscString("\u0000"), null) + + +test 'strings with null characters fail toOscString in strict mode', -> + assert.throws -> osc.toOscString("\u0000", true) + + +test 'osc buffers with no null characters fail splitOscString in strict mode', -> + assert.throws -> osc.splitOscString new Buffer("abc"), true + + +test 'osc buffers with non-null characters after a null character fail fromOscString in strict mode', -> + assert.throws -> osc.fromOscString new Buffer("abc\u0000abcd"), true + + +test 'basic strings pass fromOscString in strict mode', -> + for data in testData + testStringRoundTrip data.str, true + + +test 'osc buffers with non-four length fail in strict mode', -> + assert.throws -> osc.fromOscString new Buffer("abcd\u0000\u0000"), true + +test 'splitOscString throws when passed a non-buffer', -> + assert.throws -> osc.splitOscString "test" + +test 'splitOscString of an osc-string matches the string', -> + split = osc.splitOscString osc.toOscString "testing it" + assert.strictEqual(split?.string, "testing it") + assert.strictEqual(split?.rest?.length, 0) + + +test 'splitOscString works with an over-allocated buffer', -> + buffer = osc.toOscString "testing it" + overallocated = new Buffer(16) + buffer.copy(overallocated) + split = osc.splitOscString overallocated + assert.strictEqual(split?.string, "testing it") + assert.strictEqual(split?.rest?.length, 4) + + +test 'splitOscString works with just a string by default', -> + split = osc.splitOscString (new Buffer "testing it") + assert.strictEqual(split?.string, "testing it") + assert.strictEqual(split?.rest?.length, 0) + + +test 'splitOscString strict fails for just a string', -> + assert.throws -> osc.splitOscString (new Buffer "testing it"), true + + +test 'splitOscString strict fails for string with not enough padding', -> + assert.throws -> osc.splitOscString (new Buffer "testing \u0000\u0000"), true + + +test 'splitOscString strict succeeds for strings with valid padding', -> + split = osc.splitOscString (new Buffer "testing it\u0000\u0000aaaa"), true + assert.strictEqual(split?.string, "testing it") + assert.strictEqual(split?.rest?.length, 4) + + +test 'splitOscString strict fails for string with invalid padding', -> + assert.throws -> osc.splitOscString (new Buffer "testing it\u0000aaaaa"), true + +test 'concat throws when passed a single buffer', -> + assert.throws -> osc.concat new Buffer "test" + +test 'concat throws when passed an array of non-buffers', -> + assert.throws -> osc.concat ["bleh"] + +test 'toIntegerBuffer throws when passed a non-number', -> + assert.throws -> osc.toIntegerBuffer "abcdefg" + +test 'splitInteger fails when sent a buffer that\'s too small', -> + assert.throws -> osc.splitInteger new Buffer 3, "Int32" + +test 'splitOscArgument fails when given a bogus type', -> + assert.throws -> osc.splitOscArgument new Buffer 8, "bogus" + +test 'fromOscMessage with no type string works', -> + translate = osc.fromOscMessage osc.toOscString "/stuff" + assert.strictEqual translate?.address, "/stuff" + assert.deepEqual translate?.args, [] + +test 'fromOscMessage with type string and no args works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString "," + oscmessage = new Buffer(oscaddr.length + osctype.length) + oscaddr.copy oscmessage + osctype.copy oscmessage, oscaddr.length + translate = osc.fromOscMessage oscmessage + assert.strictEqual translate?.address, "/stuff" + assert.deepEqual translate?.args, [] + +test 'fromOscMessage with string argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",s" + oscarg = osc.toOscString "argu" + translate = osc.fromOscMessage osc.concat [oscaddr, osctype, oscarg] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "string" + assert.strictEqual translate?.args?[0]?.value, "argu" + +test 'fromOscMessage with true argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",T" + translate = osc.fromOscMessage osc.concat [oscaddr, osctype] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "true" + assert.strictEqual translate?.args?[0]?.value, true + +test 'fromOscMessage with false argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",F" + translate = osc.fromOscMessage osc.concat [oscaddr, osctype] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "false" + assert.strictEqual translate?.args?[0]?.value, false + +test 'fromOscMessage with null argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",N" + translate = osc.fromOscMessage osc.concat [oscaddr, osctype] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "null" + assert.strictEqual translate?.args?[0]?.value, null + +test 'fromOscMessage with bang argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",I" + translate = osc.fromOscMessage osc.concat [oscaddr, osctype] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "bang" + assert.strictEqual translate?.args?[0]?.value, "bang" + +test 'fromOscMessage with blob argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",b" + oscarg = osc.concat [(osc.toIntegerBuffer 4), new Buffer "argu"] + translate = osc.fromOscMessage osc.concat [oscaddr, osctype, oscarg] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "blob" + assert.strictEqual (translate?.args?[0]?.value?.toString "utf8"), "argu" + +test 'fromOscMessage with integer argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",i" + oscarg = osc.toIntegerBuffer 888 + translate = osc.fromOscMessage osc.concat [oscaddr, osctype, oscarg] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "integer" + assert.strictEqual (translate?.args?[0]?.value), 888 + +test 'fromOscMessage with timetag argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",t" + timetag = [8888, 9999] + oscarg = osc.toTimetagBuffer timetag + translate = osc.fromOscMessage osc.concat [oscaddr, osctype, oscarg] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "timetag" + assert.deepEqual (translate?.args?[0]?.value), timetag + +test 'fromOscMessage with mismatched array doesn\'t throw', -> + oscaddr = osc.toOscString "/stuff" + assert.doesNotThrow (-> osc.fromOscMessage osc.concat( + [oscaddr, osc.toOscString ",["])) + assert.doesNotThrow (-> osc.fromOscMessage osc.concat( + [oscaddr, osc.toOscString ",["])) + +test 'fromOscMessage with mismatched array throws in strict', -> + oscaddr = osc.toOscString "/stuff" + assert.throws (-> osc.fromOscMessage (osc.concat( + [oscaddr, osc.toOscString ",["])), true) + assert.throws (-> osc.fromOscMessage (osc.concat( + [oscaddr, osc.toOscString ",]"])), true) + +test 'fromOscMessage with empty array argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",[]" + translate = osc.fromOscMessage osc.concat [oscaddr, osctype] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "array" + assert.strictEqual (translate?.args?[0]?.value?.length), 0 + assert.deepEqual (translate?.args?[0]?.value), [] + +test 'fromOscMessage with bang array argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",[I]" + translate = osc.fromOscMessage osc.concat [oscaddr, osctype] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "array" + assert.strictEqual (translate?.args?[0]?.value?.length), 1 + assert.strictEqual (translate?.args?[0]?.value?[0]?.type), "bang" + assert.strictEqual (translate?.args?[0]?.value?[0]?.value), "bang" + +test 'fromOscMessage with string array argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",[s]" + oscarg = osc.toOscString "argu" + translate = osc.fromOscMessage osc.concat [oscaddr, osctype, oscarg] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "array" + assert.strictEqual (translate?.args?[0]?.value?.length), 1 + assert.strictEqual (translate?.args?[0]?.value?[0]?.type), "string" + assert.strictEqual (translate?.args?[0]?.value?[0]?.value), "argu" + +test 'fromOscMessage with nested array argument works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",[[I]]" + translate = osc.fromOscMessage osc.concat [oscaddr, osctype] + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "array" + assert.strictEqual translate?.args?[0]?.value?.length, 1 + assert.strictEqual (translate?.args?[0]?.value?[0]?.type), "array" + assert.strictEqual (translate?.args?[0]?.value?[0]?.value?.length), 1 + assert.strictEqual (translate?.args?[0]?.value?[0]?.value?[0]?.type), "bang" + assert.strictEqual (translate?.args?[0]?.value?[0]?.value?[0]?.value), "bang" + +test 'fromOscMessage with multiple args works', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString ",sbi" + oscargs = [ + (osc.toOscString "argu") + (osc.concat [(osc.toIntegerBuffer 4), new Buffer "argu"]) + (osc.toIntegerBuffer 888) + ] + + oscbuffer = osc.concat [oscaddr, osctype, (osc.concat oscargs)] + translate = osc.fromOscMessage oscbuffer + assert.strictEqual translate?.address, "/stuff" + assert.strictEqual translate?.args?[0]?.type, "string" + assert.strictEqual (translate?.args?[0]?.value), "argu" + +test 'fromOscMessage strict fails if type string has no comma', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString "fake" + assert.throws -> + osc.fromOscMessage (osc.concat [oscaddr, osctype]), true + +test 'fromOscMessage non-strict works if type string has no comma', -> + oscaddr = osc.toOscString "/stuff" + osctype = osc.toOscString "fake" + message = osc.fromOscMessage (osc.concat [oscaddr, osctype]) + assert.strictEqual message.address, "/stuff" + assert.strictEqual message.args.length, 0 + +test 'fromOscMessage strict fails if type address doesn\'t begin with /', -> + oscaddr = osc.toOscString "stuff" + osctype = osc.toOscString "," + assert.throws -> + osc.fromOscMessage (osc.concat [oscaddr, osctype]), true + +test 'fromOscBundle works with no messages', -> + oscbundle = osc.toOscString "#bundle" + timetag = [0, 0] + osctimetag = osc.toTimetagBuffer timetag + buffer = osc.concat [oscbundle, osctimetag] + translate = osc.fromOscBundle buffer + assert.deepEqual translate?.timetag, timetag + assert.deepEqual translate?.elements, [] + +test 'fromOscBundle works with single message', -> + oscbundle = osc.toOscString "#bundle" + timetag = [0, 0] + osctimetag = osc.toTimetagBuffer timetag + oscaddr = osc.toOscString "/addr" + osctype = osc.toOscString "," + oscmessage = osc.concat [oscaddr, osctype] + osclen = osc.toIntegerBuffer oscmessage.length + buffer = osc.concat [oscbundle, osctimetag, osclen, oscmessage] + translate = osc.fromOscBundle buffer + assert.deepEqual translate?.timetag, timetag + assert.strictEqual translate?.elements?.length, 1 + assert.strictEqual translate?.elements?[0]?.address, "/addr" + +test 'fromOscBundle works with multiple messages', -> + oscbundle = osc.toOscString "#bundle" + timetag = [0, 0] + osctimetag = osc.toTimetagBuffer timetag + oscaddr1 = osc.toOscString "/addr" + osctype1 = osc.toOscString "," + oscmessage1 = osc.concat [oscaddr1, osctype1] + osclen1 = osc.toIntegerBuffer oscmessage1.length + oscaddr2 = osc.toOscString "/addr2" + osctype2 = osc.toOscString "," + oscmessage2 = osc.concat [oscaddr2, osctype2] + osclen2 = osc.toIntegerBuffer oscmessage2.length + buffer = osc.concat [oscbundle, osctimetag, osclen1, oscmessage1, osclen2, oscmessage2] + translate = osc.fromOscBundle buffer + assert.deepEqual translate?.timetag, timetag + assert.strictEqual translate?.elements?.length, 2 + assert.strictEqual translate?.elements?[0]?.address, "/addr" + assert.strictEqual translate?.elements?[1]?.address, "/addr2" + +test 'fromOscBundle works with nested bundles', -> + oscbundle = osc.toOscString "#bundle" + timetag = [0, 0] + osctimetag = osc.toTimetagBuffer timetag + oscaddr1 = osc.toOscString "/addr" + osctype1 = osc.toOscString "," + oscmessage1 = osc.concat [oscaddr1, osctype1] + osclen1 = osc.toIntegerBuffer oscmessage1.length + oscbundle2 = osc.toOscString "#bundle" + timetag2 = [0, 0] + osctimetag2 = osc.toTimetagBuffer timetag2 + oscmessage2 = osc.concat [oscbundle2, osctimetag2] + osclen2 = osc.toIntegerBuffer oscmessage2.length + buffer = osc.concat [oscbundle, osctimetag, osclen1, oscmessage1, osclen2, oscmessage2] + translate = osc.fromOscBundle buffer + assert.deepEqual translate?.timetag, timetag + assert.strictEqual translate?.elements?.length, 2 + assert.strictEqual translate?.elements?[0]?.address, "/addr" + assert.deepEqual translate?.elements?[1]?.timetag, timetag2 + +test 'fromOscBundle works with non-understood messages', -> + oscbundle = osc.toOscString "#bundle" + timetag = [0, 0] + osctimetag = osc.toTimetagBuffer timetag + oscaddr1 = osc.toOscString "/addr" + osctype1 = osc.toOscString "," + oscmessage1 = osc.concat [oscaddr1, osctype1] + osclen1 = osc.toIntegerBuffer oscmessage1.length + oscaddr2 = osc.toOscString "/addr2" + osctype2 = osc.toOscString ",α" + oscmessage2 = osc.concat [oscaddr2, osctype2] + osclen2 = osc.toIntegerBuffer oscmessage2.length + buffer = osc.concat [oscbundle, osctimetag, osclen1, oscmessage1, osclen2, oscmessage2] + translate = osc.fromOscBundle buffer + assert.deepEqual translate?.timetag, timetag + assert.strictEqual translate?.elements?.length, 1 + assert.strictEqual translate?.elements?[0]?.address, "/addr" + +test 'fromOscBundle fails with bad bundle ID', -> + oscbundle = osc.toOscString "#blunder" + assert.throws -> osc.fromOscBundle oscbundle + +test 'fromOscBundle fails with ridiculous sizes', -> + timetag = [0, 0] + oscbundle = osc.concat [ + osc.toOscString "#bundle" + osc.toTimetagBuffer timetag + osc.toIntegerBuffer 999999 + ] + assert.throws -> osc.fromOscBundle oscbundle + +roundTripMessage = (args) -> + oscMessage = { + address : "/addr" + args : args + } + roundTrip = osc.fromOscMessage (osc.toOscMessage oscMessage), true + assert.strictEqual roundTrip?.address, "/addr" + assert.strictEqual roundTrip?.args?.length, args.length + for i in [0...args.length] + comp = if args[i]?.value? then args[i].value else args[i] + assert.strictEqual roundTrip?.args?[i]?.type, args[i].type if args[i]?.type? + if Buffer.isBuffer comp + for j in [0...comp.length] + assert.deepEqual roundTrip?.args?[i]?.value?[j], comp[j] + else + assert.deepEqual roundTrip?.args?[i]?.value, comp + +test 'toOscArgument fails when given bogus type', -> + assert.throws -> osc.toOscArgument "bleh", "bogus" + +# we tested fromOsc* manually, so just use roundtrip testing for toOsc* +test 'toOscMessage with no args works', -> + roundTripMessage [] + +test 'toOscMessage strict with null argument throws', -> + assert.throws -> osc.toOscMessage {address : "/addr", args : [null]}, true + +test 'toOscMessage with string argument works', -> + roundTripMessage ["strr"] + +test 'toOscMessage with empty array argument works', -> + roundTripMessage [[]] + +test 'toOscMessage with array value works', -> + roundTripMessage [{value:[]}] + +test 'toOscMessage with string array argument works', -> + roundTripMessage [[{type:"string", value:"hello"}, + {type:"string", value:"goodbye"}]] + +test 'toOscMessage with multi-type array argument works', -> + roundTripMessage [[{type:"string", value:"hello"}, + {type:"integer", value:7}]] + +test 'toOscMessage with nested array argument works', -> + roundTripMessage [[{type:"array", value:[{type:"string", value:"hello"}]}]] + +buffeq = (buff, exp_buff) -> + assert.strictEqual buff.length, exp_buff.length + for i in [0...exp_buff.length] + assert.equal buff[i], exp_buff[i] + +test 'toOscMessage with bad layout works', -> + oscMessage = { + address : "/addr" + args : [ + "strr" + ] + } + roundTrip = osc.fromOscMessage (osc.toOscMessage oscMessage), true + assert.strictEqual roundTrip?.address, "/addr" + assert.strictEqual roundTrip?.args?.length, 1 + assert.strictEqual roundTrip?.args?[0]?.value, "strr" + +test 'toOscMessage with single numeric argument works', -> + oscMessage = { + address : "/addr" + args : 13 + } + roundTrip = osc.fromOscMessage (osc.toOscMessage oscMessage) + assert.strictEqual roundTrip?.address, "/addr" + assert.strictEqual roundTrip?.args?.length, 1 + assert.strictEqual roundTrip?.args?[0]?.value, 13 + assert.strictEqual roundTrip?.args?[0]?.type, "float" + +test 'toOscMessage with args shortcut works', -> + oscMessage = { + address : "/addr" + args : 13 + } + roundTrip = osc.fromOscMessage (osc.toOscMessage oscMessage) + assert.strictEqual roundTrip?.address, "/addr" + assert.strictEqual roundTrip?.args?.length, 1 + assert.strictEqual roundTrip?.args?[0]?.value, 13 + assert.strictEqual roundTrip?.args?[0]?.type, "float" + +test 'toOscMessage with single blob argument works', -> + buff = new Buffer 18 + oscMessage = { + address : "/addr" + args : buff + } + roundTrip = osc.fromOscMessage (osc.toOscMessage oscMessage) + assert.strictEqual roundTrip?.address, "/addr" + assert.strictEqual roundTrip?.args?.length, 1 + buffeq roundTrip?.args?[0]?.value, buff + assert.strictEqual roundTrip?.args?[0]?.type, "blob" + +test 'toOscMessage with single string argument works', -> + oscMessage = { + address : "/addr" + args : "strr" + } + roundTrip = osc.fromOscMessage (osc.toOscMessage oscMessage) + assert.strictEqual roundTrip?.address, "/addr" + assert.strictEqual roundTrip?.args?.length, 1 + assert.strictEqual roundTrip?.args?[0]?.value, "strr" + assert.strictEqual roundTrip?.args?[0]?.type, "string" + +test 'toOscMessage with integer argument works', -> + roundTripMessage [8] + +test 'toOscMessage with buffer argument works', -> + # buffer will have random contents, but that's okay. + roundTripMessage [new Buffer 16] + +test 'toOscMessage strict with type true and value false throws', -> + assert.throws -> osc.toOscMessage {address: "/addr/", args: {type : "true", value : false}}, true + +test 'toOscMessage strict with type false with value true throws', -> + assert.throws -> osc.toOscMessage {address: "/addr/", args: {type : "false", value : true}}, true + +test 'toOscMessage with type true works', -> + roundTrip = osc.fromOscMessage osc.toOscMessage {address: "/addr", args : true} + assert.strictEqual roundTrip.args.length, 1 + assert.strictEqual roundTrip.args[0].value, true + assert.strictEqual roundTrip.args[0].type, "true" + +test 'toOscMessage with type false works', -> + roundTrip = osc.fromOscMessage osc.toOscMessage {address: "/addr", args : false} + assert.strictEqual roundTrip.args.length, 1 + assert.strictEqual roundTrip.args[0].value, false + assert.strictEqual roundTrip.args[0].type, "false" + +test 'toOscMessage with type bang argument works', -> + roundTrip = osc.fromOscMessage osc.toOscMessage {address: "/addr", args : {type:"bang"}} + assert.strictEqual roundTrip.args.length, 1 + assert.strictEqual roundTrip.args[0].value, "bang" + assert.strictEqual roundTrip.args[0].type, "bang" + +test 'toOscMessage with type timetag argument works', -> + roundTripMessage [{type: "timetag", value: [8888, 9999]}] + +test 'toOscMessage with type double argument works', -> + roundTripMessage [{type: "double", value: 8888}] + +test 'toOscMessage strict with type null with value true throws', -> + assert.throws -> osc.toOscMessage({address: "/addr/", args: {type : "null", value : true}}, true) + +test 'toOscMessage with type null works', -> + roundTrip = osc.fromOscMessage osc.toOscMessage {address: "/addr", args : null} + assert.strictEqual roundTrip.args.length, 1 + assert.strictEqual roundTrip.args[0].value, null + assert.strictEqual roundTrip.args[0].type, "null" + +test 'toOscMessage with float argument works', -> + roundTripMessage [{value : 6, type : "float"}] + +test 'toOscMessage just a string works', -> + message = osc.fromOscMessage osc.toOscMessage "bleh" + assert.strictEqual message.address, "bleh" + assert.strictEqual message.args.length, 0 + +test 'toOscMessage with multiple args works', -> + roundTripMessage ["str", 7, (new Buffer 30), 6] + +test 'toOscMessage with integer argument works', -> + roundTripMessage [{value : 7, type: "integer"}] + +test 'toOscMessage fails with no address', -> + assert.throws -> osc.toOscMessage {args : []} + +toOscMessageThrowsHelper = (arg) -> + assert.throws -> osc.toOscMessage( + address : "/addr" + args : [arg] + ) + +test 'toOscMessage fails when string type is specified but wrong', -> + toOscMessageThrowsHelper( + value : 7 + type : "string" + ) + +test 'toOscMessage fails when integer type is specified but wrong', -> + toOscMessageThrowsHelper( + value : "blah blah" + type : "integer" + ) + +test 'toOscMessage fails when float type is specified but wrong', -> + toOscMessageThrowsHelper( + value : "blah blah" + type : "float" + ) + +test 'toOscMessage fails when timetag type is specified but wrong', -> + toOscMessageThrowsHelper( + value : "blah blah" + type : "timetag" + ) + +test 'toOscMessage fails when double type is specified but wrong', -> + toOscMessageThrowsHelper( + value : "blah blah" + type : "double" + ) + +test 'toOscMessage fails when blob type is specified but wrong', -> + toOscMessageThrowsHelper( + value : "blah blah" + type : "blob" + ) + +test 'toOscMessage fails argument is a random type', -> + toOscMessageThrowsHelper( + random_field : 42 + "is pretty random" : 888 + ) + +roundTripBundle = (elems) -> + oscMessage = { + timetag : [0, 0] + elements : elems + } + roundTrip = osc.fromOscBundle (osc.toOscBundle oscMessage), true + assert.deepEqual roundTrip?.timetag, [0, 0] + length = if typeof elems is "object" then elems.length else 1 + assert.strictEqual roundTrip?.elements?.length, length + for i in [0...length] + if typeof elems is "object" + assert.deepEqual roundTrip?.elements?[i]?.timetag, elems[i].timetag + assert.strictEqual roundTrip?.elements?[i]?.address, elems[i].address + else + assert.strictEqual roundTrip?.elements?[i]?.address, elems + +test 'toOscBundle with no elements works', -> + roundTripBundle [] + +test 'toOscBundle with just a string works', -> + roundTripBundle "/address" + +test 'toOscBundle with just a number fails', -> + assert.throws -> roundTripBundle 78 + +test 'toOscBundle with one message works', -> + roundTripBundle [{address : "/addr"}] + +test 'toOscBundle with nested bundles works', -> + roundTripBundle [{address : "/addr"}, {timetag : [8888, 9999]}] + +test 'toOscBundle with bogus packets works', -> + roundTrip = osc.fromOscBundle osc.toOscBundle { + timetag : [0, 0] + elements : [{timetag : [0, 0]}, {maddress : "/addr"}] + } + assert.strictEqual roundTrip.elements.length, 1 + assert.deepEqual roundTrip.elements[0].timetag, [0, 0] + +test 'toOscBundle strict fails without timetags', -> + assert.throws -> osc.toOscBundle {elements :[]}, true + +test 'identity applyTransform works with single message', -> + testBuffer = osc.toOscString "/message" + assert.strictEqual (osc.applyTransform testBuffer, (a) -> a), testBuffer + +test 'nullary applyTransform works with single message', -> + testBuffer = osc.toOscString "/message" + assert.strictEqual (osc.applyTransform testBuffer, (a) -> new Buffer 0).length, 0 + +test 'toOscPacket works when explicitly set to bundle', -> + roundTrip = osc.fromOscBundle osc.toOscPacket {timetag: 0, oscType:"bundle", elements :[]}, true + assert.strictEqual roundTrip.elements.length, 0 + +test 'toOscPacket works when explicitly set to message', -> + roundTrip = osc.fromOscPacket osc.toOscPacket {address: "/bleh", oscType:"message", args :[]}, true + assert.strictEqual roundTrip.args.length, 0 + assert.strictEqual roundTrip.address, "/bleh" + +test 'identity applyTransform works with a simple bundle', -> + base = { + timetag : [0, 0] + elements : [ + {address : "test1"} + {address : "test2"} + ] + } + transformed = osc.fromOscPacket (osc.applyTransform (osc.toOscPacket base), (a) -> a) + + assert.deepEqual transformed?.timetag, [0, 0] + assert.strictEqual transformed?.elements?.length, base.elements.length + for i in [0...base.elements.length] + assert.equal transformed?.elements?[i]?.timetag, base.elements[i].timetag + assert.strictEqual transformed?.elements?[i]?.address, base.elements[i].address + +test 'applyMessageTranformerToBundle fails on bundle without tag', -> + func = osc.applyMessageTranformerToBundle ((a) -> a) + assert.throws -> func osc.concat [osc.toOscString "#grundle", osc.toIntegerBuffer 0, "Int64"] + +test 'addressTransform works with identity', -> + testBuffer = osc.concat [ + osc.toOscString "/message" + new Buffer "gobblegobblewillsnever\u0000parse blah lbha" + ] + transformed = osc.applyTransform testBuffer, osc.addressTransform((a) -> a) + for i in [0...testBuffer.length] + assert.equal transformed[i], testBuffer[i] + + +test 'addressTransform works with bundles', -> + base = { + timetag : [0, 0] + elements : [ + {address : "test1"} + {address : "test2"} + ] + } + transformed = osc.fromOscPacket (osc.applyTransform (osc.toOscPacket base), osc.addressTransform((a) -> "/prelude/" + a)) + + assert.deepEqual transformed?.timetag, [0, 0] + assert.strictEqual transformed?.elements?.length, base.elements.length + for i in [0...base.elements.length] + assert.equal transformed?.elements?[i]?.timetag, base.elements[i].timetag + assert.strictEqual transformed?.elements?[i]?.address, "/prelude/" + base.elements[i].address + +test 'messageTransform works with identity function for single message', -> + message = + address: "/addr" + args: [] + buff = osc.toOscPacket message + buffeq (osc.applyTransform buff, osc.messageTransform (a) -> a), buff + + +test 'messageTransform works with bundles', -> + message = { + timetag : [0, 0] + elements : [ + {address : "test1"} + {address : "test2"} + ] + } + buff = osc.toOscPacket message + buffeq (osc.applyTransform buff, osc.messageTransform (a) -> a), buff + +test 'toTimetagBuffer works with a delta number', -> + delta = 1.2345 + buf = osc.toTimetagBuffer delta + +# assert dates are equal to within floating point conversion error +assertDatesEqual = (date1, date2) -> + assert Math.abs(date1.getTime() - date2.getTime()) <= 1, '' + date1 + ' != ' + date2 + +test 'toTimetagBuffer works with a Date', -> + date = new Date() + buf = osc.toTimetagBuffer date + +test 'toTimetagBuffer works with a timetag array', -> + timetag = [1000, 10001] + buf = osc.toTimetagBuffer timetag + +test 'toTimetagBuffer throws with invalid', -> + assert.throws -> osc.toTimetagBuffer "some bullshit" + +test 'deltaTimetag makes array from a delta', -> + delta = 1.2345 + ntp = osc.deltaTimetag(delta) + +test 'timetagToDate converts timetag to a Date', -> + date = new Date() + timetag = osc.dateToTimetag(date) + date2 = osc.timetagToDate(timetag) + assertDatesEqual date, date2 + +test 'timestampToTimetag converts a unix time to ntp array', -> + date = new Date() + timetag = osc.timestampToTimetag(date.getTime() / 1000) + date2 = osc.timetagToDate(timetag) + assertDatesEqual date, date2 + +test 'dateToTimetag converts date to ntp array', -> + date = new Date() + timetag = osc.dateToTimetag(date) + date2 = osc.timetagToDate(timetag) + assertDatesEqual date, date2 + +test 'timestamp <-> timeTag round trip', -> + now = (new Date()).getTime() / 1000 + near = (a, b) -> Math.abs(a - b) < 1e-6 + assert near(osc.timetagToTimestamp(osc.timestampToTimetag(now)), now) + +test 'splitTimetag returns timetag from a buffer', -> + timetag = [1000, 1001] + rest = "the rest" + buf = osc.concat [ + osc.toTimetagBuffer(timetag), + new Buffer(rest) + ] + {timetag: timetag2, rest: rest2} = osc.splitTimetag buf + assert.deepEqual timetag2, timetag
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/osc.js Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,64 @@ +var dgram = require('dgram'); +var osc = require('osc-min'); + +// port numbers +var OSC_RECIEVE = 7563; +var OSC_SEND = 7562; + +// socket to send and receive OSC messages from bela +var socket = dgram.createSocket('udp4'); +socket.bind(OSC_RECIEVE, '127.0.0.1'); + +socket.on('message', (message, info) => { + + var msg = osc.fromBuffer(message); + + if (msg.oscType === 'message'){ + parseMessage(msg); + } else if (msg.elements){ + for (let element of msg.elements){ + parseMessage(element); + } + } + +}); + +function parseMessage(msg){ + + var address = msg.address.split('/'); + if (!address || !address.length || address.length <2){ + console.log('bad OSC address', address); + return; + } + + // setup handshake + if (address[1] === 'osc-setup'){ + sendHandshakeReply(); + + // start sending OSC messages to Bela + setInterval(sendOscTest, 1000); + + } else if (address[1] === 'osc-acknowledge'){ + console.log('received osc-acknowledge', msg.args); + } +} + +function sendOscTest(){ + var buffer = osc.toBuffer({ + address : '/osc-test', + args : [ + {type: 'integer', value: 78}, + {type: 'float', value: 3.14} + ] + }); + socket.send(buffer, 0, buffer.length, OSC_SEND, '127.0.0.1', function(err) { + if (err) console.log(err); + }); +} + +function sendHandshakeReply(){ + var buffer = osc.toBuffer({ address : '/osc-setup-reply' }); + socket.send(buffer, 0, buffer.length, OSC_SEND, '127.0.0.1', function(err) { + if (err) console.log(err); + }); +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/package.json Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,14 @@ +{ + "name": "osc-node", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "osc-min": "^1.1.1" + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/readme.txt Tue May 17 16:01:06 2016 +0100 @@ -0,0 +1,4 @@ +this is a simple node.js script which is designed to be used with the osc bela example project +run it from this dirctory with the command: + +node osc.js \ No newline at end of file