okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-life (final 576d06553) into f-0213-int66331f9bc

main
8.2 KiB170 linesraw
1/**
2 * CPU and SSD temperatures for the Monitor's Power card (#3628). A value that this PC cannot give stays null and its line is left out,
3 * so the card never shows a made-up number.
4 *
5 * Linux: the kernel's hwmon sensors (coretemp, k10temp, zenpower for the processor; nvme and drivetemp for the drives).
6 * Windows: the drive reports its own temperature to a query that needs no administrator (IOCTL_STORAGE_QUERY_PROPERTY with the device
7 *   temperature property). Get-StorageReliabilityCounter is tried first because it is the documented route; on a normal account it is
8 *   refused, then the query is used. One long-lived PowerShell asks every 30 s (windows-poll.mjs).
9 *   There is no unprivileged, trustworthy processor temperature on Windows, so none is shown there.
10 * macOS: none.
11 */
12import { readFile, readdir } from 'node:fs/promises';
13import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
14import { spawn } from 'node:child_process';
15import { dirname, join } from 'node:path';
16import { createPowerShellLoop, endWithHost } from './windows-poll.mjs';
17import { stateRoot } from './platform-paths.mjs';
18
19const CPU_SENSORS = new Set(['coretemp', 'k10temp', 'zenpower', 'cpu_thermal', 'cpu-thermal']);
20const DISK_SENSORS = new Set(['nvme', 'drivetemp']);
21const plausible = c => Number.isFinite(c) && c > 0 && c < 150;
22
23/** hwmon entries [{name, temps: [milli-degrees…]}] -> the hottest processor and drive sensor. */
24export function pickTemperatures(entries) {
25  let cpu = null, ssd = null;
26  for (const { name, temps } of entries) {
27    const hottest = Math.max(...temps.map(t => t / 1000).filter(plausible), -Infinity);
28    if (!Number.isFinite(hottest)) continue;
29    if (CPU_SENSORS.has(name)) cpu = Math.max(cpu ?? -Infinity, hottest);
30    else if (DISK_SENSORS.has(name)) ssd = Math.max(ssd ?? -Infinity, hottest);
31  }
32  return { cpuTempC: cpu === null ? null : Math.round(cpu), ssdTempC: ssd === null ? null : Math.round(ssd) };
33}
34
35export async function readLinuxTemperatures({ base = '/sys/class/hwmon', read = readFile, list = readdir } = {}) {
36  const entries = [];
37  let folders = [];
38  try { folders = await list(base); } catch { return { cpuTempC: null, ssdTempC: null }; }
39  for (const folder of folders) {
40    try {
41      const name = String(await read(`${base}/${folder}/name`, 'utf8')).trim();
42      if (!CPU_SENSORS.has(name) && !DISK_SENSORS.has(name)) continue;
43      const files = (await list(`${base}/${folder}`)).filter(f => /^temp\d+_input$/.test(f));
44      const temps = [];
45      for (const file of files) temps.push(Number(String(await read(`${base}/${folder}/${file}`, 'utf8')).trim()));
46      entries.push({ name, temps });
47    } catch { /* a sensor that disappears is skipped */ }
48  }
49  return pickTemperatures(entries);
50}
51
52/** One line of the Windows loop: "ssd 53" or "ssd -". */
53export function parseSsdLine(line) {
54  const m = /^\s*ssd\s+(-?\d+|-)\s*$/.exec(String(line));
55  if (!m) return undefined;
56  const value = m[1] === '-' ? NaN : Number(m[1]);
57  return plausible(value) ? value : null;
58}
59
60const WINDOWS_SCRIPT = String.raw`
61$ErrorActionPreference='SilentlyContinue'
62$cs=@'
63using System;
64using System.Runtime.InteropServices;
65public static class StrataDiskTemp {
66  [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateFile(string n, uint a, uint s, IntPtr p, uint d, uint f, IntPtr t);
67  [DllImport("kernel32.dll", SetLastError=true)] static extern bool DeviceIoControl(IntPtr h, uint c, byte[] i, uint il, byte[] o, uint ol, out uint r, IntPtr ov);
68  [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
69  public static int Read(int n) {
70    IntPtr h = CreateFile("\\\\.\\PhysicalDrive" + n, 0, 3, IntPtr.Zero, 3, 0, IntPtr.Zero);
71    if (h == (IntPtr)(-1)) return -1;
72    try {
73      byte[] q = new byte[12]; q[0] = 0x34; byte[] o = new byte[512]; uint r;
74      if (!DeviceIoControl(h, 0x002D1400, q, 12, o, 512, out r, IntPtr.Zero)) return -1;
75      if (BitConverter.ToUInt16(o, 12) < 1) return -1;
76      return BitConverter.ToInt16(o, 26);
77    } finally { CloseHandle(h); }
78  }
79}
80'@
81$compiled=$false
82while($true){
83  $max=-1
84  $c=@(Get-PhysicalDisk | Get-StorageReliabilityCounter | Where-Object { $_.Temperature -gt 0 })
85  if($c.Count -gt 0){ $max=($c | Measure-Object Temperature -Maximum).Maximum }
86  else {
87    if(-not $compiled){ Add-Type -TypeDefinition $cs; $compiled=$true }
88    # only drives Windows names as NVMe, one at a time: a RAID, SATA, USB or unknown drive is never asked (a driver stack that stalls on this query
89    # froze whole PCs, #4661)
90    foreach($d in @(Get-PhysicalDisk | Where-Object { $_.BusType -eq 'NVMe' })){ $v=[StrataDiskTemp]::Read([int]$d.DeviceId); if($v -gt $max){ $max=$v } }
91  }
92  if($max -gt 0){ [Console]::Out.WriteLine('ssd '+$max) } else { [Console]::Out.WriteLine('ssd -') }
93  [Console]::Out.Flush()
94  Start-Sleep -Seconds 30
95}`;
96
97/** How long the first pass of the reader may take before it is given up for good (a healthy pass takes a second or two). */
98export const FIRST_PASS_MS = 45_000;
99
100/** The marker file the reader leaves before it asks the drives and removes after its first answer. */
101export const sentinelPath = (env = process.env, platform = process.platform) => join(stateRoot(env, platform), 'drive-temperature.probe');
102
103/**
104 * `sentinel`: { exists(), write(), remove() }. The reader leaves the marker before it first asks a drive and removes it when the first answer has come. A host
105 * that is still there with a marker at its next start died, or the PC did, in the middle of the question: the reader stays off from then on (the line is left
106 * out of the Monitor; deleting the file brings it back). It never asks again after a first pass that took longer than FIRST_PASS_MS either.
107 */
108export function createWindowsSsdReader({ spawnFn = spawn, maxStarts = 2, now = Date.now, intervalSec = 30, sentinel = null, firstPassMs = FIRST_PASS_MS } = {}) {
109  let latest = null, off = false, startedAt = null;
110  const loop = createPowerShellLoop({
111    script: WINDOWS_SCRIPT, spawnFn, maxStarts,
112    onLine: line => {
113      const parsed = parseSsdLine(line);
114      if (parsed === undefined) return false;
115      latest = { value: parsed, at: now() };
116      if (sentinel) { try { sentinel.remove(); } catch { /* best effort */ } }
117      return true;
118    },
119  });
120  return {
121    read() {
122      if (off) return null;
123      if (startedAt === null) {
124        if (sentinel) {
125          try { if (sentinel.exists()) { off = true; return null; } sentinel.write(); } catch { off = true; return null; }   // cannot leave the marker: do not ask
126        }
127        startedAt = now();
128      } else if (latest === null && now() - startedAt > firstPassMs) {
129        off = true;                                    // the first pass is stuck: ended, and the marker stays
130        loop.stop();
131        return null;
132      }
133      loop.start();
134      return latest && now() - latest.at < 4 * intervalSec * 1000 ? latest.value : null;
135    },
136    stop() { loop.stop(); },
137    get starts() { return loop.starts; },
138    get off() { return off; },
139  };
140}
141
142/** The real marker file under Strata's state folder. */
143export function fileSentinel(path = sentinelPath()) {
144  return {
145    exists: () => existsSync(path),
146    write: () => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, String(Date.now())); },
147    remove: () => rmSync(path, { force: true }),
148  };
149}
150
151let windowsReader = null;
152let linuxCache = { at: 0, value: { cpuTempC: null, ssdTempC: null } };
153
154/** The temperatures this PC can give now: { cpuTempC, ssdTempC } (null where unreadable). Cheap to call every few seconds. */
155export async function readTemperatures({ platform = process.platform, now = Date.now } = {}) {
156  if (platform === 'linux') {
157    if (now() - linuxCache.at > 10_000) linuxCache = { at: now(), value: await readLinuxTemperatures() };
158    return linuxCache.value;
159  }
160  if (platform === 'win32') {
161    windowsReader ??= endWithHost(createWindowsSsdReader({ sentinel: fileSentinel() }));
162    return { cpuTempC: null, ssdTempC: windowsReader.read() };
163  }
164  return { cpuTempC: null, ssdTempC: null };
165}
166
167/** Ends the Windows drive-temperature loop (the Monitor has not been open for a while); the next read starts it again. */
168export function stopTemperatures() {
169  if (windowsReader) { windowsReader.stop(); windowsReader = null; }
170}