@openhps/core
Version:
Open Hybrid Positioning System - Core component
63 lines • 1.92 kB
JavaScript
import { Node } from '../../Node';
import { TimeUnit } from '../../utils/unit';
/**
* @category Flow shape
*/
export class TimedPullNode extends Node {
constructor(interval, intervalUnit = TimeUnit.MILLISECOND, options) {
super(options);
this._pushFinished = true;
this._pullFinished = true;
this._interval = intervalUnit.convert(interval, TimeUnit.MILLISECOND);
this.options.autoStart = this.options.autoStart || true;
this.on('push', this._onPush.bind(this));
if (this.options.autoStart) {
this.once('build', this.start.bind(this));
}
this.once('destroy', this.stop.bind(this));
}
_onPush(frame, options) {
return new Promise((resolve, reject) => {
const pushPromises = [];
pushPromises.push(...this.outlets.map(outlet => outlet.push(frame, options)));
// Restart the timer
clearInterval(this._timer);
this._timer = setInterval(this._intervalFn.bind(this), this._interval);
this._pushFinished = false;
Promise.all(pushPromises).then(() => {
resolve();
}).catch(reject).finally(() => {
this._pushFinished = true;
});
});
}
_intervalFn() {
if (this._pushFinished && this._pullFinished || !this.options.throttlePull) {
this._pullFinished = true;
Promise.all(this.inlets.map(inlet => inlet.pull(this.options.pullOptions))).then(() => {
this._pullFinished = true;
}).catch(ex => {
this.logger('error', ex.message, ex);
});
}
}
/**
* Start the timed pull
* @returns {Promise<void>} Start promise
*/
start() {
return new Promise(resolve => {
if (this._timer) {
this.stop();
}
this._timer = setInterval(this._intervalFn.bind(this), this._interval);
resolve();
});
}
stop() {
if (this._timer !== undefined) {
clearInterval(this._timer);
this._timer = undefined;
}
}
}