Mercurial > hg > beaglert
changeset 321:4475c0bc2aaa Doxy prerelease
Merge
author | Robert Jack <robert.h.jack@gmail.com> |
---|---|
date | Fri, 27 May 2016 12:32:11 +0100 |
parents | 634c1d1f37bc (diff) ff1d22e2c5a0 (current diff) |
children | dde921ea256b |
files | Makefile |
diffstat | 74 files changed, 7184 insertions(+), 174 deletions(-) [+] |
line wrap: on
line diff
--- a/Doxyfile Fri May 27 01:00:46 2016 +0100 +++ b/Doxyfile Fri May 27 12:32:11 2016 +0100 @@ -648,7 +648,7 @@ # directories like "/usr/src/myproject". Separate the files or directories # with spaces. -INPUT = include/BeagleRT.h include/Utilities.h include/digital_gpio_mapping.h include/PulseIn.h include/Scope.h include/Midi.h include/UdpClient.h include/WriteFile.h projects/basic/render.cpp projects/basic_analog_input/render.cpp projects/basic_passthru/render.cpp projects/basic_blink/render.cpp projects/basic_button/render.cpp projects/basic_analog_output/render.cpp projects/samples/render.cpp projects/audio_in_FFT/render.cpp projects/basic_FFT_phase_vocoder/render.cpp projects/oscillator_bank/render.cpp projects/empty_project/render.cpp projects/analogDigitalDemo/render.cpp projects/basic_network/render.cpp +INPUT = include/BeagleRT.h include/Utilities.h include/digital_gpio_mapping.h include/PulseIn.h include/Scope.h include/Midi.h include/UdpClient.h include/WriteFile.h projects/ # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is @@ -715,7 +715,7 @@ # and *.h) to filter out the source-files in the directories. If left # blank all files are included. -EXAMPLE_PATTERNS = +EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude
--- a/Makefile Fri May 27 01:00:46 2016 +0100 +++ b/Makefile Fri May 27 12:32:11 2016 +0100 @@ -1,14 +1,25 @@ # BeagleRT # Low-latency, real-time audio and sensor processing on BeagleBone Black -# (c) 2015 Andrew McPherson, Victor Zappi, Giulio Moro +# (c) 2016 Andrew McPherson, Victor Zappi, Giulio Moro, Liam Donovan # Centre for Digital Music, Queen Mary University of London # This Makefile is intended for use on the BeagleBone Black itself # and not for cross-compiling +# set the project to be compiled by calling: make all PROJECT=<project_name> + +# if the PROJECT variable is not set, throw an error and exit +# otherwise, we could have unexpected data loss when calling clean without it +ifndef PROJECT + $(error PROJECT is not set) +endif + +PROJECT_DIR := $(abspath projects/$(PROJECT)) +$(shell mkdir -p $(PROJECT_DIR)/build) RM := rm -rf STATIC_LIBS := ./libprussdrv.a ./libNE10.a -LIBS := -lrt -lnative -lxenomai -lsndfile +LIBS := -lrt -lnative -lxenomai -lsndfile + # refresh library cache and check if libpd is there TEST_LIBPD := $(shell ldconfig; ldconfig -p | grep "libpd\.so") ifeq ($(strip $(TEST_LIBPD)), ) @@ -43,19 +54,19 @@ C_FLAGS += --fast-math endif -INCLUDES := -I./source -I./include -I/usr/include/ne10 -I/usr/xenomai/include -I/usr/arm-linux-gnueabihf/include/xenomai/include -I/usr/arm-linux-gnueabihf/include/ne10 +INCLUDES := -I$(PROJECT_DIR) -I./include -I/usr/include/ne10 -I/usr/xenomai/include -I/usr/arm-linux-gnueabihf/include/xenomai/include -I/usr/arm-linux-gnueabihf/include/ne10 -ASM_SRCS := $(wildcard source/*.S) -ASM_OBJS := $(addprefix build/source/,$(notdir $(ASM_SRCS:.S=.o))) -ASM_DEPS := $(addprefix build/source/,$(notdir $(ASM_SRCS:.S=.d))) +ASM_SRCS := $(wildcard $(PROJECT_DIR)/*.S) +ASM_OBJS := $(addprefix $(PROJECT_DIR)/build/,$(notdir $(ASM_SRCS:.S=.o))) +ASM_DEPS := $(addprefix $(PROJECT_DIR)/build/,$(notdir $(ASM_SRCS:.S=.d))) -C_SRCS := $(wildcard source/*.c) -C_OBJS := $(addprefix build/source/,$(notdir $(C_SRCS:.c=.o))) -C_DEPS := $(addprefix build/source/,$(notdir $(C_SRCS:.c=.d))) +C_SRCS := $(wildcard $(PROJECT_DIR)/*.c) +C_OBJS := $(addprefix $(PROJECT_DIR)/build/,$(notdir $(C_SRCS:.c=.o))) +C_DEPS := $(addprefix $(PROJECT_DIR)/build/,$(notdir $(C_SRCS:.c=.d))) -CPP_SRCS := $(wildcard source/*.cpp) -CPP_OBJS := $(addprefix build/source/,$(notdir $(CPP_SRCS:.cpp=.o))) -CPP_DEPS := $(addprefix build/source/,$(notdir $(CPP_SRCS:.cpp=.d))) +CPP_SRCS := $(wildcard $(PROJECT_DIR)/*.cpp) +CPP_OBJS := $(addprefix $(PROJECT_DIR)/build/,$(notdir $(CPP_SRCS:.cpp=.o))) +CPP_DEPS := $(addprefix $(PROJECT_DIR)/build/,$(notdir $(CPP_SRCS:.cpp=.d))) # Core BeagleRT sources CORE_CPP_SRCS = $(filter-out core/default_main.cpp, $(wildcard core/*.cpp)) @@ -79,38 +90,38 @@ # syntax = check syntax syntax: SYNTAX_FLAG := -fsyntax-only -syntax: BeagleRT +syntax: SYNTAX # Rule for BeagleRT core C++ files build/core/%.o: ./core/%.cpp - @echo 'Building file: $<' - @echo 'Invoking: C++ Compiler' - $(CXX) $(SYNTAX_FLAG) $(INCLUDES) $(CPP_FLAGS) -Wall -c -fmessage-length=0 -U_FORTIFY_SOURCE -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" - @echo 'Finished building: $<' + @echo 'Building $(notdir $<)...' +# @echo 'Invoking: C++ Compiler' + @$(CXX) $(SYNTAX_FLAG) $(INCLUDES) $(CPP_FLAGS) -Wall -c -fmessage-length=0 -U_FORTIFY_SOURCE -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo ' ...done' @echo ' ' # Rule for user-supplied C++ files -build/source/%.o: ./source/%.cpp - @echo 'Building file: $<' - @echo 'Invoking: C++ Compiler' - $(CXX) $(SYNTAX_FLAG) $(INCLUDES) $(CPP_FLAGS) -Wall -c -fmessage-length=0 -U_FORTIFY_SOURCE -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" - @echo 'Finished building: $<' +$(PROJECT_DIR)/build/%.o: $(PROJECT_DIR)/%.cpp + @echo 'Building $(notdir $<)...' +# @echo 'Invoking: C++ Compiler' + @$(CXX) $(SYNTAX_FLAG) $(INCLUDES) $(CPP_FLAGS) -Wall -c -fmessage-length=0 -U_FORTIFY_SOURCE -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" + @echo ' ...done' @echo ' ' # Rule for user-supplied C files -build/source/%.o: ./source/%.c - @echo 'Building file: $<' - @echo 'Invoking: C Compiler' - $(CC) $(SYNTAX_FLAG) $(INCLUDES) $(C_FLAGS) -Wall -c -fmessage-length=0 -U_FORTIFY_SOURCE -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" -std=c99 - @echo 'Finished building: $<' +$(PROJECT_DIR)/build/%.o: $(PROJECT_DIR)/%.c + @echo 'Building $(notdir $<)...' +# @echo 'Invoking: C Compiler' + @$(CC) $(SYNTAX_FLAG) $(INCLUDES) $(C_FLAGS) -Wall -c -fmessage-length=0 -U_FORTIFY_SOURCE -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" -std=c99 + @echo ' ...done' @echo ' ' # Rule for user-supplied assembly files -build/source/%.o: ./source/%.S - @echo 'Building file: $<' - @echo 'Invoking: GCC Assembler' - as -o "$@" "$<" - @echo 'Finished building: $<' +$(PROJECT_DIR)/build/%.o: $(PROJECT_DIR)/%.S + @echo 'Building $(notdir $<)...' +# @echo 'Invoking: GCC Assembler' + @as -o "$@" "$<" + @echo ' ...done' @echo ' ' # This is a nasty kludge: we want to be able to optionally link in a default @@ -119,29 +130,33 @@ # we want to link in the default main file or not. The kludge is the mess of a shell script # line below. Surely there's a better way to do this? BeagleRT: $(CORE_OBJS) $(ASM_OBJS) $(C_OBJS) $(CPP_OBJS) $(STATIC_LIBS) - $(eval NEXT_TARGET := $(shell bash -c 'if [ `nm build/source/*.o | grep -w T | grep -w main | wc -l` == '0' ]; then echo "BeagleRT_with_main"; else echo "BeagleRT_without_main"; fi')) - $(MAKE) $(NEXT_TARGET) - @echo 'Finished building target: $@' - @echo ' ' -# $(MAKE) --no-print-directory post-build + $(eval NEXT_TARGET := $(shell bash -c 'if [ `nm $(PROJECT_DIR)/build/*.o | grep -w T | grep -w main | wc -l` == '0' ]; then echo "BeagleRT_with_main"; else echo "BeagleRT_without_main"; fi')) + @$(MAKE) $(NEXT_TARGET) +# @echo 'Finished building target: $@' +# @echo ' ' +# $(MAKE) --no-print-directory post-build # Rule for building BeagleRT including the default main file (no user-supplied main()) BeagleRT_with_main: $(CORE_OBJS) $(DEFAULT_MAIN_OBJS) $(ASM_OBJS) $(C_OBJS) $(CPP_OBJS) $(STATIC_LIBS) - @echo 'Building target: $@' - @echo 'Invoking: C++ Linker' - $(CXX) $(SYNTAX_FLAG) -L/usr/xenomai/lib -L/usr/arm-linux-gnueabihf/lib -L/usr/arm-linux-gnueabihf/lib/xenomai -L/usr/lib/arm-linux-gnueabihf -pthread -Wpointer-arith -o "BeagleRT" $(CORE_OBJS) $(DEFAULT_MAIN_OBJS) $(ASM_OBJS) $(C_OBJS) $(CPP_OBJS) $(STATIC_LIBS) $(LIBS) - + @echo 'Linking default main.cpp...' +# @echo 'Invoking: C++ Linker' + @$(CXX) $(SYNTAX_FLAG) -L/usr/xenomai/lib -L/usr/arm-linux-gnueabihf/lib -L/usr/arm-linux-gnueabihf/lib/xenomai -L/usr/lib/arm-linux-gnueabihf -pthread -Wpointer-arith -o "$(PROJECT_DIR)/$(PROJECT)" $(CORE_OBJS) $(DEFAULT_MAIN_OBJS) $(ASM_OBJS) $(C_OBJS) $(CPP_OBJS) $(STATIC_LIBS) $(LIBS) + @echo ' ...done' + # Rule for building BeagleRT without the default main file (user-supplied main()) BeagleRT_without_main: $(CORE_OBJS) $(ASM_OBJS) $(C_OBJS) $(CPP_OBJS) $(STATIC_LIBS) - @echo 'Building target: $@' - @echo 'Invoking: C++ Linker' - $(CXX) $(SYNTAX_FLAG) -L/usr/xenomai/lib -L/usr/arm-linux-gnueabihf/lib -L/usr/arm-linux-gnueabihf/lib/xenomai -L/usr/lib/arm-linux-gnueabihf -pthread -Wpointer-arith -o "BeagleRT" $(CORE_OBJS) $(ASM_OBJS) $(C_OBJS) $(CPP_OBJS) $(STATIC_LIBS) $(LIBS) + @echo 'Linking main.cpp from project...' +# @echo 'Invoking: C++ Linker' + @$(CXX) $(SYNTAX_FLAG) -L/usr/xenomai/lib -L/usr/arm-linux-gnueabihf/lib -L/usr/arm-linux-gnueabihf/lib/xenomai -L/usr/lib/arm-linux-gnueabihf -pthread -Wpointer-arith -o "$(PROJECT_DIR)/$(PROJECT)" $(CORE_OBJS) $(ASM_OBJS) $(C_OBJS) $(CPP_OBJS) $(STATIC_LIBS) $(LIBS) + @echo ' ...done' + +# Other Targets: +# This rule compiles c and c++ source files without output or linking +SYNTAX: $(C_OBJS) $(CPP_OBJS) -# Other Targets: - -# Remove the temporary user-supplied source, plus the objects built from them -sourceclean: - -$(RM) source/* build/source/* BeagleRT +# Remove the project's build objects & binary +projectclean: + -$(RM) $(PROJECT_DIR)/build/* $(PROJECT_DIR)/$(PROJECT) -@echo ' ' # Remove all the built objects, including the core BeagleRT objects @@ -150,12 +165,12 @@ -@echo ' ' # Remove only the user-generated objects -clean: - -$(RM) build/source/* BeagleRT - -@echo ' ' +#clean: +# -$(RM) build/source/* BeagleRT +# -@echo ' ' post-build: # Nothing to do here (for now) -.PHONY: all clean distclean sourceclean dependents debug +.PHONY: all clean distclean projectclean dependents debug .SECONDARY: post-build
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core/OSCClient.cpp Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 01:00:46 2016 +0100 +++ b/core/PRU.cpp Fri May 27 12:32:11 2016 +0100 @@ -37,8 +37,11 @@ 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 0x2000 // Length of McASP memory, in bytes +#define PRU_MEM_MCASP_LENGTH 0x1000 // Length of McASP memory, in bytes #define PRU_MEM_DAC_OFFSET 0x0 // Offset within PRU0 RAM #define PRU_MEM_DAC_LENGTH 0x2000 // Length of ADC+DAC memory, in bytes #define PRU_MEM_COMM_OFFSET 0x0 // Offset within PRU-SHARED RAM @@ -51,12 +54,13 @@ #define PRU_SHOULD_SYNC 3 #define PRU_SYNC_ADDRESS 4 #define PRU_SYNC_PIN_MASK 5 -#define PRU_LED_ADDRESS 6 -#define PRU_LED_PIN_MASK 7 -#define PRU_FRAME_COUNT 8 -#define PRU_USE_SPI 9 +#define PRU_LED_ADDRESS 6 +#define PRU_LED_PIN_MASK 7 +#define PRU_FRAME_COUNT 8 +#define PRU_USE_SPI 9 #define PRU_SPI_NUM_CHANNELS 10 -#define PRU_USE_DIGITAL 11 +#define PRU_USE_DIGITAL 11 +#define PRU_PRU_NUMBER 12 short int digitalPins[NUM_DIGITALS]={ GPIO_NO_BIT_0, @@ -332,6 +336,7 @@ pru_buffer_comm[PRU_SHOULD_SYNC] = 0; pru_buffer_comm[PRU_SYNC_ADDRESS] = 0; pru_buffer_comm[PRU_SYNC_PIN_MASK] = 0; + pru_buffer_comm[PRU_PRU_NUMBER] = pru_number; if(led_enabled) { pru_buffer_comm[PRU_LED_ADDRESS] = USERLED3_GPIO_BASE; pru_buffer_comm[PRU_LED_PIN_MASK] = USERLED3_PIN_MASK; @@ -643,6 +648,8 @@ // Set the test pin high xenomai_gpio[GPIO_CLEARDATAOUT] = TEST_PIN_MASK; } + + BeagleRT_autoScheduleAuxiliaryTasks(); // FIXME: TESTING!! // if(testCount > 100000)
--- a/core/RTAudio.cpp Fri May 27 01:00:46 2016 +0100 +++ b/core/RTAudio.cpp Fri May 27 12:32:11 2016 +0100 @@ -41,10 +41,14 @@ // can schedule typedef struct { RT_TASK task; + void (*argfunction)(void*); void (*function)(void); char *name; int priority; bool started; + bool hasArgs; + void* args; + bool autoSchedule; } InternalAuxiliaryTask; const char gRTAudioThreadName[] = "beaglert-audio"; @@ -291,7 +295,7 @@ // (equal or lower) priority. Audio priority is defined in BEAGLERT_AUDIO_PRIORITY; // priority should be generally be less than this. // Returns an (opaque) pointer to the created task on success; 0 on failure -AuxiliaryTask BeagleRT_createAuxiliaryTask(void (*functionToCall)(void), int priority, const char *name) +AuxiliaryTask BeagleRT_createAuxiliaryTask(void (*functionToCall)(void* args), int priority, const char *name, void* args, bool autoSchedule) { InternalAuxiliaryTask *newTask = (InternalAuxiliaryTask*)malloc(sizeof(InternalAuxiliaryTask)); @@ -303,15 +307,41 @@ } // Populate the rest of the data structure and store it in the vector - newTask->function = functionToCall; + newTask->argfunction = functionToCall; newTask->name = strdup(name); newTask->priority = priority; newTask->started = false; - + newTask->args = args; + newTask->hasArgs = true; + newTask->autoSchedule = autoSchedule; + getAuxTasks().push_back(newTask); return (AuxiliaryTask)newTask; } +AuxiliaryTask BeagleRT_createAuxiliaryTask(void (*functionToCall)(void), int priority, const char *name, bool autoSchedule) +{ + InternalAuxiliaryTask *newTask = (InternalAuxiliaryTask*)malloc(sizeof(InternalAuxiliaryTask)); + + // Attempt to create the task + if(rt_task_create(&(newTask->task), name, 0, priority, T_JOINABLE | T_FPU)) { + cout << "Error: unable to create auxiliary task " << name << endl; + free(newTask); + return 0; + } + + // Populate the rest of the data structure and store it in the vector + newTask->function = functionToCall; + newTask->name = strdup(name); + newTask->priority = priority; + newTask->started = false; + newTask->hasArgs = false; + newTask->autoSchedule = autoSchedule; + + getAuxTasks().push_back(newTask); + + return (AuxiliaryTask)newTask; +} // Schedule a previously created (and started) auxiliary task. It will run when the priority rules next // allow it to be scheduled. @@ -324,22 +354,38 @@ } rt_task_resume(&taskToSchedule->task); } +void BeagleRT_autoScheduleAuxiliaryTasks(){ + vector<InternalAuxiliaryTask*>::iterator it; + for(it = getAuxTasks().begin(); it != getAuxTasks().end(); it++) { + if ((InternalAuxiliaryTask *)(*it)->autoSchedule){ + BeagleRT_scheduleAuxiliaryTask(*it); + } + } +} // Calculation loop that can be used for other tasks running at a lower // priority than the audio thread. Simple wrapper for Xenomai calls. // Treat the argument as containing the task structure void auxiliaryTaskLoop(void *taskStruct) { + InternalAuxiliaryTask *task = ((InternalAuxiliaryTask *)taskStruct); + // Get function to call from the argument - void (*auxiliary_function)(void) = ((InternalAuxiliaryTask *)taskStruct)->function; - const char *name = ((InternalAuxiliaryTask *)taskStruct)->name; + void (*auxiliary_argfunction)(void* args) = task->argfunction; + void (*auxiliary_function)(void) = task->function; + + // get the task's name + const char *name = task->name; // Wait for a notification rt_task_suspend(NULL); while(!gShouldStop) { // Then run the calculations - auxiliary_function(); + if (task->hasArgs) + auxiliary_argfunction(task->args); + else + auxiliary_function(); // Wait for a notification rt_task_suspend(NULL);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core/Scope.cpp Fri May 27 12:32:11 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); + } + } +}
--- a/core/UdpClient.cpp Fri May 27 01:00:46 2016 +0100 +++ b/core/UdpClient.cpp Fri May 27 12:32:11 2016 +0100 @@ -8,6 +8,9 @@ UdpClient::UdpClient(){ outSocket=socket(AF_INET, SOCK_DGRAM, 0); + int broadcastEnable = 1; + int ret = setsockopt(outSocket, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable)); + printf("setsockopt returned %d\n", ret); isSetPort=false; isSetServer=false; enabled=false; @@ -74,4 +77,4 @@ stTimeOut.tv_usec=(int)(timeOutSecs*1000000); int descriptorReady= select(outSocket+1, NULL, &stWriteFDS, NULL, &stTimeOut); return descriptorReady>0? 1 : descriptorReady; - } \ No newline at end of file + }
--- a/include/BeagleRT.h Fri May 27 01:00:46 2016 +0100 +++ b/include/BeagleRT.h Fri May 27 12:32:11 2016 +0100 @@ -579,7 +579,8 @@ * \param priority Xenomai priority level at which the task should run. * \param name Name for this task, which should be unique system-wide (no other running program should use this name). */ -AuxiliaryTask BeagleRT_createAuxiliaryTask(void (*functionToCall)(void), int priority, const char *name); +AuxiliaryTask BeagleRT_createAuxiliaryTask(void (*functionToCall)(void*), int priority, const char *name, void* args, bool autoSchedule = false); +AuxiliaryTask BeagleRT_createAuxiliaryTask(void (*functionToCall)(void), int priority, const char *name, bool autoSchedule = false); /** * \brief Start an auxiliary task so that it can be run. @@ -608,6 +609,7 @@ * \param task Task to schedule for running. */ void BeagleRT_scheduleAuxiliaryTask(AuxiliaryTask task); +void BeagleRT_autoScheduleAuxiliaryTasks(); /** @} */ #include <Utilities.h>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/include/OSCClient.h Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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
--- a/include/pru_rtaudio_bin.h Fri May 27 01:00:46 2016 +0100 +++ b/include/pru_rtaudio_bin.h Fri May 27 12:32:11 2016 +0100 @@ -275,20 +275,24 @@ 0xe1006287, 0xe1006384, 0x209c0000, - 0x240002c3, - 0x24202083, - 0x240000e2, - 0xe1002382, - 0x240002c3, - 0x24202883, - 0x240120e2, - 0xe1002382, 0x240001d9, 0x24000099, 0x244803da, 0x2401009a, 0x244803dd, 0x2480009d, + 0x240002c0, + 0x24400080, + 0xf1303982, + 0x5101e203, + 0x240002c0, + 0x24200080, + 0x1320e0e3, + 0x240000e2, + 0xe1002382, + 0x1328e0e3, + 0x240120e2, + 0xe1002382, 0x91042480, 0x1d04e0e0, 0x81042480, @@ -630,7 +634,7 @@ 0x79000002, 0x0b10eee7, 0xf1c03d82, - 0xd500e29d, + 0xd500e299, 0xcf05e2fe, 0x10e7e7fb, 0x240208fc, @@ -693,7 +697,7 @@ 0x4902e904, 0x1101eafb, 0x6900fb08, - 0x2102b300, + 0x2102b700, 0x1103e1fb, 0x6900fb05, 0xf100269b,
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/7segment/render.cpp Fri May 27 12:32:11 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/basic/render.cpp Fri May 27 01:00:46 2016 +0100 +++ b/projects/basic/render.cpp Fri May 27 12:32:11 2016 +0100 @@ -27,11 +27,9 @@ (line 12). The sine tone is produced by incrementing the phase of a sin function on every audio frame. -The important thing to notice is the nested `for` loop structure. You will see -this in all Bela projects and in most digital audio applications. The first `for` -loop cycles through the audio frames, the second through each of the audio -channels (in this case left 0 and right 1). It is good to familiarise yourself -with this structure as it is fundamental to producing sound with the system. +In render() you'll see a nested for loop structure. You'll see this in all Bela projects. +The first for loop cycles through 'audioFrames', the second through 'audioChannels' (in this case left 0 and right 1). +It is good to familiarise yourself with this structure as it is fundamental to producing sound with the system. */
--- a/projects/basic_analog_input/render.cpp Fri May 27 01:00:46 2016 +0100 +++ b/projects/basic_analog_input/render.cpp Fri May 27 12:32:11 2016 +0100 @@ -26,6 +26,10 @@ (line 55); we adjust these values by taking in data from analog sensors (for example, a potentiometer). +- connect a 10K pot to 3.3V and GND on its 1st and 3rd pins. +- connect the 2nd middle pin of the pot to analogIn 0. +- connect another 10K pot in the same way but with the middle pin connected to analogIn 1. + The important thing to notice is that audio is sampled twice as often as analog data. The audio sampling rate is 44.1kHz (44100 frames per second) and the analog sampling rate is 22.05kHz (22050 frames per second). On line 62 you might
--- a/projects/basic_analog_output/render.cpp Fri May 27 01:00:46 2016 +0100 +++ b/projects/basic_analog_output/render.cpp Fri May 27 12:32:11 2016 +0100 @@ -23,13 +23,15 @@ connected to the eight analog out pins. Again you can see the nested `for` loop structure but this time for the analog output channels rather than the audio. -Within the first `for` loop in render we cycle through each frame in the analog +- connect an LED in series with a 470ohm resistor between each of the analogOut pins and ground. + +Within the first for loop in render we cycle through each frame in the analog output matrix. At each frame we then cycle through the analog output channels -with another `for` loop and set the output voltage according to the phase of a +with another for loop and set the output voltage according to the phase of a sine tone that acts as an LFO. The analog output pins can provide a voltage of ~4.092V. -The output on each pin is set with `analogWriteFrame` within the `for` loop that +The output on each pin is set with `analogWriteFrame()` within the for loop that cycles through the analog output channels. This needs to be provided with arguments as follows `analogWriteFrame(context, n, channel, out)`. Channel is where the you give the address of the analog output pin (in this case we cycle
--- a/projects/basic_blink/render.cpp Fri May 27 01:00:46 2016 +0100 +++ b/projects/basic_blink/render.cpp Fri May 27 12:32:11 2016 +0100 @@ -19,15 +19,17 @@ Blinking an LED --------------- -This sketch shows the simplest case of digital out. Connect an LED in series with -a 470ohm resistor between P8_07 and ground. The led is blinked on and off by -setting the digital pin `HIGH` and `LOW` every interval seconds (set it in the -`render()` function). +This sketch shows the simplest case of digital out. -Firstly the pin mode must be set to output mode: -`pinModeFrame(context, 0, P8_07, OUTPUT);` in the `setup()` function. The output -of the digital pins is set by the following code: -`digitalWriteFrame(context, n, P8_07, status);` where status can be equal to +- Connect an LED in series with a 470ohm resistor between P8_07 and ground. + +The led is blinked on and off by setting the digital pin `HIGH` and `LOW` every interval seconds which is set in +`render()`. + +In `setup()` the pin mode must be set to output mode via `pinModeFrame()`. For example: +`pinModeFrame(context, 0, P8_07, OUTPUT)`. +In `render()` the output of the digital pins is set by `digitalWriteFrame()`. For example: +`digitalWriteFrame(context, n, P8_07, status)` where `status` can be equal to either `HIGH` or `LOW`. When set `HIGH` the pin will give 3.3V, when set to `LOW` 0V.
--- a/projects/basic_button/render.cpp Fri May 27 01:00:46 2016 +0100 +++ b/projects/basic_button/render.cpp Fri May 27 12:32:11 2016 +0100 @@ -19,7 +19,7 @@ Switching an LED on and off --------------------------- -This sketch brings together digital out with digital in. The program will read +This example brings together digital input and digital output. The program will read a button and turn the LED on and off according to the state of the button. - connect an LED in series with a 470ohm resistor between P8_07 and ground. @@ -34,7 +34,7 @@ the button is pressed, P8_08 goes `LOW` and P8_07 is set to `LOW`, turning off the LED. As an exercise try and change the code so that the LED only turns on when -the button is pressed +the button is pressed. */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/basic_libpd/_main.pd Fri May 27 12:32:11 2016 +0100 @@ -0,0 +1,541 @@ +#N canvas 1575 774 1307 981 10; +#X text 425 48 ├┴┐├┤-├─┤│-┬│--├┤-╠╦╝-║- +; +#X text 425 36 ┌┐-┌─┐┌─┐┌─┐┬--┌─┐╦═╗╔╦╗ +; +#X text 425 57 └─┘└─┘┴-┴└─┘┴─┘└─┘╩╚═-╩- +; +#X text 474 76 powered by heavy; +#X text 420 68 -------------------------; +#X text 461 101 http://beaglert.cc; +#X text 172 61 ============; +#X obj 298 606 phasor~ 5; +#X obj 207 284 samphold~; +#X obj 207 259 noise~; +#X obj 288 276 phasor~ 10; +#N canvas 0 22 143 172 >~ 0; +#X obj 18 -59 -~; +#X obj 18 -80 min~; +#X obj 18 4 *~ 1e+37; +#X obj 18 -17 +~ 1e-37; +#X obj 18 -38 clip~ -1e-37 0; +#X obj 18 -105 inlet~; +#X obj 61 -105 inlet~; +#X obj 18 26 outlet~; +#X connect 0 0 4 0; +#X connect 1 0 0 0; +#X connect 2 0 7 0; +#X connect 3 0 2 0; +#X connect 4 0 3 0; +#X connect 5 0 1 0; +#X connect 6 0 0 1; +#X connect 6 0 1 1; +#X restore 298 636 pd >~; +#X obj 299 730 dac~; +#X obj 211 313 *~ 0.5; +#X obj 211 335 +~ 0.5; +#X obj 211 357 *~ 1000; +#X obj 298 666 vcf~ 10; +#X obj 344 418 wrap~; +#X obj 293 433 -~; +#N canvas 0 22 450 278 (subpatch) 0; +#X array midi 127 float 3; +#A 0 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 +51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 +51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 +51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 +51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 +51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 51.435 +51.435 50.8 50.8 50.8 50.8 50.8 50.8 50.8 50.8 50.8 50.165 50.165 50.165 +50.165 50.165 50.165 50.165 50.165 50.165 50.165 50.165 50.165 50.165 +50.165 50.165 50.165 50.165 50.165 50.165 50.165 50.165 50.165 50.165 +50.165 50.165 50.165 50.165 50.165 49.53 49.53 49.53 49.53 49.53 48.26 +48.26 48.26 48.26 47.625 47.9425 48.26 48.26 48.26 48.26 48.26 48.26 +48.26 48.26 48.26 48.26 48.26 48.26 48.26 48.26 48.26 48.26 48.26 48.26 +47.625; +#X coords 0 0 127 127 200 200 1 0 0; +#X restore 836 39 graph; +#X obj 293 479 tabread~ midi; +#X obj 326 513 wrap~; +#X obj 307 536 -~; +#X obj 294 364 *~ 127; +#X obj 294 386 +~ 0; +#X obj 420 202 sig~; +#X obj 420 359 wrap~; +#N canvas 0 22 450 300 <~ 0; +#X obj 24 -60 -~; +#X obj 24 10 +~ 1e-37; +#X obj 24 -11 clip~ -1e-37 0; +#X obj 24 -105 inlet~; +#X obj 68 -104 inlet~; +#X obj 24 -81 max~; +#X obj 24 -36 *~ -1; +#X obj 24 62 outlet~; +#X obj 24 31 *~ 1e+37; +#X connect 0 0 6 0; +#X connect 1 0 8 0; +#X connect 2 0 1 0; +#X connect 3 0 5 0; +#X connect 4 0 0 1; +#X connect 4 0 5 1; +#X connect 5 0 0 0; +#X connect 6 0 2 0; +#X connect 8 0 7 0; +#X restore 448 428 pd <~; +#X obj 473 400 sig~ 0.5; +#X obj 298 578 mtof~; +#X obj 391 579 +~; +#X obj 415 545 *~ 1; +#X obj 709 408 wrap~; +#N canvas 0 22 450 300 <~ 0; +#X obj 24 -60 -~; +#X obj 24 10 +~ 1e-37; +#X obj 24 -11 clip~ -1e-37 0; +#X obj 24 -105 inlet~; +#X obj 68 -104 inlet~; +#X obj 24 -81 max~; +#X obj 24 -36 *~ -1; +#X obj 24 62 outlet~; +#X obj 24 31 *~ 1e+37; +#X connect 0 0 6 0; +#X connect 1 0 8 0; +#X connect 2 0 1 0; +#X connect 3 0 5 0; +#X connect 4 0 0 1; +#X connect 4 0 5 1; +#X connect 5 0 0 0; +#X connect 6 0 2 0; +#X connect 8 0 7 0; +#X restore 709 460 pd <~; +#X obj 734 432 sig~ 0.5; +#X obj 723 499 rzero~ 1; +#X obj 548 196 phasor~ 10; +#X obj 421 264 /~ 44100; +#N canvas 0 22 450 300 <~ 0; +#X obj 24 -60 -~; +#X obj 24 10 +~ 1e-37; +#X obj 24 -11 clip~ -1e-37 0; +#X obj 24 -105 inlet~; +#X obj 68 -104 inlet~; +#X obj 24 -81 max~; +#X obj 24 -36 *~ -1; +#X obj 24 62 outlet~; +#X obj 24 31 *~ 1e+37; +#X connect 0 0 6 0; +#X connect 1 0 8 0; +#X connect 2 0 1 0; +#X connect 3 0 5 0; +#X connect 4 0 0 1; +#X connect 4 0 5 1; +#X connect 5 0 0 0; +#X connect 6 0 2 0; +#X connect 8 0 7 0; +#X restore 564 254 pd <~; +#X msg 340 137 0; +#X obj 420 329 /~ 128; +#X obj 699 642 /~ 44100; +#X obj 698 669 rpole~ 1; +#X obj 725 549 *~ -1; +#X obj 725 571 +~ 1; +#X obj 698 692 +~ 1; +#X obj 723 521 abs~; +#X obj 706 744 *~; +#X obj 697 613 sig~ -10; +#X obj 699 715 clip~ 0 1; +#X obj 705 816 osc~; +#X obj 705 880 dac~; +#X obj 705 794 *~ 400; +#X obj 421 291 rpole~ 1; +#X obj 589 226 sig~ 0.999; +#X obj 437 225 /~ 128; +#X text 759 820 kick; +#X obj 810 429 wrap~; +#N canvas 0 22 450 300 <~ 0; +#X obj 24 -60 -~; +#X obj 24 10 +~ 1e-37; +#X obj 24 -11 clip~ -1e-37 0; +#X obj 24 -105 inlet~; +#X obj 68 -104 inlet~; +#X obj 24 -81 max~; +#X obj 24 -36 *~ -1; +#X obj 24 62 outlet~; +#X obj 24 31 *~ 1e+37; +#X connect 0 0 6 0; +#X connect 1 0 8 0; +#X connect 2 0 1 0; +#X connect 3 0 5 0; +#X connect 4 0 0 1; +#X connect 4 0 5 1; +#X connect 5 0 0 0; +#X connect 6 0 2 0; +#X connect 8 0 7 0; +#X restore 810 480 pd <~; +#X obj 835 452 sig~ 0.5; +#X obj 824 519 rzero~ 1; +#X obj 800 662 /~ 44100; +#X obj 799 689 rpole~ 1; +#X obj 826 569 *~ -1; +#X obj 826 591 +~ 1; +#X obj 799 712 +~ 1; +#X obj 824 541 abs~; +#X obj 798 633 sig~ -10; +#X obj 800 735 clip~ 0 1; +#X obj 802 904 dac~; +#X obj 843 771 noise~; +#X obj 801 791 *~; +#X obj 800 765 *~; +#X obj 810 403 +~ 0.25; +#X obj 922 666 samphold~; +#X obj 922 645 noise~; +#X obj 909 432 wrap~; +#N canvas 0 22 450 300 <~ 0; +#X obj 24 -60 -~; +#X obj 24 10 +~ 1e-37; +#X obj 24 -11 clip~ -1e-37 0; +#X obj 24 -105 inlet~; +#X obj 68 -104 inlet~; +#X obj 24 -81 max~; +#X obj 24 -36 *~ -1; +#X obj 24 62 outlet~; +#X obj 24 31 *~ 1e+37; +#X connect 0 0 6 0; +#X connect 1 0 8 0; +#X connect 2 0 1 0; +#X connect 3 0 5 0; +#X connect 4 0 0 1; +#X connect 4 0 5 1; +#X connect 5 0 0 0; +#X connect 6 0 2 0; +#X connect 8 0 7 0; +#X restore 909 483 pd <~; +#X obj 934 455 sig~ 0.5; +#X obj 923 522 rzero~ 1; +#X obj 925 572 *~ -1; +#X obj 925 594 +~ 1; +#X obj 923 544 abs~; +#X obj 909 406 +~ 0.25; +#X obj 957 754 wrap~; +#X obj 922 778 -~; +#X obj 922 688 *~ 0.5; +#X obj 922 710 +~ 0.5; +#X obj 919 853 /~; +#X obj 922 800 +~ 1; +#X obj 810 376 /~; +#X obj 1025 663 samphold~; +#X obj 1025 642 noise~; +#X obj 1060 751 wrap~; +#X obj 1025 775 -~; +#X obj 1025 685 *~ 0.5; +#X obj 1025 707 +~ 0.5; +#X obj 1022 850 /~; +#X obj 1025 797 +~ 1; +#X obj 709 376 /~; +#X obj 922 732 *~ 2; +#X obj 919 831 sig~ 8; +#X obj 298 688 *~ 0.5; +#X text 858 864 hh; +#X obj 1022 828 sig~ 8; +#X obj 606 418 wrap~; +#N canvas 0 22 450 300 <~ 0; +#X obj 24 -60 -~; +#X obj 24 10 +~ 1e-37; +#X obj 24 -11 clip~ -1e-37 0; +#X obj 24 -105 inlet~; +#X obj 68 -104 inlet~; +#X obj 24 -81 max~; +#X obj 24 -36 *~ -1; +#X obj 24 62 outlet~; +#X obj 24 31 *~ 1e+37; +#X connect 0 0 6 0; +#X connect 1 0 8 0; +#X connect 2 0 1 0; +#X connect 3 0 5 0; +#X connect 4 0 0 1; +#X connect 4 0 5 1; +#X connect 5 0 0 0; +#X connect 6 0 2 0; +#X connect 8 0 7 0; +#X restore 606 470 pd <~; +#X obj 631 442 sig~ 0.5; +#X obj 620 494 rzero~ 1; +#X obj 596 637 /~ 44100; +#X obj 595 664 rpole~ 1; +#X obj 622 544 *~ -1; +#X obj 622 566 +~ 1; +#X obj 595 687 +~ 1; +#X obj 620 516 abs~; +#X obj 594 608 sig~ -10; +#X obj 596 710 clip~ 0 1; +#X obj 602 811 osc~; +#X obj 602 875 dac~; +#X obj 606 393 +~ 0.25; +#X obj 551 781 noise~; +#X obj 509 801 *~; +#X obj 9 664 osc~; +#X obj 57 455 -~; +#X obj 91 437 wrap~; +#X obj 10 530 tabread~ midi; +#X obj 9 797 dac~; +#X obj 11 621 mtof~; +#X obj 55 383 phasor~ 10; +#X obj 57 416 *~ 127; +#X obj 424 579 s~ midimod1; +#X obj 148 650 osc~; +#X obj 149 516 tabread~ midi; +#X obj 125 789 dac~; +#X obj 150 607 mtof~; +#X obj 151 436 wrap~; +#X obj 152 497 -~; +#X obj 186 479 wrap~; +#X obj 151 414 +~ 0.75; +#X obj 56 345 /~ 8; +#X obj 11 589 +~; +#X obj 148 574 +~; +#X obj 56 557 r~ midimod1; +#X obj 6 699 *~ 0.1; +#X obj 145 685 *~ 0.1; +#X obj 679 206 sig~ 1; +#X obj 679 228 /~; +#X obj 679 250 s~ period; +#X msg 219 150 1 \$1; +#X obj 219 172 /; +#X obj 219 194 s _period; +#X obj 152 458 *~ 122; +#X obj 287 79 loadbang; +#X obj 382 670 delread~ _del 100; +#X obj 382 773 delwrite~ _del 500; +#X obj 382 616 r _period; +#X obj 382 638 * 4000; +#X obj 382 692 lop~ 1000; +#X obj 382 713 *~ 0.85; +#X text 656 815 snr; +#X text 172 51 techno world!; +#X obj 965 500 sig~ 1; +#X obj 148 552 +~ 12; +#X obj 11 567 +~ 12; +#X msg 287 101 11; +#X obj 1107 662 samphold~; +#X obj 1107 641 noise~; +#X obj 1142 750 wrap~; +#X obj 1107 774 -~; +#X obj 1107 684 *~ 0.5; +#X obj 1107 706 +~ 0.5; +#X obj 1104 849 /~; +#X obj 1107 796 +~ 1; +#X obj 606 371 /~; +#X obj 909 379 /~ 8; +#X obj 1107 728 *~ 2; +#X obj 1025 729 *~ 1; +#X obj 1104 827 sig~ 16; +#X obj 801 813 hip~ 18000; +#X obj 802 837 bp~ 12000 10; +#X obj 509 823 hip~ 1000; +#X obj 603 739 *~ 1; +#X obj 602 789 *~ 300; +#X obj 602 833 *~ 0.1; +#X obj 802 862 *~ 0.1; +#X obj 705 838 *~ 0.333; +#X connect 7 0 11 0; +#X connect 8 0 13 0; +#X connect 9 0 8 0; +#X connect 10 0 8 1; +#X connect 11 0 16 0; +#X connect 13 0 14 0; +#X connect 14 0 11 1; +#X connect 14 0 15 0; +#X connect 14 0 23 0; +#X connect 15 0 16 1; +#X connect 16 0 102 0; +#X connect 16 0 154 0; +#X connect 17 0 18 1; +#X connect 18 0 20 0; +#X connect 20 0 21 0; +#X connect 20 0 22 0; +#X connect 21 0 22 1; +#X connect 22 0 30 0; +#X connect 23 0 24 0; +#X connect 24 0 17 0; +#X connect 24 0 18 0; +#X connect 25 0 37 0; +#X connect 25 0 55 0; +#X connect 25 0 139 0; +#X connect 25 0 146 1; +#X connect 26 0 27 0; +#X connect 27 0 31 0; +#X connect 28 0 27 1; +#X connect 29 0 7 0; +#X connect 30 0 29 0; +#X connect 31 0 30 1; +#X connect 31 0 130 0; +#X connect 32 0 33 0; +#X connect 33 0 35 0; +#X connect 34 0 33 1; +#X connect 35 0 46 0; +#X connect 36 0 38 0; +#X connect 37 0 53 0; +#X connect 38 0 53 1; +#X connect 39 0 10 1; +#X connect 39 0 36 1; +#X connect 39 0 128 1; +#X connect 40 0 26 0; +#X connect 41 0 42 0; +#X connect 42 0 45 0; +#X connect 43 0 44 0; +#X connect 44 0 42 1; +#X connect 45 0 49 0; +#X connect 46 0 43 0; +#X connect 47 0 52 0; +#X connect 48 0 41 0; +#X connect 49 0 47 1; +#X connect 49 0 47 0; +#X connect 50 0 185 0; +#X connect 52 0 50 0; +#X connect 53 0 40 0; +#X connect 53 0 90 0; +#X connect 53 0 99 0; +#X connect 53 0 173 0; +#X connect 53 0 174 0; +#X connect 54 0 38 1; +#X connect 55 0 36 0; +#X connect 57 0 58 0; +#X connect 58 0 60 0; +#X connect 59 0 58 1; +#X connect 60 0 66 0; +#X connect 61 0 62 0; +#X connect 62 0 65 0; +#X connect 63 0 64 0; +#X connect 64 0 62 1; +#X connect 65 0 68 0; +#X connect 66 0 63 0; +#X connect 67 0 61 0; +#X connect 68 0 72 0; +#X connect 68 0 72 1; +#X connect 70 0 71 1; +#X connect 71 0 178 0; +#X connect 72 0 71 0; +#X connect 73 0 57 0; +#X connect 74 0 86 0; +#X connect 75 0 74 0; +#X connect 76 0 77 0; +#X connect 77 0 79 0; +#X connect 78 0 77 1; +#X connect 79 0 82 0; +#X connect 80 0 81 0; +#X connect 81 0 74 1; +#X connect 81 0 91 1; +#X connect 81 0 165 1; +#X connect 82 0 80 0; +#X connect 83 0 76 0; +#X connect 84 0 85 1; +#X connect 85 0 89 0; +#X connect 86 0 87 0; +#X connect 87 0 100 0; +#X connect 88 0 90 1; +#X connect 89 0 88 1; +#X connect 90 0 73 0; +#X connect 91 0 95 0; +#X connect 92 0 91 0; +#X connect 93 0 94 1; +#X connect 94 0 98 0; +#X connect 95 0 96 0; +#X connect 96 0 176 0; +#X connect 97 0 99 1; +#X connect 98 0 97 1; +#X connect 99 0 32 0; +#X connect 100 0 84 0; +#X connect 100 0 85 0; +#X connect 101 0 88 0; +#X connect 102 0 12 0; +#X connect 102 0 12 1; +#X connect 104 0 97 0; +#X connect 105 0 106 0; +#X connect 106 0 108 0; +#X connect 107 0 106 1; +#X connect 108 0 114 0; +#X connect 109 0 110 0; +#X connect 110 0 113 0; +#X connect 111 0 112 0; +#X connect 112 0 110 1; +#X connect 113 0 116 0; +#X connect 114 0 111 0; +#X connect 115 0 109 0; +#X connect 116 0 181 0; +#X connect 117 0 183 0; +#X connect 119 0 105 0; +#X connect 120 0 121 1; +#X connect 121 0 180 0; +#X connect 122 0 143 0; +#X connect 123 0 125 0; +#X connect 124 0 123 1; +#X connect 125 0 163 0; +#X connect 127 0 122 0; +#X connect 128 0 129 0; +#X connect 128 0 138 0; +#X connect 129 0 123 0; +#X connect 129 0 124 0; +#X connect 131 0 144 0; +#X connect 132 0 162 0; +#X connect 134 0 131 0; +#X connect 135 0 151 0; +#X connect 136 0 132 0; +#X connect 137 0 136 1; +#X connect 138 0 135 0; +#X connect 139 0 128 0; +#X connect 140 0 127 0; +#X connect 141 0 134 0; +#X connect 142 0 140 1; +#X connect 142 0 141 1; +#X connect 143 0 126 0; +#X connect 143 0 126 1; +#X connect 144 0 133 0; +#X connect 144 0 133 1; +#X connect 145 0 146 0; +#X connect 146 0 147 0; +#X connect 148 0 149 0; +#X connect 149 0 150 0; +#X connect 151 0 136 0; +#X connect 151 0 137 0; +#X connect 152 0 164 0; +#X connect 152 0 39 0; +#X connect 153 0 157 0; +#X connect 155 0 156 0; +#X connect 156 0 153 0; +#X connect 157 0 158 0; +#X connect 158 0 154 0; +#X connect 158 0 102 0; +#X connect 161 0 79 1; +#X connect 161 0 60 1; +#X connect 161 0 35 1; +#X connect 161 0 108 1; +#X connect 162 0 141 0; +#X connect 163 0 140 0; +#X connect 164 0 148 0; +#X connect 164 0 10 0; +#X connect 164 0 25 0; +#X connect 165 0 169 0; +#X connect 166 0 165 0; +#X connect 167 0 168 1; +#X connect 168 0 172 0; +#X connect 169 0 170 0; +#X connect 170 0 175 0; +#X connect 171 0 173 1; +#X connect 172 0 171 1; +#X connect 173 0 119 0; +#X connect 174 0 83 0; +#X connect 175 0 167 0; +#X connect 175 0 168 0; +#X connect 176 0 93 0; +#X connect 176 0 94 0; +#X connect 177 0 171 0; +#X connect 178 0 179 0; +#X connect 179 0 184 0; +#X connect 180 0 183 0; +#X connect 181 0 121 0; +#X connect 181 0 182 0; +#X connect 182 0 117 0; +#X connect 183 0 118 0; +#X connect 183 0 118 1; +#X connect 184 0 69 0; +#X connect 184 0 69 1; +#X connect 185 0 51 0; +#X connect 185 0 51 1;
--- a/projects/basic_passthru/render.cpp Fri May 27 01:00:46 2016 +0100 +++ b/projects/basic_passthru/render.cpp Fri May 27 12:32:11 2016 +0100 @@ -15,29 +15,54 @@ */ /** -\example 1_basic_audio_passthrough +\example 1_basic_audio_analog_passthrough -Audio passthrough: input to output +Audio and analog passthrough: input to output ----------------------------------------- -This sketch demonstrates the simplest possible case of using audio: it passes -audio input straight to audio output. +This sketch demonstrates how to read from and write to the audio and analog input and output buffers. -Note the nested `for` loop structure. You will see this in all Bela projects. The -first `for` loop cycles through the audio frames, the second through each of the -audio channels (in this case left 0 and right 1). +In `render()` you'll see a nested for loop structure. You'll see this in all Bela projects. +The first for loop cycles through `audioFrames`, the second through +`audioChannels` (in this case left 0 and right 1). +You can access any information about current audio and sensor settings you can do the following: +`context->name_of_item`. For example `context->audioChannels` returns current number of channels, +`context->audioFrames` returns the current number of audio frames, +`context->audioSampleRate` returns the audio sample rate. -We write samples to the audio output buffer like this: -`context->audioOut[n * context->audioChannels + ch]` where `n` is the current audio -frame and `ch` is the current channel, both provided by the nested for loop structure. +You can look at all the information you can access in ::BeagleRTContext. -We can access samples in the audio input buffer in a similar way, like this: -`context->audioIn[n * context->audioChannels + ch]`. +Reading and writing from the audio buffers +------------------------------------------ -So a simple audio pass through is achieved by setting output buffer equal to -input buffer: -`context->audioOut[n * context->audioChannels + ch] = context->audioIn[n * context->audioChannels + ch]`. +The simplest way to read samples from the audio input buffer is with +`audioReadFrame()` which we pass three arguments context, current audio +frame and current channel. In this example we have +`audioReadFrame(context, n, ch)` where both `n` and `ch` are provided by +the nested for loop structure. + +We can write samples to the audio output buffer in a similar way using +`audioWriteFrame()`. This has a fourth argument which is the value of the output. +For example `audioWriteFrame(context, n, ch, value_to_output)`. + +Reading and writing from the analog buffers +------------------------------------------- + +The same is true for `analogReadFrame()` and `analogWriteFrame()`. + +Note that for the analog channels we write to and read from the buffers in a separate set +of nested for loops. This is because the they are sampled at half audio rate by default. +The first of these for loops cycles through `analogFrames`, the second through +`analogChannels`. + +By setting `audioWriteFrame(context, n, ch, audioReadFrame(context, n, ch))` and +`analogWriteFrame(context, n, ch, analogReadFrame(context, n, ch))` we have a simple +passthrough of audio input to output and analog input to output. + + +It is also possible to address the buffers directly like this: +`context->audioOut[n * context->audioChannels + ch]`. */ @@ -86,7 +111,7 @@ } } - // Same with analog channelss + // Same with analog channels for(unsigned int n = 0; n < context->analogFrames; n++) { for(unsigned int ch = 0; ch < context->analogChannels; ch++) { // Two equivalent ways to write this code
--- a/projects/cape_test/render.cpp Fri May 27 01:00:46 2016 +0100 +++ b/projects/cape_test/render.cpp Fri May 27 12:32:11 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/filter_FIR/render.cpp Fri May 27 01:00:46 2016 +0100 +++ b/projects/filter_FIR/render.cpp Fri May 27 12:32:11 2016 +0100 @@ -1,3 +1,12 @@ +/* + ____ _____ _ _ +| __ )| ____| | / \ +| _ \| _| | | / _ \ +| |_) | |___| |___ / ___ \ +|____/|_____|_____/_/ \_\.io + +*/ + /* * render.cpp * @@ -5,6 +14,16 @@ * Author: Andrew McPherson and Victor Zappi */ +/** +\example 4_filter_FIR + +Finite Impulse Response Filter +------------------------------ + +This is an example of a finite impulse response filter implementation. + +*/ + #include <BeagleRT.h> #include <cmath>
--- a/projects/filter_IIR/render.cpp Fri May 27 01:00:46 2016 +0100 +++ b/projects/filter_IIR/render.cpp Fri May 27 12:32:11 2016 +0100 @@ -1,3 +1,12 @@ +/* + ____ _____ _ _ +| __ )| ____| | / \ +| _ \| _| | | / _ \ +| |_) | |___| |___ / ___ \ +|____/|_____|_____/_/ \_\.io + +*/ + /* * render.cpp * @@ -5,6 +14,16 @@ * Author: Andrew McPherson and Victor Zappi */ +/** +\example 4_filter_IIR + +Infinite Impulse Response Filter +------------------------------ + +This is an example of a infinite impulse response filter implementation. + +*/ + #include <BeagleRT.h> // to schedule lower prio parallel process #include <rtdk.h>
--- a/projects/level_meter/render.cpp Fri May 27 01:00:46 2016 +0100 +++ b/projects/level_meter/render.cpp Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 2016 +0100 @@ -0,0 +1,97 @@ +/* + ____ _____ _ _ +| __ )| ____| | / \ +| _ \| _| | | / _ \ +| |_) | |___| |___ / ___ \ +|____/|_____|_____/_/ \_\.io + + */ + +/** +\example 5_osc + +Open Sound Control +------------------ + +This example shows an implementation of OSC (Open Sound Control) which was +developed at UC Berkeley Center for New Music and Audio Technology (CNMAT). + +It is designed to be run alongside resources/osc/osc.js + +The OSC server port on which to receive is set in `setup()` +via `oscServer.setup()`. Likewise the OSC client port on which to +send is set in `oscClient.setup()`. + +In `setup()` an OSC message to address `/osc-setup`, it then waits +1 second for a reply on `/osc-setup-reply`. + +in `render()` the code receives OSC messages, parses them, and sends +back an acknowledgment. + + +*/ + + +#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 Fri May 27 12:32:11 2016 +0100 @@ -0,0 +1,90 @@ +/* + ____ _____ _ _ +| __ )| ____| | / \ +| _ \| _| | | / _ \ +| |_) | |___| |___ / ___ \ +|____/|_____|_____/_/ \_\.io + + */ + +/** +\example 3_scope_analog + +Connecting potentiometers +------------------------- + +This example reads from analogue inputs 0 and 1 via `analogReadFrame()` and +generates a sine wave with amplitude and frequency determined by their values. +It's best to connect a 10K potentiometer to each of these analog inputs. Far +left and far right pins of the pot go to 3.3V and GND, the middle should be +connected to the analog in pins. + +The sine wave is then plotted on the oscilloscope. Click the Open Scope button to +view the results. As you turn the potentiometers you will see the amplitude and +frequency of the sine wave change. + +This project also shows as example of `map()` which allows you to re-scale a number +from one range to another. Note that `map()` does not constrain your variable +within the upper and lower limits. If you want to do this use the `constrain()` +function. + +*/ + + + + + +#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 Fri May 27 12:32:11 2016 +0100 @@ -0,0 +1,88 @@ +/* + ____ _____ _ _ +| __ )| ____| | / \ +| _ \| _| | | / _ \ +| |_) | |___| |___ / ___ \ +|____/|_____|_____/_/ \_\.io + + */ + +/** +\example 1_scope_basic + +Oscilloscope in-browser +----------------------- + +This example demonstrates the scope feature of the IDE. + +The scope is instantiated at the top of the file via `Scope scope;` + +In `setup()` we define how many channels the scope should have and the sample +rate that it should run at via `scope.setup(3, context->audioSampleRate)`. + +In `render()` we choose what the scope log via `scope.log(out, out2, out3)`. +In this example the scope is logging three sine waves with different phases. To see +the output click on the <b>Open Scope</b> button. + +An additional option is to set the trigger of the oscilloscope from within `render()`. +In this example we are triggering the scope when oscillator 1 becomes less than +oscillator 2 via `scope.trigger()`. Note that this functionality only takes effect +when the triggering mode is set to custom in the scope UI. + +*/ + + +#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 Fri May 27 12:32:11 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 Fri May 27 01:00:46 2016 +0100 +++ b/projects/tank_wars/game.cpp Fri May 27 12:32:11 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 Fri May 27 01:00:46 2016 +0100 +++ b/projects/tank_wars/game.h Fri May 27 12:32:11 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 Fri May 27 01:00:46 2016 +0100 +++ b/projects/tank_wars/main.cpp Fri May 27 12:32:11 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 Fri May 27 01:00:46 2016 +0100 +++ b/projects/tank_wars/render.cpp Fri May 27 12:32:11 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
--- a/pru_rtaudio.p Fri May 27 01:00:46 2016 +0100 +++ b/pru_rtaudio.p Fri May 27 12:32:11 2016 +0100 @@ -82,7 +82,8 @@ #define COMM_FRAME_COUNT 32 // How many frames have elapse since beginning #define COMM_USE_SPI 36 // Whether or not to use SPI ADC and DAC #define COMM_NUM_CHANNELS 40 // Low 2 bits indicate 8 [0x3], 4 [0x1] or 2 [0x0] channels -#define COMM_USE_DIGITAL 44 // Whether or not to use DIGITAL +#define COMM_USE_DIGITAL 44 // Whether or not to use DIGITAL +#define COMM_PRU_NUMBER 48 // Which PRU this code is running on #define MCASP0_BASE 0x48038000 #define MCASP1_BASE 0x4803C000 @@ -549,22 +550,30 @@ .endm START: + // Load useful registers for addressing SPI + MOV reg_comm_addr, SHARED_COMM_MEM_BASE + MOV reg_spi_addr, SPI_BASE + MOV reg_mcasp_addr, MCASP_BASE + + // Find out which PRU we are running on + // This affects the following offsets + MOV r0, 0x24000 // PRU1 control register offset + LBBO r2, reg_comm_addr, COMM_PRU_NUMBER, 4 + QBEQ PRU_NUMBER_CHECK_DONE, r2, 1 + MOV r0, 0x22000 // PRU0 control register offset +PRU_NUMBER_CHECK_DONE: + // Set up c24 and c25 offsets with CTBIR register // Thus C24 points to start of PRU0 RAM - MOV r3, 0x22020 // CTBIR0 + OR r3, r0, 0x20 // CTBIR0 MOV r2, 0 SBBO r2, r3, 0, 4 // Set up c28 pointer offset for shared PRU RAM - MOV r3, 0x22028 // CTPPR0 + OR r3, r0, 0x28 // CTPPR0 MOV r2, 0x00000120 // To get address 0x00012000 SBBO r2, r3, 0, 4 - // Load useful registers for addressing SPI - MOV reg_comm_addr, SHARED_COMM_MEM_BASE - MOV reg_spi_addr, SPI_BASE - MOV reg_mcasp_addr, MCASP_BASE - // Set ARM such that PRU can write to registers LBCO r0, C4, 4, 4 CLR r0, r0, 4
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/resources/BB-BONE-PRU-BELA-00A0.dts Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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 Fri May 27 12:32:11 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
--- a/scripts/build_project.sh Fri May 27 01:00:46 2016 +0100 +++ b/scripts/build_project.sh Fri May 27 12:32:11 2016 +0100 @@ -4,12 +4,16 @@ # optionally runs it. Pass a directory path in the first argument. # The source files in this directory are copied to the board and compiled. -BBB_ADDRESS="root@192.168.7.2" -BBB_PATH="~/BeagleRT" -RUN_PROJECT=1 -COMMAND_ARGS= -RUN_IN_FOREGROUND=0 -RUN_WITHOUT_SCREEN=0 +# set defaults unless variables are already set +[ -z "$BBB_ADDRESS" ] && BBB_ADDRESS="root@192.168.7.2" +[ -z "$BBB_BELA_HOME" ] && BBB_BELA_HOME="~/BeagleRT/" +[ -z "$BBB_SCREEN_NAME" ] && BBB_SCREEN_NAME="BeagleRT" +[ -z "$RUN_PROJECT" ] && RUN_PROJECT=1 +[ -z "$COMMAND_ARGS" ] && COMMAND_ARGS= +[ -z "$RUN_IN_FOREGROUND" ] && RUN_IN_FOREGROUND=1 +[ -z "$RUN_WITHOUT_SCREEN" ] && RUN_WITHOUT_SCREEN=0 +[ -z "$BBB_PROJECT_HOME" ] && BBB_PROJECT_HOME="${BBB_BELA_HOME}/projects/" +[ -z "$BBB_PROJECT_NAME" ] && BBB_PROJECT_NAME="scriptUploadedProject" function usage { @@ -26,23 +30,24 @@ BeagleRT files are found. The -c option passes command-line arguments to the BeagleRT program; enclose the argument string in quotes. - The -f argument runs the project in the foreground of the current terminal, + By default, the project runs in the foreground of the current terminal, within a screen session that can be detached later. The -F argument runs - the project in the foreground of the current terminal, without screen, so - the output can be piped to another destination." + the project in the foreground of the current terminal, without screen, so + the output can be piped to another destination. The -f argument runs it + in a screen in the background, so no output is shown." } OPTIND=1 while getopts "b:c:nfFh" opt; do case $opt in - b) BBB_PATH=$OPTARG + b) BBB_BELA_HOME=$OPTARG ;; c) COMMAND_ARGS=$OPTARG ;; - f) RUN_IN_FOREGROUND=1 + f) RUN_IN_FOREGROUND=0 ;; - F) RUN_WITHOUT_SCREEN=1 + F) RUN_WITHOUT_SCREEN=1 ;; n) RUN_PROJECT=0 ;; @@ -76,27 +81,35 @@ exit fi +BBB_PROJECT_FOLDER=$BBB_PROJECT_HOME"/"$BBB_PROJECT_NAME"/" +BBB_NETWORK_TARGET_FOLDER=$BBB_ADDRESS:$BBB_PROJECT_FOLDER + # Stop BeagleRT and clean out old source files -echo "Stopping BeagleRT and removing old source files..." -ssh -t -t $BBB_ADDRESS "screen -X -S BeagleRT quit &>/dev/null; pkill BeagleRT ; make sourceclean -C $BBB_PATH" +echo "Stopping running program..." +# sets the date, stops the running process +ssh $BBB_ADDRESS "date -s '`date`' > /dev/null; mkdir -p $BBB_PROJECT_FOLDER; screen -X -S '"$BBB_SCREEN_NAME"' quit &>/dev/null;" #concatenate arguments to form path. -BBB_SOURCE_PATH= #initially empty, will be filled with input arguments +HOST_SOURCE_PATH= #initially empty, will be filled with input arguments for i in "$@" #parse input arguments do - if [ -d "$1" ] #check if the path is a folder - then #if it is, include all of its files - BBB_SOURCE_PATH+=" ${1}/* " - else - BBB_SOURCE_PATH+=" $1 " - fi + HOST_SOURCE_PATH+=" $1 " shift # Copy new souce files to the board done # Copy new source files to the board echo "Copying new source files to BeagleBone..." -scp $BBB_SOURCE_PATH "$BBB_ADDRESS:$BBB_PATH/source/" +if [ -z `which rsync` ]; +then + #if rsync is not available, brutally clean the destination folder + #and copy over all the files again and recompile them + ssh bbb "make -C $BBB_BELA_HOME sourceclean PROJECT=$BBB_PROJECT_NAME"; + scp $HOST_SOURCE_PATH "$BBB_NETWORK_TARGET_FOLDER" +else + #rsync --delete makes sure it removes files that are not in the origin folder + rsync -av --delete-after --exclude=build $HOST_SOURCE_PATH "$BBB_NETWORK_TARGET_FOLDER" +fi; if [ $? -ne 0 ] then @@ -108,17 +121,17 @@ if [ $RUN_PROJECT -eq 0 ] then echo "Building project..." - ssh $BBB_ADDRESS "make all -C $BBB_PATH" + ssh $BBB_ADDRESS "make all -C $BBB_BELA_HOME PROJECT=$BBB_PROJECT_NAME" else echo "Building and running project..." if [ $RUN_WITHOUT_SCREEN -ne 0 ] then - ssh -t $BBB_ADDRESS "cd $BBB_PATH && make all && cd source && ../BeagleRT $COMMAND_ARGS" + ssh -t $BBB_ADDRESS "cd $BBB_BELA_HOME && make all && cd source && $BBB_PROJECT_FOLDER/$BBB_PROJECT_NAME $COMMAND_ARGS" elif [ $RUN_IN_FOREGROUND -eq 0 ] then - ssh $BBB_ADDRESS "cd $BBB_PATH && make all && cd source && screen -S BeagleRT -d -m ../BeagleRT $COMMAND_ARGS" + ssh $BBB_ADDRESS "cd $BBB_BELA_HOME && make all PROJECT=$BBB_PROJECT_NAME && cd source && screen -S $BBB_SCREEN_NAME -d -m $BBB_PROJECT_FOLDER/$BBB_PROJECT_NAME $COMMAND_ARGS" else - ssh -t $BBB_ADDRESS "cd $BBB_PATH && make all && cd source && screen -S BeagleRT ../BeagleRT $COMMAND_ARGS" + ssh -t $BBB_ADDRESS "cd $BBB_BELA_HOME && make all PROJECT=$BBB_PROJECT_NAME && cd source && screen -S $BBB_SCREEN_NAME $BBB_PROJECT_FOLDER/$BBB_PROJECT_NAME $COMMAND_ARGS" fi fi