43 lines
1 KiB
TypeScript
43 lines
1 KiB
TypeScript
import * as dgram from 'dgram';
|
|
import { OSCArgument, OSCType, toBuffer, OSCArgumentType } from 'osc-min';
|
|
import { EventEmitter } from 'events';
|
|
|
|
/**
|
|
* OSC Client base class, handles sending and receiving OSC messages
|
|
|
|
```
|
|
const osc = new OSCClient("192.168.0.44", 8000)
|
|
```
|
|
*/
|
|
export class OSCClient extends EventEmitter {
|
|
private socket: dgram.Socket;
|
|
private host: string;
|
|
private port: number;
|
|
constructor(host: string, port: number) {
|
|
super();
|
|
this.host = host;
|
|
this.port = port;
|
|
this.socket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
|
|
}
|
|
|
|
private sendPacket(packet: Buffer): void {
|
|
this.socket.send(packet, 0, packet.length, this.port, this.host);
|
|
}
|
|
|
|
/**
|
|
* Send an OSC message
|
|
```
|
|
osc.send("/osc/url", OSCType.String, "hello")
|
|
```
|
|
*/
|
|
|
|
public send<T extends OSCType>(address: string, type: T, value: OSCArgumentType<T>): void {
|
|
const arg: OSCArgument<T> = {
|
|
type,
|
|
value,
|
|
};
|
|
|
|
const encoded = toBuffer(address, [arg]);
|
|
this.sendPacket(encoded);
|
|
}
|
|
}
|