okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
66331f9bc
main
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 ) { 25let cpu = null , ssd = null ; 26for ( const { name, temps} of entries ) { 27const hottest = Math . max ( ...temps . map ( t => t / 1000 ). filter ( plausible ), - Infinity ); 28if ( ! Number . isFinite ( hottest )) continue ; 29if ( CPU_SENSORS . has ( name )) cpu = Math . max ( cpu ?? - Infinity , hottest ); 30else if ( DISK_SENSORS . has ( name )) ssd = Math . max ( ssd ?? - Infinity , hottest ); 31} 32return { 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 } = {}) { 36const entries = []; 37let folders = []; 38try { folders = await list ( base ); } catch { return { cpuTempC :null , ssdTempC :null }; } 39for ( const folder of folders ) { 40try { 41const name = String ( await read ( ` ${ base } / ${ folder } /name` , 'utf8' )). trim (); 42if ( ! CPU_SENSORS . has ( name ) && ! DISK_SENSORS . has ( name )) continue ; 43const files = ( await list ( ` ${ base } / ${ folder } ` )). filter ( f => / ^temp\d + _input$ / . test ( f )); 44const temps = []; 45for ( const file of files ) temps . push ( Number ( String ( await read ( ` ${ base } / ${ folder } / ${ file } ` , 'utf8' )). trim ())); 46entries . push ({ name, temps}); 47} catch { /* a sensor that disappears is skipped */ } 48} 49return pickTemperatures ( entries ); 50} 51 52/** One line of the Windows loop: "ssd 53" or "ssd -". */ 53export function parseSsdLine ( line ) { 54const m = / ^\s * ssd\s + ( - ? \d +| - ) \s * $ / . exec ( String ( line )); 55if ( ! m ) return undefined ; 56const value = m [ 1 ] === '-' ?NaN :Number ( m [ 1 ]); 57return 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); 69public static int Read(int n) { 70IntPtr h = CreateFile("\\\\.\\PhysicalDrive" + n, 0, 3, IntPtr.Zero, 3, 0, IntPtr.Zero); 71if (h == (IntPtr)(-1)) return -1; 72try { 73byte[] q = new byte[12]; q[0] = 0x34; byte[] o = new byte[512]; uint r; 74if (!DeviceIoControl(h, 0x002D1400, q, 12, o, 512, out r, IntPtr.Zero)) return -1; 75if (BitConverter.ToUInt16(o, 12) < 1) return -1; 76return 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 }) 85if($c.Count -gt 0){ $max=($c | Measure-Object Temperature -Maximum).Maximum } 86else { 87if(-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) 90foreach($d in @(Get-PhysicalDisk | Where-Object { $_.BusType -eq 'NVMe' })){ $v=[StrataDiskTemp]::Read([int]$d.DeviceId); if($v -gt $max){ $max=$v } } 91} 92if($max -gt 0){ [Console]::Out.WriteLine('ssd '+$max) } else { [Console]::Out.WriteLine('ssd -') } 93[Console]::Out.Flush() 94Start-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 } = {}) { 109let latest = null , off = false , startedAt = null ; 110const loop = createPowerShellLoop ({ 111script :WINDOWS_SCRIPT , spawnFn, maxStarts, 112onLine :line => { 113const parsed = parseSsdLine ( line ); 114if ( parsed === undefined ) return false ; 115latest = { value :parsed , at :now () }; 116if ( sentinel ) { try { sentinel . remove (); } catch { /* best effort */ } } 117return true ; 118}, 119}); 120return { 121read () { 122if ( off ) return null ; 123if ( startedAt === null ) { 124if ( sentinel ) { 125try { if ( sentinel . exists ()) { off = true ; return null ; } sentinel . write (); } catch { off = true ; return null ; } // cannot leave the marker: do not ask 126} 127startedAt = now (); 128} else if ( latest === null && now () - startedAt > firstPassMs ) { 129off = true ; // the first pass is stuck: ended, and the marker stays 130loop . stop (); 131return null ; 132} 133loop . start (); 134return latest && now () - latest . at < 4 * intervalSec * 1000 ?latest . value :null ; 135}, 136stop () { loop . stop (); }, 137get starts () { return loop . starts ; }, 138get off () { return off ; }, 139}; 140} 141 142/** The real marker file under Strata's state folder. */ 143export function fileSentinel ( path = sentinelPath ()) { 144return { 145exists :() => existsSync ( path ), 146write :() => { mkdirSync ( dirname ( path ), { recursive :true }); writeFileSync ( path , String ( Date . now ())); }, 147remove :() => 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 } = {}) { 156if ( platform === 'linux' ) { 157if ( now () - linuxCache . at > 10_000 ) linuxCache = { at :now (), value :await readLinuxTemperatures () }; 158return linuxCache . value ; 159} 160if ( platform === 'win32' ) { 161windowsReader ??= endWithHost ( createWindowsSsdReader ({ sentinel :fileSentinel () })); 162return { cpuTempC :null , ssdTempC :windowsReader . read () }; 163} 164return { 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 () { 169if ( windowsReader ) { windowsReader . stop (); windowsReader = null ; } 170}