import { Utils } from "./Utils";
/**
* Use the adapter to obtain data, and then process the data through the processor.
*/
class MonitorTask {
constructor(adapter, processor, options) {
this.adapter = adapter;
this.processor = processor;
this.options = options;
this.isRunning = false;
this.intervalId = null;
}
async run() {
if (this.isRunning) {
return;
}
this.isRunning = true;
let app = Utils.getCurrentApp();
// Take root and condition once.
this.root = this.options.root || app;
this.condition = this.options.condition;
// Receive messages sent by the server.
this.adapter.onMessage((data) => {
this.data = data;
});
// Connect this connection.
await this.adapter.connect();
// Regularly distribute messages to specified objects based on user set time intervals.
this.intervalId = setInterval(() => {
if (!this.isRunning) {
clearInterval(this.intervalId);
this.adapter.disconnect();
return;
}
// When the data source requires duplicate requests.
if (this.adapter.needsDuplicateRequest) {
this.adapter.connect();
}
if (this.data) {
// Process data and distribute messages.
const processedDataArr = this.processor.process(this.data);
// Dispatch data when received.
if (this.adapter.config.onReceiveData) {
this.adapter.config.onReceiveData(processedDataArr);
}
// this.dispatchData(processedDataArr);
}
}, this.adapter.config.interval || 5000);
}
stop() {
this.isRunning = false;
clearInterval(this.intervalId);
this.adapter.disconnect();
}
dispatchData(dataArr) {
// If root is destroyed in this loop, kill the task.
if (this.root.destroyed) {
this.stop();
return;
}
// Convert data into an array.
if (!Utils.isArray(dataArr)) {
dataArr = [dataArr];
}
dataArr.forEach((data) => {
let targetObjects = [];
// Distribute data to the monitorData attribute of the specified object.
if (data.id) {
// Clearly specify that if it is a query id, use queryById.
targetObjects = this.root.queryById(data.id).objects;
}
// Support for external transmission of conditions.
else if (this.condition) {
targetObjects = this.root.query(this.condition).objects;
}
else {
console.warn('The data is illegal and should contain an ID attribute or query condition.');
return;
}
targetObjects.forEach((targer) => {
targer.monitorData.setAttributes({
[data.key]: data.value
});
})
});
}
}
export { MonitorTask }