From 9c78cf4329d109bf331f4479eb9f723ebf29748c Mon Sep 17 00:00:00 2001 From: Joel Wetzell Date: Thu, 3 Oct 2024 21:24:01 -0500 Subject: [PATCH] add address and type string decoding --- src/models.ts | 1 + src/osc.ts | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/models.ts b/src/models.ts index d58c04f..42c0ffc 100644 --- a/src/models.ts +++ b/src/models.ts @@ -12,4 +12,5 @@ export type OSCMessage = { export type OSCTypeConverter = { toBuffer: (value: string | number | Buffer | boolean) => Buffer | undefined; fromString: (string: string) => string | number | Buffer | boolean; + fromBuffer?: (buffer: Buffer) => [string | number | Buffer | boolean | undefined, Buffer]; }; diff --git a/src/osc.ts b/src/osc.ts index 60f741a..52a9934 100644 --- a/src/osc.ts +++ b/src/osc.ts @@ -14,6 +14,24 @@ const oscTypeConverterMap: { [key in OSCType]: OSCTypeConverter } = { throw new Error('osc type s toBuffer called with non string value'); }, fromString: (string: string) => string, + fromBuffer: (bytes: Buffer) => { + let stringEnd = 0; + let stringPaddingEnd = 0; + for (let index = 0; index < bytes.length; index++) { + if(bytes[index] === 0){ + stringEnd = index; + stringPaddingEnd = index + 1; + const stringPadding = 4-(stringEnd+1) % 4; + + if(stringPadding < 4){ + stringPaddingEnd += stringPadding; + } + break; + } + } + + return [bytes.toString('ascii', 0, stringEnd), bytes.subarray(stringPaddingEnd)] + } }, f: { toBuffer: (number) => { @@ -101,4 +119,30 @@ export function messageToBuffer(message: OSCMessage) { } const argsBuffer = argsToBuffer(message.args); return Buffer.concat([addressBuffer, typesBuffer, argsBuffer]); +} + +export function messageFromBuffer(bytes: Buffer): OSCMessage | undefined { + if(bytes[0] !== 47){ + throw new Error('osc message must start with a /') + } + + const oscArgs: OSCArg[] = [] + + if(oscTypeConverterMap.s.fromBuffer) { + const [address, bytesAfterAddress] = oscTypeConverterMap.s.fromBuffer(bytes) + if(typeof address === 'string'){ + console.log(`address: ${address}`) + console.log(`bytesAfterAddresss: ${bytesAfterAddress}`) + let [typeString, bytesAfterType] = oscTypeConverterMap.s.fromBuffer(bytesAfterAddress) + console.log(`typeString: ${typeString}`) + console.log(`bytesAfterType: ${bytesAfterType}`) + if(typeof typeString === 'string'){ + if(!typeString.startsWith(',')){ + throw new Error('osc type string must start with a ,') + } + } + } + } + + return } \ No newline at end of file