Files
the_kurgan/tests/test_fan_control.py
T
paulandClaude Opus 5.5 7190db733f Privilege split 4/11: the kurgan.hw service process
- kurgan/hw/service.py, HardwareService: one loop a second reads the CPU
  package (PawnIO MSR: temperature and power) and the GPU (NVML), runs the
  fan curves, and publishes a state snapshot. It never depends on a client:
  the pipe side takes no lock the loop needs, every sensor read is guarded
  (a fault is a missing temperature, so those fans fail safe), and a bug in
  the loop fails the fans safe and retries. On exit the case fans are left at
  100% and the top fans go back to the BIOS curve.
- Without saved ports it only reads the Commander PRO's RPMs (for the app's
  power estimate). With an invalid hw-settings.json it holds every connected
  PWM fan at 100% (CommanderPro.full_speed) and says why in its state,
  instead of refusing to start and leaving the fans at their last duty.
- State carries the app's cooling snapshot unchanged (profile, groups, top,
  note, row) plus the CPU temperature and power, GPU temperature, the
  Commander PRO RPMs and the RAM lighting. NaN never reaches the pipe.
- RAM lighting runs in the service; its chase follows the app's clock
  (SyncedChase, fed by ram_chase) so it stays in step with the other chases.
- kurgan/hw/settings.py: %ProgramData%\Kurgan\hw-settings.json, the cooling
  and RAM lighting sections, as strict as settings.json (validate_cooling is
  shared). The folder is created SYSTEM/Administrators full, Users read.
- kurgan/hw/main.py: serve() wires the loop, the RAM lighting and the pipe
  (the fans run whatever happens to the pipe); `python -m kurgan.hw` runs it
  in a console. The pipe user comes from HKLM\...\Services\KurganHw\
  Parameters\UserSid; the OpenRGB check reads that user's %APPDATA%.
- control.py: CaseFanControl.step() (one guarded pass) and shutdown()
  replace run(); CpuTemperature also keeps the latest reading, the package
  power and why it has none. The fan CLI saves to hw-settings.json.
- sensors.py: the Commander PRO mutex is Global\KurganCommanderPro, so a
  console tool in the user's session sees the service's claim.
- The app still uses the old worker; it is rewired in step 6.
- Tests: 16 new or rewritten (202 pass), including the loop with no client
  and a stuck client that can't stop fan control.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:28:32 +13:00

416 lines
20 KiB
Python

