Mercurial > hg > beaglert
changeset 278:3c3d042dad12 prerelease
merge
author | Giulio Moro <giuliomoro@yahoo.it> |
---|---|
date | Tue, 17 May 2016 16:07:45 +0100 |
parents | 4b3ae93ab102 (current diff) cf98c06c72fd (diff) |
children | 8329f234d914 c55c6f6c233c |
files | |
diffstat | 57 files changed, 6232 insertions(+), 27 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core/OSCClient.cpp Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,79 @@ +/***** OSCClient.cpp *****/ +#include <OSCClient.h> + +OSCClient::OSCClient(){} + +void OSCClient::sendQueue(void* ptr){ + OSCClient *instance = (OSCClient*)ptr; + instance->queueSend(); +} + +void OSCClient::setup(int _port, const char* _address, bool scheduleTask){ + address = _address; + port = _port; + + socket.setServer(address); + socket.setPort(port); + + if (scheduleTask) + createAuxTasks(); +} + +void OSCClient::createAuxTasks(){ + char name [30]; + sprintf (name, "OSCSendTask %i", port); + OSCSendTask = BeagleRT_createAuxiliaryTask(sendQueue, BEAGLERT_AUDIO_PRIORITY-5, name, this, true); +} + +void OSCClient::queueMessage(oscpkt::Message msg){ + outQueue.push(msg); +} + +void OSCClient::queueSend(){ + if (!outQueue.empty()){ + pw.init().startBundle(); + while(!outQueue.empty()){ + pw.addMessage(outQueue.front()); + outQueue.pop(); + } + pw.endBundle(); + outBuffer = pw.packetData(); + socket.send(outBuffer, pw.packetSize()); + } +} + +void OSCClient::sendMessageNow(oscpkt::Message msg){ + pw.init().addMessage(msg); + outBuffer = pw.packetData(); + socket.send(outBuffer, pw.packetSize()); +} + +// OSCMessageFactory +OSCMessageFactory& OSCMessageFactory::to(std::string addr){ + msg.init(addr); + return *this; +} + +OSCMessageFactory& OSCMessageFactory::add(std::string in){ + msg.pushStr(in); + return *this; +} +OSCMessageFactory& OSCMessageFactory::add(int in){ + msg.pushInt32(in); + return *this; +} +OSCMessageFactory& OSCMessageFactory::add(float in){ + msg.pushFloat(in); + return *this; +} +OSCMessageFactory& OSCMessageFactory::add(bool in){ + msg.pushBool(in); + return *this; +} +OSCMessageFactory& OSCMessageFactory::add(void *ptr, int size){ + msg.pushBlob(ptr, size); + return *this; +} +oscpkt::Message OSCMessageFactory::end(){ + return msg; +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core/OSCServer.cpp Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,65 @@ +/***** OSCServer.cpp *****/ +#include <OSCServer.h> + +// constructor +OSCServer::OSCServer(){} + +// static method for checking messages +// called by messageCheckTask with pointer to OSCServer instance as argument +void OSCServer::checkMessages(void* ptr){ + OSCServer *instance = (OSCServer*)ptr; + instance->messageCheck(); +} + +void OSCServer::setup(int _port){ + port = _port; + if(!socket.init(port)) + rt_printf("socket not initialised\n"); + createAuxTasks(); +} + +void OSCServer::createAuxTasks(){ + char name [30]; + sprintf (name, "OSCRecieveTask %i", port); + OSCRecieveTask = BeagleRT_createAuxiliaryTask(OSCServer::checkMessages, BEAGLERT_AUDIO_PRIORITY-5, name, this, true); +} + +void OSCServer::messageCheck(){ + if (socket.waitUntilReady(true, UDP_RECIEVE_TIMEOUT_MS)){ + int msgLength = socket.read(&inBuffer, UDP_RECIEVE_MAX_LENGTH, false); + pr.init(inBuffer, msgLength); + oscpkt::Message *inmsg; + while (pr.isOk() && (inmsg = pr.popMessage()) != 0) { + inQueue.push(*inmsg); + } + } +} + +bool OSCServer::messageWaiting(){ + return !inQueue.empty(); +} + +oscpkt::Message OSCServer::popMessage(){ + if (!inQueue.empty()){ + poppedMessage = inQueue.front(); + inQueue.pop(); + } else { + poppedMessage.init("/error"); + } + return poppedMessage; +} + +void OSCServer::recieveMessageNow(int timeout){ + if (socket.waitUntilReady(true, timeout)){ + int msgLength = socket.read(&inBuffer, UDP_RECIEVE_MAX_LENGTH, false); + pr.init(inBuffer, msgLength); + oscpkt::Message *inmsg; + while (pr.isOk() && (inmsg = pr.popMessage()) != 0) { + inQueue.push(*inmsg); + } + } +} + + + +
--- a/core/PRU.cpp Tue May 17 16:07:35 2016 +0100 +++ b/core/PRU.cpp Tue May 17 16:07:45 2016 +0100 @@ -37,6 +37,9 @@ using namespace std; +// PRU memory: PRU0 and PRU1 RAM are 8kB (0x2000) long each +// PRU-SHARED RAM is 12kB (0x3000) long + #define PRU_MEM_MCASP_OFFSET 0x2000 // Offset within PRU-SHARED RAM #define PRU_MEM_MCASP_LENGTH 0x1000 // Length of McASP memory, in bytes #define PRU_MEM_DAC_OFFSET 0x0 // Offset within PRU0 RAM
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core/Scope.cpp Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,282 @@ +/***** Scope.cpp *****/ +#include <Scope.h> + +Scope::Scope():connected(0), triggerPrimed(false), started(false){} + +// static aux task functions +void Scope::triggerTask(void *ptr){ + Scope *instance = (Scope*)ptr; + if (instance->started) + instance->doTrigger(); +} +void Scope::sendBufferTask(void *ptr){ + Scope *instance = (Scope*)ptr; + instance->sendBuffer(); +} + +void Scope::setup(unsigned int _numChannels, float _sampleRate){ + + numChannels = _numChannels; + sampleRate = _sampleRate; + + // setup the OSC server && client + // used for sending / recieving settings + // oscClient has it's send task turned off, as we only need to send one handshake message + oscServer.setup(OSC_RECIEVE_PORT); + oscClient.setup(OSC_SEND_PORT, "127.0.0.1", false); + + // setup the udp socket + // used for sending raw frame data + socket.setServer("127.0.0.1"); + socket.setPort(SCOPE_UDP_PORT); + + // setup the auxiliary tasks + scopeTriggerTask = BeagleRT_createAuxiliaryTask(Scope::triggerTask, BEAGLERT_AUDIO_PRIORITY-2, "scopeTriggerTask", this, true); + scopeSendBufferTask = BeagleRT_createAuxiliaryTask(Scope::sendBufferTask, BEAGLERT_AUDIO_PRIORITY-1, "scopeSendBufferTask", this); + + // send an OSC message to address /scope-setup + // then wait 1 second for a reply on /scope-setup-reply + bool handshakeRecieved = false; + oscClient.sendMessageNow(oscClient.newMessage.to("/scope-setup").add((int)numChannels).add(sampleRate).end()); + oscServer.recieveMessageNow(1000); + while (oscServer.messageWaiting()){ + if (handshakeRecieved){ + parseMessage(oscServer.popMessage()); + } else if (oscServer.popMessage().match("/scope-setup-reply")){ + handshakeRecieved = true; + } + } + + if (handshakeRecieved && connected) + start(); + +} + +void Scope::start(){ + + // resize the buffers + channelWidth = frameWidth * FRAMES_STORED; + buffer.resize(numChannels*channelWidth); + outBuffer.resize(numChannels*frameWidth); + + // reset the pointers + writePointer = 0; + readPointer = 0; + triggerPointer = 0; + + // reset the trigger + triggerPrimed = true; + triggerCollecting = false; + triggerWaiting = false; + triggerCount = 0; + downSampleCount = 1; + autoTriggerCount = 0; + customTriggered = false; + + started = true; +} + +void Scope::stop(){ + started = false; +} + +void Scope::log(float chn1, ...){ + + // check for any recieved OSC messages + while (oscServer.messageWaiting()){ + parseMessage(oscServer.popMessage()); + } + + if (!started) return; + + if (downSampling > 1){ + if (downSampleCount < downSampling){ + downSampleCount++; + return; + } + downSampleCount = 1; + } + + va_list args; + va_start (args, chn1); + + int startingWritePointer = writePointer; + + // save the logged samples into the buffer + buffer[writePointer] = chn1; + + for (int i=1; i<numChannels; i++) { + // iterate over the function arguments, store them in the relevant part of the buffer + // channels are stored sequentially in the buffer i.e [[channel1], [channel2], etc...] + buffer[i*channelWidth + writePointer] = (float)va_arg(args, double); + } + + writePointer = (writePointer+1)%channelWidth; + + // if upSampling > 1, save repeated samples into the buffer + for (int j=1; j<upSampling; j++){ + + buffer[writePointer] = buffer[startingWritePointer]; + + for (int i=1; i<numChannels; i++) { + buffer[i*channelWidth + writePointer] = buffer[i*channelWidth + startingWritePointer]; + } + + writePointer = (writePointer+1)%channelWidth; + + } + + va_end (args); + +} + +bool Scope::trigger(){ + if (triggerMode == 2 && !customTriggered && triggerPrimed && started){ + customTriggerPointer = (writePointer-xOffset+channelWidth)%channelWidth; + customTriggered = true; + return true; + } + return false; +} + +void Scope::scheduleSendBufferTask(){ + BeagleRT_scheduleAuxiliaryTask(scopeSendBufferTask); +} + +bool Scope::triggered(){ + if (triggerMode == 0 || triggerMode == 1){ // normal or auto trigger + return (!triggerDir && buffer[channelWidth*triggerChannel+((readPointer-1+channelWidth)%channelWidth)] < triggerLevel // positive trigger direction + && buffer[channelWidth*triggerChannel+readPointer] >= triggerLevel) || + (triggerDir && buffer[channelWidth*triggerChannel+((readPointer-1+channelWidth)%channelWidth)] > triggerLevel // negative trigger direciton + && buffer[channelWidth*triggerChannel+readPointer] <= triggerLevel); + } else if (triggerMode == 2){ // custom trigger + return (customTriggered && readPointer == customTriggerPointer); + } + return false; +} + +void Scope::doTrigger(){ + // iterate over the samples between the read and write pointers and check for / deal with triggers + while (readPointer != writePointer){ + + // if we are currently listening for a trigger + if (triggerPrimed){ + + // if we crossed the trigger threshold + if (triggered()){ + + // stop listening for a trigger + triggerPrimed = false; + triggerCollecting = true; + + // save the readpointer at the trigger point + triggerPointer = (readPointer-xOffset+channelWidth)%channelWidth; + + triggerCount = frameWidth/2 - xOffset; + autoTriggerCount = 0; + + } else { + // auto triggering + if (triggerMode == 0 && (autoTriggerCount++ > (frameWidth+holdOff))){ + // it's been a whole frameWidth since we've found a trigger, so auto-trigger anyway + triggerPrimed = false; + triggerCollecting = true; + + // save the readpointer at the trigger point + triggerPointer = (readPointer-xOffset+channelWidth)%channelWidth; + + triggerCount = frameWidth/2 - xOffset; + autoTriggerCount = 0; + } + } + + } else if (triggerCollecting){ + + // a trigger has been detected, and we are collecting the second half of the triggered frame + if (--triggerCount > 0){ + + } else { + triggerCollecting = false; + triggerWaiting = true; + triggerCount = frameWidth/2 + holdOffSamples; + + // copy the previous to next frameWidth/2 samples into the outBuffer + int startptr = (triggerPointer-frameWidth/2 + channelWidth)%channelWidth; + int endptr = (triggerPointer+frameWidth/2 + channelWidth)%channelWidth; + + if (endptr > startptr){ + for (int i=0; i<numChannels; i++){ + std::copy(&buffer[channelWidth*i+startptr], &buffer[channelWidth*i+endptr], outBuffer.begin()+(i*frameWidth)); + } + } else { + for (int i=0; i<numChannels; i++){ + std::copy(&buffer[channelWidth*i+startptr], &buffer[channelWidth*(i+1)], outBuffer.begin()+(i*frameWidth)); + std::copy(&buffer[channelWidth*i], &buffer[channelWidth*i+endptr], outBuffer.begin()+((i+1)*frameWidth-endptr)); + } + } + + // the whole frame has been saved in outBuffer, so send it + scheduleSendBufferTask(); + + } + + } else if (triggerWaiting){ + + // a trigger has completed, so wait half a framewidth before looking for another + if (--triggerCount > 0){ + + } else { + triggerWaiting = false; + triggerPrimed = true; + customTriggered = false; + } + + } + + // increment the read pointer + readPointer = (readPointer+1)%channelWidth; + } + +} + +void Scope::sendBuffer(){ + socket.send(&(outBuffer[0]), outBuffer.size()*sizeof(float)); +} + +void Scope::parseMessage(oscpkt::Message msg){ + if (msg.partialMatch("/scope-settings/")){ + int intArg; + float floatArg; + if (msg.match("/scope-settings/connected").popInt32(intArg).isOkNoMoreArgs()){ + if (connected == 0 && intArg == 1){ + start(); + } else if (connected == 1 && intArg == 0){ + stop(); + } + connected = intArg; + } else if (msg.match("/scope-settings/frameWidth").popInt32(intArg).isOkNoMoreArgs()){ + stop(); + frameWidth = intArg; + start(); + } else if (msg.match("/scope-settings/triggerMode").popInt32(intArg).isOkNoMoreArgs()){ + triggerMode = intArg; + } else if (msg.match("/scope-settings/triggerChannel").popInt32(intArg).isOkNoMoreArgs()){ + triggerChannel = intArg; + } else if (msg.match("/scope-settings/triggerDir").popInt32(intArg).isOkNoMoreArgs()){ + triggerDir = intArg; + } else if (msg.match("/scope-settings/triggerLevel").popFloat(floatArg).isOkNoMoreArgs()){ + triggerLevel = floatArg; + } else if (msg.match("/scope-settings/xOffset").popInt32(intArg).isOkNoMoreArgs()){ + xOffset = intArg; + } else if (msg.match("/scope-settings/upSampling").popInt32(intArg).isOkNoMoreArgs()){ + upSampling = intArg; + holdOffSamples = (int)(sampleRate*0.001*holdOff*upSampling/downSampling); + } else if (msg.match("/scope-settings/downSampling").popInt32(intArg).isOkNoMoreArgs()){ + downSampling = intArg; + holdOffSamples = (int)(sampleRate*0.001*holdOff*upSampling/downSampling); + } else if (msg.match("/scope-settings/holdOff").popFloat(floatArg).isOkNoMoreArgs()){ + holdOff = floatArg; + holdOffSamples = (int)(sampleRate*0.001*holdOff*upSampling/downSampling); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/include/OSCClient.h Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,61 @@ +/***** OSCClient.h *****/ +#ifndef __OSCClient_H_INCLUDED__ +#define __OSCClient_H_INCLUDED__ + +#include <UdpClient.h> +#include <BeagleRT.h> +#include <oscpkt.hh> +#include <queue> + +class OSCMessageFactory{ + public: + OSCMessageFactory& to(std::string); + OSCMessageFactory& add(std::string); + OSCMessageFactory& add(int); + OSCMessageFactory& add(float); + OSCMessageFactory& add(bool); + OSCMessageFactory& add(void *ptr, int size); + oscpkt::Message end(); + private: + oscpkt::Message msg; +}; + +class OSCClient{ + public: + OSCClient(); + + // must be called once during setup + void setup(int port, const char* address="127.0.0.1", bool scheduleTask = true); + + // queue a message to be sent during the next aux task OSCSendTask + // audio-thread safe + void queueMessage(oscpkt::Message); + + // send a mesage immediately + // *** do not use on audio thread! *** + // to be used during setup + void sendMessageNow(oscpkt::Message); + + // allows new OSC messages to be created + // audio-thread safe + // usage: oscClient.queueMessage(oscClient.newMessage.to("/address").add(param).end()); + OSCMessageFactory newMessage; + + private: + const char* address; + int port; + + UdpClient socket; + AuxiliaryTask OSCSendTask; + std::queue<oscpkt::Message> outQueue; + oscpkt::PacketWriter pw; + char* outBuffer; + + static void sendQueue(void*); + + void createAuxTasks(); + void queueSend(); + +}; + +#endif \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/include/OSCServer.h Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,50 @@ +/***** OSCServer.h *****/ +#ifndef __OSCServer_H_INCLUDED__ +#define __OSCServer_H_INCLUDED__ + +#include <UdpServer.h> +#include <oscpkt.hh> +#include <BeagleRT.h> +#include <queue> + +#define UDP_RECIEVE_TIMEOUT_MS 20 +#define UDP_RECIEVE_MAX_LENGTH 16384 + +class OSCServer{ + public: + OSCServer(); + + // must be called once during setup + void setup(int port); + + // returns true if messages are queued + // audio-thread safe + bool messageWaiting(); + + // removes and returns the oldest message from the queue + // audio-thread safe, but don't call unless messageWaiting() returns true + oscpkt::Message popMessage(); + + // if there are OSC messages waiting, decode and queue them + // not audio-thread safe! + void recieveMessageNow(int timeout); + + private: + int port; + UdpServer socket; + + AuxiliaryTask OSCRecieveTask; + + void createAuxTasks(); + void messageCheck(); + + static void checkMessages(void*); + + int inBuffer[UDP_RECIEVE_MAX_LENGTH]; + std::queue<oscpkt::Message> inQueue; + oscpkt::Message poppedMessage; + oscpkt::PacketReader pr; +}; + + +#endif \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/include/Scope.h Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,86 @@ +/***** Scope.h *****/ +#ifndef __Scope_H_INCLUDED__ +#define __Scope_H_INCLUDED__ + +#include <OSCServer.h> +#include <OSCClient.h> +#include <stdarg.h> + +#define OSC_RECIEVE_PORT 8675 +#define OSC_SEND_PORT 8676 +#define SCOPE_UDP_PORT 8677 + +#define FRAMES_STORED 2 + +class Scope{ + public: + Scope(); + + void setup(unsigned int numChannels, float sampleRate); + void log(float chn1, ...); + bool trigger(); + + private: + OSCServer oscServer; + OSCClient oscClient; + UdpClient socket; + + void parseMessage(oscpkt::Message); + void start(); + void stop(); + void doTrigger(); + void triggerNormal(); + void triggerAuto(); + void scheduleSendBufferTask(); + void sendBuffer(); + void customTrigger(); + bool triggered(); + + // settings + int numChannels; + float sampleRate; + int connected; + int frameWidth; + int triggerMode; + int triggerChannel; + int triggerDir; + float triggerLevel; + int xOffset; + int upSampling; + int downSampling; + float holdOff; + + int channelWidth; + int downSampleCount; + int holdOffSamples; + + // buffers + std::vector<float> buffer; + std::vector<float> outBuffer; + + // pointers + int writePointer; + int readPointer; + int triggerPointer; + int customTriggerPointer; + + // trigger status + bool triggerPrimed; + bool triggerCollecting; + bool triggerWaiting; + bool triggering; + int triggerCount; + int autoTriggerCount; + bool started; + bool customTriggered; + + // aux tasks + AuxiliaryTask scopeTriggerTask; + static void triggerTask(void*); + + AuxiliaryTask scopeSendBufferTask; + static void sendBufferTask(void*); + +}; + +#endif \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/include/oscpkt.hh Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,701 @@ +/** @mainpage OSCPKT : a minimalistic OSC ( http://opensoundcontrol.org ) c++ library + + Before using this file please take the time to read the OSC spec, it + is short and not complicated: http://opensoundcontrol.org/spec-1_0 + + Features: + - handles basic OSC types: TFihfdsb + - handles bundles + - handles OSC pattern-matching rules (wildcards etc in message paths) + - portable on win / macos / linux + - robust wrt malformed packets + - optional udp transport for packets + - concise, all in a single .h file + - does not throw exceptions + + does not: + - take into account timestamp values. + - provide a cpu-scalable message dispatching. + - not suitable for use inside a realtime thread as it allocates memory when + building or reading messages. + + + There are basically 3 classes of interest: + - oscpkt::Message : read/write the content of an OSC message + - oscpkt::PacketReader : read the bundles/messages embedded in an OSC packet + - oscpkt::PacketWriter : write bundles/messages into an OSC packet + + And optionaly: + - oscpkt::UdpSocket : read/write OSC packets over UDP. + + @example: oscpkt_demo.cc + @example: oscpkt_test.cc +*/ + +/* Copyright (C) 2010 Julien Pommier + + 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 acknowledgment 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. + + (this is the zlib license) +*/ + +#ifndef OSCPKT_HH +#define OSCPKT_HH + +#ifndef _MSC_VER +#include <stdint.h> +#else +namespace oscpkt { + typedef __int32 int32_t; + typedef unsigned __int32 uint32_t; + typedef __int64 int64_t; + typedef unsigned __int64 uint64_t; +} +#endif +#include <cstring> +#include <cassert> +#include <string> +#include <vector> +#include <list> + +#if defined(OSCPKT_OSTREAM_OUTPUT) || defined(OSCPKT_TEST) +#include <iostream> +#endif + +namespace oscpkt { + +/** + OSC timetag stuff, the highest 32-bit are seconds, the lowest are fraction of a second. +*/ +class TimeTag { + uint64_t v; +public: + TimeTag() : v(1) {} + explicit TimeTag(uint64_t w): v(w) {} + operator uint64_t() const { return v; } + static TimeTag immediate() { return TimeTag(1); } +}; + +/* the various types that we handle (OSC 1.0 specifies that INT32/FLOAT/STRING/BLOB are the bare minimum) */ +enum { + TYPE_TAG_TRUE = 'T', + TYPE_TAG_FALSE = 'F', + TYPE_TAG_INT32 = 'i', + TYPE_TAG_INT64 = 'h', + TYPE_TAG_FLOAT = 'f', + TYPE_TAG_DOUBLE = 'd', + TYPE_TAG_STRING = 's', + TYPE_TAG_BLOB = 'b' +}; + +/* a few utility functions follow.. */ + +// round to the next multiple of 4, works for size_t and pointer arguments +template <typename Type> Type ceil4(Type p) { return (Type)((size_t(p) + 3)&(~size_t(3))); } + +// check that a memory area is zero padded until the next address which is a multiple of 4 +inline bool isZeroPaddingCorrect(const char *p) { + const char *q = ceil4(p); + for (;p < q; ++p) + if (*p != 0) { return false; } + return true; +} + +// stuff for reading / writing POD ("Plain Old Data") variables to unaligned bytes. +template <typename POD> union PodBytes { + char bytes[sizeof(POD)]; + POD value; +}; + +inline bool isBigEndian() { // a compile-time constant would certainly improve performances.. + PodBytes<int32_t> p; p.value = 0x12345678; + return p.bytes[0] == 0x12; +} + +/** read unaligned bytes into a POD type, assuming the bytes are a little endian representation */ +template <typename POD> POD bytes2pod(const char *bytes) { + PodBytes<POD> p; + for (size_t i=0; i < sizeof(POD); ++i) { + if (isBigEndian()) + p.bytes[i] = bytes[i]; + else + p.bytes[i] = bytes[sizeof(POD) - i - 1]; + } + return p.value; +} + +/** stored a POD type into an unaligned bytes array, using little endian representation */ +template <typename POD> void pod2bytes(const POD value, char *bytes) { + PodBytes<POD> p; p.value = value; + for (size_t i=0; i < sizeof(POD); ++i) { + if (isBigEndian()) + bytes[i] = p.bytes[i]; + else + bytes[i] = p.bytes[sizeof(POD) - i - 1]; + } +} + +/** internal stuff, handles the dynamic storage with correct alignments to 4 bytes */ +struct Storage { + std::vector<char> data; + Storage() { data.reserve(200); } + char *getBytes(size_t sz) { + assert((data.size() & 3) == 0); + if (data.size() + sz > data.capacity()) { data.reserve((data.size() + sz)*2); } + size_t sz4 = ceil4(sz); + size_t pos = data.size(); + data.resize(pos + sz4); // resize will fill with zeros, so the zero padding is OK + return &(data[pos]); + } + char *begin() { return data.size() ? &data.front() : 0; } + char *end() { return begin() + size(); } + const char *begin() const { return data.size() ? &data.front() : 0; } + const char *end() const { return begin() + size(); } + size_t size() const { return data.size(); } + void assign(const char *beg, const char *end) { data.assign(beg, end); } + void clear() { data.resize(0); } +}; + +/** check if the path matches the supplied path pattern , according to the OSC spec pattern + rules ('*' and '//' wildcards, '{}' alternatives, brackets etc) */ +bool fullPatternMatch(const std::string &pattern, const std::string &path); +/** check if the path matches the beginning of pattern */ +bool partialPatternMatch(const std::string &pattern, const std::string &path); + +#if defined(OSCPKT_DEBUG) +#define OSCPKT_SET_ERR(errcode) do { if (!err) { err = errcode; std::cerr << "set " #errcode << " at line " << __LINE__ << "\n"; } } while (0) +#else +#define OSCPKT_SET_ERR(errcode) do { if (!err) err = errcode; } while (0) +#endif + +typedef enum { OK_NO_ERROR=0, + // errors raised by the Message class: + MALFORMED_ADDRESS_PATTERN, MALFORMED_TYPE_TAGS, MALFORMED_ARGUMENTS, UNHANDLED_TYPE_TAGS, + // errors raised by ArgReader + TYPE_MISMATCH, NOT_ENOUGH_ARG, PATTERN_MISMATCH, + // errors raised by PacketReader/PacketWriter + INVALID_BUNDLE, INVALID_PACKET_SIZE, BUNDLE_REQUIRED_FOR_MULTI_MESSAGES } ErrorCode; + +/** + struct used to hold an OSC message that will be written or read. + + The list of arguments is exposed as a sort of queue. You "pop" + arguments from the front of the queue when reading, you push + arguments at the back of the queue when writing. + + Many functions return *this, so they can be chained: init("/foo").pushInt32(2).pushStr("kllk")... + + Example of use: + + creation of a message: + @code + msg.init("/foo").pushInt32(4).pushStr("bar"); + @endcode + reading a message, with error detection: + @code + if (msg.match("/foo/b*ar/plop")) { + int i; std::string s; std::vector<char> b; + if (msg.arg().popInt32(i).popStr(s).popBlob(b).isOkNoMoreArgs()) { + process message...; + } else arguments mismatch; + } + @endcode +*/ +class Message { + TimeTag time_tag; + std::string address; + std::string type_tags; + std::vector<std::pair<size_t, size_t> > arguments; // array of pairs (pos,size), pos being an index into the 'storage' array. + Storage storage; // the arguments data is stored here + ErrorCode err; +public: + /** ArgReader is used for popping arguments from a Message, holds a + pointer to the original Message, and maintains a local error code */ + class ArgReader { + const Message *msg; + ErrorCode err; + size_t arg_idx; // arg index of the next arg that will be popped out. + public: + ArgReader(const Message &m, ErrorCode e = OK_NO_ERROR) : msg(&m), err(msg->getErr()), arg_idx(0) { + if (e != OK_NO_ERROR && err == OK_NO_ERROR) err=e; + } + ArgReader(const ArgReader &other) : msg(other.msg), err(other.err), arg_idx(other.arg_idx) {} + bool isBool() { return currentTypeTag() == TYPE_TAG_TRUE || currentTypeTag() == TYPE_TAG_FALSE; } + bool isInt32() { return currentTypeTag() == TYPE_TAG_INT32; } + bool isInt64() { return currentTypeTag() == TYPE_TAG_INT64; } + bool isFloat() { return currentTypeTag() == TYPE_TAG_FLOAT; } + bool isDouble() { return currentTypeTag() == TYPE_TAG_DOUBLE; } + bool isStr() { return currentTypeTag() == TYPE_TAG_STRING; } + bool isBlob() { return currentTypeTag() == TYPE_TAG_BLOB; } + + size_t nbArgRemaining() const { return msg->arguments.size() - arg_idx; } + bool isOk() const { return err == OK_NO_ERROR; } + operator bool() const { return isOk(); } // implicit bool conversion is handy here + /** call this at the end of the popXXX() chain to make sure everything is ok and + all arguments have been popped */ + bool isOkNoMoreArgs() const { return err == OK_NO_ERROR && nbArgRemaining() == 0; } + ErrorCode getErr() const { return err; } + + /** retrieve an int32 argument */ + ArgReader &popInt32(int32_t &i) { return popPod<int32_t>(TYPE_TAG_INT32, i); } + /** retrieve an int64 argument */ + ArgReader &popInt64(int64_t &i) { return popPod<int64_t>(TYPE_TAG_INT64, i); } + /** retrieve a single precision floating point argument */ + ArgReader &popFloat(float &f) { return popPod<float>(TYPE_TAG_FLOAT, f); } + /** retrieve a double precision floating point argument */ + ArgReader &popDouble(double &d) { return popPod<double>(TYPE_TAG_DOUBLE, d); } + /** retrieve a string argument (no check performed on its content, so it may contain any byte value except 0) */ + ArgReader &popStr(std::string &s) { + if (precheck(TYPE_TAG_STRING)) { + s = argBeg(arg_idx++); + } + return *this; + } + /** retrieve a binary blob */ + ArgReader &popBlob(std::vector<char> &b) { + if (precheck(TYPE_TAG_BLOB)) { + b.assign(argBeg(arg_idx)+4, argEnd(arg_idx)); + ++arg_idx; + } + return *this; + } + /** retrieve a boolean argument */ + ArgReader &popBool(bool &b) { + b = false; + if (arg_idx >= msg->arguments.size()) OSCPKT_SET_ERR(NOT_ENOUGH_ARG); + else if (currentTypeTag() == TYPE_TAG_TRUE) b = true; + else if (currentTypeTag() == TYPE_TAG_FALSE) b = false; + else OSCPKT_SET_ERR(TYPE_MISMATCH); + ++arg_idx; + return *this; + } + /** skip whatever comes next */ + ArgReader &pop() { + if (arg_idx >= msg->arguments.size()) OSCPKT_SET_ERR(NOT_ENOUGH_ARG); + else ++arg_idx; + return *this; + } + private: + const char *argBeg(size_t idx) { + if (err || idx >= msg->arguments.size()) return 0; + else return msg->storage.begin() + msg->arguments[idx].first; + } + const char *argEnd(size_t idx) { + if (err || idx >= msg->arguments.size()) return 0; + else return msg->storage.begin() + msg->arguments[idx].first + msg->arguments[idx].second; + } + int currentTypeTag() { + if (!err && arg_idx < msg->type_tags.size()) return msg->type_tags[arg_idx]; + else OSCPKT_SET_ERR(NOT_ENOUGH_ARG); + return -1; + } + template <typename POD> ArgReader &popPod(int tag, POD &v) { + if (precheck(tag)) { + v = bytes2pod<POD>(argBeg(arg_idx)); + ++arg_idx; + } else v = POD(0); + return *this; + } + /* pre-check stuff before popping an argument from the message */ + bool precheck(int tag) { + if (arg_idx >= msg->arguments.size()) OSCPKT_SET_ERR(NOT_ENOUGH_ARG); + else if (!err && currentTypeTag() != tag) OSCPKT_SET_ERR(TYPE_MISMATCH); + return err == OK_NO_ERROR; + } + }; + + Message() { clear(); } + Message(const std::string &s, TimeTag tt = TimeTag::immediate()) : time_tag(tt), address(s), err(OK_NO_ERROR) {} + Message(const void *ptr, size_t sz, TimeTag tt = TimeTag::immediate()) { buildFromRawData(ptr, sz); time_tag = tt; } + + bool isOk() const { return err == OK_NO_ERROR; } + ErrorCode getErr() const { return err; } + + /** return the type_tags string, with its initial ',' stripped. */ + const std::string &typeTags() const { return type_tags; } + /** retrieve the address pattern. If you want to follow to the whole OSC spec, you + have to handle its matching rules for address specifications -- this file does + not provide this functionality */ + const std::string &addressPattern() const { return address; } + TimeTag timeTag() const { return time_tag; } + /** clear the message and start a new message with the supplied address and time_tag. */ + Message &init(const std::string &addr, TimeTag tt = TimeTag::immediate()) { + clear(); + address = addr; time_tag = tt; + if (address.empty() || address[0] != '/') OSCPKT_SET_ERR(MALFORMED_ADDRESS_PATTERN); + return *this; + } + + /** start a matching test. The typical use-case is to follow this by + a sequence of calls to popXXX() and a final call to + isOkNoMoreArgs() which will allow to check that everything went + fine. For example: + @code + if (msg.match("/foo").popInt32(i).isOkNoMoreArgs()) { blah(i); } + else if (msg.match("/bar").popStr(s).popInt32(i).isOkNoMoreArgs()) { plop(s,i); } + else cerr << "unhandled message: " << msg << "\n"; + @endcode + */ + ArgReader match(const std::string &test) const { + return ArgReader(*this, fullPatternMatch(address.c_str(), test.c_str()) ? OK_NO_ERROR : PATTERN_MISMATCH); + } + /** return true if the 'test' path matched by the first characters of addressPattern(). + For ex. ("/foo/bar").partialMatch("/foo/") is true */ + ArgReader partialMatch(const std::string &test) const { + return ArgReader(*this, partialPatternMatch(address.c_str(), test.c_str()) ? OK_NO_ERROR : PATTERN_MISMATCH); + } + ArgReader arg() const { return ArgReader(*this, OK_NO_ERROR); } + + /** build the osc message for raw data (the message will keep a copy of that data) */ + void buildFromRawData(const void *ptr, size_t sz) { + clear(); + storage.assign((const char*)ptr, (const char*)ptr + sz); + const char *address_beg = storage.begin(); + const char *address_end = (const char*)memchr(address_beg, 0, storage.end()-address_beg); + if (!address_end || !isZeroPaddingCorrect(address_end+1) || address_beg[0] != '/') { + OSCPKT_SET_ERR(MALFORMED_ADDRESS_PATTERN); return; + } else address.assign(address_beg, address_end); + + const char *type_tags_beg = ceil4(address_end+1); + const char *type_tags_end = (const char*)memchr(type_tags_beg, 0, storage.end()-type_tags_beg); + if (!type_tags_end || !isZeroPaddingCorrect(type_tags_end+1) || type_tags_beg[0] != ',') { + OSCPKT_SET_ERR(MALFORMED_TYPE_TAGS); return; + } else type_tags.assign(type_tags_beg+1, type_tags_end); // we do not copy the initial ',' + + const char *arg = ceil4(type_tags_end+1); assert(arg <= storage.end()); + size_t iarg = 0; + while (isOk() && iarg < type_tags.size()) { + assert(arg <= storage.end()); + size_t len = getArgSize(type_tags[iarg], arg); + if (isOk()) arguments.push_back(std::make_pair(arg - storage.begin(), len)); + arg += ceil4(len); ++iarg; + } + if (iarg < type_tags.size() || arg != storage.end()) { + OSCPKT_SET_ERR(MALFORMED_ARGUMENTS); + } + } + + /* below are all the functions that serve when *writing* a message */ + Message &pushBool(bool b) { + type_tags += (b ? TYPE_TAG_TRUE : TYPE_TAG_FALSE); + arguments.push_back(std::make_pair(storage.size(), storage.size())); + return *this; + } + Message &pushInt32(int32_t i) { return pushPod(TYPE_TAG_INT32, i); } + Message &pushInt64(int64_t h) { return pushPod(TYPE_TAG_INT64, h); } + Message &pushFloat(float f) { return pushPod(TYPE_TAG_FLOAT, f); } + Message &pushDouble(double d) { return pushPod(TYPE_TAG_DOUBLE, d); } + Message &pushStr(const std::string &s) { + assert(s.size() < 2147483647); // insane values are not welcome + type_tags += TYPE_TAG_STRING; + arguments.push_back(std::make_pair(storage.size(), s.size() + 1)); + strcpy(storage.getBytes(s.size()+1), s.c_str()); + return *this; + } + Message &pushBlob(void *ptr, size_t num_bytes) { + assert(num_bytes < 2147483647); // insane values are not welcome + type_tags += TYPE_TAG_BLOB; + arguments.push_back(std::make_pair(storage.size(), num_bytes+4)); + pod2bytes<int32_t>((int32_t)num_bytes, storage.getBytes(4)); + if (num_bytes) + memcpy(storage.getBytes(num_bytes), ptr, num_bytes); + return *this; + } + + /** reset the message to a clean state */ + void clear() { + address.clear(); type_tags.clear(); storage.clear(); arguments.clear(); + err = OK_NO_ERROR; time_tag = TimeTag::immediate(); + } + + /** write the raw message data (used by PacketWriter) */ + void packMessage(Storage &s, bool write_size) const { + if (!isOk()) return; + size_t l_addr = address.size()+1, l_type = type_tags.size()+2; + if (write_size) + pod2bytes<uint32_t>(uint32_t(ceil4(l_addr) + ceil4(l_type) + ceil4(storage.size())), s.getBytes(4)); + strcpy(s.getBytes(l_addr), address.c_str()); + strcpy(s.getBytes(l_type), ("," + type_tags).c_str()); + if (storage.size()) + memcpy(s.getBytes(storage.size()), const_cast<Storage&>(storage).begin(), storage.size()); + } + +private: + + /* get the number of bytes occupied by the argument */ + size_t getArgSize(int type, const char *p) { + if (err) return 0; + size_t sz = 0; + assert(p >= storage.begin() && p <= storage.end()); + switch (type) { + case TYPE_TAG_TRUE: + case TYPE_TAG_FALSE: sz = 0; break; + case TYPE_TAG_INT32: + case TYPE_TAG_FLOAT: sz = 4; break; + case TYPE_TAG_INT64: + case TYPE_TAG_DOUBLE: sz = 8; break; + case TYPE_TAG_STRING: { + const char *q = (const char*)memchr(p, 0, storage.end()-p); + if (!q) OSCPKT_SET_ERR(MALFORMED_ARGUMENTS); + else sz = (q-p)+1; + } break; + case TYPE_TAG_BLOB: { + if (p == storage.end()) { OSCPKT_SET_ERR(MALFORMED_ARGUMENTS); return 0; } + sz = 4+bytes2pod<uint32_t>(p); + } break; + default: { + OSCPKT_SET_ERR(UNHANDLED_TYPE_TAGS); return 0; + } break; + } + if (p+sz > storage.end() || /* string or blob too large.. */ + p+sz < p /* or even blob so large that it did overflow */) { + OSCPKT_SET_ERR(MALFORMED_ARGUMENTS); return 0; + } + if (!isZeroPaddingCorrect(p+sz)) { OSCPKT_SET_ERR(MALFORMED_ARGUMENTS); return 0; } + return sz; + } + + template <typename POD> Message &pushPod(int tag, POD v) { + type_tags += (char)tag; + arguments.push_back(std::make_pair(storage.size(), sizeof(POD))); + pod2bytes(v, storage.getBytes(sizeof(POD))); + return *this; + } + +#ifdef OSCPKT_OSTREAM_OUTPUT + friend std::ostream &operator<<(std::ostream &os, const Message &msg) { + os << "osc_address: '" << msg.address << "', types: '" << msg.type_tags << "', timetag=" << msg.time_tag << ", args=["; + Message::ArgReader arg(msg); + while (arg.nbArgRemaining() && arg.isOk()) { + if (arg.isBool()) { bool b; arg.popBool(b); os << (b?"True":"False"); } + else if (arg.isInt32()) { int32_t i; arg.popInt32(i); os << i; } + else if (arg.isInt64()) { int64_t h; arg.popInt64(h); os << h << "ll"; } + else if (arg.isFloat()) { float f; arg.popFloat(f); os << f << "f"; } + else if (arg.isDouble()) { double d; arg.popDouble(d); os << d; } + else if (arg.isStr()) { std::string s; arg.popStr(s); os << "'" << s << "'"; } + else if (arg.isBlob()) { std::vector<char> b; arg.popBlob(b); os << "Blob " << b.size() << " bytes"; } + else { + assert(0); // I forgot a case.. + } + if (arg.nbArgRemaining()) os << ", "; + } + if (!arg.isOk()) { os << " ERROR#" << arg.getErr(); } + os << "]"; + return os; + } +#endif +}; + +/** + parse an OSC packet and extracts the embedded OSC messages. +*/ +class PacketReader { +public: + PacketReader() { err = OK_NO_ERROR; } + /** pointer and size of the osc packet to be parsed. */ + PacketReader(const void *ptr, size_t sz) { init(ptr, sz); } + + void init(const void *ptr, size_t sz) { + err = OK_NO_ERROR; messages.clear(); + if ((sz%4) == 0) { + parse((const char*)ptr, (const char *)ptr+sz, TimeTag::immediate()); + } else OSCPKT_SET_ERR(INVALID_PACKET_SIZE); + it_messages = messages.begin(); + } + + /** extract the next osc message from the packet. return 0 when all messages have been read, or in case of error. */ + Message *popMessage() { + if (!err && !messages.empty() && it_messages != messages.end()) return &*it_messages++; + else return 0; + } + bool isOk() const { return err == OK_NO_ERROR; } + ErrorCode getErr() const { return err; } + +private: + std::list<Message> messages; + std::list<Message>::iterator it_messages; + ErrorCode err; + + void parse(const char *beg, const char *end, TimeTag time_tag) { + assert(beg <= end && !err); assert(((end-beg)%4)==0); + + if (beg == end) return; + if (*beg == '#') { + /* it's a bundle */ + if (end - beg >= 20 + && memcmp(beg, "#bundle\0", 8) == 0) { + TimeTag time_tag2(bytes2pod<uint64_t>(beg+8)); + const char *pos = beg + 16; + do { + uint32_t sz = bytes2pod<uint32_t>(pos); pos += 4; + if ((sz&3) != 0 || pos + sz > end || pos+sz < pos) { + OSCPKT_SET_ERR(INVALID_BUNDLE); + } else { + parse(pos, pos+sz, time_tag2); + pos += sz; + } + } while (!err && pos != end); + } else { + OSCPKT_SET_ERR(INVALID_BUNDLE); + } + } else { + messages.push_back(Message(beg, end-beg, time_tag)); + if (!messages.back().isOk()) OSCPKT_SET_ERR(messages.back().getErr()); + } + } +}; + + +/** + Assemble messages into an OSC packet. Example of use: + @code + PacketWriter pkt; + Message msg; + pkt.startBundle(); + pkt.addMessage(msg.init("/foo").pushBool(true).pushStr("plop").pushFloat(3.14f)); + pkt.addMessage(msg.init("/bar").pushBool(false)); + pkt.endBundle(); + if (pkt.isOk()) { + send(pkt.data(), pkt.size()); + } + @endcode +*/ +class PacketWriter { +public: + PacketWriter() { init(); } + PacketWriter &init() { err = OK_NO_ERROR; storage.clear(); bundles.clear(); return *this; } + + /** begin a new bundle. If you plan to pack more than one message in the Osc packet, you have to + put them in a bundle. Nested bundles inside bundles are also allowed. */ + PacketWriter &startBundle(TimeTag ts = TimeTag::immediate()) { + char *p; + if (bundles.size()) storage.getBytes(4); // hold the bundle size + p = storage.getBytes(8); strcpy(p, "#bundle"); bundles.push_back(p - storage.begin()); + p = storage.getBytes(8); pod2bytes<uint64_t>(ts, p); + return *this; + } + /** close the current bundle. */ + PacketWriter &endBundle() { + if (bundles.size()) { + if (storage.size() - bundles.back() == 16) { + pod2bytes<uint32_t>(0, storage.getBytes(4)); // the 'empty bundle' case, not very elegant + } + if (bundles.size()>1) { // no size stored for the top-level bundle + pod2bytes<uint32_t>(uint32_t(storage.size() - bundles.back()), storage.begin() + bundles.back()-4); + } + bundles.pop_back(); + } else OSCPKT_SET_ERR(INVALID_BUNDLE); + return *this; + } + + /** insert an Osc message into the current bundle / packet. + */ + PacketWriter &addMessage(const Message &msg) { + if (storage.size() != 0 && bundles.empty()) OSCPKT_SET_ERR(BUNDLE_REQUIRED_FOR_MULTI_MESSAGES); + else msg.packMessage(storage, bundles.size()>0); + if (!msg.isOk()) OSCPKT_SET_ERR(msg.getErr()); + return *this; + } + + /** the error flag will be raised if an opened bundle is not closed, or if more than one message is + inserted in the packet without a bundle */ + bool isOk() { return err == OK_NO_ERROR; } + ErrorCode getErr() { return err; } + + /** return the number of bytes of the osc packet -- will always be a + multiple of 4 -- returns 0 if the construction of the packet has + failed. */ + uint32_t packetSize() { return err ? 0 : (uint32_t)storage.size(); } + + /** return the bytes of the osc packet (NULL if the construction of the packet has failed) */ + char *packetData() { return err ? 0 : storage.begin(); } +private: + std::vector<size_t> bundles; // hold the position in the storage array of the beginning marker of each bundle + Storage storage; + ErrorCode err; +}; + +// see the OSC spec for the precise pattern matching rules +inline const char *internalPatternMatch(const char *pattern, const char *path) { + while (*pattern) { + const char *p = pattern; + if (*p == '?' && *path) { ++p; ++path; } + else if (*p == '[' && *path) { // bracketted range, e.g. [a-zABC] + ++p; + bool reverse = false; + if (*p == '!') { reverse = true; ++p; } + bool match = reverse; + for (; *p && *p != ']'; ++p) { + char c0 = *p, c1 = c0; + if (p[1] == '-' && p[2] && p[2] != ']') { p += 2; c1 = *p; } + if (*path >= c0 && *path <= c1) { match = !reverse; } + } + if (!match || *p != ']') return pattern; + ++p; ++path; + } else if (*p == '*') { // wildcard '*' + while (*p == '*') ++p; + const char *best = 0; + while (true) { + const char *ret = internalPatternMatch(p, path); + if (ret && ret > best) best = ret; + if (*path == 0 || *path == '/') break; + else ++path; + } + return best; + } else if (*p == '/' && *(p+1) == '/') { // the super-wildcard '//' + while (*(p+1)=='/') ++p; + const char *best = 0; + while (true) { + const char *ret = internalPatternMatch(p, path); + if (ret && ret > best) best = ret; + if (*path == 0) break; + if (*path == 0 || (path = strchr(path+1, '/')) == 0) break; + } + return best; + } else if (*p == '{') { // braced list {foo,bar,baz} + const char *end = strchr(p, '}'), *q; + if (!end) return 0; // syntax error in brace list.. + bool match = false; + do { + ++p; + q = strchr(p, ','); + if (q == 0 || q > end) q = end; + if (strncmp(p, path, q-p)==0) { + path += (q-p); p = end+1; match = true; + } else p=q; + } while (q != end && !match); + if (!match) return pattern; + } else if (*p == *path) { ++p; ++path; } // any other character + else break; + pattern = p; + } + return (*path == 0 ? pattern : 0); +} + +inline bool partialPatternMatch(const std::string &pattern, const std::string &test) { + const char *q = internalPatternMatch(pattern.c_str(), test.c_str()); + return q != 0; +} + +inline bool fullPatternMatch(const std::string &pattern, const std::string &test) { + const char *q = internalPatternMatch(pattern.c_str(), test.c_str()); + return q && *q == 0; +} + +} // namespace oscpkt + +#endif // OSCPKT_HH
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/7segment/render.cpp Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,127 @@ +/* + * render.cpp + * + * Created on: Oct 24, 2014 + * Author: parallels + */ + + +#include <BeagleRT.h> +#include <Utilities.h> + +#define NUM_PINS 12 + +// Breadboard wiring layout: +// 11 10 12 9 8 7 +// [ LED DISP ] +// 1 2 3 6 4 5 + +// Organised by display segments: +// e d . X c g b X X X f a +const int kPins[NUM_PINS] = {P8_07, P8_08, P8_09, P8_10, P8_11, P8_12, + P8_15, P8_16, P8_27, P8_28, P8_29, P8_30}; + +// Indices into the above array: pins 12, 9, 8, 6 +const int kDigits[4] = {9, 8, 7, 3}; + +int gCurrentlyDisplayingDigit = 0; +int gDigitDisplayTime = 0; +const int kDigitMaxDisplayTime = 44; + +int gState = 0; +int gStateCounter = 0; +const int kMaxState = 25; + +// . g f e d c b a +//const unsigned char kBELA[4] = {0x7C, 0x79, 0x38, 0x77}; +const unsigned char kBELA[4] = {0x7C, 0x7B, 0x38, 0x5F}; +const unsigned char kPerimeter[6] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20}; + +int gCharacterToDisplay[4] = {0, 0, 0, 0}; + +// setup() is called once before the audio rendering starts. +// Use it to perform any initialisation and allocation which is dependent +// on the period size or sample rate. +// +// userData holds an opaque pointer to a data structure that was passed +// in from the call to initAudio(). +// +// Return true on success; returning false halts the program. + +bool setup(BeagleRTContext *context, void *userData) +{ + // This project makes the assumption that the audio and digital + // sample rates are the same. But check it to be sure! + if(context->audioFrames != context->digitalFrames) { + rt_printf("Error: this project needs the audio and digital sample rates to be the same.\n"); + return false; + } + + for(int i = 0; i < NUM_PINS; i++) { + pinModeFrame(context, 0, kPins[i], OUTPUT); + } + + return true; +} + +// render() is called regularly at the highest priority by the audio engine. +// Input and output are given from the audio hardware and the other +// ADCs and DACs (if available). If only audio is available, numMatrixFrames +// will be 0. + +void render(BeagleRTContext *context, void *userData) +{ + for(unsigned int n = 0; n < context->audioFrames; n++) { + // Check for rotation between digits + if(--gDigitDisplayTime <= 0) { + gCurrentlyDisplayingDigit = (gCurrentlyDisplayingDigit + 1) % 4; + gDigitDisplayTime = kDigitMaxDisplayTime; + } + + // Write the currently displaying digit low and the rest high + for(int i = 0; i < 4; i++) + digitalWriteFrameOnce(context, n, kPins[kDigits[i]], HIGH); + digitalWriteFrameOnce(context, n, kPins[kDigits[gCurrentlyDisplayingDigit]], LOW); + + // Write the digit to the other outputs + digitalWriteFrameOnce(context, n, kPins[11], + gCharacterToDisplay[gCurrentlyDisplayingDigit] & 0x01); // a + digitalWriteFrameOnce(context, n, kPins[6], + gCharacterToDisplay[gCurrentlyDisplayingDigit] & 0x02); // b + digitalWriteFrameOnce(context, n, kPins[4], + gCharacterToDisplay[gCurrentlyDisplayingDigit] & 0x04); // c + digitalWriteFrameOnce(context, n, kPins[1], + gCharacterToDisplay[gCurrentlyDisplayingDigit] & 0x08); // d + digitalWriteFrameOnce(context, n, kPins[0], + gCharacterToDisplay[gCurrentlyDisplayingDigit] & 0x10); // e + digitalWriteFrameOnce(context, n, kPins[10], + gCharacterToDisplay[gCurrentlyDisplayingDigit] & 0x20); // f + digitalWriteFrameOnce(context, n, kPins[5], + gCharacterToDisplay[gCurrentlyDisplayingDigit] & 0x40); // g + digitalWriteFrameOnce(context, n, kPins[2], + gCharacterToDisplay[gCurrentlyDisplayingDigit] & 0x80); // . + + // Check for changing state + if(--gStateCounter <= 0) { + gState = (gState + 1) % kMaxState; + if(gState != (kMaxState - 1)) { + for(int i = 0; i < 4; i++) + gCharacterToDisplay[i] = 1 << (gState % 6); + gStateCounter = 2000; + } + else { + for(int i = 0; i < 4; i++) + gCharacterToDisplay[i] = kBELA[i]; + gStateCounter = 50000; + } + } + } +} + +// cleanup() is called once at the end, after the audio has stopped. +// Release any resources that were allocated in setup(). + +void cleanup(BeagleRTContext *context, void *userData) +{ + +}
--- a/projects/cape_test/render.cpp Tue May 17 16:07:35 2016 +0100 +++ b/projects/cape_test/render.cpp Tue May 17 16:07:45 2016 +0100 @@ -14,10 +14,29 @@ const int gDACPinOrder[] = {6, 4, 2, 0, 1, 3, 5, 7}; +enum { + kStateTestingAudioLeft = 0, + kStateTestingAudioRight, + kStateTestingAudioDone +}; + uint64_t gLastErrorFrame = 0; uint32_t gEnvelopeSampleCount = 0; -float gEnvelopeValue = 0.5; +float gEnvelopeValueL = 0.5, gEnvelopeValueR = 0.5; float gEnvelopeDecayRate = 0.9995; +int gEnvelopeLastChannel = 0; + +float gPositivePeakLevels[2] = {0, 0}; +float gNegativePeakLevels[2] = {0, 0}; +float gPeakLevelDecayRate = 0.999; +const float gPeakLevelLowThreshold = 0.02; +const float gPeakLevelHighThreshold = 0.2; +const float gDCOffsetThreshold = 0.1; +int gAudioTestState = kStateTestingAudioLeft; +int gAudioTestStateSampleCount = 0; +int gAudioTestSuccessCounter = 0; +const int gAudioTestSuccessCounterThreshold = 64; +const int gAudioTestStateSampleThreshold = 16384; // setup() is called once before the audio rendering starts. // Use it to perform any initialisation and allocation which is dependent @@ -47,27 +66,146 @@ // Play a sine wave on the audio output for(unsigned int n = 0; n < context->audioFrames; n++) { - context->audioOut[2*n] = context->audioOut[2*n + 1] = gEnvelopeValue * sinf(phase); + + // Peak detection on the audio inputs, with offset to catch + // DC errors + for(int ch = 0; ch < 2; ch++) { + if(context->audioIn[2*n + ch] > gPositivePeakLevels[ch]) + gPositivePeakLevels[ch] = context->audioIn[2*n + ch]; + gPositivePeakLevels[ch] += 0.1; + gPositivePeakLevels[ch] *= gPeakLevelDecayRate; + gPositivePeakLevels[ch] -= 0.1; + if(context->audioIn[2*n + ch] < gNegativePeakLevels[ch]) + gNegativePeakLevels[ch] = context->audioIn[2*n + ch]; + gNegativePeakLevels[ch] -= 0.1; + gNegativePeakLevels[ch] *= gPeakLevelDecayRate; + gNegativePeakLevels[ch] += 0.1; + } + + if(gAudioTestState == kStateTestingAudioLeft) { + context->audioOut[2*n] = 0.2 * sinf(phase); + context->audioOut[2*n + 1] = 0; + + frequency = 3000.0; + phase += 2.0 * M_PI * frequency / 44100.0; + if(phase >= 2.0 * M_PI) + phase -= 2.0 * M_PI; + + gAudioTestStateSampleCount++; + if(gAudioTestStateSampleCount >= gAudioTestStateSampleThreshold) { + // Check if we have the expected input: signal on the left but not + // on the right. Also check that there is not too much DC offset on the + // inactive signal + if((gPositivePeakLevels[0] - gNegativePeakLevels[0]) >= gPeakLevelHighThreshold + && (gPositivePeakLevels[1] - gNegativePeakLevels[1]) <= gPeakLevelLowThreshold && + fabsf(gPositivePeakLevels[1]) < gDCOffsetThreshold && + fabsf(gNegativePeakLevels[1]) < gDCOffsetThreshold) { + // Successful test: increment counter + gAudioTestSuccessCounter++; + if(gAudioTestSuccessCounter >= gAudioTestSuccessCounterThreshold) { + gAudioTestState = kStateTestingAudioRight; + gAudioTestStateSampleCount = 0; + gAudioTestSuccessCounter = 0; + } - // If one second has gone by with no error, play one sound, else - // play another - if(context->audioSampleCount + n - gLastErrorFrame > 44100) { - gEnvelopeValue *= gEnvelopeDecayRate; - gEnvelopeSampleCount++; - if(gEnvelopeSampleCount > 22050) { - gEnvelopeValue = 0.5; - gEnvelopeSampleCount = 0; + } + else { + if(!((context->audioSampleCount + n) % 22050)) { + // Debugging print messages + if((gPositivePeakLevels[0] - gNegativePeakLevels[0]) < gPeakLevelHighThreshold) + rt_printf("Left Audio In FAIL: insufficient signal: %f\n", + gPositivePeakLevels[0] - gNegativePeakLevels[0]); + else if(gPositivePeakLevels[1] - gNegativePeakLevels[1] > gPeakLevelLowThreshold) + rt_printf("Right Audio In FAIL: signal present when it should not be: %f\n", + gPositivePeakLevels[1] - gNegativePeakLevels[1]); + else if(fabsf(gPositivePeakLevels[1]) >= gDCOffsetThreshold || + fabsf(gNegativePeakLevels[1]) >= gDCOffsetThreshold) + rt_printf("Right Audio In FAIL: DC offset: (%f, %f)\n", + gPositivePeakLevels[1], gNegativePeakLevels[1]); + } + gAudioTestSuccessCounter--; + if(gAudioTestSuccessCounter <= 0) + gAudioTestSuccessCounter = 0; + } } - frequency = 880.0; + } + else if(gAudioTestState == kStateTestingAudioRight) { + context->audioOut[2*n] = 0; + context->audioOut[2*n + 1] = 0.2 * sinf(phase); + + frequency = 3000.0; + phase += 2.0 * M_PI * frequency / 44100.0; + if(phase >= 2.0 * M_PI) + phase -= 2.0 * M_PI; + + gAudioTestStateSampleCount++; + if(gAudioTestStateSampleCount >= gAudioTestStateSampleThreshold) { + // Check if we have the expected input: signal on the left but not + // on the right + if((gPositivePeakLevels[1] - gNegativePeakLevels[1]) >= gPeakLevelHighThreshold + && (gPositivePeakLevels[0] - gNegativePeakLevels[0]) <= gPeakLevelLowThreshold && + fabsf(gPositivePeakLevels[0]) < gDCOffsetThreshold && + fabsf(gNegativePeakLevels[0]) < gDCOffsetThreshold) { + // Successful test: increment counter + gAudioTestSuccessCounter++; + if(gAudioTestSuccessCounter >= gAudioTestSuccessCounterThreshold) { + gAudioTestSuccessCounter = 0; + gAudioTestStateSampleCount = 0; + gAudioTestState = kStateTestingAudioDone; + } + } + else { + if(!((context->audioSampleCount + n) % 22050)) { + // Debugging print messages + if((gPositivePeakLevels[1] - gNegativePeakLevels[1]) < gPeakLevelHighThreshold) + rt_printf("Right Audio In FAIL: insufficient signal: %f\n", + gPositivePeakLevels[1] - gNegativePeakLevels[1]); + else if(gPositivePeakLevels[0] - gNegativePeakLevels[0] > gPeakLevelLowThreshold) + rt_printf("Left Audio In FAIL: signal present when it should not be: %f\n", + gPositivePeakLevels[0] - gNegativePeakLevels[0]); + else if(fabsf(gPositivePeakLevels[0]) >= gDCOffsetThreshold || + fabsf(gNegativePeakLevels[0]) >= gDCOffsetThreshold) + rt_printf("Left Audio In FAIL: DC offset: (%f, %f)\n", + gPositivePeakLevels[0], gNegativePeakLevels[0]); + } + gAudioTestSuccessCounter--; + if(gAudioTestSuccessCounter <= 0) + gAudioTestSuccessCounter = 0; + } + } } else { - gEnvelopeValue = 0.5; - frequency = 220.0; + // Audio input testing finished. Play tones depending on status of + // analog testing + context->audioOut[2*n] = gEnvelopeValueL * sinf(phase); + context->audioOut[2*n + 1] = gEnvelopeValueR * sinf(phase); + + // If one second has gone by with no error, play one sound, else + // play another + if(context->audioSampleCount + n - gLastErrorFrame > 44100) { + gEnvelopeValueL *= gEnvelopeDecayRate; + gEnvelopeValueR *= gEnvelopeDecayRate; + gEnvelopeSampleCount++; + if(gEnvelopeSampleCount > 22050) { + if(gEnvelopeLastChannel == 0) + gEnvelopeValueR = 0.5; + else + gEnvelopeValueL = 0.5; + gEnvelopeLastChannel = !gEnvelopeLastChannel; + gEnvelopeSampleCount = 0; + } + frequency = 880.0; + } + else { + gEnvelopeValueL = gEnvelopeValueR = 0.5; + gEnvelopeLastChannel = 0; + frequency = 220.0; + } + + phase += 2.0 * M_PI * frequency / 44100.0; + if(phase >= 2.0 * M_PI) + phase -= 2.0 * M_PI; } - - phase += 2.0 * M_PI * frequency / 44100.0; - if(phase >= 2.0 * M_PI) - phase -= 2.0 * M_PI; } for(unsigned int n = 0; n < context->analogFrames; n++) {
--- a/projects/level_meter/render.cpp Tue May 17 16:07:35 2016 +0100 +++ b/projects/level_meter/render.cpp Tue May 17 16:07:45 2016 +0100 @@ -21,6 +21,7 @@ // Thresholds for LEDs: set in setup() float gThresholds[NUMBER_OF_SEGMENTS + 1]; +int gSamplesToLight[NUMBER_OF_SEGMENTS]; // High-pass filter on the input float gLastX[2] = {0}; @@ -57,8 +58,10 @@ gThresholds[i] = powf(10.0f, (-1.0 * (NUMBER_OF_SEGMENTS - i)) * .05); } - for(int i = 0; i < NUMBER_OF_SEGMENTS; i++) + for(int i = 0; i < NUMBER_OF_SEGMENTS; i++) { + gSamplesToLight[i] = 0; pinModeFrame(context, 0, i, OUTPUT); + } return true; } @@ -111,9 +114,15 @@ // for the peak level also remains lit. int state = LOW; - if(gAudioLocalLevel > gThresholds[led]) + if(gAudioLocalLevel > gThresholds[led]) { state = HIGH; - else if(gAudioPeakLevel > gThresholds[led] && gAudioPeakLevel <= gThresholds[led + 1]) + gSamplesToLight[led] = 1000; + } + /*else if(gAudioPeakLevel > gThresholds[led] && gAudioPeakLevel <= gThresholds[led + 1]) { + state = HIGH; + gSamplesToLight[led] = 1000; + }*/ + else if(--gSamplesToLight[led] > 0) state = HIGH; // Write LED
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/mpr121/I2C_MPR121.cpp Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,176 @@ +/* + * I2C_MPR121.cpp + * + * Created on: Oct 14, 2013 + * Author: Victor Zappi + */ + + +#include "I2C_MPR121.h" + +I2C_MPR121::I2C_MPR121() { + +} + +boolean I2C_MPR121::begin(uint8_t bus, uint8_t i2caddr) { + _i2c_address = i2caddr; + + if(initI2C_RW(bus, i2caddr, 0) > 0) + return false; + + // soft reset + writeRegister(MPR121_SOFTRESET, 0x63); + usleep(1000); + //delay(1); + for (uint8_t i=0; i<0x7F; i++) { + // Serial.print("$"); Serial.print(i, HEX); + // Serial.print(": 0x"); Serial.println(readRegister8(i)); + } + + + writeRegister(MPR121_ECR, 0x0); + + uint8_t c = readRegister8(MPR121_CONFIG2); + + if (c != 0x24) { + rt_printf("MPR121 read 0x%x instead of 0x24\n", c); + return false; + } + + setThresholds(12, 6); + writeRegister(MPR121_MHDR, 0x01); + writeRegister(MPR121_NHDR, 0x01); + writeRegister(MPR121_NCLR, 0x0E); + writeRegister(MPR121_FDLR, 0x00); + + writeRegister(MPR121_MHDF, 0x01); + writeRegister(MPR121_NHDF, 0x05); + writeRegister(MPR121_NCLF, 0x01); + writeRegister(MPR121_FDLF, 0x00); + + writeRegister(MPR121_NHDT, 0x00); + writeRegister(MPR121_NCLT, 0x00); + writeRegister(MPR121_FDLT, 0x00); + + writeRegister(MPR121_DEBOUNCE, 0); + writeRegister(MPR121_CONFIG1, 0x10); // default, 16uA charge current + writeRegister(MPR121_CONFIG2, 0x20); // 0.5uS encoding, 1ms period + +// writeRegister(MPR121_AUTOCONFIG0, 0x8F); + +// writeRegister(MPR121_UPLIMIT, 150); +// writeRegister(MPR121_TARGETLIMIT, 100); // should be ~400 (100 shifted) +// writeRegister(MPR121_LOWLIMIT, 50); + // enable all electrodes + writeRegister(MPR121_ECR, 0x8F); // start with first 5 bits of baseline tracking + + return true; +} + +void I2C_MPR121::setThresholds(uint8_t touch, uint8_t release) { + for (uint8_t i=0; i<12; i++) { + writeRegister(MPR121_TOUCHTH_0 + 2*i, touch); + writeRegister(MPR121_RELEASETH_0 + 2*i, release); + } +} + +uint16_t I2C_MPR121::filteredData(uint8_t t) { + if (t > 12) return 0; + return readRegister16(MPR121_FILTDATA_0L + t*2); +} + +uint16_t I2C_MPR121::baselineData(uint8_t t) { + if (t > 12) return 0; + uint16_t bl = readRegister8(MPR121_BASELINE_0 + t); + return (bl << 2); +} + +uint16_t I2C_MPR121::touched(void) { + uint16_t t = readRegister16(MPR121_TOUCHSTATUS_L); + return t & 0x0FFF; +} + +/*********************************************************************/ + + +uint8_t I2C_MPR121::readRegister8(uint8_t reg) { + unsigned char inbuf, outbuf; + struct i2c_rdwr_ioctl_data packets; + struct i2c_msg messages[2]; + + /* + * In order to read a register, we first do a "dummy write" by writing + * 0 bytes to the register we want to read from. This is similar to + * the packet in set_i2c_register, except it's 1 byte rather than 2. + */ + outbuf = reg; + messages[0].addr = 0x5A; + messages[0].flags = 0; + messages[0].len = sizeof(outbuf); + messages[0].buf = &outbuf; + + /* The data will get returned in this structure */ + messages[1].addr = 0x5A; + messages[1].flags = I2C_M_RD/* | I2C_M_NOSTART*/; + messages[1].len = sizeof(inbuf); + messages[1].buf = &inbuf; + + /* Send the request to the kernel and get the result back */ + packets.msgs = messages; + packets.nmsgs = 2; + if(ioctl(i2C_file, I2C_RDWR, &packets) < 0) { + rt_printf("Unable to send data"); + return 0; + } + + return inbuf; +} + +uint16_t I2C_MPR121::readRegister16(uint8_t reg) { + unsigned char inbuf[2], outbuf; + struct i2c_rdwr_ioctl_data packets; + struct i2c_msg messages[2]; + + /* + * In order to read a register, we first do a "dummy write" by writing + * 0 bytes to the register we want to read from. This is similar to + * the packet in set_i2c_register, except it's 1 byte rather than 2. + */ + outbuf = reg; + messages[0].addr = _i2c_address; + messages[0].flags = 0; + messages[0].len = sizeof(outbuf); + messages[0].buf = &outbuf; + + /* The data will get returned in this structure */ + messages[1].addr = _i2c_address; + messages[1].flags = I2C_M_RD/* | I2C_M_NOSTART*/; + messages[1].len = sizeof(inbuf); + messages[1].buf = inbuf; + + /* Send the request to the kernel and get the result back */ + packets.msgs = messages; + packets.nmsgs = 2; + if(ioctl(i2C_file, I2C_RDWR, &packets) < 0) { + rt_printf("Unable to send data"); + return 0; + } + + return (uint16_t)inbuf[0] | (((uint16_t)inbuf[1]) << 8); +} + +/**************************************************************************/ +/*! + @brief Writes 8-bits to the specified destination register +*/ +/**************************************************************************/ +void I2C_MPR121::writeRegister(uint8_t reg, uint8_t value) { + uint8_t buf[2] = { reg, value }; + + if(write(i2C_file, buf, 2) != 2) + { + cout << "Failed to write register " << (int)reg << " on MPR121\n"; + return; + } +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/mpr121/I2C_MPR121.h Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,82 @@ +/* + * MPR121 Bela demo + * + * Andrew McPherson + * Based on Adafruit library by Limor Fried/Ladyada + */ + +#ifndef I2CTK_H_ +#define I2CTK_H_ + +#include <I2c.h> +#include "Utilities.h" + +typedef bool boolean; + +#define MPR121_I2CADDR_DEFAULT 0x5A + +#define MPR121_TOUCHSTATUS_L 0x00 +#define MPR121_TOUCHSTATUS_H 0x01 +#define MPR121_FILTDATA_0L 0x04 +#define MPR121_FILTDATA_0H 0x05 +#define MPR121_BASELINE_0 0x1E +#define MPR121_MHDR 0x2B +#define MPR121_NHDR 0x2C +#define MPR121_NCLR 0x2D +#define MPR121_FDLR 0x2E +#define MPR121_MHDF 0x2F +#define MPR121_NHDF 0x30 +#define MPR121_NCLF 0x31 +#define MPR121_FDLF 0x32 +#define MPR121_NHDT 0x33 +#define MPR121_NCLT 0x34 +#define MPR121_FDLT 0x35 + +#define MPR121_TOUCHTH_0 0x41 +#define MPR121_RELEASETH_0 0x42 +#define MPR121_DEBOUNCE 0x5B +#define MPR121_CONFIG1 0x5C +#define MPR121_CONFIG2 0x5D +#define MPR121_CHARGECURR_0 0x5F +#define MPR121_CHARGETIME_1 0x6C +#define MPR121_ECR 0x5E +#define MPR121_AUTOCONFIG0 0x7B +#define MPR121_AUTOCONFIG1 0x7C +#define MPR121_UPLIMIT 0x7D +#define MPR121_LOWLIMIT 0x7E +#define MPR121_TARGETLIMIT 0x7F + +#define MPR121_GPIODIR 0x76 +#define MPR121_GPIOEN 0x77 +#define MPR121_GPIOSET 0x78 +#define MPR121_GPIOCLR 0x79 +#define MPR121_GPIOTOGGLE 0x7A + +#define MPR121_SOFTRESET 0x80 + +class I2C_MPR121 : public I2c +{ +public: + // Hardware I2C + I2C_MPR121(); + + boolean begin(uint8_t bus = 1, uint8_t i2caddr = MPR121_I2CADDR_DEFAULT); + + uint16_t filteredData(uint8_t t); + uint16_t baselineData(uint8_t t); + + uint8_t readRegister8(uint8_t reg); + uint16_t readRegister16(uint8_t reg); + void writeRegister(uint8_t reg, uint8_t value); + uint16_t touched(void); + + void setThresholds(uint8_t touch, uint8_t release); + + int readI2C() { return 0; } // Unused + +private: + int _i2c_address; +}; + + +#endif /* I2CTK_H_ */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/mpr121/render.cpp Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,129 @@ +#include <BeagleRT.h> +#include <Utilities.h> +#include <cmath> +#include <rtdk.h> +#include "I2C_MPR121.h" + +// How many pins there are +#define NUM_TOUCH_PINS 12 + +// Define this to print data to terminal +#undef DEBUG_MPR121 + +// Change this to change how often the MPR121 is read (in Hz) +int readInterval = 50; + +// Change this threshold to set the minimum amount of touch +int threshold = 40; + +// This array holds the continuous sensor values +int sensorValue[NUM_TOUCH_PINS]; + +// ---- test code stuff -- can be deleted for your example ---- + +// 12 notes of a C major scale... +float gFrequencies[NUM_TOUCH_PINS] = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25, 587.33, 659.25, 698.25, 783.99}; + +// This is internal stuff for the demo +float gNormFrequencies[NUM_TOUCH_PINS]; +float gPhases[NUM_TOUCH_PINS] = {0}; + +// ---- internal stuff -- do not change ----- + +I2C_MPR121 mpr121; // Object to handle MPR121 sensing +AuxiliaryTask i2cTask; // Auxiliary task to read I2C + +int readCount = 0; // How long until we read again... +int readIntervalSamples = 0; // How many samples between reads + +void readMPR121(); + +// setup() is called once before the audio rendering starts. +// Use it to perform any initialisation and allocation which is dependent +// on the period size or sample rate. +// +// userData holds an opaque pointer to a data structure that was passed +// in from the call to initAudio(). +// +// Return true on success; returning false halts the program. + +bool setup(BeagleRTContext *context, void *userData) +{ + if(!mpr121.begin(1, 0x5A)) { + rt_printf("Error initialising MPR121\n"); + return false; + } + + i2cTask = BeagleRT_createAuxiliaryTask(readMPR121, 50, "beaglert-mpr121"); + readIntervalSamples = context->audioSampleRate / readInterval; + + for(int i = 0; i < NUM_TOUCH_PINS; i++) { + gNormFrequencies[i] = 2.0 * M_PI * gFrequencies[i] / context->audioSampleRate; + } + + return true; +} + +// render() is called regularly at the highest priority by the audio engine. +// Input and output are given from the audio hardware and the other +// ADCs and DACs (if available). If only audio is available, numAnalogFrames +// will be 0. + +void render(BeagleRTContext *context, void *userData) +{ + for(int n = 0; n < context->audioFrames; n++) { + // Keep this code: it schedules the touch sensor readings + if(++readCount >= readIntervalSamples) { + readCount = 0; + BeagleRT_scheduleAuxiliaryTask(i2cTask); + } + + float sample = 0.0; + + // This code can be replaced with your favourite audio code + for(int i = 0; i < NUM_TOUCH_PINS; i++) { + float amplitude = sensorValue[i] / 400.0; + + // Prevent clipping + if(amplitude > 0.5) + amplitude = 0.5; + + sample += amplitude * sinf(gPhases[i]); + gPhases[i] += gNormFrequencies[i]; + if(gPhases[i] > 2.0 * M_PI) + gPhases[i] -= 2.0 * M_PI; + } + + for(int ch = 0; ch < context->audioChannels; ch++) + context->audioOut[context->audioChannels * n + ch] = sample; + } +} + +// cleanup() is called once at the end, after the audio has stopped. +// Release any resources that were allocated in setup(). + +void cleanup(BeagleRTContext *context, void *userData) +{ + // Nothing to do here +} + + +// Auxiliary task to read the I2C board +void readMPR121() +{ + for(int i = 0; i < NUM_TOUCH_PINS; i++) { + sensorValue[i] = -(mpr121.filteredData(i) - mpr121.baselineData(i)); + sensorValue[i] -= threshold; + if(sensorValue[i] < 0) + sensorValue[i] = 0; +#ifdef DEBUG_MPR121 + rt_printf("%d ", sensorValue[i]); +#endif + } +#ifdef DEBUG_MPR121 + rt_printf("\n"); +#endif + + // You can use this to read binary on/off touch state more easily + //rt_printf("Touched: %x\n", mpr121.touched()); +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/osc/render.cpp Tue May 17 16:07:45 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/projects/scope_analogue/render.cpp Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,59 @@ +// this example reads the analogue inputs 0 and 1 +// and generates a sine wave with an amplitude and +// frequency determined by their values +// it then plots these on the oscilloscope + +#include <BeagleRT.h> +#include <cmath> +#include <Scope.h> + +Scope scope; + +float gInverseSampleRate; +float gPhase; + +bool setup(BeagleRTContext *context, void *userData) +{ + + // setup the scope with 3 channels at the audio sample rate + scope.setup(3, context->audioSampleRate); + + gInverseSampleRate = 1.0 / context->audioSampleRate; + gPhase = 0.0; + + return true; +} + +void render(BeagleRTContext *context, void *userData) +{ + + for(unsigned int n = 0; n < context->audioFrames; n++) { + + // read analogIn channels 0 and 1 + float in1 = analogReadFrame(context, n, 0); + float in2 = analogReadFrame(context, n, 1); + + // map in1 to amplitude and in2 to frequency + float amplitude = in1 * 0.8f; + float frequency = map(in2, 0, 1, 100, 1000); + + // generate a sine wave with the amplitude and frequency + float out = amplitude * sinf(gPhase); + gPhase += 2.0 * M_PI * frequency * gInverseSampleRate; + if(gPhase > 2.0 * M_PI) + gPhase -= 2.0 * M_PI; + + // log the sine wave and sensor values on the scope + scope.log(out, in1, in2); + + // pass the sine wave to the audio outputs + for(unsigned int channel = 0; channel < context->audioChannels; channel++) + context->audioOut[n * context->audioChannels + channel] = out; + + } +} + +void cleanup(BeagleRTContext *context, void *userData) +{ + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/scope_basic/render.cpp Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,54 @@ +#include <BeagleRT.h> +#include <Scope.h> +#include <cmath> + +// set the frequency of the oscillators +float gFrequency = 110.0; +float gPhase; +float gInverseSampleRate; + +// instantiate the scope +Scope scope; + +bool setup(BeagleRTContext *context, void *userData) +{ + // tell the scope how many channels and the sample rate + scope.setup(3, context->audioSampleRate); + + gPhase = 0; + gInverseSampleRate = 1.0f/context->audioSampleRate; + + return true; +} + +float lastOut = 0.0; +float lastOut2 = 0.0; +void render(BeagleRTContext *context, void *userData) +{ + // iterate over the audio frames and create three oscillators, seperated in phase by PI/2 + for (unsigned int n=0; n<context->audioFrames; n++){ + float out = 0.8f * sinf(gPhase); + float out2 = 0.8f * sinf(gPhase - M_PI/2); + float out3 = 0.8f * sinf(gPhase + M_PI/2); + gPhase += 2.0 * M_PI * gFrequency * gInverseSampleRate; + if(gPhase > 2.0 * M_PI) + gPhase -= 2.0 * M_PI; + + // log the three oscillators to the scope + scope.log(out, out2, out3); + + // optional - tell the scope to trigger when oscillator 1 becomes less than oscillator 2 + // note this has no effect unless trigger mode is set to custom in the scope UI + if (lastOut >= lastOut2 && out < out2){ + scope.trigger(); + } + + lastOut = out; + lastOut2 = out2; + } +} + +void cleanup(BeagleRTContext *context, void *userData) +{ + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/stepper/render.cpp Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,151 @@ +/* + * render.cpp + * + * Created on: Oct 24, 2014 + * Author: parallels + */ + + +#include <BeagleRT.h> +#include <Utilities.h> + +const int kStepLengthSlow = 1000; +const int kStepLengthFast = 500; + +int gStepLengthSamples = kStepLengthSlow; + +const int gPinA1 = P8_27; +const int gPinA2 = P8_28; +const int gPinB1 = P8_29; +const int gPinB2 = P8_30; +const int gPinServo = P9_16; + +int gStepCounter = 0; +int gPhase = 0; + +int gServoCounter = 0; + + +enum { + kStateMoveRight1 = 0, + kStateMoveLeft1, + kStateMoveRight2, + kStateMoveLeft2, + kStateMoveRight3, + kStateMoveLeft3, + kStateSpin, + kStateMax +}; + +int gState = 0; +int gStateCounter = 0; + +// setup() is called once before the audio rendering starts. +// Use it to perform any initialisation and allocation which is dependent +// on the period size or sample rate. +// +// userData holds an opaque pointer to a data structure that was passed +// in from the call to initAudio(). +// +// Return true on success; returning false halts the program. + +bool setup(BeagleRTContext *context, void *userData) +{ + // This project makes the assumption that the audio and digital + // sample rates are the same. But check it to be sure! + if(context->audioFrames != context->digitalFrames) { + rt_printf("Error: this project needs the audio and digital sample rates to be the same.\n"); + return false; + } + + pinModeFrame(context, 0, gPinA1, OUTPUT); + pinModeFrame(context, 0, gPinA2, OUTPUT); + pinModeFrame(context, 0, gPinB1, OUTPUT); + pinModeFrame(context, 0, gPinB2, OUTPUT); + pinModeFrame(context, 0, gPinServo, OUTPUT); + + return true; +} + +// render() is called regularly at the highest priority by the audio engine. +// Input and output are given from the audio hardware and the other +// ADCs and DACs (if available). If only audio is available, numMatrixFrames +// will be 0. + +void render(BeagleRTContext *context, void *userData) +{ + for(unsigned int n = 0; n < context->audioFrames; n++) { + if(gPhase == 0 || gPhase == 1) { + digitalWriteFrameOnce(context, n, gPinB1, HIGH); + digitalWriteFrameOnce(context, n, gPinB2, LOW); + } + else { + digitalWriteFrameOnce(context, n, gPinB1, LOW); + digitalWriteFrameOnce(context, n, gPinB2, HIGH); + } + + if(gPhase == 1 || gPhase == 2) { + digitalWriteFrameOnce(context, n, gPinA1, HIGH); + digitalWriteFrameOnce(context, n, gPinA2, LOW); + } + else { + digitalWriteFrameOnce(context, n, gPinA1, LOW); + digitalWriteFrameOnce(context, n, gPinA2, HIGH); + } + + if(--gServoCounter > 0) + digitalWriteFrameOnce(context, n, gPinServo, HIGH); + else + digitalWriteFrameOnce(context, n, gPinServo, LOW); + + if(++gStepCounter >= gStepLengthSamples) { + gStateCounter++; + + switch(gState) { + case kStateMoveRight1: + case kStateMoveRight2: + case kStateMoveRight3: + gPhase = (gPhase + 1) & 3; + break; + case kStateMoveLeft1: + case kStateMoveLeft2: + case kStateMoveLeft3: + gPhase = (gPhase + 3) & 3; + break; + case kStateSpin: + gPhase = (gPhase + 1) & 3; + break; + } + + if(gState == kStateSpin) { + if(gStateCounter >= 48) { + gStateCounter = 0; + gState = 0; + gStepLengthSamples = kStepLengthSlow; + } + } + else { + if(gStateCounter >= 16) { + gStateCounter = 0; + gState++; + if(gState & 1) + gServoCounter = 120; + else + gServoCounter = 80; + if(gState == kStateSpin) + gStepLengthSamples = kStepLengthFast; + } + } + + gStepCounter = 0; + } + } +} + +// cleanup() is called once at the end, after the audio has stopped. +// Release any resources that were allocated in setup(). + +void cleanup(BeagleRTContext *context, void *userData) +{ + +}
--- a/projects/tank_wars/game.cpp Tue May 17 16:07:35 2016 +0100 +++ b/projects/tank_wars/game.cpp Tue May 17 16:07:45 2016 +0100 @@ -35,6 +35,7 @@ // Infor needed for sound rendering bool collisionJustOccurred = false; +bool tankHitJustOccurred = false; // Useful utility function for generating random floating-point values float randomFloat(float low, float hi) @@ -46,8 +47,8 @@ // Restart the game, without reallocating memory void restartGame() { - float player1Height = randomFloat(screenHeight/2, screenHeight-5); - float player2Height = randomFloat(screenHeight/2, screenHeight-5); + float player1Height = screenHeight * 3/4; // randomFloat(screenHeight/2, screenHeight-5); + float player2Height = screenHeight - 5; // randomFloat(screenHeight/2, screenHeight-5); for(int i = 0; i < screenWidth * 0.2; i++) { groundLevel[i] = player1Height; } @@ -104,7 +105,8 @@ <= tankRadius * tankRadius) { projectileInMotion = false; - collisionJustOccurred = true; + collisionJustOccurred = false; + tankHitJustOccurred = true; playerHasWon = 2; } else if((tank2X - projectilePositionX)*(tank2X - projectilePositionX) + @@ -112,7 +114,8 @@ <= tankRadius * tankRadius) { projectileInMotion = false; - collisionJustOccurred = true; + collisionJustOccurred = false; + tankHitJustOccurred = true; playerHasWon = 1; } else if(projectilePositionX < 0 || projectilePositionX >= screenWidth) { @@ -201,6 +204,16 @@ return false; } +bool gameStatusTankHitOccurred() +{ + if(tankHitJustOccurred) { + tankHitJustOccurred = false; + return true; + } + return false; +} + + float gameStatusProjectileHeight() { return projectilePositionY / (float)screenHeight;
--- a/projects/tank_wars/game.h Tue May 17 16:07:35 2016 +0100 +++ b/projects/tank_wars/game.h Tue May 17 16:07:45 2016 +0100 @@ -27,6 +27,7 @@ bool gameStatusProjectileInMotion(); int gameStatusWinner(); bool gameStatusCollisionOccurred(); +bool gameStatusTankHitOccurred(); float gameStatusProjectileHeight(); // Render screen; returns length of buffer used
--- a/projects/tank_wars/main.cpp Tue May 17 16:07:35 2016 +0100 +++ b/projects/tank_wars/main.cpp Tue May 17 16:07:45 2016 +0100 @@ -19,6 +19,9 @@ int gMusicBufferLength = 0; float *gSoundBoomBuffer = 0; int gSoundBoomBufferLength = 0; +float *gSoundHitBuffer = 0; +int gSoundHitBufferLength = 0; + using namespace std; @@ -80,7 +83,8 @@ BeagleRTInitSettings settings; // Standard audio settings string musicFileName = "music.wav"; string soundBoomFileName = "boom.wav"; - + string soundHitFileName = "hit.wav"; + struct option customOptions[] = { {"help", 0, NULL, 'h'}, @@ -121,7 +125,10 @@ if(loadSoundFile(soundBoomFileName, &gSoundBoomBuffer, &gSoundBoomBufferLength) != 0) { cout << "Warning: unable to load sound file " << soundBoomFileName << endl; } - + if(loadSoundFile(soundHitFileName, &gSoundHitBuffer, &gSoundHitBufferLength) != 0) { + cout << "Warning: unable to load sound file " << soundHitFileName << endl; + } + // Initialise the PRU audio device if(BeagleRT_initAudio(&settings, 0) != 0) { cout << "Error: unable to initialise audio" << endl; @@ -154,7 +161,9 @@ free(gMusicBuffer); if(gSoundBoomBuffer != 0) free(gSoundBoomBuffer); - + if(gSoundHitBuffer != 0) + free(gSoundHitBuffer); + // All done! return 0; }
--- a/projects/tank_wars/render.cpp Tue May 17 16:07:35 2016 +0100 +++ b/projects/tank_wars/render.cpp Tue May 17 16:07:45 2016 +0100 @@ -68,10 +68,13 @@ extern int gMusicBufferLength; extern float *gSoundBoomBuffer; extern int gSoundBoomBufferLength; +extern float *gSoundHitBuffer; +extern int gSoundHitBufferLength; // Current state for sound and music int gMusicBufferPointer = 0; // 0 means start of buffer... int gSoundBoomBufferPointer = -1; // -1 means don't play... +int gSoundHitBufferPointer = -1; float gSoundProjectileOscillatorPhase = 0; float gSoundProjectileOscillatorGain = 0.2; float gOscillatorPhaseScaler = 0; @@ -178,6 +181,12 @@ gSoundBoomBufferPointer = -1; } + if(gSoundHitBuffer != 0 && gSoundHitBufferPointer >= 0) { + audioSample += gSoundHitBuffer[gSoundHitBufferPointer++]; + if(gSoundHitBufferPointer >= gSoundHitBufferLength) + gSoundHitBufferPointer = -1; + } + // Oscillator plays to indicate projectile height if(gameStatusProjectileInMotion()) { audioSample += gSoundProjectileOscillatorGain * sinf(gSoundProjectileOscillatorPhase); @@ -237,6 +246,10 @@ if(gameStatusCollisionOccurred()) { gSoundBoomBufferPointer = 0; } + + if(gameStatusTankHitOccurred()) { + gSoundHitBufferPointer = 0; + } } if(gScreenBufferReadPointer >= gScreenBufferReadLength - 1
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/BB-BONE-PRU-BELA-00A0.dts Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,59 @@ +/* +* Copyright (C) 2013 Matt Ranostay <mranostay@gmail.com> +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License version 2 as +* published by the Free Software Foundation. +*/ +/dts-v1/; +/plugin/; + +/ { + compatible = "ti,beaglebone", "ti,beaglebone-black", "ti,beaglebone-green"; + + /* identification */ + part-number = "BB-BONE-PRU-BELA"; + version = "00A0"; + + /* state the resources this cape uses */ + exclusive-use = + /* the pin header uses */ + "P8.41", /* pru1: pr1_pru1_pru_r30_4 */ + "P8.42", /* pru1: pr1_pru1_pru_r30_5 */ + "P8.43", /* pru1: pr1_pru1_pru_r30_2 */ + "P8.44", /* pru1: pr1_pru1_pru_r30_3 */ + "P8.45", /* pru1: pr1_pru1_pru_r30_0 */ + "P8.46", /* pru1: pr1_pru1_pru_r30_1 */ + "P9.27", + /* the hardware IP uses */ + "pru0", + "pru1"; + + fragment@0 { + target = <&am33xx_pinmux>; + __overlay__ { + + pru_bela_pins: pinmux_pru_bela_pins { + pinctrl-single,pins = < + 0x1a4 0x37 /* P9 27 GPIO3_19: mcasp0_fsr.gpio3[19] | MODE7 | INPUT | pullup */ + 0x0b0 0x25 /* lcd_data4.pr1_pru1_pru_r30_4, MODE5 | OUTPUT | PRU */ + 0x0b4 0x25 /* lcd_data5.pr1_pru1_pru_r30_5, MODE5 | OUTPUT | PRU */ + 0x0ac 0x25 /* lcd_data3.pr1_pru1_pru_r30_3, MODE5 | OUTPUT | PRU */ + 0x0a0 0x25 /* lcd_data0.pr1_pru1_pru_r30_0, MODE5 | OUTPUT | PRU */ + 0x0a4 0x25 /* lcd_data1.pr1_pru1_pru_r30_1, MODE5 | OUTPUT | PRU */ + 0x0a8 0x25 /* lcd_data2.pr1_pru1_pru_r30_2, MODE5 | OUTPUT | PRU */ + >; + }; + }; + }; + + fragment@2 { + target = <&pruss>; + __overlay__ { + status = "okay"; + + pinctrl-names = "default"; + pinctrl-0 = <&pru_bela_pins>; + }; + }; +}; \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/osc/node_modules/binpack/.npmignore Tue May 17 16:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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:07:45 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
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/shutdown_switch.sh Tue May 17 16:07:45 2016 +0100 @@ -0,0 +1,65 @@ +#!/bin/bash +# +# shutdown_switch.sh: script for gracefully halting the BeagleBone Black +# when an onboard button is pressed. +# +# (c) 2016 Andrew McPherson, C4DM, QMUL +# Developed for Bela: http://bela.io + + +# Prepare P9.27 as input (will be configured with pullup) +# via BB-BONE-PRU-BELA overlay + +BUTTON_PIN=115 + +echo $BUTTON_PIN > /sys/class/gpio/export +echo in > /sys/class/gpio/gpio"$BUTTON_PIN"/direction + +if [ ! -r /sys/class/gpio/gpio"$BUTTON_PIN"/value ] +then + echo "$(basename $0): Unable to read GPIO pin $BUTTON_PIN for shutdown button." + exit +fi + +# First, wait for pin to go high. If it starts at 0, that's more +# likely that the GPIO is not set correctly, so do not treat this +# as a button press + +while [ $(cat /sys/class/gpio/gpio"$BUTTON_PIN"/value) -ne 1 ]; do + # Keep checking pin is readable in case it gets unexported + if [ ! -r /sys/class/gpio/gpio"$BUTTON_PIN"/value ] + then + echo "$(basename $0): Unable to read GPIO pin $BUTTON_PIN for shutdown button." + exit + fi + sleep 0.5 +done + +# Now for button press. Make sure the button is held at least +# 1 second before shutting down + +PRESS_COUNT=0 + +while true; do + # Keep checking pin is readable in case it gets unexported + if [ ! -r /sys/class/gpio/gpio"$BUTTON_PIN"/value ] + then + echo "$(basename $0): Unable to read GPIO pin $BUTTON_PIN for shutdown button." + exit + fi + + # Button pressed? (pressed = low) + if [ $(cat /sys/class/gpio/gpio"$BUTTON_PIN"/value) -eq 0 ] + then + PRESS_COUNT=$((PRESS_COUNT+1)) + if [ "$PRESS_COUNT" -ge 4 ] + then + echo "$(basename $0): Shutdown button pressed. Halting system..." + halt + exit 1 + fi + else + PRESS_COUNT=0 + fi + sleep 0.5 +done \ No newline at end of file