lightman-agent 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent.config.template.json +30 -0
- package/bin/cms-agent.js +233 -0
- package/nssm/nssm.exe +0 -0
- package/package.json +52 -0
- package/public/assets/index-CcBNCz6h.css +1 -0
- package/public/assets/index-H-8HDl46.js +1 -0
- package/public/index.html +19 -0
- package/scripts/guardian.ps1 +75 -0
- package/scripts/install-linux.sh +134 -0
- package/scripts/install-rpi.sh +117 -0
- package/scripts/install-windows.ps1 +529 -0
- package/scripts/launch-kiosk.vbs +101 -0
- package/scripts/lightman-agent.logrotate +12 -0
- package/scripts/lightman-agent.service +38 -0
- package/scripts/lightman-shell.bat +128 -0
- package/scripts/reinstall-windows.ps1 +26 -0
- package/scripts/restore-desktop.ps1 +32 -0
- package/scripts/setup.ps1 +116 -0
- package/scripts/setup.sh +115 -0
- package/scripts/uninstall-linux.sh +50 -0
- package/scripts/uninstall-windows.ps1 +54 -0
- package/src/commands/display.ts +177 -0
- package/src/commands/kiosk.ts +113 -0
- package/src/commands/maintenance.ts +106 -0
- package/src/commands/network.ts +129 -0
- package/src/commands/power.ts +163 -0
- package/src/commands/rpi.ts +45 -0
- package/src/commands/screenshot.ts +166 -0
- package/src/commands/serial.ts +17 -0
- package/src/commands/update.ts +124 -0
- package/src/index.ts +652 -0
- package/src/lib/config.ts +69 -0
- package/src/lib/identity.ts +40 -0
- package/src/lib/logger.ts +137 -0
- package/src/lib/platform.ts +10 -0
- package/src/lib/rpi.ts +180 -0
- package/src/lib/screens.ts +128 -0
- package/src/lib/types.ts +176 -0
- package/src/services/commands.ts +107 -0
- package/src/services/health.ts +161 -0
- package/src/services/kiosk.ts +395 -0
- package/src/services/localEvents.ts +60 -0
- package/src/services/logForwarder.ts +72 -0
- package/src/services/multiScreenKiosk.ts +324 -0
- package/src/services/oscBridge.ts +186 -0
- package/src/services/powerScheduler.ts +260 -0
- package/src/services/provisioning.ts +120 -0
- package/src/services/serialBridge.ts +230 -0
- package/src/services/serviceLauncher.ts +183 -0
- package/src/services/staticServer.ts +226 -0
- package/src/services/updater.ts +249 -0
- package/src/services/watchdog.ts +310 -0
- package/src/services/websocket.ts +152 -0
- package/tsconfig.json +28 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { readFileSync, existsSync } from 'fs';
|
|
2
|
+
import { resolve } from 'path';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import type { AgentConfig } from './types.js';
|
|
5
|
+
|
|
6
|
+
const kioskSchema = z.object({
|
|
7
|
+
browserPath: z.string().default('chromium-browser'),
|
|
8
|
+
defaultUrl: z.string().url().default('http://localhost:3401/display'),
|
|
9
|
+
extraArgs: z.array(z.string()).default([]),
|
|
10
|
+
pollIntervalMs: z.number().int().min(1000).default(10_000),
|
|
11
|
+
maxCrashesInWindow: z.number().int().min(1).default(10),
|
|
12
|
+
crashWindowMs: z.number().int().min(10_000).default(300_000),
|
|
13
|
+
shellMode: z.boolean().default(false),
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
const screenshotSchema = z.object({
|
|
17
|
+
captureCommand: z.string().default('scrot'),
|
|
18
|
+
quality: z.number().int().min(1).max(100).default(80),
|
|
19
|
+
uploadEndpoint: z.string().default('/api/devices/{deviceId}/screenshot'),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const powerScheduleSchema = z.object({
|
|
23
|
+
shutdownCron: z.string().optional(),
|
|
24
|
+
startupCron: z.string().optional(),
|
|
25
|
+
timezone: z.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone),
|
|
26
|
+
shutdownWarningSeconds: z.number().int().min(0).max(600).default(60),
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const configSchema = z.object({
|
|
30
|
+
serverUrl: z.string().url(),
|
|
31
|
+
deviceSlug: z.string().min(1),
|
|
32
|
+
healthIntervalMs: z.number().int().min(5000).default(60000),
|
|
33
|
+
logLevel: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
|
|
34
|
+
logFile: z.string().default('agent.log'),
|
|
35
|
+
identityFile: z.string().default('.lightman-identity.json'),
|
|
36
|
+
localServices: z.boolean().default(true),
|
|
37
|
+
kiosk: kioskSchema.optional(),
|
|
38
|
+
screenshot: screenshotSchema.optional(),
|
|
39
|
+
powerSchedule: powerScheduleSchema.optional(),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
export function loadConfig(configPath?: string): AgentConfig {
|
|
43
|
+
const filePath = configPath || resolve(process.cwd(), 'agent.config.json');
|
|
44
|
+
|
|
45
|
+
if (!existsSync(filePath)) {
|
|
46
|
+
throw new Error(`Config file not found: ${filePath}`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
let raw: Record<string, unknown>;
|
|
50
|
+
try {
|
|
51
|
+
raw = JSON.parse(readFileSync(filePath, 'utf-8'));
|
|
52
|
+
} catch (err) {
|
|
53
|
+
throw new Error(`Invalid JSON in config file ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Apply environment overrides
|
|
57
|
+
const merged = {
|
|
58
|
+
...raw,
|
|
59
|
+
...(process.env.LIGHTMAN_SERVER_URL && { serverUrl: process.env.LIGHTMAN_SERVER_URL }),
|
|
60
|
+
...(process.env.LIGHTMAN_DEVICE_SLUG && { deviceSlug: process.env.LIGHTMAN_DEVICE_SLUG }),
|
|
61
|
+
...(process.env.LIGHTMAN_HEALTH_INTERVAL && { healthIntervalMs: parseInt(process.env.LIGHTMAN_HEALTH_INTERVAL, 10) }),
|
|
62
|
+
...(process.env.LIGHTMAN_LOG_LEVEL && { logLevel: process.env.LIGHTMAN_LOG_LEVEL }),
|
|
63
|
+
...(process.env.LIGHTMAN_LOG_FILE && { logFile: process.env.LIGHTMAN_LOG_FILE }),
|
|
64
|
+
...(process.env.LIGHTMAN_IDENTITY_FILE && { identityFile: process.env.LIGHTMAN_IDENTITY_FILE }),
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const result = configSchema.parse(merged);
|
|
68
|
+
return result as AgentConfig;
|
|
69
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, existsSync, chmodSync } from 'fs';
|
|
2
|
+
import { resolve, dirname } from 'path';
|
|
3
|
+
import { mkdirSync } from 'fs';
|
|
4
|
+
import type { Identity } from './types.js';
|
|
5
|
+
|
|
6
|
+
export function readIdentity(filePath: string): Identity | null {
|
|
7
|
+
const fullPath = resolve(process.cwd(), filePath);
|
|
8
|
+
|
|
9
|
+
if (!existsSync(fullPath)) {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
try {
|
|
14
|
+
const raw = JSON.parse(readFileSync(fullPath, 'utf-8'));
|
|
15
|
+
if (raw.deviceId && raw.apiKey) {
|
|
16
|
+
return { deviceId: raw.deviceId, apiKey: raw.apiKey };
|
|
17
|
+
}
|
|
18
|
+
return null;
|
|
19
|
+
} catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function writeIdentity(filePath: string, identity: Identity): void {
|
|
25
|
+
const fullPath = resolve(process.cwd(), filePath);
|
|
26
|
+
const dir = dirname(fullPath);
|
|
27
|
+
|
|
28
|
+
if (!existsSync(dir)) {
|
|
29
|
+
mkdirSync(dir, { recursive: true });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
writeFileSync(fullPath, JSON.stringify(identity, null, 2), { mode: 0o600 });
|
|
33
|
+
|
|
34
|
+
// Ensure permissions are correct even if file already existed
|
|
35
|
+
try {
|
|
36
|
+
chmodSync(fullPath, 0o600);
|
|
37
|
+
} catch {
|
|
38
|
+
// Ignore permission errors on Windows
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, statSync, renameSync, unlinkSync } from 'fs';
|
|
2
|
+
import { dirname } from 'path';
|
|
3
|
+
import type { LogEntry } from './types.js';
|
|
4
|
+
|
|
5
|
+
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
|
6
|
+
|
|
7
|
+
const LEVEL_ORDER: Record<LogLevel, number> = {
|
|
8
|
+
debug: 0,
|
|
9
|
+
info: 1,
|
|
10
|
+
warn: 2,
|
|
11
|
+
error: 3,
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const LEVEL_LABELS: Record<LogLevel, string> = {
|
|
15
|
+
debug: 'DEBUG',
|
|
16
|
+
info: 'INFO ',
|
|
17
|
+
warn: 'WARN ',
|
|
18
|
+
error: 'ERROR',
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const MAX_LOG_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
|
|
22
|
+
const MAX_ROTATED_FILES = 3; // Keep agent.log.1, .2, .3
|
|
23
|
+
|
|
24
|
+
export class Logger {
|
|
25
|
+
private level: LogLevel;
|
|
26
|
+
private logFile: string | null;
|
|
27
|
+
private listeners: Array<(entry: LogEntry) => void> = [];
|
|
28
|
+
private writesSinceRotateCheck = 0;
|
|
29
|
+
|
|
30
|
+
constructor(level: LogLevel = 'info', logFile?: string) {
|
|
31
|
+
this.level = level;
|
|
32
|
+
this.logFile = logFile || null;
|
|
33
|
+
|
|
34
|
+
if (this.logFile) {
|
|
35
|
+
const dir = dirname(this.logFile);
|
|
36
|
+
if (!existsSync(dir)) {
|
|
37
|
+
mkdirSync(dir, { recursive: true });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
onLog(fn: (entry: LogEntry) => void): void {
|
|
43
|
+
this.listeners = [...this.listeners, fn];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
setLevel(level: LogLevel): void {
|
|
47
|
+
this.level = level;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
debug(message: string, ...args: unknown[]): void {
|
|
51
|
+
this.log('debug', message, ...args);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
info(message: string, ...args: unknown[]): void {
|
|
55
|
+
this.log('info', message, ...args);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
warn(message: string, ...args: unknown[]): void {
|
|
59
|
+
this.log('warn', message, ...args);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
error(message: string, ...args: unknown[]): void {
|
|
63
|
+
this.log('error', message, ...args);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private log(level: LogLevel, message: string, ...args: unknown[]): void {
|
|
67
|
+
if (LEVEL_ORDER[level] < LEVEL_ORDER[this.level]) {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const timestamp = new Date().toISOString();
|
|
72
|
+
const label = LEVEL_LABELS[level];
|
|
73
|
+
const formatted = `[${timestamp}] [${label}] ${message}`;
|
|
74
|
+
|
|
75
|
+
// Console output
|
|
76
|
+
if (level === 'error') {
|
|
77
|
+
console.error(formatted, ...args);
|
|
78
|
+
} else if (level === 'warn') {
|
|
79
|
+
console.warn(formatted, ...args);
|
|
80
|
+
} else {
|
|
81
|
+
console.log(formatted, ...args);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// File output (with rotation)
|
|
85
|
+
if (this.logFile) {
|
|
86
|
+
try {
|
|
87
|
+
const extra = args.length > 0 ? ' ' + args.map(a => JSON.stringify(a)).join(' ') : '';
|
|
88
|
+
appendFileSync(this.logFile, formatted + extra + '\n');
|
|
89
|
+
|
|
90
|
+
// Check rotation every 100 writes to avoid stat() on every log line
|
|
91
|
+
this.writesSinceRotateCheck++;
|
|
92
|
+
if (this.writesSinceRotateCheck >= 100) {
|
|
93
|
+
this.writesSinceRotateCheck = 0;
|
|
94
|
+
this.rotateIfNeeded();
|
|
95
|
+
}
|
|
96
|
+
} catch {
|
|
97
|
+
// Silently fail file writes to avoid recursive errors
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Notify listeners
|
|
102
|
+
const entry: LogEntry = { timestamp, level, message, source: 'agent' };
|
|
103
|
+
for (const listener of this.listeners) {
|
|
104
|
+
try {
|
|
105
|
+
listener(entry);
|
|
106
|
+
} catch {
|
|
107
|
+
// Prevent listener errors from breaking logging
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private rotateIfNeeded(): void {
|
|
113
|
+
if (!this.logFile) return;
|
|
114
|
+
try {
|
|
115
|
+
const stat = statSync(this.logFile);
|
|
116
|
+
if (stat.size < MAX_LOG_SIZE_BYTES) return;
|
|
117
|
+
|
|
118
|
+
// Rotate: agent.log.3 → delete, agent.log.2 → .3, agent.log.1 → .2, agent.log → .1
|
|
119
|
+
for (let i = MAX_ROTATED_FILES; i >= 1; i--) {
|
|
120
|
+
const src = i === 1 ? this.logFile : `${this.logFile}.${i - 1}`;
|
|
121
|
+
const dst = `${this.logFile}.${i}`;
|
|
122
|
+
try {
|
|
123
|
+
if (i === MAX_ROTATED_FILES && existsSync(dst)) {
|
|
124
|
+
unlinkSync(dst);
|
|
125
|
+
}
|
|
126
|
+
if (existsSync(src)) {
|
|
127
|
+
renameSync(src, dst);
|
|
128
|
+
}
|
|
129
|
+
} catch {
|
|
130
|
+
// Best effort rotation
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
} catch {
|
|
134
|
+
// stat failed, skip rotation
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
package/src/lib/rpi.ts
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { execFileSync } from 'child_process';
|
|
2
|
+
import { existsSync, readFileSync, openSync, writeSync, closeSync } from 'fs';
|
|
3
|
+
|
|
4
|
+
// --- RPi Detection ---
|
|
5
|
+
|
|
6
|
+
let isRpiCached: boolean | null = null;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Detect if this machine is a Raspberry Pi by checking /proc/device-tree/model.
|
|
10
|
+
*/
|
|
11
|
+
export function isRaspberryPi(): boolean {
|
|
12
|
+
if (isRpiCached !== null) return isRpiCached;
|
|
13
|
+
try {
|
|
14
|
+
if (!existsSync('/proc/device-tree/model')) {
|
|
15
|
+
isRpiCached = false;
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
const model = readFileSync('/proc/device-tree/model', 'utf-8');
|
|
19
|
+
isRpiCached = model.toLowerCase().includes('raspberry pi');
|
|
20
|
+
return isRpiCached;
|
|
21
|
+
} catch {
|
|
22
|
+
isRpiCached = false;
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Reset detection cache (for testing). */
|
|
28
|
+
export function resetRpiCache(): void {
|
|
29
|
+
isRpiCached = null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// --- RPi Model Info ---
|
|
33
|
+
|
|
34
|
+
export interface RpiInfo {
|
|
35
|
+
model: string | null;
|
|
36
|
+
serial: string | null;
|
|
37
|
+
revision: string | null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function getRpiInfo(): RpiInfo {
|
|
41
|
+
const info: RpiInfo = { model: null, serial: null, revision: null };
|
|
42
|
+
try {
|
|
43
|
+
info.model = readFileSync('/proc/device-tree/model', 'utf-8').replace(/\0/g, '').trim();
|
|
44
|
+
} catch { /* not available */ }
|
|
45
|
+
try {
|
|
46
|
+
const cpuinfo = readFileSync('/proc/cpuinfo', 'utf-8');
|
|
47
|
+
const serialMatch = cpuinfo.match(/Serial\s*:\s*([0-9a-fA-F]+)/);
|
|
48
|
+
if (serialMatch) info.serial = serialMatch[1];
|
|
49
|
+
const revisionMatch = cpuinfo.match(/Revision\s*:\s*([0-9a-fA-F]+)/);
|
|
50
|
+
if (revisionMatch) info.revision = revisionMatch[1];
|
|
51
|
+
} catch { /* not available */ }
|
|
52
|
+
return info;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// --- GPU Temperature ---
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Read GPU temperature via vcgencmd. Returns null if not available.
|
|
59
|
+
*/
|
|
60
|
+
export function getGpuTemp(): number | null {
|
|
61
|
+
try {
|
|
62
|
+
const output = execFileSync('vcgencmd', ['measure_temp'], {
|
|
63
|
+
timeout: 3000,
|
|
64
|
+
stdio: 'pipe',
|
|
65
|
+
}).toString();
|
|
66
|
+
// Output format: temp=42.8'C
|
|
67
|
+
const match = output.match(/temp=([\d.]+)/);
|
|
68
|
+
if (match) return Math.round(parseFloat(match[1]) * 10) / 10;
|
|
69
|
+
return null;
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// --- Throttle Status ---
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Read throttle/undervoltage status via vcgencmd. Returns null if not available.
|
|
79
|
+
* See: https://www.raspberrypi.com/documentation/computers/os.html#get_throttled
|
|
80
|
+
*
|
|
81
|
+
* Bit meanings:
|
|
82
|
+
* 0: Under-voltage detected
|
|
83
|
+
* 1: Arm frequency capped
|
|
84
|
+
* 2: Currently throttled
|
|
85
|
+
* 3: Soft temperature limit active
|
|
86
|
+
* 16: Under-voltage has occurred
|
|
87
|
+
* 17: Arm frequency capping has occurred
|
|
88
|
+
* 18: Throttling has occurred
|
|
89
|
+
* 19: Soft temperature limit has occurred
|
|
90
|
+
*/
|
|
91
|
+
export function getThrottled(): number | null {
|
|
92
|
+
try {
|
|
93
|
+
const output = execFileSync('vcgencmd', ['get_throttled'], {
|
|
94
|
+
timeout: 3000,
|
|
95
|
+
stdio: 'pipe',
|
|
96
|
+
}).toString();
|
|
97
|
+
// Output format: throttled=0x0
|
|
98
|
+
const match = output.match(/throttled=(0x[0-9a-fA-F]+)/);
|
|
99
|
+
if (match) return parseInt(match[1], 16);
|
|
100
|
+
return null;
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// --- SD Card Read-Only Check ---
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Check if the root filesystem is mounted read-only.
|
|
110
|
+
*/
|
|
111
|
+
export function isSdCardReadOnly(): boolean {
|
|
112
|
+
try {
|
|
113
|
+
const mounts = readFileSync('/proc/mounts', 'utf-8');
|
|
114
|
+
const rootLine = mounts.split('\n').find((line) => {
|
|
115
|
+
const parts = line.split(' ');
|
|
116
|
+
return parts[1] === '/';
|
|
117
|
+
});
|
|
118
|
+
if (!rootLine) return false;
|
|
119
|
+
const options = rootLine.split(' ')[3] || '';
|
|
120
|
+
return options.split(',').includes('ro');
|
|
121
|
+
} catch {
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// --- Hardware Watchdog ---
|
|
127
|
+
|
|
128
|
+
let watchdogFd: number | null = null;
|
|
129
|
+
let watchdogTimer: NodeJS.Timeout | null = null;
|
|
130
|
+
const WATCHDOG_DEVICE = '/dev/watchdog';
|
|
131
|
+
const WATCHDOG_INTERVAL_MS = 10_000; // Pet every 10 seconds
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Start the hardware watchdog. Writes to /dev/watchdog every 10s.
|
|
135
|
+
* If the agent dies, the kernel will reboot after ~15s.
|
|
136
|
+
* Returns true if started, false if not available.
|
|
137
|
+
*/
|
|
138
|
+
export function startWatchdog(): boolean {
|
|
139
|
+
if (watchdogFd !== null) return true; // Already running
|
|
140
|
+
try {
|
|
141
|
+
if (!existsSync(WATCHDOG_DEVICE)) return false;
|
|
142
|
+
watchdogFd = openSync(WATCHDOG_DEVICE, 'w');
|
|
143
|
+
// Pet immediately
|
|
144
|
+
petWatchdog();
|
|
145
|
+
// Set up periodic petting
|
|
146
|
+
watchdogTimer = setInterval(petWatchdog, WATCHDOG_INTERVAL_MS);
|
|
147
|
+
return true;
|
|
148
|
+
} catch {
|
|
149
|
+
watchdogFd = null;
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Stop the hardware watchdog gracefully.
|
|
156
|
+
* Writes 'V' (magic close character) to disable the watchdog before closing.
|
|
157
|
+
*/
|
|
158
|
+
export function stopWatchdog(): void {
|
|
159
|
+
if (watchdogTimer) {
|
|
160
|
+
clearInterval(watchdogTimer);
|
|
161
|
+
watchdogTimer = null;
|
|
162
|
+
}
|
|
163
|
+
if (watchdogFd !== null) {
|
|
164
|
+
try {
|
|
165
|
+
// Magic close character 'V' disables the watchdog
|
|
166
|
+
writeSync(watchdogFd, 'V');
|
|
167
|
+
closeSync(watchdogFd);
|
|
168
|
+
} catch { /* ignore close errors */ }
|
|
169
|
+
watchdogFd = null;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function petWatchdog(): void {
|
|
174
|
+
if (watchdogFd === null) return;
|
|
175
|
+
try {
|
|
176
|
+
writeSync(watchdogFd, '1');
|
|
177
|
+
} catch {
|
|
178
|
+
// If write fails, watchdog will trigger reboot — this is by design
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { execSync } from 'child_process';
|
|
2
|
+
import { getPlatform } from './platform.js';
|
|
3
|
+
import type { Logger } from './logger.js';
|
|
4
|
+
|
|
5
|
+
export interface DetectedScreen {
|
|
6
|
+
/** Windows display device ID, e.g. "\\.\DISPLAY1" */
|
|
7
|
+
hardwareId: string;
|
|
8
|
+
/** Friendly name / adapter description */
|
|
9
|
+
name: string;
|
|
10
|
+
/** Display index (0-based) */
|
|
11
|
+
index: number;
|
|
12
|
+
/** Screen bounds */
|
|
13
|
+
x: number;
|
|
14
|
+
y: number;
|
|
15
|
+
width: number;
|
|
16
|
+
height: number;
|
|
17
|
+
/** Whether this is the primary monitor */
|
|
18
|
+
primary: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Detect all connected displays on this machine.
|
|
23
|
+
* Windows: uses PowerShell + CIM to get monitor positions and IDs.
|
|
24
|
+
* Linux/macOS: uses xrandr / system_profiler (basic fallback).
|
|
25
|
+
*/
|
|
26
|
+
export function detectScreens(logger: Logger): DetectedScreen[] {
|
|
27
|
+
const platform = getPlatform();
|
|
28
|
+
|
|
29
|
+
if (platform === 'windows') {
|
|
30
|
+
return detectScreensWindows(logger);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (platform === 'linux') {
|
|
34
|
+
return detectScreensLinux(logger);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
logger.warn('[Screens] Screen detection not supported on this platform');
|
|
38
|
+
return [];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function detectScreensWindows(logger: Logger): DetectedScreen[] {
|
|
42
|
+
try {
|
|
43
|
+
// PowerShell script — use regular string to avoid JS template literal eating $variables
|
|
44
|
+
const psScript = [
|
|
45
|
+
'Add-Type -AssemblyName System.Windows.Forms;',
|
|
46
|
+
'$screens = [System.Windows.Forms.Screen]::AllScreens;',
|
|
47
|
+
'$result = @();',
|
|
48
|
+
'$i = 0;',
|
|
49
|
+
'foreach ($s in $screens) {',
|
|
50
|
+
' $result += [PSCustomObject]@{',
|
|
51
|
+
' hardwareId = $s.DeviceName;',
|
|
52
|
+
' name = $s.DeviceName;',
|
|
53
|
+
' index = $i;',
|
|
54
|
+
' x = $s.Bounds.X;',
|
|
55
|
+
' y = $s.Bounds.Y;',
|
|
56
|
+
' width = $s.Bounds.Width;',
|
|
57
|
+
' height = $s.Bounds.Height;',
|
|
58
|
+
' primary = $s.Primary',
|
|
59
|
+
' };',
|
|
60
|
+
' $i++',
|
|
61
|
+
'};',
|
|
62
|
+
'$result | ConvertTo-Json -Compress',
|
|
63
|
+
].join(' ');
|
|
64
|
+
|
|
65
|
+
const result = execSync('powershell -NoProfile -Command "' + psScript + '"', {
|
|
66
|
+
encoding: 'utf-8',
|
|
67
|
+
timeout: 10_000,
|
|
68
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
69
|
+
}).trim();
|
|
70
|
+
|
|
71
|
+
if (!result) {
|
|
72
|
+
logger.warn('[Screens] PowerShell returned empty result');
|
|
73
|
+
return [];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// PowerShell returns a single object (not array) when there's only 1 screen
|
|
77
|
+
const parsed = JSON.parse(result);
|
|
78
|
+
const screens: DetectedScreen[] = Array.isArray(parsed) ? parsed : [parsed];
|
|
79
|
+
|
|
80
|
+
logger.info(`[Screens] Detected ${screens.length} display(s)`);
|
|
81
|
+
for (const s of screens) {
|
|
82
|
+
logger.debug(`[Screens] ${s.hardwareId} — ${s.width}x${s.height} @ (${s.x},${s.y})${s.primary ? ' [PRIMARY]' : ''}`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return screens;
|
|
86
|
+
} catch (err) {
|
|
87
|
+
logger.error('[Screens] Failed to detect screens on Windows:', err instanceof Error ? err.message : String(err));
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function detectScreensLinux(logger: Logger): DetectedScreen[] {
|
|
93
|
+
try {
|
|
94
|
+
const result = execSync('xrandr --query', {
|
|
95
|
+
encoding: 'utf-8',
|
|
96
|
+
timeout: 5_000,
|
|
97
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const screens: DetectedScreen[] = [];
|
|
101
|
+
const lines = result.split('\n');
|
|
102
|
+
let index = 0;
|
|
103
|
+
|
|
104
|
+
for (const line of lines) {
|
|
105
|
+
// Match lines like: "HDMI-1 connected primary 1920x1080+0+0"
|
|
106
|
+
const match = line.match(/^(\S+)\s+connected\s+(primary\s+)?(\d+)x(\d+)\+(\d+)\+(\d+)/);
|
|
107
|
+
if (match) {
|
|
108
|
+
screens.push({
|
|
109
|
+
hardwareId: match[1],
|
|
110
|
+
name: match[1],
|
|
111
|
+
index,
|
|
112
|
+
x: parseInt(match[5], 10),
|
|
113
|
+
y: parseInt(match[6], 10),
|
|
114
|
+
width: parseInt(match[3], 10),
|
|
115
|
+
height: parseInt(match[4], 10),
|
|
116
|
+
primary: !!match[2],
|
|
117
|
+
});
|
|
118
|
+
index++;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
logger.info(`[Screens] Detected ${screens.length} display(s) via xrandr`);
|
|
123
|
+
return screens;
|
|
124
|
+
} catch (err) {
|
|
125
|
+
logger.error('[Screens] Failed to detect screens on Linux:', err instanceof Error ? err.message : String(err));
|
|
126
|
+
return [];
|
|
127
|
+
}
|
|
128
|
+
}
|