sensitivebox 0.1.0__py3-none-any.whl

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.
Files changed (95) hide show
  1. sensitivebox/__init__.py +10 -0
  2. sensitivebox/alerts/__init__.py +94 -0
  3. sensitivebox/alerts/config.py +85 -0
  4. sensitivebox/alerts/defaults.toml +126 -0
  5. sensitivebox/alerts/engine.py +624 -0
  6. sensitivebox/alerts/events.py +87 -0
  7. sensitivebox/alerts/globs.py +84 -0
  8. sensitivebox/alerts/model.py +215 -0
  9. sensitivebox/alerts/mute.py +55 -0
  10. sensitivebox/alerts/replay.py +99 -0
  11. sensitivebox/alerts/routing.py +247 -0
  12. sensitivebox/api/__init__.py +6 -0
  13. sensitivebox/api/app.py +225 -0
  14. sensitivebox/api/data.py +109 -0
  15. sensitivebox/api/host.py +27 -0
  16. sensitivebox/api/model.py +90 -0
  17. sensitivebox/api/security.py +89 -0
  18. sensitivebox/api/server.py +108 -0
  19. sensitivebox/api/state.py +220 -0
  20. sensitivebox/api/static/assets/archivo-latin-wdth-normal-DY7AcnAa.woff2 +0 -0
  21. sensitivebox/api/static/assets/ibm-plex-mono-medium-BpyVxOr_.woff2 +0 -0
  22. sensitivebox/api/static/assets/index-BH9EydfS.js +10 -0
  23. sensitivebox/api/static/assets/index-RMruxW54.css +1 -0
  24. sensitivebox/api/static/assets/mark-on-dark-CpSxozdM.png +0 -0
  25. sensitivebox/api/static/assets/mark-on-light-DgUAeHTp.png +0 -0
  26. sensitivebox/api/static/assets/mark-raised-Bg5z6PGs.png +0 -0
  27. sensitivebox/api/static/index.html +14 -0
  28. sensitivebox/browser.py +106 -0
  29. sensitivebox/cli.py +467 -0
  30. sensitivebox/collector.py +319 -0
  31. sensitivebox/completion.py +117 -0
  32. sensitivebox/daemon.py +181 -0
  33. sensitivebox/data/icons/128.png +0 -0
  34. sensitivebox/data/icons/256.png +0 -0
  35. sensitivebox/data/icons/512.png +0 -0
  36. sensitivebox/data/proart-p16.tar.gz +0 -0
  37. sensitivebox/data/sensitivebox.desktop.in +8 -0
  38. sensitivebox/data/sensitivebox.service.in +11 -0
  39. sensitivebox/doctor.py +322 -0
  40. sensitivebox/fixtures.py +177 -0
  41. sensitivebox/history.py +298 -0
  42. sensitivebox/hwmon/__init__.py +20 -0
  43. sensitivebox/hwmon/classify.py +74 -0
  44. sensitivebox/hwmon/discovery.py +139 -0
  45. sensitivebox/hwmon/ids.py +35 -0
  46. sensitivebox/hwmon/model.py +78 -0
  47. sensitivebox/hwmon/normalise.py +42 -0
  48. sensitivebox/hwmon/reader.py +65 -0
  49. sensitivebox/inspect.py +175 -0
  50. sensitivebox/live.py +56 -0
  51. sensitivebox/notify/__init__.py +7 -0
  52. sensitivebox/notify/base.py +60 -0
  53. sensitivebox/notify/desktop.py +84 -0
  54. sensitivebox/notify/log.py +30 -0
  55. sensitivebox/operations.py +44 -0
  56. sensitivebox/output.py +76 -0
  57. sensitivebox/process.py +25 -0
  58. sensitivebox/py.typed +0 -0
  59. sensitivebox/redact.py +85 -0
  60. sensitivebox/report.py +357 -0
  61. sensitivebox/runtime.py +313 -0
  62. sensitivebox/sample.py +84 -0
  63. sensitivebox/service.py +112 -0
  64. sensitivebox/simulate.py +220 -0
  65. sensitivebox/sources/__init__.py +83 -0
  66. sensitivebox/sources/apps.py +135 -0
  67. sensitivebox/sources/bluez.py +96 -0
  68. sensitivebox/sources/bluez_watch.py +214 -0
  69. sensitivebox/sources/changes.py +121 -0
  70. sensitivebox/sources/cpu.py +152 -0
  71. sensitivebox/sources/dbus.py +174 -0
  72. sensitivebox/sources/logind.py +88 -0
  73. sensitivebox/sources/memory.py +127 -0
  74. sensitivebox/sources/net.py +128 -0
  75. sensitivebox/sources/power_profiles.py +116 -0
  76. sensitivebox/sources/power_supply.py +70 -0
  77. sensitivebox/sources/psi.py +78 -0
  78. sensitivebox/sources/report.py +85 -0
  79. sensitivebox/sources/wifi.py +90 -0
  80. sensitivebox/sources/wifi_nm.py +269 -0
  81. sensitivebox/status.py +205 -0
  82. sensitivebox/store/__init__.py +5 -0
  83. sensitivebox/store/changes.py +58 -0
  84. sensitivebox/store/db.py +423 -0
  85. sensitivebox/store/events.py +337 -0
  86. sensitivebox/store/mutes.py +58 -0
  87. sensitivebox/store/quality.py +51 -0
  88. sensitivebox/store/read.py +40 -0
  89. sensitivebox/store/schema.py +194 -0
  90. sensitivebox/store/status.py +105 -0
  91. sensitivebox-0.1.0.dist-info/METADATA +424 -0
  92. sensitivebox-0.1.0.dist-info/RECORD +95 -0
  93. sensitivebox-0.1.0.dist-info/WHEEL +4 -0
  94. sensitivebox-0.1.0.dist-info/entry_points.txt +4 -0
  95. sensitivebox-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,298 @@
