50 lines
1.1 KiB
TypeScript
50 lines
1.1 KiB
TypeScript
import * as dgram from 'dgram';
|
|
import { toBuffer } from 'osc-min';
|
|
import { OSCArgument, OSCType, OSCArgumentType } from './types';
|
|
|
|
/**
|
|
* OSC Client, handles sending OSC messages
|
|
|
|
```
|
|
const osc = new OSCClient("192.168.0.44", 8000);
|
|
```
|
|
*/
|
|
export class OSCClient {
|
|
public socket: dgram.Socket;
|
|
private host: string;
|
|
private port: number;
|
|
constructor(host: string, port: number) {
|
|
this.host = host;
|
|
this.port = port;
|
|
this.socket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
|
|
}
|
|
|
|
public 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);
|
|
}
|
|
|
|
/**
|
|
* Close the connection
|
|
*/
|
|
|
|
public close(): void {
|
|
this.socket.close();
|
|
}
|
|
}
|