add makeosc utility

This commit is contained in:
2024-10-09 18:48:40 -05:00
parent e997b784c0
commit c404299e3e
8 changed files with 220 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env node
const { Option, program } = require('commander');
const slip = require('slip');
const { argToTypedArg } = require('./utils');
const osc = require('@jwetzell/osc');
const packageInfo = require('../package.json');
program.name(packageInfo.name);
program.version(packageInfo.version);
program.description('simple util to make osc buffers');
program.addOption(new Option('--address <address>', 'OSC address').makeOptionMandatory());
program.addOption(new Option('--args <args...>', 'osc args').default([]));
program.addOption(new Option('--slip', 'slip encode message').default(false));
program.addOption(new Option('--types <types...>', 'osc arg types').choices(['s', 'i', 'f', 'b']).default([]));
program.action((options) => {
const { address, args, types } = options;
const typedArgs = args?.map((rawArg, index) => {
const argType = types[index] || 's';
return {
type: argType,
value: argToTypedArg(rawArg, argType),
};
});
let oscMsgBuffer = osc.messageToBuffer({
address,
args: typedArgs,
});
if (options.slip) {
oscMsgBuffer = slip.encode(oscMsgBuffer);
}
process.stdout.write(oscMsgBuffer);
});
program.parse();
process.stdout.on('error', (err) => {
if (err.code === 'EPIPE') {
process.exit(0);
}
});
+31
View File
@@ -0,0 +1,31 @@
const oscTypeConverterMap = {
s: {
fromString: (string) => string,
},
f: {
fromString: (string) => Number.parseFloat(string),
},
i: {
fromString: (string) => Number.parseInt(string, 10),
},
b: {
fromString: (string) => Buffer.from(string, 'hex'),
},
};
function argToTypedArg(rawArg, type = 's') {
const typeConverter = oscTypeConverterMap[type];
if (typeConverter === undefined) {
throw new Error('osc type error: unknown type '.concat(type));
}
if (typeConverter.fromString === undefined) {
throw new Error('osc type error: no string converter for type '.concat(type));
}
return typeConverter.fromString(rawArg);
}
module.exports = {
argToTypedArg,
};