-
Notifications
You must be signed in to change notification settings - Fork 3
/
acpi.ts
65 lines (54 loc) · 1.45 KB
/
acpi.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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 }