Files
factorio-scenario-ExpCluster/exp_server_ups/instance.ts
Cooldude2606 ce80ae9021 Refactored UPS monitor as clusterio plugin (#398)
* Refactor server ups

* Use catalogs

* Move to own plugin

* Use web config

* Remove External.get_server_ups

* Update workspace version requirement

* Remove need for storage

* Add locale

* Fix CI
2025-08-08 16:36:22 +01:00

49 lines
1.4 KiB
TypeScript

import * as lib from "@clusterio/lib";
import { BaseInstancePlugin } from "@clusterio/host";
export class InstancePlugin extends BaseInstancePlugin {
private updateInterval?: ReturnType<typeof setInterval>;
private gameTimes: number[] = [];
async onStart() {
this.updateInterval = setInterval(this.updateUps.bind(this), this.instance.config.get("exp_server_ups.update_interval"));
}
async onStop() {
if (this.updateInterval) {
clearInterval(this.updateInterval);
}
}
async onInstanceConfigFieldChanged(field: string, curr: unknown): Promise<void> {
if (field === "exp_server_ups.update_interval") {
await this.onStop();
await this.onStart();
} else if (field === "exp_server_ups.average_interval") {
this.gameTimes.splice(curr as number);
}
}
async updateUps() {
let ups = 0;
const collected = this.gameTimes.length - 1;
if (collected > 0) {
const minTick = this.gameTimes[0];
const maxTick = this.gameTimes[collected];
const interval = this.instance.config.get("exp_server_ups.update_interval") / 1000;
ups = (maxTick - minTick) / (collected * interval);
}
try {
const newGameTime = await this.sendRcon(`/_rcon return exp_server_ups.update(${ups})`);
this.gameTimes.push(Number(newGameTime));
} catch (error: any) {
this.logger.error(`Failed to receive new game time: ${error}`);
}
if (collected > this.instance.config.get("exp_server_ups.average_interval")) {
this.gameTimes.shift();
}
}
}