Initial Commit
This commit is contained in:
commit
4c5d981e7f
9 changed files with 382 additions and 0 deletions
62
src/oscClient.ts
Normal file
62
src/oscClient.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import * as dgram from 'dgram';
|
||||
import {OSCArgument, OSCType, toBuffer, fromBuffer, OSCArgumentType} from 'osc-min';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
|
||||
interface OSCClientOptions {
|
||||
outHost: string;
|
||||
outPort: number;
|
||||
inPort?: number;
|
||||
}
|
||||
|
||||
interface ReceivedOSCMessage<T extends OSCType> {
|
||||
address: string;
|
||||
type: T;
|
||||
value: OSCArgumentType<T>
|
||||
}
|
||||
|
||||
// declare types for events
|
||||
export declare interface OSCClient {
|
||||
on(event: 'message', listener: (message: ReceivedOSCMessage<OSCType>) => void): this;
|
||||
}
|
||||
|
||||
export class OSCClient extends EventEmitter{
|
||||
private socket: dgram.Socket;
|
||||
private options: OSCClientOptions;
|
||||
constructor(options: OSCClientOptions){
|
||||
super();
|
||||
this.socket = dgram.createSocket({type: "udp4", reuseAddr: true});
|
||||
this.options = options;
|
||||
|
||||
if(options.inPort){
|
||||
this.socket.bind(options.inPort);
|
||||
}
|
||||
|
||||
this.socket.on('message', (msg)=>{
|
||||
const decoded = fromBuffer(msg)
|
||||
if(decoded.oscType === "message"){
|
||||
decoded.args.forEach((arg)=>{
|
||||
this.emit('message', {
|
||||
address: decoded.address,
|
||||
type: arg.type,
|
||||
value: arg.value
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private sendPacket(packet: Buffer): void{
|
||||
this.socket.send(packet, 0, packet.length, this.options.outPort, this.options.outHost)
|
||||
}
|
||||
|
||||
public send<T extends OSCType>(address: string, type: T, value: OSCArgumentType<T>){
|
||||
const arg: OSCArgument<T> = {
|
||||
type,
|
||||
value
|
||||
}
|
||||
|
||||
const encoded = toBuffer(address, [arg]);
|
||||
this.sendPacket(encoded);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue