Debian Codegraph @

s_tui/sources/source.py

raw symbols SCIP
1 #!/usr/bin/env python
2 #
3 # Copyright (C) 2017-2025 Alex Manuskin, Gil Tsuker
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
18 """This module implements a parent source class for s-tui"""
19
20 from __future__ import annotations
21
22 import contextlib
23 import logging
24 import os
25 from collections import OrderedDict
26 from typing import TYPE_CHECKING
27
28 if TYPE_CHECKING:
29 from s_tui.sources.hook import Hook
30
31 try:
32 import psutil
33 except ImportError:
34 psutil = None
35
36
37 class Source:
38 """This is a basic source class for s-tui"""
39
40 def __init__(self) -> None:
41 self.edge_hooks: list[Hook] = []
42 self.measurement_unit = ""
43 self.last_measurement: list[float] = []
44 self.last_thresholds: list[float | None] = []
45 self.is_available = True
46 self.available_sensors: list[str] = []
47 self.sensor_available: list[bool] = [] # Per-sensor availability
48 self.name = ""
49 self.pallet = (
50 "temp light",
51 "temp dark",
52 "temp light smooth",
53 "temp dark smooth",
54 )
55 self.alert_pallet = None
56
57 def update(self) -> None:
58 """Updates the last measurement, invokes hooks if present"""
59 self.eval_hooks()
60
61 def get_maximum(self) -> float:
62 """Returns the maximum measurement as measured so far"""
63 raise NotImplementedError("Get maximum is not implemented")
64
65 def get_top(self) -> float:
66 """Returns highest theoretical value the sensors can reach"""
67 raise NotImplementedError("get_top is not implemented")
68
69 def get_is_available(self) -> bool:
70 """Returns is_available"""
71 return self.is_available
72
73 def reset(self) -> None:
74 """Resets source state, e.g. current max"""
75 raise NotImplementedError("Reset is not implemented")
76
77 def _format_measurement(self, value: float) -> str:
78 """Format a single measurement value for display. Override to customise."""
79 return str(round(value, 1))
80
81 def get_sensors_summary(self) -> OrderedDict[str, str]:
82 """This returns a dict of sensor of the source and their values"""
83 summary = OrderedDict()
84 for idx, name in enumerate(self.get_sensor_list()):
85 if idx < len(self.sensor_available) and not self.sensor_available[idx]:
86 summary[name] = "N/A"
87 elif idx < len(self.last_measurement):
88 summary[name] = self._format_measurement(self.last_measurement[idx])
89 else:
90 summary[name] = "N/A"
91 return summary
92
93 def get_summary(self) -> OrderedDict[str, str]:
94 """Returns a dict of source name and sensors with their values"""
95 graph_vector_summary = OrderedDict()
96 graph_vector_summary[self.get_source_name()] = "[" + self.measurement_unit + "]"
97 graph_vector_summary.update(self.get_sensors_summary())
98 return graph_vector_summary
99
100 def get_source_name(self) -> str:
101 """Returns source name"""
102 return self.name
103
104 def get_edge_triggered(self) -> bool:
105 """Returns true if a measurement was higher than some thershhold"""
106 raise NotImplementedError("Get Edge triggered not implemented")
107
108 def get_measurement_unit(self) -> str:
109 """Returns measurement unit of source"""
110 return self.measurement_unit
111
112 def get_pallet(self) -> tuple[str, ...]:
113 """Returns the pallet of the source for graph plotting"""
114 return self.pallet
115
116 def get_alert_pallet(self) -> tuple[str, ...] | None:
117 """Returns the 'alert' pallet for graph plotting"""
118 return self.alert_pallet
119
120 def get_sensor_alerts(self) -> list[str | None]:
121 """Per-sensor urwid attribute for summary coloring, or None."""
122 return [None] * len(self.available_sensors)
123
124 def get_sensor_suffixes(self) -> list[str]:
125 """Per-sensor TUI-only display suffixes (e.g. throttle labels)."""
126 return [""] * len(self.available_sensors)
127
128 def get_sensor_list(self) -> list[str]:
129 """Returns list of a available sensors for source"""
130 return self.available_sensors
131
132 def get_reading_list(self) -> list[float]:
133 """Returns a list of the last measurement"""
134 return self.last_measurement
135
136 def get_threshold_list(self) -> list[float | None]:
137 """Returns a list of the last threshold values"""
138 return self.last_thresholds
139
140 def add_edge_hook(self, hook: Hook | None) -> None:
141 """
142 Add hook to be triggered when the threshold of this Source is surpassed
143 """
144 if hook is None:
145 return
146
147 self.edge_hooks.append(hook)
148
149 def eval_hooks(self) -> None:
150 """
151 Evaluate the current state of this Source and
152 invoke any attached hooks if they've been triggered
153 """
154 logging.debug("Evaluating hooks")
155 if self.get_edge_triggered():
156 logging.debug("Hook triggered")
157 for hook in [h for h in self.edge_hooks if h.is_ready()]:
158 logging.debug("Hook invoked")
159 hook.invoke()
160
161 def _mark_offline_cores(
162 self, total_cores: int, online_ids: list[int] | None
163 ) -> None:
164 """Mark cores not in online_ids as unavailable in sensor_available."""
165 if online_ids is None:
166 return
167 online_set = set(online_ids)
168 for core_id in range(total_cores):
169 if core_id not in online_set:
170 self.sensor_available[core_id + 1] = False
171
172 @staticmethod
173 def _get_online_cpu_ids() -> list[int] | None:
174 """Get sorted list of online CPU core IDs using psutil.
175
176 Uses Process.cpu_affinity() which reflects which CPUs are online.
177 Available on Linux, Windows, and FreeBSD.
178 Returns a sorted list of online core IDs, or None if unavailable.
179 """
180 if psutil is None:
181 return None
182 try:
183 return sorted(psutil.Process().cpu_affinity())
184 except (AttributeError, OSError, psutil.Error):
185 return None
186
187 @staticmethod
188 def _get_total_core_count() -> int:
189 """Get the total number of CPU cores, including offline ones.
190
191 psutil.cpu_count() and cpu_affinity() may only reflect online cores.
192 os.sysconf('SC_NPROCESSORS_CONF') returns all configured processors
193 including offline ones. Available on POSIX (Linux, BSD, macOS).
194 """
195 if psutil is None:
196 return 0
197 total = psutil.cpu_count(logical=True) or 0
198
199 try:
200 online_ids = psutil.Process().cpu_affinity()
201 if online_ids:
202 total = max(total, max(online_ids) + 1)
203 except (AttributeError, OSError, psutil.Error):
204 pass
205
206 with contextlib.suppress(AttributeError, ValueError, OSError):
207 total = max(total, os.sysconf("SC_NPROCESSORS_CONF"))
208
209 return total
210
211
212 class MockSource(Source):
213 """Mock class for testing"""
214
215 def get_maximum(self) -> int:
216 return 20
217
218 def get_summary(self) -> OrderedDict[str, str]:
219 return OrderedDict({"MockValue": "5", "Tahat": "34"})
220
221 def get_edge_triggered(self) -> bool:
222 raise NotImplementedError("Get Edge triggered not implemented")