1
+ """Bounded incident history, event following and rule replay through the live engine."""
2
+
3
+ import subprocess
4
+ import threading
5
+ import time
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass
8
+ from datetime import datetime, timedelta
9
+ from pathlib import Path
10
+
11
+ import msgspec
12
+
13
+ from sensitivebox.alerts.engine import Evaluation, format_duration
14
+ from sensitivebox.alerts.model import parse_duration
15
+ from sensitivebox.alerts.replay import replay
16
+ from sensitivebox.alerts.routing import Notification
17
+ from sensitivebox.output import Output
18
+ from sensitivebox.redact import redact
19
+ from sensitivebox.store.events import AlertEvent, Events, Incident, IncidentSummary
20
+ from sensitivebox.store.quality import Weekly, local_zone
21
+ from sensitivebox.store.read import inputs, reader
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class IncidentLog:
26
+ incident: Incident
27
+ events: tuple[AlertEvent, ...]
28
+ summary: IncidentSummary | None = None
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class LogView:
33
+ incidents: tuple[IncidentLog, ...]
34
+ truncated: bool
35
+ since: float
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class RuleReplay:
40
+ rule_id: str
41
+ evaluations: tuple[Evaluation, ...]
42
+ reason: str | None = None
43
+
44
+
45
+ def parse_since(value: str | None, now: float) -> float:
46
+ local = datetime.fromtimestamp(now, local_zone())
47
+ if value is None or value == "yesterday":
48
+ return (
49
+ (local - timedelta(days=1))
50
+ .replace(hour=0, minute=0, second=0, microsecond=0)
51
+ .timestamp()
52
+ )
53
+ try:
54
+ return now - parse_duration(value)
55
+ except ValueError:
56
+ pass
57
+ try:
58
+ date = datetime.fromisoformat(value)
59
+ if date.tzinfo is None:
60
+ date = date.replace(tzinfo=local_zone())
61
+ return date.timestamp()
62
+ except ValueError:
63
+ raise ValueError("--since needs a duration, yesterday, ISO date or timestamp") from None
64
+
65
+
66
+ def rule_replay(path: Path, rule: str) -> RuleReplay:
67
+ events = inputs(path)
68
+ result = replay([], events)
69
+ rows = tuple(e for e in result.evaluations if e.rule_id == rule)
70
+ return RuleReplay(rule, rows, None if rows else "no retained evaluations for this rule")
71
+
72
+
73
+ def log_view(path: Path, since: float, limit: int, rule: str | None = None) -> LogView:
74
+ with reader(path) as db:
75
+ if db is None:
76
+ return LogView((), False, since)
77
+ rows = db.execute(
78
+ "SELECT * FROM alert_incidents WHERE (closed IS NULL OR closed>=?)"
79
+ " AND (? IS NULL OR rule_id=?) ORDER BY opened DESC,id DESC LIMIT ?",
80
+ (since, rule, rule, limit + 1),
81
+ ).fetchall()
82
+ result: list[IncidentLog] = []
83
+ truncated = len(rows) > limit
84
+ for row in rows[:limit]:
85
+ incident = Incident(*row)
86
+ # Bound event rows too; only the newest routing facts are needed in the summary.
87
+ events = tuple(
88
+ e
89
+ for e in Events(db, time.time, writer=False).history(
90
+ 0, limit + 1, incident=incident.id
91
+ )
92
+ if e.incident_id == incident.id
93
+ )
94
+ truncated |= len(events) > limit
95
+ summary = db.execute(
96
+ "SELECT name,severity,peak,unit FROM incident_summaries WHERE incident_id=?",
97
+ (incident.id,),
98
+ ).fetchone()
99
+ result.append(
100
+ IncidentLog(
101
+ incident, events[:limit], None if summary is None else IncidentSummary(*summary)
102
+ )
103
+ )
104
+ return LogView(tuple(result), truncated, since)
105
+
106
+
107
+ def render_log(view: LogView, now: float) -> str:
108
+ today = datetime.fromtimestamp(now, local_zone()).date()
109
+ lines: list[str] = []
110
+ heading = ""
111
+ for item in view.incidents:
112
+ incident = item.incident
113
+ stamp = datetime.fromtimestamp(incident.opened, local_zone())
114
+ label = (
115
+ "Today"
116
+ if stamp.date() == today
117
+ else "Yesterday"
118
+ if stamp.date() == today - timedelta(days=1)
119
+ else stamp.date().isoformat()
120
+ )
121
+ if heading != label:
122
+ lines.append(label)
123
+ heading = label
124
+ reasons = (
125
+ ", ".join(
126
+ dict.fromkeys(
127
+ "muted (quiet hours)" if e.reason == "quiet hours" else e.reason
128
+ for e in reversed(item.events)
129
+ )
130
+ )
131
+ or "recorded"
132
+ )
133
+ status = (
134
+ "open"
135
+ if incident.closed is None
136
+ else f"resolved {datetime.fromtimestamp(incident.closed, local_zone()):%H:%M}"
137
+ )
138
+ summary = item.summary
139
+ severity = (
140
+ summary.severity
141
+ if summary is not None
142
+ else item.events[0].notification.severity
143
+ if item.events
144
+ else "unknown"
145
+ )
146
+ name = summary.name if summary is not None else incident.rule_id
147
+ peak = (
148
+ f"{summary.peak:g} {summary.unit}".rstrip()
149
+ if summary is not None and summary.peak is not None
150
+ else "unavailable"
151
+ )
152
+ duration = (
153
+ format_duration(incident.active_s)
154
+ .replace(" min", "m")
155
+ .replace(" s", "s")
156
+ .replace(" h", "h")
157
+ )
158
+ incomplete = " · duration incomplete" if incident.incomplete else ""
159
+ lines.append(
160
+ f" {stamp:%H:%M} {severity.upper():8} {name:16} firing {duration}"
161
+ f" peak {peak} · {status} · {reasons}{incomplete}"
162
+ )
163
+ if view.truncated:
164
+ lines.append("Truncated at --limit; narrow --since or raise --limit.")
165
+ return "\n".join(lines) or "No alerts in this period."
166
+
167
+
168
+ def follow(
169
+ path: Path,
170
+ since: float,
171
+ limit: int,
172
+ rule: str | None,
173
+ output: Output,
174
+ *,
175
+ wait: Callable[[float], bool] | None = None,
176
+ ) -> None:
177
+ wait = wait or threading.Event().wait
178
+ cursor = 0
179
+ while True:
180
+ with reader(path) as db:
181
+ if db is not None:
182
+ rows = db.execute(
183
+ "SELECT id,incident_id,ts,kind,reason,notification FROM alert_events"
184
+ " WHERE id>? AND ts>=? AND (? IS NULL OR incident_id IN"
185
+ " (SELECT id FROM alert_incidents WHERE rule_id=?)) ORDER BY id LIMIT ?",
186
+ (cursor, since, rule, rule, limit + 1),
187
+ ).fetchall()
188
+
189
+ for row in rows[:limit]:
190
+ event = AlertEvent(
191
+ row[0],
192
+ row[1],
193
+ row[2],
194
+ row[3],
195
+ row[4],
196
+ msgspec.json.decode(row[5], type=Notification),
197
+ )
198
+ cursor = event.id
199
+ output.emit(
200
+ "alert_event",
201
+ event,
202
+ f"{event.kind} · {event.notification.rule_id}"
203
+ f" · {event.reason} · {event.notification.body}",
204
+ )
205
+ if len(rows) > limit:
206
+ output.emit("truncated", True, "Truncated batch at --limit; continuing.")
207
+ continue
208
+ if wait(0.5):
209
+ return
210
+
211
+
212
+ def journal(since: str | None, limit: int, following: bool, output: Output) -> int:
213
+ args = [
214
+ "journalctl",
215
+ "--user",
216
+ "--unit=sensitivebox.service",
217
+ "--no-pager",
218
+ f"--lines={limit}",
219
+ "--output=short-iso",
220
+ ]
221
+ stamp = datetime.fromtimestamp(parse_since(since, time.time()), local_zone())
222
+ args += ["--since", stamp.isoformat(sep=" ")]
223
+ if following:
224
+ args.append("--follow")
225
+ if not following:
226
+ try:
227
+ result = subprocess.run( # noqa: S603 - fixed executable, no shell
228
+ args,
229
+ capture_output=True,
230
+ text=True,
231
+ timeout=5,
232
+ check=False,
233
+ )
234
+ except subprocess.TimeoutExpired:
235
+ raise OSError("journalctl timed out") from None
236
+ if result.returncode:
237
+ raise OSError(redact(result.stderr or "journalctl failed"))
238
+ for line in result.stdout.splitlines():
239
+ output.emit("journal", line, line)
240
+ return 0
241
+ process = subprocess.Popen( # noqa: S603 - fixed executable, no shell
242
+ args,
243
+ stdout=subprocess.PIPE,
244
+ stderr=subprocess.STDOUT,
245
+ text=True,
246
+ )
247
+ try:
248
+ if process.stdout is None:
249
+ raise OSError("journal pipe unavailable")
250
+ for line in process.stdout:
251
+ output.emit("journal", line.rstrip(), line.rstrip())
252
+ code = process.wait(timeout=2)
253
+ if code:
254
+ raise OSError(f"journalctl failed ({code})")
255
+ finally:
256
+ if process.poll() is None:
257
+ process.terminate()
258
+ try:
259
+ process.wait(timeout=2)
260
+ except subprocess.TimeoutExpired:
261
+ process.kill()
262
+ process.wait(timeout=2)
263
+ if process.stdout:
264
+ process.stdout.close()
265
+ return 0
266
+
267
+
268
+ def render_weekly(rows: list[Weekly], truncated: bool = False) -> str:
269
+ if not rows:
270
+ return "No weekly alert measurements."
271
+ ack = any(row.percent_acknowledged is not None for row in rows)
272
+ header = "Rule Week Zone Fires Firing min Median Closed <5 min Muted Incomplete"
273
+ if ack:
274
+ header += " Acknowledged"
275
+ lines = [header]
276
+
277
+ def percentage(value: float | None) -> str:
278
+ return "unavailable" if value is None else f"{value:g} %"
279
+
280
+ for row in rows:
281
+ median = (
282
+ "unavailable"
283
+ if row.median_duration_s is None
284
+ else format_duration(row.median_duration_s)
285
+ )
286
+ line = (
287
+ f"{row.rule_id} {row.week} {row.zone} {row.fires} {row.firing_minutes:g} "
288
+ f"{median} {percentage(row.percent_closed_under_5m)} "
289
+ f"{percentage(row.percent_muted)} {row.incomplete_durations}"
290
+ )
291
+ if ack:
292
+ line += " " + percentage(row.percent_acknowledged)
293
+ lines.append(line)
294
+ if not ack:
295
+ lines.append("Acknowledgement percentage unavailable.")
296
+ if truncated:
297
+ lines.append("Truncated at --limit.")
298
+ return "\n".join(lines)
@@ -0,0 +1,20 @@
1
+ """hwmon discovery, stable IDs, SI normalisation and classification. Read-only."""
2
+
3
+ from sensitivebox.hwmon.discovery import discover, read, read_all
4
+ from sensitivebox.hwmon.model import Chip, Group, Kind, Limits, Reading, ReadStatus, Sensor
5
+ from sensitivebox.hwmon.reader import Opener, default_opener
6
+
7
+ __all__ = [
8
+ "Chip",
9
+ "Group",
10
+ "Kind",
11
+ "Limits",
12
+ "Opener",
13
+ "ReadStatus",
14
+ "Reading",
15
+ "Sensor",
16
+ "default_opener",
17
+ "discover",
18
+ "read",
19
+ "read_all",
20
+ ]
@@ -0,0 +1,74 @@
1
+ """Decide which files are sensors, what they measure, and which dashboard group they go in."""
2
+
3
+ import re
4
+ from collections.abc import Iterable
5
+ from fnmatch import fnmatchcase
6
+ from typing import NamedTuple
7
+
8
+ from sensitivebox.hwmon.model import Group, Kind
9
+
10
+ _INPUT_RE = re.compile(r"^(temp|fan|in|curr|power|freq)(\d+)_input$")
11
+ _PWM_RE = re.compile(r"^pwm(\d+)$")
12
+ _POWER_AVERAGE_RE = re.compile(r"^power(\d+)_average$")
13
+
14
+
15
+ class Attr(NamedTuple):
16
+ kind: Kind
17
+ channel: str
18
+ fallback: bool # only used when the channel has no primary input file
19
+
20
+
21
+ def parse_attr(name: str) -> Attr | None:
22
+ """Classify one hwmon file name; ``None`` for anything that isn't a sensor value."""
23
+ if m := _INPUT_RE.match(name):
24
+ return Attr(Kind(m[1]), f"{m[1]}{m[2]}", fallback=False)
25
+ if m := _PWM_RE.match(name):
26
+ return Attr(Kind.PWM, f"pwm{m[1]}", fallback=False)
27
+ if m := _POWER_AVERAGE_RE.match(name):
28
+ # Older amdgpu kernels expose only power1_average.
29
+ return Attr(Kind.POWER, f"power{m[1]}", fallback=True)
30
+ return None
31
+
32
+
33
+ _KIND_ORDER = {kind: i for i, kind in enumerate(Kind)}
34
+
35
+
36
+ def _channel_number(channel: str) -> int:
37
+ return int(re.sub(r"\D", "", channel))
38
+
39
+
40
+ def select_inputs(names: Iterable[str]) -> list[tuple[Kind, str, str]]:
41
+ """Pick one value file per channel → ``(kind, channel, file name)`` in natural order."""
42
+ chosen: dict[str, tuple[Attr, str]] = {}
43
+ for name in names:
44
+ attr = parse_attr(name)
45
+ if attr is None:
46
+ continue
47
+ current = chosen.get(attr.channel)
48
+ if current is None or (current[0].fallback and not attr.fallback):
49
+ chosen[attr.channel] = (attr, name)
50
+ ordered = sorted(
51
+ chosen.values(),
52
+ key=lambda item: (_KIND_ORDER[item[0].kind], _channel_number(item[0].channel)),
53
+ )
54
+ return [(attr.kind, attr.channel, name) for attr, name in ordered]
55
+
56
+
57
+ # Ordered: first match wins. Patterns are case-sensitive fnmatch globs on the chip name.
58
+ _GROUP_PATTERNS: tuple[tuple[Group, tuple[str, ...]], ...] = (
59
+ (Group.CPU, ("k10temp", "coretemp", "zenpower", "cpu_thermal")),
60
+ (Group.GPU, ("amdgpu", "radeon", "nouveau", "i915", "xe")),
61
+ (Group.STORAGE, ("nvme", "drivetemp")),
62
+ (Group.MEMORY, ("spd5118", "jc42")),
63
+ (Group.POWER, ("BAT*", "AC", "ACAD", "AC[0-9]*", "ADP*", "ucsi_source_psy_*", "*_battery*")),
64
+ (Group.NETWORK, ("mt7*", "iwlwifi*", "ath*", "rtw*", "*_phy[0-9]*")),
65
+ )
66
+
67
+
68
+ def group_for(chip: str, kind: Kind) -> Group:
69
+ for group, patterns in _GROUP_PATTERNS:
70
+ if any(fnmatchcase(chip, pattern) for pattern in patterns):
71
+ return group
72
+ if kind in (Kind.FAN, Kind.PWM):
73
+ return Group.COOLING
74
+ return Group.SYSTEM
@@ -0,0 +1,139 @@
1
+ """Scan ``<sysfs_root>/class/hwmon`` once, and read sensor values on every poll."""
2
+
3
+ from collections.abc import Iterable
4
+ from dataclasses import replace
5
+ from pathlib import Path
6
+
7
+ from sensitivebox.hwmon.classify import group_for, select_inputs
8
+ from sensitivebox.hwmon.ids import bus_id, sensor_id
9
+ from sensitivebox.hwmon.model import Chip, Kind, Limits, Reading, ReadStatus, Sensor
10
+ from sensitivebox.hwmon.normalise import UNIT, is_junk, to_si
11
+ from sensitivebox.hwmon.reader import Opener, default_opener, read_attr, read_int, read_raw
12
+
13
+ _LIMIT_NAMES = ("min", "max", "crit")
14
+
15
+
16
+ def discover(sysfs_root: Path, *, opener: Opener = default_opener) -> list[Chip]:
17
+ """Find every hwmon chip and its sensors. Raises ``FileNotFoundError`` without hwmon."""
18
+ class_dir = sysfs_root / "class" / "hwmon"
19
+ if not class_dir.is_dir():
20
+ raise FileNotFoundError(f"no hwmon class directory at {class_dir}")
21
+
22
+ named: list[tuple[Path, str, str]] = []
23
+ for entry in class_dir.iterdir():
24
+ try:
25
+ hwmon_dir = entry.resolve()
26
+ name = read_attr(hwmon_dir / "name", opener)
27
+ if name:
28
+ named.append((hwmon_dir, name, bus_id(hwmon_dir)))
29
+ except OSError:
30
+ continue # unplugged while we looked, or unreadable: the other chips still count
31
+
32
+ by_key: dict[tuple[str, str], list[Chip]] = {}
33
+ for hwmon_dir, name, bus in named:
34
+ try:
35
+ chip = _scan_chip(hwmon_dir, name, bus, opener)
36
+ except OSError:
37
+ continue # hot-unplugged between reading its name and scanning it (ADV-007)
38
+ by_key.setdefault((name, bus), []).append(chip)
39
+
40
+ chips: list[Chip] = []
41
+ for siblings in by_key.values():
42
+ # Same chip name on the same device (rare): number them by what they measure, which is
43
+ # stable, and fall back to the path only when even that is identical (ADV-008).
44
+ siblings.sort(key=lambda c: (_fingerprint(c), str(c.path)))
45
+ chips += [
46
+ c if n == 1 else _with_bus(c, f"{c.bus_id}~{n}") for n, c in enumerate(siblings, 1)
47
+ ]
48
+ return sorted(chips, key=lambda c: (c.name.lower(), c.bus_id))
49
+
50
+
51
+ def _fingerprint(chip: Chip) -> tuple[tuple[str, str], ...]:
52
+ return tuple(sorted((s.channel, s.label) for s in chip.sensors))
53
+
54
+
55
+ def _with_bus(chip: Chip, bus: str) -> Chip:
56
+ sensors = tuple(
57
+ replace(s, bus_id=bus, id=sensor_id(chip.name, bus, s.channel)) for s in chip.sensors
58
+ )
59
+ return replace(chip, bus_id=bus, sensors=sensors)
60
+
61
+
62
+ def _scan_chip(hwmon_dir: Path, name: str, bus: str, opener: Opener) -> Chip:
63
+ files = {p.name for p in hwmon_dir.iterdir() if p.is_file() and not p.is_symlink()}
64
+ sensors = tuple(
65
+ _make_sensor(hwmon_dir, files, name, bus, kind, channel, filename, opener)
66
+ for kind, channel, filename in select_inputs(files)
67
+ )
68
+ return Chip(name=name, bus_id=bus, path=hwmon_dir, sensors=sensors)
69
+
70
+
71
+ def _make_sensor(
72
+ hwmon_dir: Path,
73
+ files: set[str],
74
+ chip: str,
75
+ bus: str,
76
+ kind: Kind,
77
+ channel: str,
78
+ filename: str,
79
+ opener: Opener,
80
+ ) -> Sensor:
81
+ label_file = f"{channel}_label"
82
+ label = read_attr(hwmon_dir / label_file, opener) if label_file in files else None
83
+ limits, dropped = _read_limits(hwmon_dir, files, kind, channel, opener)
84
+ return Sensor(
85
+ id=sensor_id(chip, bus, channel),
86
+ chip=chip,
87
+ bus_id=bus,
88
+ channel=channel,
89
+ kind=kind,
90
+ label=label or channel,
91
+ group=group_for(chip, kind),
92
+ unit=UNIT[kind],
93
+ input_path=hwmon_dir / filename,
94
+ limits=limits,
95
+ dropped_limits=dropped,
96
+ )
97
+
98
+
99
+ def _read_limits(
100
+ hwmon_dir: Path, files: set[str], kind: Kind, channel: str, opener: Opener
101
+ ) -> tuple[Limits, tuple[tuple[str, float], ...]]:
102
+ values: dict[str, float | None] = dict.fromkeys(_LIMIT_NAMES)
103
+ dropped: list[tuple[str, float]] = []
104
+ for limit in _LIMIT_NAMES:
105
+ filename = f"{channel}_{limit}"
106
+ if filename not in files:
107
+ continue
108
+ raw = read_int(hwmon_dir / filename, opener)
109
+ if raw is None:
110
+ continue
111
+ value = to_si(kind, raw)
112
+ if is_junk(kind, value):
113
+ dropped.append((limit, value))
114
+ else:
115
+ values[limit] = value
116
+
117
+ alarm: bool | None = None
118
+ if f"{channel}_alarm" in files:
119
+ raw_alarm = read_int(hwmon_dir / f"{channel}_alarm", opener)
120
+ alarm = None if raw_alarm is None else raw_alarm != 0
121
+
122
+ limits = Limits(min=values["min"], max=values["max"], crit=values["crit"], alarm=alarm)
123
+ return limits, tuple(dropped)
124
+
125
+
126
+ def read(sensor: Sensor, opener: Opener = default_opener) -> Reading:
127
+ """Read one sensor now. One small file read; never spawns a process."""
128
+ result = read_raw(sensor.input_path, opener)
129
+ raw = result.value
130
+ if raw is None:
131
+ return Reading(sensor.id, None, ReadStatus.UNAVAILABLE, reason=result.reason)
132
+ value = to_si(sensor.kind, raw)
133
+ if is_junk(sensor.kind, value):
134
+ return Reading(sensor.id, None, ReadStatus.JUNK, raw)
135
+ return Reading(sensor.id, value, ReadStatus.OK, raw)
136
+
137
+
138
+ def read_all(chips: Iterable[Chip], opener: Opener = default_opener) -> dict[str, Reading]:
139
+ return {s.id: read(s, opener) for chip in chips for s in chip.sensors}
@@ -0,0 +1,35 @@
1
+ """Stable sensor IDs: ``<chip name>/<bus id>/<channel>``, never ``hwmonN``.
2
+
3
+ ``hwmonN`` numbers are assigned in probe order and change between boots. The device a chip hangs
4
+ off (a PCI address, a platform device name, a power supply) does not.
5
+
6
+ Some drivers hang the chip off a *class* device numbered in probe order, under its physical
7
+ device: an NVMe drive's ``…/0000:61:00.0/nvme/nvme0``. ``nvme0`` can become ``nvme1`` when the
8
+ controllers probe in another order, so the ID uses the physical device instead (review ADV-008).
9
+ """
10
+
11
+ import re
12
+ from pathlib import Path
13
+
14
+ NO_DEVICE = "virtual"
15
+
16
+
17
+ def _is_numbered_class_device(device: Path) -> bool:
18
+ """``<class>/<class><N>``, e.g. ``nvme/nvme0``: an instance number, not an identity."""
19
+ return re.fullmatch(re.escape(device.parent.name) + r"\d+", device.name) is not None
20
+
21
+
22
+ def bus_id(hwmon_dir: Path) -> str:
23
+ """Where the chip's ``device`` symlink resolves, e.g. ``0000:00:18.3``; for a numbered class
24
+ device, the physical device above it."""
25
+ device = hwmon_dir / "device"
26
+ if not device.is_symlink():
27
+ return NO_DEVICE
28
+ resolved = device.resolve()
29
+ if _is_numbered_class_device(resolved) and resolved.parent.parent.name:
30
+ return resolved.parent.parent.name
31
+ return resolved.name
32
+
33
+
34
+ def sensor_id(chip: str, bus: str, channel: str) -> str:
35
+ return f"{chip}/{bus}/{channel}"
@@ -0,0 +1,78 @@
1
+ """Typed data model for hwmon chips, sensors and readings."""
2
+
3
+ from dataclasses import dataclass
4
+ from enum import StrEnum
5
+ from pathlib import Path
6
+
7
+
8
+ class Kind(StrEnum):
9
+ """What a sensor measures. Declaration order is the natural order within a chip."""
10
+
11
+ TEMP = "temp"
12
+ FAN = "fan"
13
+ PWM = "pwm"
14
+ IN = "in"
15
+ CURR = "curr"
16
+ POWER = "power"
17
+ FREQ = "freq"
18
+
19
+
20
+ class Group(StrEnum):
21
+ """Dashboard card a sensor belongs to. Declaration order is the dashboard order."""
22
+
23
+ CPU = "CPU"
24
+ MEMORY = "Memory"
25
+ GPU = "GPU"
26
+ STORAGE = "Storage"
27
+ NETWORK = "Network"
28
+ POWER = "Power"
29
+ COOLING = "Cooling"
30
+ SYSTEM = "System"
31
+
32
+
33
+ class ReadStatus(StrEnum):
34
+ OK = "ok"
35
+ UNAVAILABLE = "unavailable" # read error (e.g. -ENODATA) or non-numeric ("N/A"); hidden in UI
36
+ JUNK = "junk" # physically impossible value; dropped
37
+
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class Limits:
41
+ """The chip's own limits, in the sensor's SI unit. ``None`` when absent or junk."""
42
+
43
+ min: float | None = None
44
+ max: float | None = None
45
+ crit: float | None = None
46
+ alarm: bool | None = None
47
+
48
+
49
+ @dataclass(frozen=True, slots=True)
50
+ class Sensor:
51
+ id: str # "<chip>/<bus id>/<channel>", never hwmonN
52
+ chip: str
53
+ bus_id: str
54
+ channel: str # e.g. "temp1", "pwm2"
55
+ kind: Kind
56
+ label: str
57
+ group: Group
58
+ unit: str
59
+ input_path: Path
60
+ limits: Limits = Limits()
61
+ dropped_limits: tuple[tuple[str, float], ...] = () # junk limits, (name, SI value)
62
+
63
+
64
+ @dataclass(frozen=True, slots=True)
65
+ class Chip:
66
+ name: str
67
+ bus_id: str
68
+ path: Path
69
+ sensors: tuple[Sensor, ...]
70
+
71
+
72
+ @dataclass(frozen=True, slots=True)
73
+ class Reading:
74
+ sensor_id: str
75
+ value: float | None # SI; None unless status is OK
76
+ status: ReadStatus
77
+ raw: int | None = None # raw sysfs integer, kept for diagnostics
78
+ reason: str | None = None # why it is unavailable, e.g. "ENODATA", "not a number: 'N/A'"
@@ -0,0 +1,42 @@
1
+ """Convert raw sysfs integers to SI floats and spot physically impossible values."""
2
+
3
+ from sensitivebox.hwmon.model import Kind
4
+
5
+ # sysfs units (Documentation/hwmon/sysfs-interface.rst) → divisor to reach the display unit.
6
+ _DIVISOR: dict[Kind, float] = {
7
+ Kind.TEMP: 1000.0, # millidegree Celsius
8
+ Kind.IN: 1000.0, # millivolt
9
+ Kind.CURR: 1000.0, # milliampere
10
+ Kind.POWER: 1_000_000.0, # microwatt
11
+ Kind.FREQ: 1.0, # Hz
12
+ Kind.FAN: 1.0, # RPM
13
+ Kind.PWM: 255 / 100, # 0-255 duty cycle → percent
14
+ }
15
+
16
+ UNIT: dict[Kind, str] = {
17
+ Kind.TEMP: "°C",
18
+ Kind.IN: "V",
19
+ Kind.CURR: "A",
20
+ Kind.POWER: "W",
21
+ Kind.FREQ: "Hz",
22
+ Kind.FAN: "RPM",
23
+ Kind.PWM: "%",
24
+ }
25
+
26
+ # Anything at or below absolute zero, or hotter than this, is a firmware placeholder
27
+ # (e.g. NVMe "Sensor 1" reporting a 65 261.85 °C high limit).
28
+ TEMP_MIN_C = -273.0
29
+ TEMP_MAX_C = 65_000.0
30
+
31
+
32
+ def to_si(kind: Kind, raw: int) -> float:
33
+ return raw / _DIVISOR[kind]
34
+
35
+
36
+ def is_junk(kind: Kind, value: float) -> bool:
37
+ """True for values no real sensor can report. Zero is always a valid reading."""
38
+ if kind is Kind.TEMP:
39
+ return value <= TEMP_MIN_C or value > TEMP_MAX_C
40
+ if kind is Kind.FAN:
41
+ return value < 0
42
+ return False