camstreamerlib
Version:
Helper library for CamStreamer ACAP applications.
85 lines (84 loc) • 2.62 kB
JavaScript
import { EventEmitter2 as EventEmitter } from 'eventemitter2';
import { WsClient } from './WsClient';
export class VapixEvents extends EventEmitter {
tls;
tlsInsecure;
ip;
port;
user;
pass;
ws;
constructor(options = {}) {
super();
this.tls = options.tls ?? false;
this.tlsInsecure = options.tlsInsecure ?? false;
this.ip = options.ip ?? '127.0.0.1';
this.port = options.port ?? (this.tls ? 443 : 80);
this.user = options.user ?? 'root';
this.pass = options.pass ?? '';
this.createWsClient();
EventEmitter.call(this);
}
connect() {
this.ws.open();
}
disconnect() {
this.ws.destroy();
}
createWsClient() {
const options = {
tls: this.tls,
tlsInsecure: this.tlsInsecure,
user: this.user,
pass: this.pass,
ip: this.ip,
port: this.port,
address: '/vapix/ws-data-stream?sources=events',
};
this.ws = new WsClient(options);
this.ws.onOpen = () => {
const topics = [];
const eventNames = this.eventNames();
for (const eventName of eventNames) {
if (!this.isReservedEventName(eventName)) {
const topic = {
topicFilter: eventName,
};
topics.push(topic);
}
}
const topicFilter = {
apiVersion: '1.0',
method: 'events:configure',
params: {
eventFilterList: topics,
},
};
this.ws.send(JSON.stringify(topicFilter));
};
this.ws.onMessage = (data) => {
const dataJSON = JSON.parse(data.toString());
if (dataJSON.method === 'events:configure') {
if (dataJSON.error === undefined) {
this.emit('open');
}
else {
this.emit('error', dataJSON.error);
this.disconnect();
}
return;
}
const eventName = dataJSON.params.notification.topic;
this.emit(eventName, dataJSON);
};
this.ws.onError = (error) => {
this.emit('error', error);
};
this.ws.onClose = () => {
this.emit('close');
};
}
isReservedEventName(eventName) {
return eventName === 'open' || eventName === 'close' || eventName === 'error';
}
}