You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.5 KiB
TypeScript
66 lines
1.5 KiB
TypeScript
const child_process = require('child_process')
|
|
// import * as child_process from 'child_process'
|
|
// import { logger } from '../logger'
|
|
|
|
const logger = {
|
|
error: console.error,
|
|
debug: console.log
|
|
}
|
|
|
|
type Callback = (data: string) => void;
|
|
|
|
class ACPIController {
|
|
public constructor() {
|
|
if (this.checkAcpi()) this.listen()
|
|
else logger.error('ACPI: acpi_listen does not exists')
|
|
}
|
|
|
|
protected tries = 0;
|
|
protected callbacks: Callback[] = [];
|
|
|
|
public connect(cb: Callback): void {
|
|
this.callbacks.push(cb)
|
|
}
|
|
|
|
public disconnect(cb: Callback): void {
|
|
const ind = this.callbacks.findIndex((c) => {
|
|
return c === cb
|
|
})
|
|
if (ind == -1) return
|
|
this.callbacks.splice(ind, 1)
|
|
}
|
|
|
|
private checkAcpi(): boolean {
|
|
const res = child_process.spawnSync('which', ['acpi_listen'], {
|
|
encoding: 'utf-8'
|
|
})
|
|
if (res.status == 0) return true
|
|
else return false
|
|
}
|
|
|
|
private listen(): void {
|
|
const acpi = child_process.spawn('acpi_listen')
|
|
acpi.on('error', (err) => {
|
|
logger.error('ACPI: ' + err.message)
|
|
})
|
|
acpi.on('close', () => {
|
|
if (this.tries < 5) {
|
|
this.tries++
|
|
logger.debug('Restarting acpi_listen')
|
|
return this.listen()
|
|
}
|
|
})
|
|
|
|
acpi.stdout.addListener('data', (d: Buffer) => {
|
|
const data = d.toString().trim()
|
|
this.callbacks.forEach((cb) => {
|
|
if (cb !== undefined) cb(data)
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
const ACPI = new ACPIController()
|
|
|
|
export { ACPI }
|