#!/usr/bin/env python3 import os import re import subprocess import time from pathlib import Path CACHE_FILE = Path("/run/control-rpi-disk-temp") DISK = "/dev/sda" INTERVAL_SECONDS = 5 SMARTCTL = "/usr/sbin/smartctl" def parse_temp(output): for line in output.splitlines(): stripped = line.strip() if stripped.startswith("Temperature:"): match = re.search(r"([0-9]+(?:\.[0-9]+)?)", stripped) if match: return float(match.group(1)) if "Temperature_Celsius" in stripped or "Airflow_Temperature_Cel" in stripped: parts = stripped.split() for part in reversed(parts): if part.isdigit(): return float(part) return None def read_temp(): result = subprocess.run( [SMARTCTL, "-A", "-d", "sntasmedia", DISK], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=4, check=False, ) if result.returncode not in (0, 4, 64): return None return parse_temp(result.stdout) def write_cache(temp): tmp = CACHE_FILE.with_suffix(".tmp") if temp is None: content = f"UPDATED={time.time():.3f}\nTEMP=\nOK=0\n" else: content = f"UPDATED={time.time():.3f}\nTEMP={temp:.1f}\nOK=1\n" tmp.write_text(content, encoding="utf-8") os.replace(tmp, CACHE_FILE) os.chmod(CACHE_FILE, 0o644) def main(): while True: try: write_cache(read_temp()) except Exception: write_cache(None) time.sleep(INTERVAL_SECONDS) if __name__ == "__main__": main()