takt/src/shared/utils/sleep.ts

49 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { spawn } from 'node:child_process';
import { platform } from 'node:os';
import { existsSync } from 'node:fs';
import { createLogger } from './debug.js';
const log = createLogger('sleep');
let caffeinateStarted = false;
/**
* takt実行中のmacOSアイドルスリープおよびディスプレイスリープを防止する。
* -d: ディスプレイスリープ防止App Nap によるプロセス凍結を回避)
* -i: アイドルスリープ防止
* 蓋を閉じた場合のスリープは防げない(-s はAC電源が必要なため
*/
export function preventSleep(): void {
if (caffeinateStarted) {
return;
}
if (platform() !== 'darwin') {
return;
}
const caffeinatePath = '/usr/bin/caffeinate';
if (!existsSync(caffeinatePath)) {
log.info('caffeinate not found, sleep prevention disabled');
return;
}
const child = spawn(caffeinatePath, ['-di', '-w', String(process.pid)], {
stdio: 'ignore',
detached: true,
});
child.unref();
caffeinateStarted = true;
log.debug('Started caffeinate for sleep prevention', { pid: child.pid });
}
/**
* テスト用: caffeinateStarted フラグをリセットする
*/
export function resetPreventSleepState(): void {
caffeinateStarted = false;
}