Files
custum-hyprpanel/services/Cpu.ts
Jas Singh a4f5fb5917 Refactor Polling Mechanism: Implement Class-Based Poller with Start/Stop Control (#528)
* custom module updates to class based.

* Finish poller logic.

* Use composition for pollers

* Rename poller

* Handle recorder polling.

* Fix quotes in bash command

* Remove logs
2024-11-23 03:55:00 -08:00

48 lines
1.4 KiB
TypeScript

// TODO: Convert to a real service
// @ts-expect-error: This import is a special directive that tells the compiler to use the GTop library
import GTop from 'gi://GTop';
import { FunctionPoller } from 'lib/poller/FunctionPoller';
class Cpu {
private updateFrequency = Variable(2000);
public cpu = Variable(0);
private previousCpuData = new GTop.glibtop_cpu();
constructor() {
GTop.glibtop_get_cpu(this.previousCpuData);
this.calculateUsage = this.calculateUsage.bind(this);
const cpuPoller = new FunctionPoller<number, []>(
this.cpu,
[],
this.updateFrequency.bind('value'),
this.calculateUsage,
);
cpuPoller.start();
}
public calculateUsage(): number {
const currentCpuData = new GTop.glibtop_cpu();
GTop.glibtop_get_cpu(currentCpuData);
// Calculate the differences from the previous to current data
const totalDiff = currentCpuData.total - this.previousCpuData.total;
const idleDiff = currentCpuData.idle - this.previousCpuData.idle;
const cpuUsagePercentage = totalDiff > 0 ? ((totalDiff - idleDiff) / totalDiff) * 100 : 0;
this.previousCpuData = currentCpuData;
return cpuUsagePercentage;
}
public updateTimer(timerInMs: number): void {
this.updateFrequency.value = timerInMs;
}
}
export default Cpu;