import GLib from "gi://GLib?version=2.0"; import { Binding } from "types/service"; import { Variable as VariableType } from "types/variable"; type GenericFunction = (...args: any[]) => any; /** * @param {VariableType} targetVariable - The Variable to update with the function's result. * @param {Array>} trackers - Array of trackers to watch. * @param {Binding} pollingInterval - The polling interval in milliseconds. * @param {GenericFunction} someFunc - The function to execute at each interval, which updates the Variable. * @param {...any} params - Parameters to pass to someFunc. */ export const pollVariable = ( targetVariable: VariableType, trackers: Array>, pollingInterval: Binding, someFunc: GenericFunction, ...params: any[] ): void => { let intervalInstance: number | null = null; const intervalFn = (pollIntrvl: number) => { if (intervalInstance !== null) { GLib.source_remove(intervalInstance); } intervalInstance = Utils.interval(pollIntrvl, () => { targetVariable.value = someFunc(...params); }); }; Utils.merge([pollingInterval, ...trackers], (pollIntrvl: number) => { intervalFn(pollIntrvl); }); }; /** * @param {VariableType} targetVariable - The Variable to update with the result of the command. * @param {Binding} pollingInterval - The polling interval in milliseconds. * @param {string} someCommand - The bash command to execute. * @param {GenericFunction} someFunc - The function to execute after processing the command result. * @param {...any} params - Parameters to pass to someFunc. */ export const pollVariableBash = ( targetVariable: VariableType, trackers: Array>, pollingInterval: Binding, someCommand: string, someFunc: (res: any, ...params: any[]) => T, ...params: any[] ): void => { let intervalInstance: number | null = null; const intervalFn = (pollIntrvl: number) => { if (intervalInstance !== null) { GLib.source_remove(intervalInstance); } intervalInstance = Utils.interval(pollIntrvl, () => { Utils.execAsync(`bash -c "${someCommand}"`).then((res: any) => { try { targetVariable.value = someFunc(res, ...params); } catch (error) { console.warn(`An error occurred when running interval bash function: ${error}`); } }) .catch((err) => console.error(`Error running command "${someCommand}": ${err}`)); }); }; Utils.merge([pollingInterval, ...trackers], (pollIntrvl: number) => { intervalFn(pollIntrvl); }); };