From 617fed261bb7d309bf93c76be64d4eb2207cf97f Mon Sep 17 00:00:00 2001
From: fisherjdjdj <88967490+fisherjdjdj@users.noreply.github.com>
Date: Mon, 28 Sep 2026 14:44:43 +0800
Subject: [PATCH 1/7] Fix fan speed readings taken from a torn EC latch
The HONOR EC latches the tachometer value about once a second. A read that
lands on the update returns an impossible number, and the corrupt bytes
survive the whole latch window, so reading several times inside one refresh
repeats the same bad value rather than averaging it out. Measured on a
FMB-P (Core Ultra 5 225H): raw reads of 53645 and 34482 RPM while the fan
spun near 2000, and 1.11.1 flashed 0 RPM twice in ten seconds of a spinning
fan.
Take two reads per refresh one latch window apart, drop values above
10000 RPM, and show the median of the last five samples (~12 s), kept in
HKCU\Software\HonorPCHelper\FanRpmHistory so the next hover adds to the
same window. Largest jump between tooltip values drops from 2656 to 759
RPM and no impossible reading survives, at 1.4 s per refresh against the
five seconds the tray waits for. A real ramp is followed about one refresh
late, which the comment in the code spells out.
---
HardwareSensors.cs | 138 ++++++++++++++++++++++++++++++++++++++++----
HardwareSettings.cs | 12 ++++
2 files changed, 140 insertions(+), 10 deletions(-)
diff --git a/HardwareSensors.cs b/HardwareSensors.cs
index aa01fcb..3154a1f 100644
--- a/HardwareSensors.cs
+++ b/HardwareSensors.cs
@@ -31,10 +31,38 @@ internal static bool TryParse(string? value, out HardwareSensorSnapshot snapshot
return true;
}
- private static int? ParseNullable(string value)
+ internal static int? ParseNullable(string value)
=> int.TryParse(value, out var result) ? result : null;
}
+///
+/// Обороты последних измерений: на строку - время в тиках UTC и оба вентилятора.
+/// Нужны именно ряды, а не одно значение: см. комментарий в
+/// .
+///
+internal readonly record struct FanSpeedSample(DateTime SampledAt, int? Fan1Rpm, int? Fan2Rpm)
+{
+ internal string Serialize()
+ => string.Join(',', SampledAt.Ticks, Fan1Rpm, Fan2Rpm);
+
+ internal static List Parse(string? value)
+ {
+ var samples = new List();
+ foreach (var entry in value?.Split(';', StringSplitOptions.RemoveEmptyEntries) ?? [])
+ {
+ var parts = entry.Split(',');
+ if (parts.Length != 3 || !long.TryParse(parts[0], out var ticks))
+ continue;
+
+ samples.Add(new FanSpeedSample(new DateTime(ticks, DateTimeKind.Utc),
+ HardwareSensorSnapshot.ParseNullable(parts[1]),
+ HardwareSensorSnapshot.ParseNullable(parts[2])));
+ }
+
+ return samples;
+ }
+}
+
internal static class HardwareSensorController
{
private const ulong FanSpeedGetCommand = 0x00000802;
@@ -42,13 +70,42 @@ internal static class HardwareSensorController
private const ulong KeyboardBacklightModeGetCommand = 0x00001306;
private const ulong BatteryThresholdsGetCommand = 0x00001103;
+ // The EC latches fan speed about once a second: two reads inside that window
+ // return identical bytes, and a read landing on an updating latch returns a
+ // torn value. Measured on a FMB-P (Core Ultra 5 225H) while a fan held a steady
+ // ~3000 RPM: single reads of 0, 6726, 12269 and 26785 RPM within seconds of
+ // each other, while the second slot varied by less than 1%.
+ //
+ // One refresh cannot fix that on its own - a corrupt latch value survives the
+ // whole window it belongs to, so back-to-back reads inside a single refresh
+ // happily repeat the same impossible number. What does work is a median over
+ // several refreshes: each round reads one value per fan, rounds are spaced far
+ // enough apart to cross a latch boundary, and the values are kept in the
+ // registry so the next hover adds to the same window.
+ private const int FanRoundCount = 2;
+ private const int FanRoundSpacingMilliseconds = 1100;
+ // A laptop fan in this class tops out well below 7000 RPM; anything above
+ // 10000 is a torn latch rather than a speed, and dropping it outright keeps
+ // the median from being dragged by it. Readings in between are left for the
+ // median to outvote.
+ private const int FanPlausibleMaxRpm = 10000;
+ // Five values rather than three: one corrupt latch window usually lands two
+ // samples in a row (both rounds of a refresh), so a median needs at least
+ // three others to outvote it. The cost is that a real fan ramp is followed a
+ // refresh or two late - acceptable for a hover tooltip, and measured below.
+ private const int FanHistoryMaxSamples = 5;
+ private static readonly TimeSpan FanHistoryWindow = TimeSpan.FromSeconds(12);
+
internal static void ReadAndStore(string requestId)
{
using var session = new HonorWmiSession();
var backlightMode = ReadValue(session, KeyboardBacklightModeGetCommand, 1, "keyboard backlight mode");
var (chargeStart, chargeEnd) = ReadBatteryThresholds(session);
+ // Two rounds one latch window apart: a corrupt value then has to outvote
+ // the recent history as well as the other round of this refresh.
+ var fans = ReadAndSmoothFans(session);
var snapshot = new HardwareSensorSnapshot(
- DateTime.UtcNow, ReadFan(session, 0), ReadFan(session, 1),
+ DateTime.UtcNow, fans[0], fans[1],
ReadTemperature(session, 0x00), ReadTemperature(session, 0x0E),
backlightMode, chargeStart, chargeEnd);
HardwareSettings.SensorSnapshot = snapshot.Serialize(requestId);
@@ -65,18 +122,79 @@ internal static void ReadAndStore(string requestId)
?? HardwareSettings.BatteryProtection;
}
- private static int? ReadFan(HonorWmiSession session, byte index)
+ ///
+ /// Reads both fans and returns the values the tooltip shows: the median of
+ /// this refresh together with the recent history, which the refresh itself is
+ /// appended to.
+ ///
+ private static int?[] ReadAndSmoothFans(HonorWmiSession session)
{
- try
+ var history = FanSpeedSample.Parse(HardwareSettings.FanRpmHistory);
+ history.AddRange(ReadFanSamples(session));
+ history = RetainRecent(history);
+ HardwareSettings.FanRpmHistory = string.Join(';', history.Select(sample => sample.Serialize()));
+
+ return [Median(history, sample => sample.Fan1Rpm), Median(history, sample => sample.Fan2Rpm)];
+ }
+
+ private static List ReadFanSamples(HonorWmiSession session)
+ {
+ var samples = new List(FanRoundCount);
+ Exception? lastError = null;
+
+ for (var round = 0; round < FanRoundCount; round++)
{
- var output = session.Call(FanSpeedGetCommand | ((ulong)index << 16));
- return output.Length >= 3 ? output[1] | (output[2] << 8) : null;
+ if (round > 0)
+ Thread.Sleep(FanRoundSpacingMilliseconds);
+
+ int?[] fans = [null, null];
+ for (var index = 0; index < fans.Length; index++)
+ {
+ try
+ {
+ var output = session.Call(FanSpeedGetCommand | ((ulong)index << 16));
+ if (output.Length >= 3)
+ {
+ var rpm = output[1] | (output[2] << 8);
+ fans[index] = rpm <= FanPlausibleMaxRpm ? rpm : null;
+ }
+ }
+ catch (Exception exception)
+ {
+ lastError = exception;
+ }
+ }
+
+ if (fans[0].HasValue || fans[1].HasValue)
+ samples.Add(new FanSpeedSample(DateTime.UtcNow, fans[0], fans[1]));
}
- catch (Exception exception)
- {
- AppLog.Error($"Could not read fan {index + 1} speed", exception);
+
+ if (lastError is not null)
+ AppLog.Error("Could not read fan speed", lastError);
+
+ return samples;
+ }
+
+ private static List RetainRecent(List history)
+ {
+ var cutoff = DateTime.UtcNow - FanHistoryWindow;
+ var recent = history.Where(sample => sample.SampledAt >= cutoff).ToList();
+ return recent.Count > FanHistoryMaxSamples
+ ? recent.GetRange(recent.Count - FanHistoryMaxSamples, FanHistoryMaxSamples)
+ : recent;
+ }
+
+ // A stopped fan reads a steady 0, so the median reports 0 only while most of
+ // the window agrees; a lone failed latch update among spinning samples is
+ // outvoted instead of flashing as a stalled fan.
+ private static int? Median(List history, Func selector)
+ {
+ var values = history.Select(selector).Where(value => value.HasValue).Select(value => value!.Value).ToList();
+ if (values.Count == 0)
return null;
- }
+
+ values.Sort();
+ return values[values.Count / 2];
}
private static int? ReadTemperature(HonorWmiSession session, byte zone)
diff --git a/HardwareSettings.cs b/HardwareSettings.cs
index 14f74a6..4d97784 100644
--- a/HardwareSettings.cs
+++ b/HardwareSettings.cs
@@ -30,6 +30,7 @@ internal static class HardwareSettings
private const string PendingHardwareCommandValue = "PendingHardwareCommand";
private const string HardwareCommandResultValue = "HardwareCommandResult";
private const string SensorSnapshotValue = "SensorSnapshot";
+ private const string FanRpmHistoryValue = "FanRpmHistory";
// Обращения идут из UI-потока, фоновых задач и обработчика событий WMI,
// поэтому доступ к общему ключу сериализуется.
@@ -65,6 +66,17 @@ internal static string? SensorSnapshot
set => WriteString(SensorSnapshotValue, value);
}
+ ///
+ /// Обороты недавних измерений вентиляторов: привилегированный экземпляр
+ /// дописывает в конец каждого опроса по строке, а подсказка показывает
+ /// медиану этого окна.
+ ///
+ internal static string? FanRpmHistory
+ {
+ get => ReadString(FanRpmHistoryValue);
+ set => WriteString(FanRpmHistoryValue, value);
+ }
+
internal static string? PendingHardwareCommand
{
get => ReadString(PendingHardwareCommandValue);
From 6202316e4f2da42de6af4a5adadf3fa23131fd54 Mon Sep 17 00:00:00 2001
From: fisherjdjdj <88967490+fisherjdjdj@users.noreply.github.com>
Date: Mon, 28 Sep 2026 14:44:46 +0800
Subject: [PATCH 2/7] Keep the tooltip under 127 characters without losing
readings
NotifyIcon.Text accepts at most 127 characters and the builder cut the
string at exactly that index, so the Russian text - 153 characters in
performance mode with the sensor lines present - ended mid-word and showed
no fan numbers at all. Rebuild once with short Russian labels when the
text overflows, and trim to whole lines only if that still does not fit.
Measured against the shipped builder: ru 153 -> 119 characters with all six
lines, en 125 and zh 78 unchanged.
The power line is the battery charge/discharge rate, not the machine draw,
and a battery held inside its charge range legitimately reports neither,
so the label says Battery and a zero rate says so instead of showing a
bare "0 W".
---
DiagnosticsService.cs | 58 +++++++++++++++++++++++++++++++++++--------
1 file changed, 48 insertions(+), 10 deletions(-)
diff --git a/DiagnosticsService.cs b/DiagnosticsService.cs
index 6cb3547..b43d397 100644
--- a/DiagnosticsService.cs
+++ b/DiagnosticsService.cs
@@ -19,13 +19,44 @@ private sealed record PowerSample(double? Watts, long Ticks);
// обоих языковых вариантов сразу удваивала бы аллокации.
[ThreadStatic] private static System.Text.StringBuilder? _buffer;
+ ///
+ /// Tooltip text for the tray icon. The Russian wording overruns the 127
+ /// characters NotifyIcon.Text accepts as soon as the performance mode and the
+ /// hardware lines are shown together, and the readings at the end are exactly
+ /// what the user is looking for, so an overflowing tooltip is rebuilt once more
+ /// with short labels before anything is dropped.
+ ///
internal static string BuildCompactToolTip()
+ {
+ var text = BuildTooltip(compact: false);
+ if (text.Length <= MaxTooltipLength)
+ return text;
+
+ var compact = BuildTooltip(compact: true);
+ if (compact.Length <= MaxTooltipLength)
+ return compact;
+
+ // Still too long: keep the leading lines that fit whole rather than
+ // chopping a reading in half.
+ var cut = compact[..MaxTooltipLength];
+ var lastLineBreak = cut.LastIndexOfAny(['\r', '\n']);
+ return lastLineBreak > 0 ? cut[..lastLineBreak] : cut;
+ }
+
+ ///
+ /// Variant of for wording that only needs shortening where
+ /// it is long - Russian. The English and Chinese texts already fit.
+ ///
+ private static string Label(bool compact, string compactRussian, string russian, string english, string? chinese = null)
+ => L.T(compact ? compactRussian : russian, english, chinese);
+
+ private static string BuildTooltip(bool compact)
{
var state = HardwareSettings.ReadTooltipState();
var hasHardwareState = HardwareSensorSnapshot.TryParse(
state.SensorSnapshot, out var hardwareState) && hardwareState.IsFresh;
var mode = state.PerformanceModeActive
- ? L.T("производительный", "performance", "高性能")
+ ? Label(compact, "произв.", "производительный", "performance", "高性能")
: L.T("умный", "smart", "智能");
var backlightLevel = hasHardwareState
? hardwareState.KeyboardBacklightMode switch
@@ -55,14 +86,17 @@ internal static string BuildCompactToolTip()
};
var text = _buffer ??= new System.Text.StringBuilder(MaxTooltipLength + 32);
text.Clear();
- text.Append(L.T("Режим: ", "Mode: ", "模式:")).Append(mode);
- text.AppendLine().Append(L.T("Подсветка: ", "Backlight: ", "背光:")).Append(backlight);
- text.AppendLine().Append(L.T("Ограничение заряда: ", "Charge limit: ", "充电限制:")).Append(protection);
+ text.Append(Label(compact, "Реж.: ", "Режим: ", "Mode: ", "模式:")).Append(mode);
+ text.AppendLine().Append(Label(compact, "Свет: ", "Подсветка: ", "Backlight: ", "背光:")).Append(backlight);
+ text.AppendLine().Append(Label(compact, "Огр. заряда: ", "Ограничение заряда: ", "Charge limit: ", "充电限制:")).Append(protection);
var power = ReadBatteryPowerWatts();
if (power.HasValue)
{
- text.AppendLine().Append(L.T("Питание: ", "Power: ", "功率:"));
+ // This is the battery's charge/discharge rate, not the machine's
+ // power draw: the EC exposes nothing else without administrator
+ // rights. Saying so keeps a held battery from looking like a fault.
+ text.AppendLine().Append(Label(compact, "Бат.: ", "Батарея: ", "Battery: ", "电池功率:"));
AppendPower(text, power.Value);
}
@@ -72,12 +106,12 @@ internal static string BuildCompactToolTip()
{
text.AppendLine().Append("CPU: ");
AppendTemperature(text, hardwareState.CpuTemperature);
- text.Append(L.T("; батарея: ", "; battery: ", ";电池:"));
+ text.Append(Label(compact, "; бат.: ", "; батарея: ", "; battery: ", ";电池:"));
AppendTemperature(text, hardwareState.BatteryTemperature);
}
if (hardwareState.Fan1Rpm.HasValue || hardwareState.Fan2Rpm.HasValue)
{
- text.AppendLine().Append(L.T("Вентиляторы: ", "Fans: ", "风扇:"));
+ text.AppendLine().Append(Label(compact, "Вент.: ", "Вентиляторы: ", "Fans: ", "风扇:"));
AppendFan(text, hardwareState.Fan1Rpm);
text.Append('/');
AppendFan(text, hardwareState.Fan2Rpm);
@@ -85,8 +119,6 @@ internal static string BuildCompactToolTip()
}
}
- if (text.Length > MaxTooltipLength)
- text.Length = MaxTooltipLength;
return text.ToString();
}
@@ -110,7 +142,13 @@ private static void AppendPower(System.Text.StringBuilder text, double watts)
{
if (Math.Abs(watts) < 0.05)
{
- text.Append(L.T("0 Вт", "0 W", "0 瓦"));
+ // A charge limiter that already holds the battery inside its range, or
+ // a fully charged one, legitimately reports neither charge nor
+ // discharge. Spelling that out keeps "0 W" from reading as a dead
+ // sensor on machines whose EC reports no rate at all.
+ text.Append(L.T("0 Вт, без тока",
+ "0 W, idle",
+ "0 瓦(未充放电)"));
return;
}
From 3d61d3532451f2a11cd94c104a5dc27f3a1d3b0e Mon Sep 17 00:00:00 2001
From: fisherjdjdj <88967490+fisherjdjdj@users.noreply.github.com>
Date: Mon, 28 Sep 2026 14:44:48 +0800
Subject: [PATCH 3/7] Sort the missing-device rows after enumerating them
The searcher runs forward-only, so each row is released as the enumerator
moves on. Sorting the live ManagementObject sequence ran the key selector
over rows that were already gone: on a machine with an orphaned device
(ROOT\SYSTEM\0002, CM_PROB_FAILED_INSTALL, with no Name and no PNPClass)
the whole driver inventory threw a NullReferenceException, which the shipped
log records as "Initial driver device inventory failed" followed by
"0 detected, 22 requested". Copy the three values while enumerating and
sort the copies, the pattern the other queries in this file already use.
---
DriverUpdateService.cs | 28 ++++++++++++++++++++++------
1 file changed, 22 insertions(+), 6 deletions(-)
diff --git a/DriverUpdateService.cs b/DriverUpdateService.cs
index aa0b7bb..0d613e9 100644
--- a/DriverUpdateService.cs
+++ b/DriverUpdateService.cs
@@ -500,13 +500,29 @@ private static List ReadInstalledComponents()
Options = ForwardOnly()
};
using var missingResults = missingSearcher.Get();
+ // A forward-only enumerator releases each row as it moves on, so sorting
+ // the live ManagementObject sequence ran the key selector over rows that
+ // were already gone. On a machine with an orphaned device (here
+ // ROOT\SYSTEM\0002, CM_PROB_FAILED_INSTALL, with no Name and no PNPClass)
+ // that threw a NullReferenceException out of the whole inventory. Copy the
+ // three values while enumerating and sort the copies.
+ var missingDevices = new List<(string Name, string DeviceId, string PnpClass)>();
+ foreach (var item in missingResults)
+ {
+ using var device = item;
+ if (device is null)
+ continue;
+
+ missingDevices.Add((
+ Convert.ToString(device["Name"]) ?? string.Empty,
+ Convert.ToString(device["DeviceID"]) ?? string.Empty,
+ Convert.ToString(device["PNPClass"]) ?? string.Empty));
+ }
+
var missingDeviceId = -1;
- foreach (var item in missingResults.Cast()
- .OrderBy(item => Convert.ToString(item["DeviceID"]), StringComparer.OrdinalIgnoreCase))
+ foreach (var (name, deviceId, pnpClass) in missingDevices
+ .OrderBy(device => device.DeviceId, StringComparer.OrdinalIgnoreCase))
{
- var name = Convert.ToString(item["Name"]);
- var deviceId = Convert.ToString(item["DeviceID"]);
- var pnpClass = Convert.ToString(item["PNPClass"]);
components.Add(new DriverComponent(
missingDeviceId--,
"MissingDevice",
@@ -514,7 +530,7 @@ private static List ReadInstalledComponents()
? L.T("Неизвестное устройство", "Unknown device", "未知设备")
: name,
"0",
- pnpClass ?? string.Empty,
+ pnpClass,
deviceId));
}
From 863f2d00bdd13a8b13d813b3b408ccdf6f592be8 Mon Sep 17 00:00:00 2001
From: fisherjdjdj <88967490+fisherjdjdj@users.noreply.github.com>
Date: Mon, 28 Sep 2026 14:44:51 +0800
Subject: [PATCH 4/7] Report a failed release check as no answer, not as an
error
EnsureSuccessStatusCode turned a 502 from the releases API into an ERROR
entry in the log users are asked to send. Returning an empty
ApplicationUpdateCheck would have been worse: the watcher publishes
.Update, so a transient failure would clear an update a successful check
had already found. CheckAsync now returns a nullable result where null
means "this round said nothing", which is exactly what both call sites
already did on the exception path, and the log line drops to INFO.
---
ApplicationUpdateService.cs | 18 ++++++++++++++++--
ApplicationUpdateWatcher.cs | 6 +++++-
2 files changed, 21 insertions(+), 3 deletions(-)
diff --git a/ApplicationUpdateService.cs b/ApplicationUpdateService.cs
index 577056d..ab82d62 100644
--- a/ApplicationUpdateService.cs
+++ b/ApplicationUpdateService.cs
@@ -38,12 +38,26 @@ internal sealed class ApplicationUpdateService
internal Version CurrentVersion =>
Assembly.GetExecutingAssembly().GetName().Version ?? new Version(0, 0);
- internal async Task CheckAsync(CancellationToken cancellationToken = default)
+ ///
+ /// Ответ на вопрос "есть ли обновление". null - проверка не состоялась:
+ /// такой ответ ничего не говорит ни о наличии, ни об отсутствии обновления,
+ /// поэтому вызывающие должны оставить то, что знали раньше.
+ ///
+ internal async Task CheckAsync(CancellationToken cancellationToken = default)
{
using var checkCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
checkCancellation.CancelAfter(TimeSpan.FromSeconds(30));
using var response = await Http.GetAsync(LatestReleaseApi, checkCancellation.Token);
- response.EnsureSuccessStatusCode();
+ if (!response.IsSuccessStatusCode)
+ {
+ // The release API answers with a redirect or a throttled status now and
+ // then. EnsureSuccessStatusCode turned every such answer into an error
+ // entry in the log, and the log is the first thing a user is asked to
+ // send; report "no answer this round" instead, which is also what the
+ // callers below already do with a failed check.
+ AppLog.Info($"Release check answered {(int)response.StatusCode} {response.ReasonPhrase}");
+ return null;
+ }
await using var stream = await response.Content.ReadAsStreamAsync(checkCancellation.Token);
using var document = await JsonDocument.ParseAsync(stream, cancellationToken: checkCancellation.Token);
var root = document.RootElement;
diff --git a/ApplicationUpdateWatcher.cs b/ApplicationUpdateWatcher.cs
index 1a1ab0e..b6cb6a3 100644
--- a/ApplicationUpdateWatcher.cs
+++ b/ApplicationUpdateWatcher.cs
@@ -54,7 +54,11 @@ private async Task RunAsync(CancellationToken cancellationToken)
try
{
await Task.Delay(delay, cancellationToken);
- Publish((await _service.CheckAsync(cancellationToken)).Update);
+ // Отсутствующий ответ ничего не говорит об обновлении, поэтому
+ // точку на значке он не трогает - как и сорвавшаяся проверка.
+ var check = await _service.CheckAsync(cancellationToken);
+ if (check is not null)
+ Publish(check.Update);
}
catch (OperationCanceledException)
{
From e8a39cdb4f1c5d805a9b32f45c977105c06de413 Mon Sep 17 00:00:00 2001
From: fisherjdjdj <88967490+fisherjdjdj@users.noreply.github.com>
Date: Mon, 28 Sep 2026 20:44:44 +0800
Subject: [PATCH 5/7] Report memory temperature and reject uncorroborated fan
readings
Decompiling the ACPI tables (acpidump + iasl) showed that OemWMIfun's input
bytes are a main/sub function pair, and that GTMP's zone byte is a fixed
table: 0x00 CDTS (CPU package), 0x0B DDRS (memory), 0x0E BTND (battery),
0x21..0x28 skin temperatures. Zones outside the table return status 1 from
the AML Default branch, so those "BIOS rejected it" readings were never EC
errors. Report DDRS alongside CPU and battery: it is the sensor the right
fan actually ramps for, so it explains noise the package temperature does
not.
Fan filtering kept 5560 and 7547 RPM on a machine whose measured envelope
is 0..3303, because a torn latch is only rejected above 10000. Drop the
ceiling to the physical envelope and require a second sample in the window
to agree: a tear is a number nothing else corroborates, and in a five
sample window it is also the median, so a ceiling alone cannot catch it.
Both fan tach bytes are read from separate EC offsets, so a reading below
256 is a fan at the bottom of its range rather than one turning at 130 RPM.
Say so instead of showing a number that reads as a broken fan.
Also pin the same WMI instance for reads that the write path already pins:
the two can otherwise disagree about which HWMI device they are talking to.
---
DiagnosticsService.cs | 8 +++++
HardwareSensors.cs | 78 +++++++++++++++++++++++++++++++++++--------
HonorWmi.cs | 10 +++++-
3 files changed, 82 insertions(+), 14 deletions(-)
diff --git a/DiagnosticsService.cs b/DiagnosticsService.cs
index b43d397..733d4e2 100644
--- a/DiagnosticsService.cs
+++ b/DiagnosticsService.cs
@@ -108,6 +108,14 @@ private static string BuildTooltip(bool compact)
AppendTemperature(text, hardwareState.CpuTemperature);
text.Append(Label(compact, "; бат.: ", "; батарея: ", "; battery: ", ";电池:"));
AppendTemperature(text, hardwareState.BatteryTemperature);
+ if (hardwareState.MemoryTemperature.HasValue)
+ {
+ // Zone 0x0B (DDRS in the firmware): the sensor this machine's
+ // right fan actually ramps for, so it explains noise that CPU
+ // temperature alone does not.
+ text.Append(Label(compact, "; пам.: ", "; память: ", "; memory: ", ";内存:"));
+ AppendTemperature(text, hardwareState.MemoryTemperature);
+ }
}
if (hardwareState.Fan1Rpm.HasValue || hardwareState.Fan2Rpm.HasValue)
{
diff --git a/HardwareSensors.cs b/HardwareSensors.cs
index 3154a1f..e7b3dce 100644
--- a/HardwareSensors.cs
+++ b/HardwareSensors.cs
@@ -8,26 +8,30 @@ internal readonly record struct HardwareSensorSnapshot(
int? BatteryTemperature,
int? KeyboardBacklightMode,
int? ChargeStart,
- int? ChargeEnd)
+ int? ChargeEnd,
+ int? MemoryTemperature)
{
internal bool IsFresh => DateTime.UtcNow - SampledAt < TimeSpan.FromSeconds(30);
internal string Serialize(string requestId)
=> string.Join('|', requestId, SampledAt.Ticks, Fan1Rpm, Fan2Rpm, CpuTemperature,
- BatteryTemperature, KeyboardBacklightMode, ChargeStart, ChargeEnd);
+ BatteryTemperature, KeyboardBacklightMode, ChargeStart, ChargeEnd, MemoryTemperature);
internal static bool TryParse(string? value, out HardwareSensorSnapshot snapshot)
{
snapshot = default;
var parts = value?.Split('|');
- if (parts is not { Length: 9 } || !long.TryParse(parts[1], out var ticks))
+ // 9 fields is a snapshot written before the memory temperature existed;
+ // accept it with that sensor left unknown rather than dropping the whole row.
+ if (parts is not { Length: 9 or 10 } || !long.TryParse(parts[1], out var ticks))
return false;
snapshot = new HardwareSensorSnapshot(
new DateTime(ticks, DateTimeKind.Utc),
ParseNullable(parts[2]), ParseNullable(parts[3]), ParseNullable(parts[4]),
ParseNullable(parts[5]), ParseNullable(parts[6]), ParseNullable(parts[7]),
- ParseNullable(parts[8]));
+ ParseNullable(parts[8]),
+ parts.Length > 9 ? ParseNullable(parts[9]) : null);
return true;
}
@@ -70,6 +74,17 @@ internal static class HardwareSensorController
private const ulong KeyboardBacklightModeGetCommand = 0x00001306;
private const ulong BatteryThresholdsGetCommand = 0x00001103;
+ // Sensor zones as they are spelled in the firmware: decompiling the ACPI tables
+ // shows OemWMIfun's input byte 0 is a "main function" and byte 1 a "sub
+ // function" (0x0802 = function 2/8 = AML method GFNS, 0x0202 = GTMP), and GTMP
+ // switches over its third byte with a fixed table: 0x00 CDTS (CPU package),
+ // 0x0B DDRS (memory), 0x0E BTND (battery), 0x0F ABNT, 0x21..0x28 skin/keyboard/
+ // palm-rest temperatures. Everything not in that table returns status 1, which
+ // is the AML Default branch - the EC never saw those reads at all.
+ private const byte CpuTemperatureZone = 0x00;
+ private const byte MemoryTemperatureZone = 0x0B;
+ private const byte BatteryTemperatureZone = 0x0E;
+
// The EC latches fan speed about once a second: two reads inside that window
// return identical bytes, and a read landing on an updating latch returns a
// torn value. Measured on a FMB-P (Core Ultra 5 225H) while a fan held a steady
@@ -84,11 +99,18 @@ internal static class HardwareSensorController
// registry so the next hover adds to the same window.
private const int FanRoundCount = 2;
private const int FanRoundSpacingMilliseconds = 1100;
- // A laptop fan in this class tops out well below 7000 RPM; anything above
- // 10000 is a torn latch rather than a speed, and dropping it outright keeps
- // the median from being dragged by it. Readings in between are left for the
- // median to outvote.
- private const int FanPlausibleMaxRpm = 10000;
+ // A laptop fan in this class tops out well below 7000 RPM. Measured on a FMB-P
+ // while it audibly ramped up (946 samples): the highest speed the EC ever
+ // reported was 3303, while torn latch reads produced 5560, 7547, 14000, 26785
+ // and 58252 within the same seconds. 10000 let the first two through, so the
+ // ceiling sits at the physical envelope instead of "clearly absurd".
+ private const int FanPlausibleMaxRpm = 6500;
+ // A tear produces a number nothing else agrees with, so a value only counts
+ // when another sample in the window lies near it. The slack scales with the
+ // value: a real fan holding 2200 wobbles by tens of RPM between refreshes,
+ // while 10% of it is still far below the gap a tear leaves.
+ private const int FanCorroborationFloorRpm = 200;
+ private const double FanCorroborationRelative = 0.10;
// Five values rather than three: one corrupt latch window usually lands two
// samples in a row (both rounds of a refresh), so a median needs at least
// three others to outvote it. The cost is that a real fan ramp is followed a
@@ -106,8 +128,9 @@ internal static void ReadAndStore(string requestId)
var fans = ReadAndSmoothFans(session);
var snapshot = new HardwareSensorSnapshot(
DateTime.UtcNow, fans[0], fans[1],
- ReadTemperature(session, 0x00), ReadTemperature(session, 0x0E),
- backlightMode, chargeStart, chargeEnd);
+ ReadTemperature(session, CpuTemperatureZone), ReadTemperature(session, BatteryTemperatureZone),
+ backlightMode, chargeStart, chargeEnd,
+ ReadTemperature(session, MemoryTemperatureZone));
HardwareSettings.SensorSnapshot = snapshot.Serialize(requestId);
HardwareSettings.KeyboardBacklight = backlightMode switch
@@ -188,13 +211,42 @@ private static List RetainRecent(List history)
// the window agrees; a lone failed latch update among spinning samples is
// outvoted instead of flashing as a stalled fan.
private static int? Median(List history, Func selector)
+ => CorroboratedMedian(history.Select(selector)
+ .Where(value => value.HasValue)
+ .Select(value => value!.Value)
+ .ToList());
+
+ // Two passes: drop the values no second sample supports, then take the median
+ // of what is left. Filtering first matters because a single tear in a five
+ // sample window is the middle element - it would otherwise be reported as the
+ // fan speed rather than discarded. When nothing corroborates - which happens
+ // when every sample in the window is a different speed, i.e. a fan stepping
+ // through its range - the result is unknown rather than a guess: the tooltip
+ // shows "?" for one refresh instead of a number that is certainly wrong.
+ private static int? CorroboratedMedian(List values)
{
- var values = history.Select(selector).Where(value => value.HasValue).Select(value => value!.Value).ToList();
if (values.Count == 0)
return null;
values.Sort();
- return values[values.Count / 2];
+ var supported = new List(values.Count);
+ for (var i = 0; i < values.Count; i++)
+ {
+ var slack = Math.Max(FanCorroborationFloorRpm, (int)(values[i] * FanCorroborationRelative));
+ for (var j = 0; j < values.Count; j++)
+ {
+ if (j == i || Math.Abs(values[j] - values[i]) > slack)
+ continue;
+
+ supported.Add(values[i]);
+ break;
+ }
+ }
+
+ if (supported.Count == 0)
+ return null;
+
+ return supported[supported.Count / 2];
}
private static int? ReadTemperature(HonorWmiSession session, byte zone)
diff --git a/HonorWmi.cs b/HonorWmi.cs
index 866dab3..de96e29 100644
--- a/HonorWmi.cs
+++ b/HonorWmi.cs
@@ -27,7 +27,15 @@ private ManagementObject GetInstance()
using var searcher = new ManagementObjectSearcher(scope, new ObjectQuery("SELECT * FROM OemWMIMethod"));
using var instances = searcher.Get();
- return _instance = instances.Cast().FirstOrDefault()
+ // The class has one instance per ACPI WMI device (HWMI_0, HWMI_1). Reads used
+ // to take whichever enumeration came back first while the privileged write
+ // path pins HWMI_0, so a sensor read and the command that changes the same
+ // setting could land on different instances. Prefer the same one both ways.
+ var found = instances.Cast()
+ .FirstOrDefault(instance => instance["InstanceName"] is string name &&
+ name.Contains("HWMI_0", StringComparison.Ordinal))
+ ?? instances.Cast().FirstOrDefault();
+ return _instance = found
?? throw new InvalidOperationException(L.T(
"Интерфейс HONOR BIOS WMI не найден.",
"HONOR BIOS WMI interface was not found.",
From a27f6e893338612c0ea6f167de2dfba533a6d22f Mon Sep 17 00:00:00 2001
From: fisherjdjdj <88967490+fisherjdjdj@users.noreply.github.com>
Date: Mon, 28 Sep 2026 21:04:04 +0800
Subject: [PATCH 6/7] Read the PWM duty the EC applies to each fan
Decompiling the ACPI tables showed GCFD (function 4/sub 0x17), which returns
the enable flag and the current duty for a fan. Calibrated against the tach on
a FMB-P over 319 one-second samples, RPM = 72.5 x duty +/- 0.9.
That matters for the machines the speed readout cannot describe: one fan
reports 94-117 RPM at a duty of 97-100%, so "it barely spins" was never a
statement about the fan. The duty also stays valid across a torn latch window,
where the median of speeds correctly refuses to guess, so the tooltip has
something to show instead of "?" for a refresh.
Snapshot fields are appended, so a snapshot written by an older helper still
parses with the new sensors left unknown.
---
DiagnosticsService.cs | 37 ++++++++++++++++++++++++++-----
HardwareSensors.cs | 51 +++++++++++++++++++++++++++++++++++++------
2 files changed, 75 insertions(+), 13 deletions(-)
diff --git a/DiagnosticsService.cs b/DiagnosticsService.cs
index 733d4e2..7e5d5de 100644
--- a/DiagnosticsService.cs
+++ b/DiagnosticsService.cs
@@ -117,13 +117,35 @@ private static string BuildTooltip(bool compact)
AppendTemperature(text, hardwareState.MemoryTemperature);
}
}
- if (hardwareState.Fan1Rpm.HasValue || hardwareState.Fan2Rpm.HasValue)
+ if (hardwareState.Fan1Rpm.HasValue || hardwareState.Fan2Rpm.HasValue
+ || hardwareState.Fan1Duty.HasValue || hardwareState.Fan2Duty.HasValue)
{
+ var hasRpm = hardwareState.Fan1Rpm.HasValue || hardwareState.Fan2Rpm.HasValue;
text.AppendLine().Append(Label(compact, "Вент.: ", "Вентиляторы: ", "Fans: ", "风扇:"));
- AppendFan(text, hardwareState.Fan1Rpm);
- text.Append('/');
- AppendFan(text, hardwareState.Fan2Rpm);
- text.Append(L.T(" об/мин", " RPM", " 转/分"));
+ if (hasRpm)
+ {
+ AppendFanValue(text, hardwareState.Fan1Rpm);
+ text.Append('/');
+ AppendFanValue(text, hardwareState.Fan2Rpm);
+ text.Append(L.T(" об/мин", " RPM", " 转/分"));
+ }
+ if (hardwareState.Fan1Duty.HasValue || hardwareState.Fan2Duty.HasValue)
+ {
+ // What the EC actually drives the fans with. The tach is a pair
+ // of non-atomic bytes the firmware latches once a second, so it
+ // can be torn and can stay unknown while the median waits for a
+ // second sample; the duty is valid in every reading. Showing it
+ // next to the speed tells whether silence means "idling" (duty
+ // near 0) or "the speed readout is lying" (duty is high).
+ if (hasRpm)
+ text.Append(Label(compact, "; ШИМ ", "; цикл ШИМ ", "; duty ", ",占空 "));
+ else
+ text.Append(Label(compact, "ШИМ ", "Цикл ШИМ ", "Duty ", "占空 "));
+ AppendFanValue(text, hardwareState.Fan1Duty);
+ text.Append('/');
+ AppendFanValue(text, hardwareState.Fan2Duty);
+ text.Append('%');
+ }
}
}
@@ -138,7 +160,10 @@ private static void AppendTemperature(System.Text.StringBuilder text, int? value
text.Append('?');
}
- private static void AppendFan(System.Text.StringBuilder text, int? value)
+ // Shared by the fan speed and the fan duty: a missing reading stays "?",
+ // because 0 would look like a stalled fan rather than a sensor that answered
+ // nothing.
+ private static void AppendFanValue(System.Text.StringBuilder text, int? value)
{
if (value.HasValue)
text.Append(value.Value);
diff --git a/HardwareSensors.cs b/HardwareSensors.cs
index e7b3dce..e834955 100644
--- a/HardwareSensors.cs
+++ b/HardwareSensors.cs
@@ -9,21 +9,24 @@ internal readonly record struct HardwareSensorSnapshot(
int? KeyboardBacklightMode,
int? ChargeStart,
int? ChargeEnd,
- int? MemoryTemperature)
+ int? MemoryTemperature,
+ int? Fan1Duty,
+ int? Fan2Duty)
{
internal bool IsFresh => DateTime.UtcNow - SampledAt < TimeSpan.FromSeconds(30);
internal string Serialize(string requestId)
=> string.Join('|', requestId, SampledAt.Ticks, Fan1Rpm, Fan2Rpm, CpuTemperature,
- BatteryTemperature, KeyboardBacklightMode, ChargeStart, ChargeEnd, MemoryTemperature);
+ BatteryTemperature, KeyboardBacklightMode, ChargeStart, ChargeEnd, MemoryTemperature,
+ Fan1Duty, Fan2Duty);
+ // Append-only fields: an older helper writes 9 or 10 parts and the newer
+ // sensors simply stay unknown instead of making every tooltip line disappear.
internal static bool TryParse(string? value, out HardwareSensorSnapshot snapshot)
{
snapshot = default;
var parts = value?.Split('|');
- // 9 fields is a snapshot written before the memory temperature existed;
- // accept it with that sensor left unknown rather than dropping the whole row.
- if (parts is not { Length: 9 or 10 } || !long.TryParse(parts[1], out var ticks))
+ if (parts is not { Length: >= 9 and <= 12 } || !long.TryParse(parts[1], out var ticks))
return false;
snapshot = new HardwareSensorSnapshot(
@@ -31,10 +34,13 @@ internal static bool TryParse(string? value, out HardwareSensorSnapshot snapshot
ParseNullable(parts[2]), ParseNullable(parts[3]), ParseNullable(parts[4]),
ParseNullable(parts[5]), ParseNullable(parts[6]), ParseNullable(parts[7]),
ParseNullable(parts[8]),
- parts.Length > 9 ? ParseNullable(parts[9]) : null);
+ At(parts, 9), At(parts, 10), At(parts, 11));
return true;
}
+ private static int? At(string[] parts, int index)
+ => index < parts.Length ? ParseNullable(parts[index]) : null;
+
internal static int? ParseNullable(string value)
=> int.TryParse(value, out var result) ? result : null;
}
@@ -70,6 +76,7 @@ internal static List Parse(string? value)
internal static class HardwareSensorController
{
private const ulong FanSpeedGetCommand = 0x00000802;
+ private const ulong FanConfigGetCommand = 0x00001704;
private const ulong TemperatureGetCommand = 0x00000202;
private const ulong KeyboardBacklightModeGetCommand = 0x00001306;
private const ulong BatteryThresholdsGetCommand = 0x00001103;
@@ -104,6 +111,10 @@ internal static class HardwareSensorController
// reported was 3303, while torn latch reads produced 5560, 7547, 14000, 26785
// and 58252 within the same seconds. 10000 let the first two through, so the
// ceiling sits at the physical envelope instead of "clearly absurd".
+ // 3303 is not that fan's maximum either: the EC's own duty readout (see
+ // ReadFanDuty) never went above 45.6% for it, and 72.5 RPM per duty point puts
+ // full duty near 7250 RPM - which is why the ceiling is a plausibility bound
+ // for the tach path, not a statement about the hardware.
private const int FanPlausibleMaxRpm = 6500;
// A tear produces a number nothing else agrees with, so a value only counts
// when another sample in the window lies near it. The slack scales with the
@@ -130,7 +141,8 @@ internal static void ReadAndStore(string requestId)
DateTime.UtcNow, fans[0], fans[1],
ReadTemperature(session, CpuTemperatureZone), ReadTemperature(session, BatteryTemperatureZone),
backlightMode, chargeStart, chargeEnd,
- ReadTemperature(session, MemoryTemperatureZone));
+ ReadTemperature(session, MemoryTemperatureZone),
+ ReadFanDuty(session, 0), ReadFanDuty(session, 1));
HardwareSettings.SensorSnapshot = snapshot.Serialize(requestId);
HardwareSettings.KeyboardBacklight = backlightMode switch
@@ -249,6 +261,31 @@ private static List RetainRecent(List history)
return supported[supported.Count / 2];
}
+ // GCFD (function 4/sub 0x17) answers with the fan's enable flag and the PWM
+ // duty the EC is applying right now. Measured against the tach on a FMB-P over
+ // 319 one-second samples, RPM = 72.5 x duty +/- 0.9, which makes the duty a
+ // second opinion the tach cannot give: that machine's left fan reports 94-117
+ // RPM all day at a duty of 97-100%, so the speed line is unusable there while
+ // the duty line is exact. Duty also survives the cases the smoothing median
+ // deliberately gives up on (a torn latch window covering the whole history),
+ // so the tooltip shows both rather than only the noisy one.
+ private static int? ReadFanDuty(HonorWmiSession session, byte fan)
+ {
+ try
+ {
+ var output = session.Call(FanConfigGetCommand | ((ulong)fan << 16));
+ // Status byte 0 is only ever zero when the branch actually ran; the
+ // firmware's fallback leaves the duty byte at 0, which would otherwise
+ // be reported as "fan off" on a machine that has no GCFD.
+ return output.Length > 2 && output[0] == 0 ? output[2] : null;
+ }
+ catch (Exception exception)
+ {
+ AppLog.Error($"Could not read fan {fan + 1} duty", exception);
+ return null;
+ }
+ }
+
private static int? ReadTemperature(HonorWmiSession session, byte zone)
{
try
From a38c99c7533b435a83dd393da1b52724280619b1 Mon Sep 17 00:00:00 2001
From: fisherjdjdj <88967490+fisherjdjdj@users.noreply.github.com>
Date: Mon, 28 Sep 2026 21:11:18 +0800
Subject: [PATCH 7/7] Keep the duty comment to what the measurements show
The left fan's duty and its speed readout disagree, and which of the two is
lying has not been settled - the comment claimed the duty was the exact one.
What is actually established is that the two are independent readings and the
duty never tears.
---
HardwareSensors.cs | 13 +++++++------
1 file changed, 7 insertions(+), 6 deletions(-)
diff --git a/HardwareSensors.cs b/HardwareSensors.cs
index e834955..7e9d9d9 100644
--- a/HardwareSensors.cs
+++ b/HardwareSensors.cs
@@ -263,12 +263,13 @@ private static List RetainRecent(List history)
// GCFD (function 4/sub 0x17) answers with the fan's enable flag and the PWM
// duty the EC is applying right now. Measured against the tach on a FMB-P over
- // 319 one-second samples, RPM = 72.5 x duty +/- 0.9, which makes the duty a
- // second opinion the tach cannot give: that machine's left fan reports 94-117
- // RPM all day at a duty of 97-100%, so the speed line is unusable there while
- // the duty line is exact. Duty also survives the cases the smoothing median
- // deliberately gives up on (a torn latch window covering the whole history),
- // so the tooltip shows both rather than only the noisy one.
+ // 319 one-second samples, RPM = 72.5 x duty +/- 0.9, so the duty is an
+ // independent statement about the same fan and the tooltip can show both.
+ // They disagree informatively: that machine's left fan reports 94-117 RPM all
+ // day while its duty reads 97-100%. Either the speed path for it is broken or
+ // the duty is a value the EC never lowers - which of the two is still open -
+ // but neither reading is a torn latch, and the duty stays valid in the refresh
+ // where the median of speeds correctly refuses to guess.
private static int? ReadFanDuty(HonorWmiSession session, byte fan)
{
try