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) { diff --git a/DiagnosticsService.cs b/DiagnosticsService.cs index 6cb3547..7e5d5de 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,21 +106,49 @@ 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.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) + if (hardwareState.Fan1Rpm.HasValue || hardwareState.Fan2Rpm.HasValue + || hardwareState.Fan1Duty.HasValue || hardwareState.Fan2Duty.HasValue) { - text.AppendLine().Append(L.T("Вентиляторы: ", "Fans: ", "风扇:")); - AppendFan(text, hardwareState.Fan1Rpm); - text.Append('/'); - AppendFan(text, hardwareState.Fan2Rpm); - text.Append(L.T(" об/мин", " RPM", " 转/分")); + var hasRpm = hardwareState.Fan1Rpm.HasValue || hardwareState.Fan2Rpm.HasValue; + text.AppendLine().Append(Label(compact, "Вент.: ", "Вентиляторы: ", "Fans: ", "风扇:")); + 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('%'); + } } } - if (text.Length > MaxTooltipLength) - text.Length = MaxTooltipLength; return text.ToString(); } @@ -98,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); @@ -110,7 +175,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; } 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)); } diff --git a/HardwareSensors.cs b/HardwareSensors.cs index aa01fcb..7e9d9d9 100644 --- a/HardwareSensors.cs +++ b/HardwareSensors.cs @@ -8,49 +8,141 @@ internal readonly record struct HardwareSensorSnapshot( int? BatteryTemperature, int? KeyboardBacklightMode, int? ChargeStart, - int? ChargeEnd) + int? ChargeEnd, + 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); + 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('|'); - if (parts is not { Length: 9 } || !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( 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]), + At(parts, 9), At(parts, 10), At(parts, 11)); return true; } - private static int? ParseNullable(string value) + 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; } +/// +/// Обороты последних измерений: на строку - время в тиках 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; + private const ulong FanConfigGetCommand = 0x00001704; private const ulong TemperatureGetCommand = 0x00000202; 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 + // ~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. 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". + // 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 + // 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 + // 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), - ReadTemperature(session, 0x00), ReadTemperature(session, 0x0E), - backlightMode, chargeStart, chargeEnd); + DateTime.UtcNow, fans[0], fans[1], + ReadTemperature(session, CpuTemperatureZone), ReadTemperature(session, BatteryTemperatureZone), + backlightMode, chargeStart, chargeEnd, + ReadTemperature(session, MemoryTemperatureZone), + ReadFanDuty(session, 0), ReadFanDuty(session, 1)); HardwareSettings.SensorSnapshot = snapshot.Serialize(requestId); HardwareSettings.KeyboardBacklight = backlightMode switch @@ -65,16 +157,132 @@ 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) + { + 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++) + { + 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])); + } + + 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) + => 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) + { + if (values.Count == 0) + return null; + + values.Sort(); + 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]; + } + + // 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, 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 { - var output = session.Call(FanSpeedGetCommand | ((ulong)index << 16)); - return output.Length >= 3 ? output[1] | (output[2] << 8) : null; + 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 {index + 1} speed", exception); + AppLog.Error($"Could not read fan {fan + 1} duty", exception); return null; } } 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); 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.",