import argparse
import contextlib
import unittest
from unittest.mock import Mock, call, mock_open, patch
from kurgan.cooling.board_fans import Nct6687
from kurgan.cooling.control import CaseFanControl, CpuTemperature, TopFanCurve, cpu_duty, gpu_duty, parse_ports
from kurgan.telemetry.sensors import CommanderPro, corsair_software_running
class FanCurveTest(unittest.TestCase):
def test_cpu_curve_and_failsafe(self):
for temp, expected in ((30, 40), (50, 40), (60, 50), (70, 65), (75, 83), (80, 100),
(88, 100), (100, 100), (None, 100), (float("nan"), 100)):
with self.subTest(temp=temp):
self.assertEqual(cpu_duty(temp), expected)
def test_temperature_curve_and_failsafe(self):
for temp, expected in ((20, 40), (40, 40), (50, 50), (55, 58), (60, 65),
(68, 93), (70, 100), (75, 100), (95, 100),
(None, 100), (float("nan"), 100),
(float("inf"), 100), (-1, 100), (111, 100)):
with self.subTest(temp=temp):
self.assertEqual(gpu_duty(temp), expected)
def test_only_three_distinct_physical_ports_are_accepted(self):
self.assertEqual(parse_ports(" 4, 6, 5 "), (4, 6, 5))
for text in ("", "1,2", "1,2,3,4", "1,1,2", "0,1,2", "4,5,7", "a,2,3"):
with self.subTest(text=text):
with self.assertRaises(argparse.ArgumentTypeError):
parse_ports(text)
class TopFanCurveTest(unittest.TestCase):
def setUp(self):
self.board = Mock(spec=Nct6687)
self.mask = 0
self.duties = []
self.board.manual_mask.side_effect = lambda: self.mask
self.board.rpms.return_value = [0] * 16 # nothing has been seen turning yet
def manual(ch, duty):
self.mask |= 0x24
self.duties.append(duty)
self.board.set_manual.side_effect = manual
self.board.set_auto.side_effect = lambda ch: setattr(self, "mask", self.mask & ~0x24)
self.top = TopFanCurve((2, 5), board_factory=lambda: self.board)
def test_stopped_while_cool_kicks_on_start_and_follows_curve(self):
self.top.update(40, 44, 0)
self.assertEqual((self.top.duty, self.mask), (0, 0x24))
self.top.update(40, 49, 1)
self.assertEqual(self.top.duty, 0) # below the start point
self.top.update(40, 50, 2)
self.assertEqual(self.top.duty, 40) # spin-up kick
self.top.update(40, 55, 5)
self.assertEqual(self.top.duty, 45)
for now, temp, duty in ((6, 60, 60), (7, 65, 80), (8, 70, 100), (9, 90, 100)):
self.top.update(40, temp, now)
self.assertEqual(self.top.duty, duty)
def test_stop_has_hysteresis_and_hold_time(self):
self.top.update(40, 52, 0)
for now in range(3, 40):
self.top.update(40, 46, now) # between stop and start: keeps running at minimum
self.assertEqual(self.top.duty, 30)
self.top.update(40, 44, 40)
self.top.update(40, 44, 69)
self.assertEqual(self.top.duty, 30)
self.top.update(40, 44, 70)
self.assertEqual(self.top.duty, 0)
def test_falls_slowly_and_case_fan_boost_forces_full_speed(self):
self.top.update(40, 70, 0)
self.top.update(40, 60, 5)
self.assertEqual(self.top.duty, 100) # holds after a rise
self.top.update(40, 60, 11)
self.assertEqual(self.top.duty, 96) # 2% per second
self.top.update(85, 40, 12)
self.assertEqual((self.top.duty, self.top.boosted), (100, True))
self.top.update(66, 40, 13)
self.assertTrue(self.top.boosted)
self.top.update(65, 40, 14)
self.assertFalse(self.top.boosted)
def test_invalid_temperature_is_failsafe_full_speed(self):
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.top.update(40, None, 0)
self.assertEqual(self.top.duty, 100)
self.assertIn("FAILSAFE", self.top.status)
def test_firmware_reset_is_corrected(self):
self.top.update(40, 40, 0)
self.top.update(40, 40, 1)
self.assertEqual(self.board.set_manual.call_count, 1) # unchanged duty is not rewritten
self.mask = 0x04 # one channel reverted to the BIOS after sleep
self.top.update(40, 40, 2)
self.assertEqual(self.board.set_manual.call_count, 2)
def test_unavailable_board_reports_and_retries_later(self):
factory = Mock(side_effect=OSError("run as administrator"))
top = TopFanCurve((2, 5), board_factory=factory)
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
top.update(100, 60, 0)
self.assertIn("UNAVAILABLE", top.status)
top.update(100, 60, 10)
self.assertEqual(factory.call_count, 1)
factory.side_effect = None
factory.return_value = self.board
top.update(100, 60, 31)
self.board.set_manual.assert_called_once_with((2, 5), 100)
def test_a_failed_write_hands_the_fans_back_to_the_bios_curve(self):
self.top.update(40, 70, 0) # manual 100% written on channels 2,5
self.mask = 0 # the EC forgot (sleep, crash): a rewrite is due ...
self.board.set_manual.side_effect = OSError("bus busy") # ... and fails
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.top.update(40, 70, 1)
self.board.set_auto.assert_called_with((2, 5))
self.assertIn("BIOS curve keeps control", self.top.status)
def test_a_failed_hand_back_says_what_the_fans_are_left_at(self):
self.top.update(40, 70, 0)
self.mask = 0
self.board.set_manual.side_effect = OSError("bus busy")
self.board.set_auto.side_effect = OSError("still busy") # even the hand-back fails
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.top.update(40, 70, 1)
self.assertIn("held at the last written duty (100%)", self.top.status)
def test_a_top_fan_that_stops_turning_is_detected(self):
tachs = [0] * 16
self.board.rpms.return_value = tachs
for now in range(10): # spinning, but no tach has been seen turning: no evidence yet
self.top.update(40, 55, now)
self.assertNotIn("FAILSAFE", self.top.status)
tachs[2], tachs[5] = 1500, 1400
self.top.update(40, 55, 10)
self.top.update(40, 55, 11)
self.assertNotIn("FAILSAFE", self.top.status) # learned: both tachs turn
tachs[5] = 0
self.top.update(40, 55, 12)
self.top.update(40, 55, 13)
self.assertNotIn("FAILSAFE", self.top.status) # one glitchy reading is not a stall
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.top.update(40, 55, 14)
self.assertIn("FAILSAFE", self.top.status)
self.assertIn("[5]", self.top.status)
self.assertEqual(self.top.duty, 100)
self.board.set_manual.assert_called_with((2, 5), 100)
tachs[5] = 1300 # the fan turns again: the failsafe lifts on the next poll
self.top.update(40, 55, 15)
self.assertNotIn("FAILSAFE", self.top.status)
self.assertEqual(self.top.snapshot()["rpms"], {"2": 1500, "5": 1300})
def test_a_tach_never_seen_turning_shows_no_reading(self):
tachs = [0] * 16
self.board.rpms.return_value = tachs
tachs[5] = 1040 # channel 2's tach isn't wired: it always reads 0
for now in range(5):
self.top.update(40, 55, now)
self.assertEqual(self.top.snapshot()["rpms"], {"2": None, "5": 1040})
def test_an_unexpected_board_error_hands_back_to_the_bios_instead_of_escaping(self):
self.top.update(40, 70, 0)
self.board.rpms.side_effect = AttributeError("no rpms") # a bug, not a device error
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
self.top.update(40, 70, 1) # must not raise into the case fans' loop
self.board.set_auto.assert_called_with((2, 5))
self.assertIn("UNAVAILABLE", self.top.status)
def test_the_demo_board_supports_stall_detection(self):
from kurgan.demo import FakeBoard
top = TopFanCurve((2, 5), board_factory=FakeBoard)
for now in range(8):
top.update(40, 60, now)
self.assertNotIn("UNAVAILABLE", top.status)
self.assertNotIn("FAILSAFE", top.status)
self.assertEqual(top.snapshot()["rpms"], {"2": 14 * top.duty, "5": 14 * top.duty})
def test_gpu_worker_drives_top_fans_and_releases_them_on_exit(self):
commander = Mock(spec=CommanderPro)
commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
control = CaseFanControl(commander, (4, 5, 6), None, self.top)
control.update(40, 0) # startup runs the case fans at 100%
self.assertTrue(self.top.boosted)
control.shutdown()
self.assertEqual(self.mask, 0)
self.board.close.assert_called()
def test_top_fans_follow_the_hotter_side(self):
commander = Mock(spec=CommanderPro)
commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
control = CaseFanControl(commander, (4, 5, 6), (1, 2, 3), self.top)
for now in range(70): # startup boost ends, then the top fans stop after the hold time
control.update(40, now, 44)
self.assertEqual((control.gpu.duty, control.cpu.duty, self.top.boosted), (40, 40, False))
self.assertEqual(self.top.duty, 0)
control.update(40, 70, 60) # CPU hotter than GPU
self.assertEqual(self.top.duty, 60)
control.update(40, 71, None)
self.assertEqual(self.top.duty, 100)
def test_cpu_side_follows_cpu_temperature_and_can_boost_alone(self):
commander = Mock(spec=CommanderPro)
commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
control = CaseFanControl(commander, (4, 5, 6), (1, 2, 3), self.top)
for now in range(40):
control.update(40, now, 50)
self.assertEqual((control.gpu.duty, control.cpu.duty), (40, 40))
self.assertFalse(self.top.boosted)
commander.set_duty.assert_any_call((1, 2, 3), 40)
control.update(40, 40, 78) # CPU hot, GPU cool
commander.set_duty.assert_any_call((1, 2, 3), 93)
self.assertEqual(control.gpu.duty, 40)
self.assertTrue(self.top.boosted)
control.update(40, 41, None)
self.assertIn("FAILSAFE", control.cpu.status)
self.assertNotIn("FAILSAFE", control.gpu.status)
with self.assertRaises(ValueError):
CaseFanControl(commander, (4, 5, 6), (1, 2, 4))
def test_cpu_temperature_is_averaged_and_gaps_are_not(self):
pkg = Mock()
pkg.temperature.side_effect = [50, 90, None, 60]
pkg.power.return_value = 35.0
cpu = CpuTemperature(factory=lambda: pkg)
self.assertEqual(cpu.read(0), 50)
self.assertEqual(cpu.read(1), 70)
self.assertEqual((cpu.temp, cpu.power, cpu.error), (90, 35.0, None)) # the latest, for the app
self.assertIsNone(cpu.read(2))
self.assertIsNotNone(cpu.error)
self.assertEqual(cpu.read(3), 60)
def test_cpu_temperature_failures_say_why_and_back_off(self):
cpu = CpuTemperature(factory=Mock(side_effect=OSError("Cannot open PawnIO")))
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.assertIsNone(cpu.read(0))
self.assertEqual((cpu.temp, cpu.power, cpu.error), (None, None, "Cannot open PawnIO"))
cpu.read(30) # within the minute: not re-opened
self.assertEqual(cpu._factory.call_count, 1)
class Nct6687ControlTest(unittest.TestCase):
def test_override_uses_config_handshake_and_keeps_other_channels(self):
nct = Nct6687.__new__(Nct6687)
nct._bus = contextlib.nullcontext
nct.read = Mock(return_value=0x01)
nct.write = Mock()
with patch("kurgan.cooling.board_fans.time.sleep"):
nct.set_manual((2, 5), 100)
self.assertEqual(nct.write.call_args_list, [
call(0xA01, 0x80), call(0xA00, 0x25), call(0xA2A, 255), call(0xA2D, 255), call(0xA01, 0x40)])
nct.write.reset_mock()
nct.read.return_value = 0x25
nct.set_auto((2, 5))
self.assertEqual(nct.write.call_args_list, [call(0xA01, 0x80), call(0xA00, 0x01), call(0xA01, 0x40)])
with self.assertRaises(ValueError):
nct.set_manual((8,), 100)
class FanWorkerTest(unittest.TestCase):
def setUp(self):
self.commander = Mock(spec=CommanderPro)
self.commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
self.control = CaseFanControl(self.commander, (4, 5, 6))
def settle(self, temp=50):
for now in range(36):
self.control.update(temp, now)
def test_rises_immediately_and_falls_slowly_after_hold(self):
self.control.update(40, 0)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
self.control.update(40, 9)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
for now in range(10, 45):
self.control.update(50, now)
self.commander.set_duty.assert_called_with((4, 5, 6), 50)
self.control.update(68, 45)
self.commander.set_duty.assert_called_with((4, 5, 6), 93)
for now in range(46, 55):
self.control.update(40, now)
self.commander.set_duty.assert_called_with((4, 5, 6), 93)
self.control.update(40, 55)
self.commander.set_duty.assert_called_with((4, 5, 6), 91)
def test_missing_sensor_and_delayed_worker_use_full_speed(self):
self.settle()
self.control.update(None, 36)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
self.assertIn("FAILSAFE", self.control.status)
for now in range(37, 73):
self.control.update(50, now)
self.commander.set_duty.assert_called_with((4, 5, 6), 50)
self.control.update(40, 85)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
def test_stalled_selected_fan_forces_full_speed_but_other_side_does_not(self):
self.commander.set_duty.return_value = {1: 0, 4: 900, 5: 900, 6: 900}
self.settle()
self.assertNotIn("FAILSAFE", self.control.status)
# One glitchy reading is not a stall; STALL_READINGS in a row are.
self.commander.set_duty.return_value = {4: 900, 5: 0, 6: 900}
self.control.update(50, 36)
self.control.update(50, 37)
self.assertNotIn("FAILSAFE", self.control.status)
self.commander.set_duty.reset_mock()
self.control.update(50, 38)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
self.assertIn("FAILSAFE", self.control.status)
self.assertIn("[5]", self.control.status)
def test_shutdown_leaves_selected_ports_at_full_speed(self):
self.control.shutdown()
self.commander.set_duty.assert_called_once_with((4, 5, 6), 100)
self.commander.close.assert_called_once()
def test_a_device_error_fails_safe_reopens_and_backs_off(self):
self.commander.set_duty.side_effect = [OSError("no reply to command 0x20"), {4: 900, 5: 900, 6: 900}]
self.assertEqual(self.control.step(50, None, 0), CaseFanControl.ERROR_RETRY_SECONDS)
self.assertIn("CONTROL ERROR", self.control.status)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
self.commander.close.assert_called_once() # reopened on the next pass
def test_a_control_bug_fails_safe_and_the_next_pass_runs(self):
ok = {p: 900 for p in range(1, 7)}
self.commander.set_duty.side_effect = [RuntimeError("bug"), ok, ok]
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
self.assertEqual(self.control.step(50, None, 0), CaseFanControl.ERROR_RETRY_SECONDS)
self.assertIn("CONTROL ERROR", self.control.status)
self.assertEqual(self.commander.set_duty.call_args_list[1], call((4, 5, 6), 100))
self.assertEqual(self.control.step(50, None, 5), 1.0) # not dead: the next pass works
def test_unexpected_errors_fail_the_top_fans_safe_too(self):
top = Mock(spec=TopFanCurve)
self.control.top = top
self.commander.set_duty.side_effect = [RuntimeError("bug"), {p: 900 for p in range(1, 7)}]
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
self.control.step(50, None, 0)
self.assertEqual(top.update.call_args.args[:2], (100, None))
self.control.shutdown()
top.release.assert_called_once()
class CommanderControlTest(unittest.TestCase):
def setUp(self):
self.commander = CommanderPro()
self.commander.ports = list(range(6))
self.commander.ch = Mock()
self.commander._corsair_software_running = Mock(return_value=False)
self.commander._open = Mock()
def reply(self, op, *args):
if op == 0x20:
return bytes((0, 0, 2, 2, 2, 2, 2, 2))
if op == 0x21:
return bytes((0, 0, 3, 132)) # 900 RPM
return bytes(4)
def test_only_confirmed_side_receives_duty_commands(self):
self.commander._cmd = Mock(side_effect=self.reply)
rpms = self.commander.set_duty((4, 5, 6), 81)
writes = [c.args for c in self.commander._cmd.call_args_list if c.args[0] == 0x23]
self.assertEqual(writes, [(0x23, 3, 81), (0x23, 4, 81), (0x23, 5, 81)])
self.assertEqual(rpms, {p: 900 for p in range(1, 7)})
self.commander.controlled = True
self.commander._cmd.reset_mock()
self.assertEqual(self.commander.read(), [900] * 6)
self.commander._cmd.assert_not_called()
def test_disconnected_or_dc_port_rejected_before_any_write(self):
for modes in (bytes((0, 0, 2, 2, 0, 2, 2, 2)),
bytes((0, 0, 2, 2, 1, 2, 2, 2)), bytes(4)):
self.commander._cmd = Mock(return_value=modes)
with self.assertRaises(OSError):
self.commander.set_duty((1, 2, 3), 80)
self.commander._cmd.assert_called_once_with(0x20)
def test_competing_software_prevents_all_usb_writes(self):
self.commander._corsair_software_running.return_value = True
self.commander._cmd = Mock()
with self.assertRaisesRegex(OSError, "busy"):
self.commander.set_duty((1, 2, 3), 100)
self.commander._cmd.assert_not_called()
self.assertIsNone(self.commander.ch)
def test_openrgb_counts_as_released_only_when_detector_disabled_everywhere(self):
commander = CommanderPro()
disabled = '{"Detectors":{"detectors":{"Corsair Commander Pro":false}}}'
configs = {"user": disabled, "service": disabled}
def fake_open(path, *args, **kwargs):
return mock_open(read_data=configs["service" if "service_config" in path else "user"])()
with patch("kurgan.telemetry.sensors._process_names", return_value=["openrgb.exe"]), \
patch("kurgan.telemetry.sensors.os.path.exists", return_value=True), \
patch("builtins.open", side_effect=fake_open):
self.assertFalse(commander._corsair_software_running())
configs["service"] = disabled.replace("false", "true")
with self.assertLogs("kurgan.telemetry.sensors", level="WARNING"):
self.assertTrue(commander._corsair_software_running())
with patch("kurgan.telemetry.sensors._process_names", return_value=["openrgb.exe"]), \
patch("kurgan.telemetry.sensors.os.path.exists", return_value=True), \
patch("builtins.open", side_effect=OSError("missing config")):
with self.assertLogs("kurgan.telemetry.sensors", level="WARNING"):
self.assertTrue(commander._corsair_software_running())
with patch("kurgan.telemetry.sensors._process_names", return_value=["fancontrol.exe"]):
self.assertTrue(commander._corsair_software_running())
self.assertFalse(corsair_software_running("Corsair Lighting Node Core", fan_tools=False))
if __name__ == "__main__":
unittest.main()