-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemperature_monitor.py
More file actions
1496 lines (1307 loc) · 52.7 KB
/
Copy pathtemperature_monitor.py
File metadata and controls
1496 lines (1307 loc) · 52.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Record, analyze, plot, and export hardware temperature measurements.
Usage: python3.14 temperature_monitor.py [GLOBAL_OPTIONS] COMMAND [OPTIONS]
Requires psutil and matplotlib; the Windows LHM backend also needs pythonnet.
"""
from __future__ import annotations
import argparse
import csv
import json
import sqlite3
import statistics
import subprocess
import sys
import threading
import time
from abc import ABC, abstractmethod
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, ClassVar
import matplotlib.dates as mdates
import psutil
from matplotlib.backends._backend_tk import NavigationToolbar2Tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
try:
import tkinter as tk
from tkinter import messagebox, ttk
except ImportError as exc: # pragma: no cover - tkinter is part of stdlib on normal installs
raise SystemExit("Tkinter is required for the 'live' mode.") from exc
APP_NAME = "temperature-monitor"
DEFAULT_DB_PATH = Path.home() / ".temperature_monitor.sqlite3"
@dataclass(frozen=True, slots=True)
class SensorDescriptor:
key: str
name: str
component: str
unit: str
source: str
metadata: dict[str, Any]
@dataclass(frozen=True, slots=True)
class SensorReading:
sensor_key: str
captured_at: datetime
value: float
@dataclass(frozen=True, slots=True)
class SessionRecord:
id: int
name: str | None
backend_name: str
started_at: str
ended_at: str | None
def utc_now() -> datetime:
return datetime.now(UTC)
def utc_now_text() -> str:
return utc_now().isoformat()
def parse_timestamp(value: str) -> datetime:
return datetime.fromisoformat(value)
def read_psutil_temperatures() -> dict[str, Any]:
getter = getattr(psutil, "sensors_temperatures", None)
if getter is None:
raise NotImplementedError(
"psutil does not expose sensors_temperatures() in this environment"
)
return getter()
def format_session_label(session: SessionRecord) -> str:
title = session.name or f"session-{session.id}"
return f"{session.id}: {title} [{session.started_at}]"
def quantiles(values: list[float]) -> tuple[float, float, float]:
ordered = sorted(values)
if len(ordered) == 1:
return ordered[0], ordered[0], ordered[0]
quartiles = statistics.quantiles(ordered, n=4, method="inclusive")
return quartiles[0], quartiles[1], quartiles[2]
class MetricBackend(ABC):
backend_name: str
@abstractmethod
def check_support(self) -> tuple[bool, str | None]:
raise NotImplementedError
@abstractmethod
def discover_sensors(self) -> list[SensorDescriptor]:
raise NotImplementedError
@abstractmethod
def sample(self) -> list[SensorReading]:
raise NotImplementedError
def close(self) -> None:
return None
class PsutilTemperatureBackend(MetricBackend):
backend_name = "psutil"
def check_support(self) -> tuple[bool, str | None]:
try:
sensors = read_psutil_temperatures()
except (AttributeError, NotImplementedError) as exc:
return False, f"psutil sensors API is unavailable: {exc}"
if not sensors:
return False, "psutil did not return any temperature sensors on this system"
return True, None
def discover_sensors(self) -> list[SensorDescriptor]:
sensors = read_psutil_temperatures()
descriptors: list[SensorDescriptor] = []
for chip_name, entries in sensors.items():
for index, entry in enumerate(entries):
label = entry.label or f"{chip_name}-{index}"
sensor_key = f"{chip_name}:{label}:{index}"
descriptors.append(
SensorDescriptor(
key=sensor_key,
name=label,
component=chip_name,
unit="C",
source=self.backend_name,
metadata={
"chip": chip_name,
"index": index,
"high": entry.high,
"critical": entry.critical,
},
)
)
return descriptors
def sample(self) -> list[SensorReading]:
captured_at = utc_now()
readings: list[SensorReading] = []
for chip_name, entries in read_psutil_temperatures().items():
for index, entry in enumerate(entries):
if entry.current is None:
continue
label = entry.label or f"{chip_name}-{index}"
sensor_key = f"{chip_name}:{label}:{index}"
readings.append(
SensorReading(
sensor_key=sensor_key,
captured_at=captured_at,
value=float(entry.current),
)
)
return readings
class LibreHardwareMonitorBackend(MetricBackend):
backend_name = "librehardwaremonitor"
REQUIRED_SIBLING_ASSEMBLIES: ClassVar[set[str]] = {
"BlackSharp.Core",
"DiskInfoToolkit",
"HidSharp",
"RAMSPDToolkit-NDD",
"System.Memory",
"System.Runtime.CompilerServices.Unsafe",
}
def __init__(self, dll_path: Path | None = None) -> None:
self._dll_path = dll_path
self._computer: Any | None = None
self._assembly: Any | None = None
def check_support(self) -> tuple[bool, str | None]:
if not sys.platform.startswith("win"):
return False, "LibreHardwareMonitor backend is supported only on Windows"
try:
self._ensure_initialized()
except RuntimeError as exc:
return False, str(exc)
return True, None
def discover_sensors(self) -> list[SensorDescriptor]:
self._ensure_initialized()
descriptors: list[SensorDescriptor] = []
for hardware_name, hardware_type, sensor in self._iter_temperature_sensors():
sensor_key = self._sensor_key(hardware_name, sensor.Name, sensor.Identifier)
descriptors.append(
SensorDescriptor(
key=sensor_key,
name=str(sensor.Name),
component=f"{hardware_type}:{hardware_name}",
unit="C",
source=self.backend_name,
metadata={
"identifier": str(sensor.Identifier),
"hardware_name": hardware_name,
"hardware_type": hardware_type,
},
)
)
return descriptors
def sample(self) -> list[SensorReading]:
self._ensure_initialized()
captured_at = utc_now()
readings: list[SensorReading] = []
for hardware_name, _, sensor in self._iter_temperature_sensors():
if sensor.Value is None:
continue
sensor_key = self._sensor_key(hardware_name, sensor.Name, sensor.Identifier)
readings.append(
SensorReading(
sensor_key=sensor_key,
captured_at=captured_at,
value=float(sensor.Value),
)
)
return readings
def close(self) -> None:
if self._computer is not None:
self._computer.Close()
self._computer = None
self._assembly = None
def _ensure_initialized(self) -> None:
if self._computer is not None:
return
dll_path = self._resolve_dll_path()
try:
import clr # type: ignore[import-not-found]
except ImportError as exc:
raise RuntimeError(
"pythonnet is not installed. Install it first, then provide LibreHardwareMonitorLib.dll."
) from exc
try:
clr.AddReference(str(dll_path)) # type: ignore[attr-defined]
from System import Activator # type: ignore[import-not-found]
from System.Reflection import Assembly # type: ignore[import-not-found]
assembly = Assembly.LoadFile(str(dll_path))
target_framework = self._read_target_framework(assembly)
if target_framework and target_framework.startswith(".NETCoreApp"):
raise RuntimeError(
"The detected LibreHardwareMonitorLib.dll targets "
f"{target_framework}, but pythonnet is running on .NET Framework. "
"Use the LibreHardwareMonitor-net472 build instead of the .NET/NET.10 build."
)
missing_dependencies = self._missing_sibling_assemblies(assembly, dll_path.parent)
if missing_dependencies:
missing_list = ", ".join(f"{name}.dll" for name in missing_dependencies)
raise RuntimeError(
"LibreHardwareMonitor dependencies are missing next to the main DLL: "
f"{missing_list}. Copy the full contents of LibreHardwareMonitor-net472.zip, "
"not just LibreHardwareMonitorLib.dll."
)
computer_type = assembly.GetType("LibreHardwareMonitor.Hardware.Computer")
if computer_type is None:
raise RuntimeError(
"Type LibreHardwareMonitor.Hardware.Computer was not found in the DLL."
)
computer = Activator.CreateInstance(computer_type)
except Exception as exc: # pragma: no cover - depends on external DLL/runtime
raise RuntimeError(
f"Failed to initialize LibreHardwareMonitor from {dll_path}. Original error: {exc}"
) from exc
computer.IsBatteryEnabled = True
computer.IsControllerEnabled = True
computer.IsCpuEnabled = True
computer.IsGpuEnabled = True
computer.IsMemoryEnabled = True
computer.IsMotherboardEnabled = True
computer.IsNetworkEnabled = True
computer.IsPsuEnabled = True
computer.IsStorageEnabled = True
if hasattr(computer, "IsPowerMonitorEnabled"):
computer.IsPowerMonitorEnabled = True
computer.Open()
self._computer = computer
self._assembly = assembly
def _resolve_dll_path(self) -> Path:
candidates: list[Path] = []
if self._dll_path is not None:
candidates.append(normalize_lhm_path(self._dll_path))
env_path = Path.home() / "LibreHardwareMonitor" / "LibreHardwareMonitorLib.dll"
configured_lhm_path = get_configured_lhm_path()
if configured_lhm_path is not None:
candidates.append(configured_lhm_path)
candidates.extend(
[
Path.cwd() / "LibreHardwareMonitorLib.dll",
Path(__file__).resolve().parent / "liblhm" / "LibreHardwareMonitorLib.dll",
Path(__file__).with_name("LibreHardwareMonitorLib.dll"),
env_path,
]
)
for candidate in candidates:
if candidate.is_file():
return candidate
looked = ", ".join(str(path) for path in candidates)
raise RuntimeError(
"LibreHardwareMonitorLib.dll was not found. "
f"Looked in: {looked}. Set TEMPMON_LHM_DLL or use --windows-lhm-dll."
)
def _iter_temperature_sensors(self) -> list[tuple[str, str, Any]]:
assert self._computer is not None
sensors: list[tuple[str, str, Any]] = []
for hardware in self._computer.Hardware:
sensors.extend(self._collect_from_hardware(hardware))
return sensors
def _collect_from_hardware(self, hardware: Any) -> list[tuple[str, str, Any]]:
hardware.Update()
hardware_name = str(hardware.Name)
hardware_type = str(hardware.HardwareType)
found = [
(hardware_name, hardware_type, sensor)
for sensor in hardware.Sensors
if str(sensor.SensorType) == "Temperature"
]
for sub_hardware in hardware.SubHardware:
found.extend(self._collect_from_hardware(sub_hardware))
return found
@staticmethod
def _sensor_key(hardware_name: str, sensor_name: Any, sensor_identifier: Any) -> str:
return f"{hardware_name}:{sensor_name}:{sensor_identifier}"
@staticmethod
def _read_target_framework(assembly: Any) -> str | None:
for attr in assembly.GetCustomAttributesData():
if attr.AttributeType.FullName == "System.Runtime.Versioning.TargetFrameworkAttribute":
arguments = list(attr.ConstructorArguments)
if arguments:
return str(arguments[0].Value)
return None
@classmethod
def _missing_sibling_assemblies(cls, assembly: Any, dll_dir: Path) -> list[str]:
missing: list[str] = []
for reference in assembly.GetReferencedAssemblies():
name = str(reference.Name)
if name not in cls.REQUIRED_SIBLING_ASSEMBLIES:
continue
if not (dll_dir / f"{name}.dll").is_file():
missing.append(name)
return missing
def os_environ() -> Mapping[str, str]:
import os
return os.environ
def normalize_lhm_path(path: Path) -> Path:
if path.is_dir():
return path / "LibreHardwareMonitorLib.dll"
return path
def get_configured_lhm_path() -> Path | None:
value = os_environ().get("TEMPMON_LHM_DLL")
if not value:
return None
return normalize_lhm_path(Path(value))
def is_windows_admin() -> bool:
if not sys.platform.startswith("win"):
return False
try:
import ctypes
windll = vars(ctypes)["windll"]
return bool(windll.shell32.IsUserAnAdmin())
except Exception:
return False
def should_auto_relaunch_as_admin(args: argparse.Namespace) -> bool:
if not sys.platform.startswith("win"):
return False
if args.command not in {"watch", "live"}:
return False
if args.backend == "psutil":
return False
if getattr(args, "_elevated_relaunch", False):
return False
if getattr(args, "no_admin_relaunch", False):
return False
return not is_windows_admin()
def relaunch_as_admin() -> int:
import ctypes
script_path = Path(sys.argv[0]).resolve()
original_args = list(sys.argv[1:])
command_index = next(
(
index
for index, value in enumerate(original_args)
if value in {"watch", "live", "analyze", "stats", "export"}
),
len(original_args),
)
pre_command_args = original_args[:command_index]
post_command_args = original_args[command_index:]
forwarded_args = [str(script_path), *pre_command_args]
configured_lhm_path = get_configured_lhm_path()
if configured_lhm_path is not None and "--windows-lhm-dll" not in original_args:
forwarded_args.extend(["--windows-lhm-dll", str(configured_lhm_path)])
forwarded_args.extend(["--_elevated-relaunch", *post_command_args])
parameters = subprocess.list2cmdline(forwarded_args)
windll = vars(ctypes)["windll"]
result = windll.shell32.ShellExecuteW(
None,
"runas",
sys.executable,
parameters,
str(Path.cwd()),
1,
)
if result <= 32:
raise RuntimeError(
"LibreHardwareMonitor needs administrator rights on this machine to read temperature/clock sensors. "
"UAC elevation was not completed."
)
return 0
def show_windows_error_dialog(title: str, message: str) -> None:
if not sys.platform.startswith("win"):
return
try:
import ctypes
windll = vars(ctypes)["windll"]
windll.user32.MessageBoxW(None, message, title, 0x10)
except Exception:
return
class BackendFactory:
def __init__(self, windows_lhm_dll: Path | None = None) -> None:
self._windows_lhm_dll = windows_lhm_dll
def create(self, requested: str) -> MetricBackend:
backends = self._candidate_backends(requested)
errors: list[str] = []
for backend in backends:
supported, reason = backend.check_support()
if supported:
return backend
errors.append(f"{backend.backend_name}: {reason}")
backend.close()
raise RuntimeError("No supported temperature backend found.\n" + "\n".join(errors))
def _candidate_backends(self, requested: str) -> list[MetricBackend]:
if requested == "psutil":
return [PsutilTemperatureBackend()]
if requested == "librehardwaremonitor":
return [LibreHardwareMonitorBackend(self._windows_lhm_dll)]
if sys.platform.startswith("win"):
return [
LibreHardwareMonitorBackend(self._windows_lhm_dll),
PsutilTemperatureBackend(),
]
return [PsutilTemperatureBackend()]
class MeasurementStore:
def __init__(self, db_path: Path) -> None:
self.db_path = db_path
self.connection = sqlite3.connect(self.db_path)
self.connection.row_factory = sqlite3.Row
self._init_schema()
def close(self) -> None:
self.connection.close()
def _init_schema(self) -> None:
self.connection.executescript(
"""
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
backend_name TEXT NOT NULL,
started_at TEXT NOT NULL,
ended_at TEXT,
metadata_json TEXT NOT NULL DEFAULT '{}'
);
CREATE TABLE IF NOT EXISTS sensors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id INTEGER NOT NULL,
sensor_key TEXT NOT NULL,
name TEXT NOT NULL,
component TEXT NOT NULL,
unit TEXT NOT NULL,
source TEXT NOT NULL,
metadata_json TEXT NOT NULL DEFAULT '{}',
UNIQUE(session_id, sensor_key),
FOREIGN KEY(session_id) REFERENCES sessions(id)
);
CREATE TABLE IF NOT EXISTS measurements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id INTEGER NOT NULL,
sensor_id INTEGER NOT NULL,
captured_at TEXT NOT NULL,
value REAL NOT NULL,
FOREIGN KEY(session_id) REFERENCES sessions(id),
FOREIGN KEY(sensor_id) REFERENCES sensors(id)
);
CREATE INDEX IF NOT EXISTS idx_sessions_started_at ON sessions(started_at DESC);
CREATE INDEX IF NOT EXISTS idx_sensors_session ON sensors(session_id);
CREATE INDEX IF NOT EXISTS idx_measurements_session_time ON measurements(session_id, captured_at);
CREATE INDEX IF NOT EXISTS idx_measurements_sensor_time ON measurements(sensor_id, captured_at);
"""
)
self.connection.commit()
def create_session(
self, backend_name: str, name: str | None, metadata: dict[str, Any]
) -> SessionRecord:
started_at = utc_now_text()
cursor = self.connection.execute(
"""
INSERT INTO sessions (name, backend_name, started_at, metadata_json)
VALUES (?, ?, ?, ?)
""",
(name, backend_name, started_at, json.dumps(metadata, ensure_ascii=False)),
)
self.connection.commit()
session_id = cursor.lastrowid
if session_id is None:
raise RuntimeError("Failed to create a session row.")
return SessionRecord(
id=int(session_id),
name=name,
backend_name=backend_name,
started_at=started_at,
ended_at=None,
)
def mark_session_closed(self, session_id: int) -> None:
self.connection.execute(
"UPDATE sessions SET ended_at = ? WHERE id = ?",
(utc_now_text(), session_id),
)
self.connection.commit()
def clear_session_closed(self, session_id: int) -> None:
self.connection.execute("UPDATE sessions SET ended_at = NULL WHERE id = ?", (session_id,))
self.connection.commit()
def resolve_session(self, session_spec: str | None) -> SessionRecord:
if session_spec is None:
row = self.connection.execute(
"""
SELECT id, name, backend_name, started_at, ended_at
FROM sessions
ORDER BY started_at DESC
LIMIT 1
"""
).fetchone()
if row is None:
raise RuntimeError("There are no sessions yet.")
return self._row_to_session(row)
if session_spec.isdigit():
row = self.connection.execute(
"""
SELECT id, name, backend_name, started_at, ended_at
FROM sessions
WHERE id = ?
""",
(int(session_spec),),
).fetchone()
if row is not None:
return self._row_to_session(row)
row = self.connection.execute(
"""
SELECT id, name, backend_name, started_at, ended_at
FROM sessions
WHERE name = ?
ORDER BY started_at DESC
LIMIT 1
""",
(session_spec,),
).fetchone()
if row is None:
raise RuntimeError(f"Session '{session_spec}' was not found.")
return self._row_to_session(row)
def list_sessions(self) -> list[SessionRecord]:
rows = self.connection.execute(
"""
SELECT id, name, backend_name, started_at, ended_at
FROM sessions
ORDER BY started_at DESC
"""
).fetchall()
return [self._row_to_session(row) for row in rows]
def register_sensors(self, session_id: int, sensors: list[SensorDescriptor]) -> None:
rows = [
(
session_id,
sensor.key,
sensor.name,
sensor.component,
sensor.unit,
sensor.source,
json.dumps(sensor.metadata, ensure_ascii=False),
)
for sensor in sensors
]
self.connection.executemany(
"""
INSERT INTO sensors (session_id, sensor_key, name, component, unit, source, metadata_json)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(session_id, sensor_key) DO UPDATE SET
name = excluded.name,
component = excluded.component,
unit = excluded.unit,
source = excluded.source,
metadata_json = excluded.metadata_json
""",
rows,
)
self.connection.commit()
def insert_measurements(self, session_id: int, readings: list[SensorReading]) -> int:
if not readings:
return 0
sensor_map = self._sensor_ids(session_id)
rows = []
for reading in readings:
sensor_id = sensor_map.get(reading.sensor_key)
if sensor_id is None:
continue
rows.append(
(
session_id,
sensor_id,
reading.captured_at.isoformat(),
reading.value,
)
)
if not rows:
return 0
self.connection.executemany(
"""
INSERT INTO measurements (session_id, sensor_id, captured_at, value)
VALUES (?, ?, ?, ?)
""",
rows,
)
self.connection.commit()
return len(rows)
def get_sensor_rows(self, session_id: int) -> list[sqlite3.Row]:
return self.connection.execute(
"""
SELECT id, sensor_key, name, component, unit, source, metadata_json
FROM sensors
WHERE session_id = ?
ORDER BY component, name
""",
(session_id,),
).fetchall()
def get_measurements_for_session(self, session_id: int) -> list[sqlite3.Row]:
return self.connection.execute(
"""
SELECT
m.captured_at,
m.value,
s.sensor_key,
s.name,
s.component,
s.unit
FROM measurements AS m
JOIN sensors AS s ON s.id = m.sensor_id
WHERE m.session_id = ?
ORDER BY m.captured_at ASC
""",
(session_id,),
).fetchall()
def get_measurements_for_sensor(self, session_id: int, sensor_key: str) -> list[sqlite3.Row]:
return self.connection.execute(
"""
SELECT
m.captured_at,
m.value
FROM measurements AS m
JOIN sensors AS s ON s.id = m.sensor_id
WHERE m.session_id = ? AND s.sensor_key = ?
ORDER BY m.captured_at ASC
""",
(session_id, sensor_key),
).fetchall()
def _sensor_ids(self, session_id: int) -> dict[str, int]:
rows = self.connection.execute(
"SELECT sensor_key, id FROM sensors WHERE session_id = ?",
(session_id,),
).fetchall()
return {str(row["sensor_key"]): int(row["id"]) for row in rows}
@staticmethod
def _row_to_session(row: sqlite3.Row) -> SessionRecord:
session_id = row["id"]
if session_id is None:
raise RuntimeError("Session row does not contain an id.")
return SessionRecord(
id=int(session_id),
name=row["name"],
backend_name=str(row["backend_name"]),
started_at=str(row["started_at"]),
ended_at=row["ended_at"],
)
class Recorder:
def __init__(
self, store: MeasurementStore, backend: MetricBackend, session: SessionRecord
) -> None:
self.store = store
self.backend = backend
self.session = session
def prepare(self) -> list[SensorDescriptor]:
sensors = self.backend.discover_sensors()
if not sensors:
raise RuntimeError("No temperature sensors were discovered.")
self.store.register_sensors(self.session.id, sensors)
return sensors
def capture_once(self) -> int:
readings = self.backend.sample()
inserted = self.store.insert_measurements(self.session.id, readings)
if inserted == 0 and readings:
sensors = self.backend.discover_sensors()
if sensors:
self.store.register_sensors(self.session.id, sensors)
inserted = self.store.insert_measurements(self.session.id, readings)
return inserted
def collect_initial_readings(
backend: MetricBackend,
attempts: int = 5,
delay_seconds: float = 0.5,
) -> list[SensorReading]:
for attempt in range(attempts):
readings = backend.sample()
if readings:
return readings
if attempt < attempts - 1:
time.sleep(delay_seconds)
return []
def describe_sensor_readability(
backend: MetricBackend,
sensors: list[SensorDescriptor],
readings: list[SensorReading],
) -> str:
if not sensors:
return "No temperature sensors were discovered yet."
if readings:
return f"Discovered {len(sensors)} sensors and collected {len(readings)} readings."
if backend.backend_name == "librehardwaremonitor" and not is_windows_admin():
return (
f"Discovered {len(sensors)} sensors via {backend.backend_name}, "
"but readable temperature values are not available in this non-admin session. "
"Relaunch elevated to unlock MSR-backed CPU temperature sensors."
)
return (
f"Discovered {len(sensors)} sensors via {backend.backend_name}, "
"but none of them currently expose readable temperature values."
)
def bootstrap_new_session(
store: MeasurementStore,
backend: MetricBackend,
session_name: str | None,
metadata: dict[str, Any],
) -> tuple[SessionRecord, Recorder, list[SensorDescriptor], int]:
sensors = backend.discover_sensors()
if not sensors:
raise RuntimeError("No temperature sensors were discovered.")
initial_readings = collect_initial_readings(backend)
if not initial_readings:
raise RuntimeError(
"Temperature sensors were discovered, but no readable temperature values were returned."
)
session = store.create_session(
backend_name=backend.backend_name,
name=session_name,
metadata=metadata,
)
store.register_sensors(session.id, sensors)
inserted = store.insert_measurements(session.id, initial_readings)
if inserted == 0:
raise RuntimeError(
"Initial temperature readings were collected, but they did not match the registered sensors."
)
return session, Recorder(store, backend, session), sensors, inserted
def wait_for_bootstrap_session(
store: MeasurementStore,
backend: MetricBackend,
session_name: str | None,
metadata: dict[str, Any],
interval_seconds: float,
) -> tuple[SessionRecord, Recorder, list[SensorDescriptor], int]:
while True:
sensors = backend.discover_sensors()
readings = collect_initial_readings(backend, attempts=1, delay_seconds=0.0)
if sensors and readings:
session = store.create_session(
backend_name=backend.backend_name,
name=session_name,
metadata=metadata,
)
store.register_sensors(session.id, sensors)
inserted = store.insert_measurements(session.id, readings)
if inserted == 0:
raise RuntimeError(
"Initial temperature readings were collected, but they did not match the registered sensors."
)
return session, Recorder(store, backend, session), sensors, inserted
print(describe_sensor_readability(backend, sensors, readings))
time.sleep(interval_seconds)
class WatchWorker:
def __init__(
self,
db_path: Path,
factory: BackendFactory,
backend_name: str,
session_id: int | None,
interval_seconds: float,
session_name: str | None = None,
metadata: dict[str, Any] | None = None,
) -> None:
self.db_path = db_path
self.factory = factory
self.backend_name = backend_name
self.session_id = session_id
self.interval_seconds = interval_seconds
self.session_name = session_name
self.metadata = metadata or {}
self._stop_event = threading.Event()
thread_suffix = session_id if session_id is not None else "pending"
self._thread = threading.Thread(target=self._run, name=f"watch-session-{thread_suffix}")
self._status_lock = threading.Lock()
self._status = "Collector is starting..."
self._error: str | None = None
def start(self) -> None:
self._thread.start()
def stop(self) -> None:
self._stop_event.set()
self._thread.join(timeout=max(1.0, self.interval_seconds + 1.0))
def status_text(self) -> str:
with self._status_lock:
return self._status
def error_text(self) -> str | None:
with self._status_lock:
return self._error
def _set_status(self, status: str, error: str | None = None) -> None:
with self._status_lock:
self._status = status
self._error = error
def _run(self) -> None:
store = MeasurementStore(self.db_path)
backend: MetricBackend | None = None
active_session_id: int | None = None
try:
backend = self.factory.create(self.backend_name)
if self.session_id is None:
session, recorder, sensors, inserted = self._wait_for_new_session(store, backend)
self.session_id = session.id
active_session_id = session.id
self._set_status(
f"Collecting into session {session.id} with {len(sensors)} sensors every {self.interval_seconds:g}s. "
f"Initial insert: {inserted} readings."
)
else:
session = store.resolve_session(str(self.session_id))
active_session_id = session.id
recorder = Recorder(store, backend, session)
sensors = recorder.prepare()
self._set_status(
f"Collecting into session {session.id} with {len(sensors)} sensors every {self.interval_seconds:g}s."
)
while not self._stop_event.is_set():
inserted = recorder.capture_once()
self._set_status(
f"Collecting into session {session.id}; last insert: {inserted} readings."
)
if self._stop_event.wait(self.interval_seconds):
break
except Exception as exc:
session_label = self.session_id if self.session_id is not None else "pending session"
self._set_status(f"Collector error in session {session_label}: {exc}", error=str(exc))
finally:
try:
if active_session_id is not None:
store.mark_session_closed(active_session_id)
finally:
if backend is not None:
backend.close()
store.close()
def _wait_for_new_session(
self,
store: MeasurementStore,
backend: MetricBackend,
) -> tuple[SessionRecord, Recorder, list[SensorDescriptor], int]:
while not self._stop_event.is_set():
sensors = backend.discover_sensors()
readings = collect_initial_readings(backend, attempts=1, delay_seconds=0.0)
if sensors and readings:
session = store.create_session(
backend_name=backend.backend_name,
name=self.session_name,
metadata=self.metadata,
)
store.register_sensors(session.id, sensors)
inserted = store.insert_measurements(session.id, readings)
if inserted == 0:
raise RuntimeError(
"Initial temperature readings were collected, but they did not match the registered sensors."
)
return session, Recorder(store, backend, session), sensors, inserted
self._set_status(describe_sensor_readability(backend, sensors, readings))
if self._stop_event.wait(self.interval_seconds):
raise RuntimeError(
"Collector was stopped before any readable temperature values appeared."
)
raise RuntimeError("Collector was stopped before initialization.")
class LiveMonitorWindow:
def __init__(
self,
store: MeasurementStore,
initial_session_id: int | None,