| 1 | import * as si from "systeminformation"; |
| 2 | import { Disposable, EventEmitter } from "vscode"; |
| 3 | |
| 4 | const UPDATE_INTERVAL_MS = 1000; |
| 5 | |
| 6 | export class Battery implements Disposable { |
| 7 | private updateTimeout: NodeJS.Timeout | undefined; |
| 8 | private readonly onChangeACEmitter = new EventEmitter<boolean>(); |
| 9 | private readonly onChangeLevelEmitter = new EventEmitter<number>(); |
| 10 | private acConnected: boolean = true; |
| 11 | private level = 100; |
| 12 | private readonly batteryStatsPromise = si.battery(); |
| 13 | |
| 14 | constructor() { |
| 15 | this.updateTimeout = setInterval(() => this.update(), UPDATE_INTERVAL_MS); |
| 16 | } |
| 17 | |
| 18 | dispose() { |
| 19 | if (this.updateTimeout) { |
| 20 | clearInterval(this.updateTimeout); |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | private async update() { |
| 25 | const stats = await this.batteryStatsPromise; |
| 26 | const level = stats.hasBattery ? stats.percent : 100; |
| 27 | const isACConnected = |
| 28 | !stats.hasBattery || stats.acConnected || level == 100; |
| 29 | |
| 30 | if (isACConnected !== this.acConnected) { |
| 31 | this.acConnected = isACConnected; |
| 32 | this.onChangeACEmitter.fire(isACConnected); |
| 33 | } |
| 34 | |
| 35 | if (level !== this.level) { |
| 36 | this.level = level; |
| 37 | this.onChangeLevelEmitter.fire(level); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | public getLevel(): number { |
| 42 | return this.level; |
| 43 | } |
| 44 | |
| 45 | public isACConnected(): boolean { |
| 46 | return false; |
| 47 | return this.acConnected; |
| 48 | } |
| 49 | |
| 50 | public readonly onChangeLevel = this.onChangeLevelEmitter.event; |
| 51 | public readonly onChangeAC = this.onChangeACEmitter.event; |
| 52 | } |