diff --git a/README.md b/README.md index 513c822..5f33236 100644 --- a/README.md +++ b/README.md @@ -24,11 +24,13 @@ installations keep their settings, install folder and autostart entry. | Frontend | WinUI 3 app with tray icon, plus the `m4ctl` command line | Qt app `momentum-control`, plus the `momentumctl` command line | | How to get it | Installer or portable zip from the releases | `tar.gz` from the releases (x64, arm64) or built from source, see [`linux/README.md`](linux/README.md) | | MOMENTUM 4 | Checked on a real headset, firmware 3.37.3 and 3.38.3 | Same commands and firmware gates through the shared core; the Linux hardware checks were done with a MOMENTUM 5 | -| MOMENTUM 5 | The shared core recognises it, but nobody has tested it on Windows yet, and the M5-only controls have no UI here | Checked on a real headset, firmware 6.21.5 (model M5AEBT); any other firmware is read-only | -| BTD 700 dongle | Not supported | USB status and codec selection; the firmware updater is experimental and flashing was never verified on hardware | +| MOMENTUM 5 | Same controls and session as on Linux (firmware 6.21.5), but only tested against the simulator, not yet on a real headset under Windows | Checked on a real headset, firmware 6.21.5 (model M5AEBT); any other firmware is read-only | +| BTD 700 dongle | Not supported (Linux only) | USB status and codec selection; the firmware updater is experimental and flashing was never verified on hardware | -On the MOMENTUM 5 the Linux app adds transparency level, immersive audio, head tracking and battery protection. Its -equalizer has eight bands instead of five, and wind reduction only knows off and maximum. The details, the BTD 700 +On the MOMENTUM 5 both apps add transparency level, immersive audio with head tracking, battery protection and +transparency during calls. Its equalizer has eight bands instead of five, and wind reduction only knows off and +maximum. On Windows an M5 is driven exactly like on Linux: no notification registration, the state is read every poll +interval. The details, the BTD 700 permissions and the remaining limits are in the [Linux guide](linux/README.md), the [validation notes](docs/linux-validation.md) and the [architecture overview](docs/architecture.md). @@ -49,6 +51,8 @@ All of this is checked on a real headset (firmware 3.37.3 and 3.38.3). - Tray icon with a quick panel on left-click and the full menu on right-click; about 5 MB of RAM while it sits in the tray - Reads the battery over Windows when the GAIA link is down (shown as "(Windows)") - Rename the headset +- MOMENTUM 5 (firmware 6.21.5): transparency level, immersive audio, head tracking, battery protection, transparency + during calls; shown only when an M5 is connected (not yet tested on a real M5 under Windows) - A small command line, `m4ctl`, for scripts and hotkeys - Optional start with Windows, minimized to the tray - Reconnects on its own when the headset comes back @@ -95,6 +99,8 @@ m4ctl strength 80 # ANC strength m4ctl preset MyCurve m4ctl battery # just the number, for scripts m4ctl autooff 30 +m4ctl immersive on # MOMENTUM 5 only +m4ctl sidetone 2 # transparency during calls, MOMENTUM 5 only for now ``` Settings, presets and logs are in `%LOCALAPPDATA%\Momentum4Control\`. Logs are deleted after 14 days. @@ -106,7 +112,10 @@ Settings, presets and logs are in `%LOCALAPPDATA%\Momentum4Control\`. Logs are d - It can't put the headset into pairing mode. Do that on the headset. - Sound Personalization (sound mode 3) is left alone; its preconditions aren't clear. - The bundled EQ presets are my own, not the ones from Smart Control. -- Only one paired MOMENTUM 4 at a time. +- Only one paired headset at a time. +- Transparency during calls (sidetone) is not offered on the MOMENTUM 4 yet: the headset reports the level, but nobody + has confirmed by ear that changing it works. +- No BTD 700 dongle support on Windows. - The phone's Smart Control app uses the same channel. I haven't tested both connected at once. ## Troubleshooting diff --git a/src/Momentum4.App/App.xaml.cs b/src/Momentum4.App/App.xaml.cs index 072e8f2..144fc85 100644 --- a/src/Momentum4.App/App.xaml.cs +++ b/src/Momentum4.App/App.xaml.cs @@ -163,7 +163,7 @@ private void OnWindowClosed(object sender, WindowEventArgs args) if (!_host.Settings.TrayHintShown) { - _tray?.ShowBalloon(Localization.L.Get("TrayHintTitle"), Localization.L.Get("TrayHintBody")); + _tray?.ShowBalloon(Localization.L.Get("TrayHintTitle", Momentum4.Core.State.ProductName.For(_host.Service?.Store.Current.Device?.ModelId)), Localization.L.Get("TrayHintBody")); _host.SaveSettings(_host.Settings with { TrayHintShown = true }); } diff --git a/src/Momentum4.App/Localization/L.cs b/src/Momentum4.App/Localization/L.cs index f8ba18d..14e5077 100644 --- a/src/Momentum4.App/Localization/L.cs +++ b/src/Momentum4.App/Localization/L.cs @@ -86,11 +86,25 @@ public static void Init(AppLanguage language) ["HintOff"] = "Keine Geräuschunterdrückung, nur passive Dämpfung.", ["ActNoiseControl"] = "Noise Control „{0}“", ["ActAntiWind"] = "Anti-Wind „{0}“", + ["TransparencyLevel"] = "Transparenzstufe", + ["SpatialTitle"] = "Raumklang", + ["ImmersiveAudio"] = "Immersive Audio", + ["HeadTracking"] = "Head Tracking", + ["SpatialPersonalizationHint"] = "Im Klangmodus Sound Personalization ist Raumklang nicht verfügbar.", + ["CallTransparency"] = "Transparenz bei Anrufen", + ["CallTransparencyOff"] = "Aus", + ["BatteryProtection"] = "Akkuschutz", + ["NameTooLong"] = "Name zu lang: höchstens {0} Byte (Umlaute zählen doppelt).", + ["ActSidetone"] = "Transparenz bei Anrufen „{0}“", + ["ActImmersive"] = "Immersive Audio {0}", + ["ActHeadTracking"] = "Head Tracking {0}", + ["ActBatteryProtection"] = "Akkuschutz {0}", + ["ActTransparencyLevel"] = "Transparenzstufe {0}", ["ActAutoPauseOn"] = "Automatische Pause an", ["ActAutoPauseOff"] = "Automatische Pause aus", ["ActAncStrength"] = "ANC-Stärke {0} %", // Status / Verbindung (Code) - ["SearchingHeadset"] = "Suche MOMENTUM 4 …", + ["SearchingHeadset"] = "Suche MOMENTUM 4 oder 5 …", ["Connecting"] = "Verbinde …", ["NotConnected"] = "Nicht verbunden", ["NoHeadset"] = "Kein Headset", @@ -102,7 +116,7 @@ public static void Init(AppLanguage language) ["NotWornState"] = "abgesetzt", ["DisconnectedRetry"] = "Getrennt – nächster Versuch folgt", ["Disconnected"] = "Getrennt", - ["HeadsetDisconnected"] = "MOMENTUM 4 getrennt", + ["HeadsetDisconnected"] = "{0} getrennt", ["DisconnectedMessage"] = "Headset aus, außer Reichweite oder Bluetooth aus. Die App verbindet sich automatisch wieder.", ["BatteryWindows"] = "{0} % (Windows)", // Geräte / Aktionen @@ -197,17 +211,17 @@ public static void Init(AppLanguage language) ["InspWaiting"] = "Wartet auf Verkehr …", ["InspFrames"] = "{0} Frames (neueste oben, höchstens {1})", ["InspUnreadable"] = "Frame nicht lesbar", - ["NoHeadsetProblem"] = "Kein gekoppeltes MOMENTUM 4 gefunden. In den Windows-Bluetooth-Einstellungen koppeln und erneut suchen.", - ["MultipleHeadsets"] = "{0} MOMENTUM 4 gekoppelt – mehrere Headsets werden noch nicht unterstützt.", - ["TrayHintTitle"] = "MOMENTUM 4 läuft weiter", + ["NoHeadsetProblem"] = "Kein gekoppeltes MOMENTUM 4 oder 5 gefunden. In den Windows-Bluetooth-Einstellungen koppeln und erneut suchen.", + ["MultipleHeadsets"] = "{0} MOMENTUM-Headsets gekoppelt – mehrere Headsets werden noch nicht unterstützt.", + ["TrayHintTitle"] = "{0} läuft weiter", ["TrayHintBody"] = "Die App ist jetzt nur im Infobereich der Taskleiste. Beenden über das Tray-Menü.", - ["TrayConnected"] = "MOMENTUM 4 – verbunden", - ["TrayConnectedBattery"] = "MOMENTUM 4 – {0} %", + ["TrayConnected"] = "{0} – verbunden", + ["TrayConnectedBattery"] = "{0} – {1} %", ["ChargingSuffix"] = " (lädt)", - ["TrayConnecting"] = "MOMENTUM 4 – verbinde …", - ["TrayNoHeadset"] = "MOMENTUM 4 – kein Headset gefunden", - ["TrayWindows"] = "MOMENTUM 4 – {0} % (über Windows, Steuerung getrennt)", - ["TrayDisconnected"] = "MOMENTUM 4 – getrennt", + ["TrayConnecting"] = "{0} – verbinde …", + ["TrayNoHeadset"] = "MOMENTUM – kein Headset gefunden", + ["TrayWindows"] = "{0} – {1} % (über Windows, Steuerung getrennt)", + ["TrayDisconnected"] = "{0} – getrennt", ["TrayBattery"] = "Akku: {0} %", ["TrayBatteryWindows"] = "Akku: {0} % (Windows) – Steuerung getrennt", ["TrayEqPreset"] = "Equalizer-Preset", @@ -258,10 +272,24 @@ public static void Init(AppLanguage language) ["HintOff"] = "No noise cancelling, only passive isolation.", ["ActNoiseControl"] = "Noise Control “{0}”", ["ActAntiWind"] = "Anti-wind “{0}”", + ["TransparencyLevel"] = "Transparency level", + ["SpatialTitle"] = "Spatial audio", + ["ImmersiveAudio"] = "Immersive audio", + ["HeadTracking"] = "Head tracking", + ["SpatialPersonalizationHint"] = "Spatial audio is not available in the Sound Personalization sound mode.", + ["CallTransparency"] = "Transparency during calls", + ["CallTransparencyOff"] = "Off", + ["BatteryProtection"] = "Battery protection", + ["NameTooLong"] = "Name too long: at most {0} bytes (accented letters count twice).", + ["ActSidetone"] = "Transparency during calls “{0}”", + ["ActImmersive"] = "Immersive audio {0}", + ["ActHeadTracking"] = "Head tracking {0}", + ["ActBatteryProtection"] = "Battery protection {0}", + ["ActTransparencyLevel"] = "Transparency level {0}", ["ActAutoPauseOn"] = "Auto-pause on", ["ActAutoPauseOff"] = "Auto-pause off", ["ActAncStrength"] = "ANC strength {0} %", - ["SearchingHeadset"] = "Searching for MOMENTUM 4 …", + ["SearchingHeadset"] = "Searching for MOMENTUM 4 or 5 …", ["Connecting"] = "Connecting …", ["NotConnected"] = "Not connected", ["NoHeadset"] = "No headset", @@ -273,7 +301,7 @@ public static void Init(AppLanguage language) ["NotWornState"] = "off", ["DisconnectedRetry"] = "Disconnected — retrying", ["Disconnected"] = "Disconnected", - ["HeadsetDisconnected"] = "MOMENTUM 4 disconnected", + ["HeadsetDisconnected"] = "{0} disconnected", ["DisconnectedMessage"] = "Headset off, out of range, or Bluetooth off. The app reconnects automatically.", ["BatteryWindows"] = "{0} % (Windows)", ["Connect"] = "Connect", @@ -365,17 +393,17 @@ public static void Init(AppLanguage language) ["InspWaiting"] = "Waiting for traffic …", ["InspFrames"] = "{0} frames (newest on top, at most {1})", ["InspUnreadable"] = "frame unreadable", - ["NoHeadsetProblem"] = "No paired MOMENTUM 4 found. Pair it in Windows' Bluetooth settings and search again.", - ["MultipleHeadsets"] = "{0} MOMENTUM 4 paired — multiple headsets are not supported yet.", - ["TrayHintTitle"] = "MOMENTUM 4 keeps running", + ["NoHeadsetProblem"] = "No paired MOMENTUM 4 or 5 found. Pair it in Windows' Bluetooth settings and search again.", + ["MultipleHeadsets"] = "{0} MOMENTUM headsets paired — multiple headsets are not supported yet.", + ["TrayHintTitle"] = "{0} keeps running", ["TrayHintBody"] = "The app is now only in the notification area. Quit via the tray menu.", - ["TrayConnected"] = "MOMENTUM 4 — connected", - ["TrayConnectedBattery"] = "MOMENTUM 4 — {0} %", + ["TrayConnected"] = "{0} — connected", + ["TrayConnectedBattery"] = "{0} — {1} %", ["ChargingSuffix"] = " (charging)", - ["TrayConnecting"] = "MOMENTUM 4 — connecting …", - ["TrayNoHeadset"] = "MOMENTUM 4 — no headset found", - ["TrayWindows"] = "MOMENTUM 4 — {0} % (via Windows, control disconnected)", - ["TrayDisconnected"] = "MOMENTUM 4 — disconnected", + ["TrayConnecting"] = "{0} — connecting …", + ["TrayNoHeadset"] = "MOMENTUM — no headset found", + ["TrayWindows"] = "{0} — {1} % (via Windows, control disconnected)", + ["TrayDisconnected"] = "{0} — disconnected", ["TrayBattery"] = "Battery: {0} %", ["TrayBatteryWindows"] = "Battery: {0} % (Windows) — control disconnected", ["TrayEqPreset"] = "Equalizer preset", diff --git a/src/Momentum4.App/MainWindow.xaml b/src/Momentum4.App/MainWindow.xaml index 424bf40..26a6e33 100644 --- a/src/Momentum4.App/MainWindow.xaml +++ b/src/Momentum4.App/MainWindow.xaml @@ -5,7 +5,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="using:Momentum4.App.ViewModels" xmlns:loc="using:Momentum4.App.Localization" - Title="MOMENTUM 4"> + Title="MOMENTUM Control"> @@ -26,7 +26,7 @@ - + + + @@ -304,6 +313,23 @@ + + + + + + + + + + + + + Title="MOMENTUM Control"> - + (); - _icon = new TrayIcon("MOMENTUM 4", Path.Combine(AppContext.BaseDirectory, "Assets")); + _icon = new TrayIcon("MOMENTUM Control", Path.Combine(AppContext.BaseDirectory, "Assets")); _icon.OpenRequested += (_, _) => _dispatcher.TryEnqueue(() => _open()); _icon.SelectRequested += (_, _) => { @@ -87,14 +87,15 @@ private void Attach() private void UpdateTooltip(Momentum4State? state) { + var product = ProductName.For(state?.Device?.ModelId); var text = state?.Connection switch { - ConnectionState.Connected when !_host.Settings.BatteryInTooltip || state.BatteryPercent is null => L.Get("TrayConnected"), - ConnectionState.Connected => L.Get("TrayConnectedBattery", state.BatteryPercent) + (state.Charging == true ? L.Get("ChargingSuffix") : string.Empty), - ConnectionState.Connecting or ConnectionState.Initializing => L.Get("TrayConnecting"), + ConnectionState.Connected when !_host.Settings.BatteryInTooltip || state.BatteryPercent is null => L.Get("TrayConnected", product), + ConnectionState.Connected => L.Get("TrayConnectedBattery", product, state.BatteryPercent) + (state.Charging == true ? L.Get("ChargingSuffix") : string.Empty), + ConnectionState.Connecting or ConnectionState.Initializing => L.Get("TrayConnecting", product), null when _host.StartupProblem is not null => L.Get("TrayNoHeadset"), - _ when state?.DisplayBattery is (var percent, true) && _host.Settings.BatteryInTooltip => L.Get("TrayWindows", percent), - _ => L.Get("TrayDisconnected"), + _ when state?.DisplayBattery is (var percent, true) && _host.Settings.BatteryInTooltip => L.Get("TrayWindows", product, percent), + _ => L.Get("TrayDisconnected", product), }; _icon.SetTooltip(text); } @@ -105,7 +106,7 @@ private void ShowMenu() var connected = state?.Connection == ConnectionState.Connected; var items = new List { - new("MOMENTUM 4", Enabled: false), + new(ProductName.For(state?.Device?.ModelId), Enabled: false), new(state?.DisplayBattery switch { (var percent, false) => L.Get("TrayBattery", percent), diff --git a/src/Momentum4.App/ViewModels/BehaviorViewModel.cs b/src/Momentum4.App/ViewModels/BehaviorViewModel.cs index a409390..b2ca0e8 100644 --- a/src/Momentum4.App/ViewModels/BehaviorViewModel.cs +++ b/src/Momentum4.App/ViewModels/BehaviorViewModel.cs @@ -27,6 +27,24 @@ public sealed partial class BehaviorViewModel(IActionRunner run) : ObservableObj public List PromptOptions { get; } = [L.Get("PromptTonesVoice"), L.Get("PromptTonesOnly"), L.Get("PromptOff")]; + /// Transparenz bei Anrufen (Sidetone) 0…5; Eintrag 0 heißt „Aus“. + public List SidetoneOptions { get; } = [L.Get("CallTransparencyOff"), "1", "2", "3", "4", "5"]; + + private int? _lastSidetone; + private bool? _lastBatteryProtection; + + [ObservableProperty] + public partial bool ShowSidetone { get; set; } + + [ObservableProperty] + public partial int SidetoneIndex { get; set; } = -1; + + [ObservableProperty] + public partial bool ShowBatteryProtection { get; set; } + + [ObservableProperty] + public partial bool BatteryProtection { get; set; } + [ObservableProperty] public partial int PromptIndex { get; set; } = -1; @@ -57,14 +75,21 @@ public sealed partial class BehaviorViewModel(IActionRunner run) : ObservableObj [ObservableProperty] public partial bool TouchControl { get; set; } - public void Apply(BehaviorState? state, int? autoOffSeconds, AudioPromptMode? prompts, bool connected) + public void Apply(BehaviorState? state, int? autoOffSeconds, AudioPromptMode? prompts, bool connected, Momentum4State? full = null) { _last = state; _lastAutoOff = autoOffSeconds; _lastPrompts = prompts; + _lastSidetone = full?.Sidetone; + _lastBatteryProtection = full?.BatteryProtection; _applying = true; try { + // Nur zeigen, was der Core für dieses Gerät schreiben würde (am M4 Sidetone erst nach einem Hardware-Test). + ShowSidetone = full is not null && full.CanWrite(HeadsetControl.Sidetone) && full.Sidetone is not null; + SidetoneIndex = ShowSidetone ? full!.Sidetone!.Value : -1; + ShowBatteryProtection = full is not null && full.CanWrite(HeadsetControl.BatteryProtection) && full.BatteryProtection is not null; + BatteryProtection = full?.BatteryProtection == true; PromptIndex = prompts is { } mode ? Array.IndexOf(PromptOrder, mode) : -1; AutoOffIndex = autoOffSeconds is { } seconds ? IndexOf(seconds) : -1; AutoOffHint = autoOffSeconds is { } other && IndexOf(other) < 0 ? L.Get("AutoOffOther", other % 60 == 0 ? $"{other / 60} min" : $"{other} s") : string.Empty; @@ -114,6 +139,26 @@ partial void OnAutoOffIndexChanged(int value) _ = run.RunAsync(L.Get("ActAutoOff", AutoOffOptions[value]), (service, ct) => service.SetAutoPowerOffAsync(seconds, ct)); } + partial void OnSidetoneIndexChanged(int value) + { + if (_applying || value < 0 || value >= SidetoneOptions.Count || _lastSidetone == value) + { + return; + } + + _ = run.RunAsync(L.Get("ActSidetone", SidetoneOptions[value]), (service, ct) => service.SetSidetoneAsync(value, ct)); + } + + partial void OnBatteryProtectionChanged(bool value) + { + if (_applying || _lastBatteryProtection is null || _lastBatteryProtection == value) + { + return; + } + + _ = run.RunAsync(L.Get("ActBatteryProtection", L.Get(value ? "StateOn" : "StateOff")), (service, ct) => service.SetBatteryProtectionAsync(value, ct)); + } + private static int IndexOf(int seconds) { for (var i = 0; i < Momentum4State.AutoPowerOffChoices.Count; i++) diff --git a/src/Momentum4.App/ViewModels/DevicesViewModel.cs b/src/Momentum4.App/ViewModels/DevicesViewModel.cs index 0997e63..c6a8477 100644 --- a/src/Momentum4.App/ViewModels/DevicesViewModel.cs +++ b/src/Momentum4.App/ViewModels/DevicesViewModel.cs @@ -31,21 +31,24 @@ public sealed partial class DevicesViewModel(IActionRunner run) : ObservableObje { private MultipointState? _last; private bool _lastConnected; + private bool _lastCanConnect; public ObservableCollection Peers { get; } = []; [ObservableProperty] public partial string Hint { get; set; } = string.Empty; - public void Apply(MultipointState? state, bool connected) + /// Verbinden nur am MOMENTUM 4; am MOMENTUM 5 bleibt die Liste nur lesend (wie unter Linux). + public void Apply(MultipointState? state, bool connected, bool canConnectPeers = true) { - if (Equals(state, _last) && connected == _lastConnected && Peers.Count > 0) + if (Equals(state, _last) && connected == _lastConnected && canConnectPeers == _lastCanConnect && Peers.Count > 0) { return; } _last = state; _lastConnected = connected; + _lastCanConnect = canConnectPeers; Peers.Clear(); if (state is null) { @@ -57,7 +60,7 @@ public void Apply(MultipointState? state, bool connected) var full = state.MaxConnections is { } max && connectedCount >= max; foreach (var device in state.Devices) { - Peers.Add(new PeerViewModel(device, connected && !device.Connected && !device.IsThisComputer && !full, ConnectAsync)); + Peers.Add(new PeerViewModel(device, canConnectPeers && connected && !device.Connected && !device.IsThisComputer && !full, ConnectAsync)); } Hint = full diff --git a/src/Momentum4.App/ViewModels/MainViewModel.cs b/src/Momentum4.App/ViewModels/MainViewModel.cs index a86e983..e42caea 100644 --- a/src/Momentum4.App/ViewModels/MainViewModel.cs +++ b/src/Momentum4.App/ViewModels/MainViewModel.cs @@ -32,6 +32,7 @@ public MainViewModel(HeadsetHost host, DispatcherQueue dispatcher, Action settin Equalizer = new EqualizerViewModel(this, host.Presets, dispatcher); Behavior = new BehaviorViewModel(this); Devices = new DevicesViewModel(this); + Spatial = new SpatialViewModel(this); Settings = new SettingsViewModel(host, settingsChanged); _hostChanged = (_, _) => _dispatcher.TryEnqueue(Attach); _stateChanged = (_, e) => _dispatcher.TryEnqueue(() => Apply(e.Current)); @@ -47,6 +48,8 @@ public MainViewModel(HeadsetHost host, DispatcherQueue dispatcher, Action settin public DevicesViewModel Devices { get; } + public SpatialViewModel Spatial { get; } + public SettingsViewModel Settings { get; } /// Für den Protokoll-Inspektor; null, solange kein Service läuft. @@ -64,6 +67,10 @@ public MainViewModel(HeadsetHost host, DispatcherQueue dispatcher, Action settin [ObservableProperty] public partial string BatteryText { get; set; } = string.Empty; + /// Modellname in Kopfzeile und Schnellzugriff („MOMENTUM 4“, „MOMENTUM 5“, vor dem Verbinden „MOMENTUM“). + [ObservableProperty] + public partial string ProductTitle { get; set; } = ProductName.For(null); + [ObservableProperty] public partial string DetailText { get; set; } = string.Empty; @@ -194,19 +201,22 @@ private void Apply(Momentum4State state) ConnectionState.WaitingRetry => L.Get("DisconnectedRetry"), _ => L.Get("Disconnected"), }; + ProductTitle = ProductName.For(state.Device?.ModelId); DetailText = state.Device is { } device ? $"{device.ModelId} · Firmware {device.Firmware}" + (state.Codec is { } codec ? $" · {Momentum4.Protocol.Features.GenericAudioCodec.CodecName(codec)}" : string.Empty) : string.Empty; ShowProblem = state.Connection is ConnectionState.WaitingRetry or ConnectionState.Disconnected; - ProblemTitle = L.Get("HeadsetDisconnected"); + ProblemTitle = L.Get("HeadsetDisconnected", ProductName.For(state.Device?.ModelId)); ProblemMessage = L.Get("DisconnectedMessage"); ProblemAction = L.Get("Reconnect"); - NoiseControl.Apply(state.NoiseControl, state.AutoPauseOnTransparency, connected); + NoiseControl.Apply(state.NoiseControl, state.AutoPauseOnTransparency, connected, state.TransparencyLevel, + state.CanWrite(HeadsetControl.TransparencyLevel), state.ControlChoices?.GetValueOrDefault(HeadsetIntegerControl.AntiWind)); Equalizer.Apply(state.Equalizer, connected); - Behavior.Apply(state.Behavior, state.AutoPowerOffSeconds, state.PromptMode, connected); - Devices.Apply(state.Multipoint, connected); + Behavior.Apply(state.Behavior, state.AutoPowerOffSeconds, state.PromptMode, connected, state); + Spatial.Apply(state, connected); + Devices.Apply(state.Multipoint, connected, state.Device is not { } peerDevice || new FeatureGate(peerDevice.Firmware, peerDevice.ModelId).IsMomentum4); Settings.Apply(state); } } diff --git a/src/Momentum4.App/ViewModels/NoiseControlViewModel.cs b/src/Momentum4.App/ViewModels/NoiseControlViewModel.cs index 65844bf..cb05a08 100644 --- a/src/Momentum4.App/ViewModels/NoiseControlViewModel.cs +++ b/src/Momentum4.App/ViewModels/NoiseControlViewModel.cs @@ -20,6 +20,12 @@ public sealed partial class NoiseControlViewModel : ObservableObject private readonly IActionRunner _run; private readonly DispatcherQueueTimer _strengthDebounce; + private readonly DispatcherQueueTimer _transparencyDebounce; + private int[] _antiWindValues = [0, 1, 2]; + private int? _lastTransparencyLevel; + + /// Transparenzstufe, die der User gerade einstellt (nur MOMENTUM 5). + private int? _pendingTransparency; private NoiseControlState? _last; private bool _applying; @@ -33,12 +39,29 @@ public NoiseControlViewModel(IActionRunner run, DispatcherQueue dispatcher) _strengthDebounce.Interval = TimeSpan.FromMilliseconds(300); // [MC]: nur den Endwert senden _strengthDebounce.IsRepeating = false; _strengthDebounce.Tick += async (_, _) => await SendStrengthAsync(); + _transparencyDebounce = dispatcher.CreateTimer(); + _transparencyDebounce.Interval = TimeSpan.FromMilliseconds(300); + _transparencyDebounce.IsRepeating = false; + _transparencyDebounce.Tick += async (_, _) => await SendTransparencyAsync(); } // List statt Collection-Expression: WinRT/AOT kann nur echte Listen als ItemsSource übergeben. public List Modes { get; } = [L.Get("ModeTransparency"), L.Get("ModeAnc"), L.Get("ModeAdaptive"), L.Get("ModeOff")]; - public List AntiWindOptions { get; } = [L.Get("AntiWindOff"), L.Get("AntiWindMax"), L.Get("AntiWindAuto")]; + /// Anti-Wind-Stufen, die der Core für das Gerät erlaubt (MOMENTUM 5: nur Aus und Maximal). + [ObservableProperty] + public partial List AntiWindOptions { get; set; } = [L.Get("AntiWindOff"), L.Get("AntiWindMax"), L.Get("AntiWindAuto")]; + + /// Transparenzstufe 0…100, nur MOMENTUM 5 mit FW 6.21.5 (Core-Freigabe). + [ObservableProperty] + public partial bool ShowTransparencyLevel { get; set; } + + /// Bei ANC aus gesperrt: Der Regler schaltet ANC nie selbst ein (wie unter Linux). + [ObservableProperty] + public partial bool TransparencyLevelEnabled { get; set; } + + [ObservableProperty] + public partial double TransparencyLevel { get; set; } [ObservableProperty] public partial bool IsAvailable { get; set; } @@ -64,15 +87,25 @@ public NoiseControlViewModel(IActionRunner run, DispatcherQueue dispatcher) private bool? _lastAutoPause; - public void Apply(NoiseControlState? state, bool? autoPause, bool connected) + public void Apply(NoiseControlState? state, bool? autoPause, bool connected, int? transparencyLevel = null, + bool canWriteTransparencyLevel = false, IReadOnlyList? antiWindChoices = null) { _last = state; _lastAutoPause = autoPause; + _lastTransparencyLevel = transparencyLevel; _applying = true; try { AutoPause = autoPause == true; IsAvailable = connected && state is not null; + ApplyAntiWindChoices(antiWindChoices); + ShowTransparencyLevel = canWriteTransparencyLevel && transparencyLevel is not null && state is not null; + TransparencyLevelEnabled = ShowTransparencyLevel && state?.AncEnabled == true; + if (_pendingTransparency is null && transparencyLevel is { } shownLevel) + { + TransparencyLevel = shownLevel; + } + if (state is null) { SelectedModeIndex = -1; @@ -89,7 +122,7 @@ public void Apply(NoiseControlState? state, bool? autoPause, bool connected) Strength = 100 - state.Level; } - AntiWindIndex = (int)state.AntiWind; + AntiWindIndex = Array.IndexOf(_antiWindValues, (int)state.AntiWind); ModeHint = state.Mode switch { NoiseControlMode.Transparency => L.Get("HintTransparency"), @@ -129,12 +162,12 @@ partial void OnStrengthChanged(double value) partial void OnAntiWindIndexChanged(int value) { - if (_applying || value is < 0 or > 2 || _last is { } last && (int)last.AntiWind == value) + if (_applying || value < 0 || value >= _antiWindValues.Length || _last is { } last && (int)last.AntiWind == _antiWindValues[value]) { return; } - var antiWind = (AntiWindMode)value; + var antiWind = (AntiWindMode)_antiWindValues[value]; _ = _run.RunAsync(L.Get("ActAntiWind", AntiWindOptions[value]), (service, ct) => service.SetAntiWindAsync(antiWind, ct)); } @@ -148,6 +181,60 @@ partial void OnAutoPauseChanged(bool value) _ = _run.RunAsync(L.Get(value ? "ActAutoPauseOn" : "ActAutoPauseOff"), (service, ct) => service.SetAutoPauseAsync(value, ct)); } + partial void OnTransparencyLevelChanged(double value) + { + if (_applying) + { + return; + } + + _pendingTransparency = (int)Math.Round(value); + _transparencyDebounce.Stop(); + _transparencyDebounce.Start(); + } + + private void ApplyAntiWindChoices(IReadOnlyList? choices) + { + int[] values = choices is { Count: > 0 } ? [.. choices.Where(v => v is >= 0 and <= 2)] : [0, 1, 2]; + if (values.SequenceEqual(_antiWindValues)) + { + return; + } + + string[] names = [L.Get("AntiWindOff"), L.Get("AntiWindMax"), L.Get("AntiWindAuto")]; + _antiWindValues = values; + AntiWindOptions = values.Select(v => names[v]).ToList(); + } + + private async Task SendTransparencyAsync() + { + if (_pendingTransparency is not { } level) + { + return; + } + + if (level == _lastTransparencyLevel) + { + _pendingTransparency = null; + return; + } + + await _run.RunAsync(L.Get("ActTransparencyLevel", level), async (service, ct) => + { + try + { + await service.SetTransparencyLevelAsync(level, ct); + } + finally + { + if (_pendingTransparency == level) + { + _pendingTransparency = null; + } + } + }); + } + private async Task SendStrengthAsync() { if (_pendingLevel is not { } level) diff --git a/src/Momentum4.App/ViewModels/SettingsViewModel.cs b/src/Momentum4.App/ViewModels/SettingsViewModel.cs index 2cb3521..05bcae3 100644 --- a/src/Momentum4.App/ViewModels/SettingsViewModel.cs +++ b/src/Momentum4.App/ViewModels/SettingsViewModel.cs @@ -129,8 +129,11 @@ public SettingsViewModel(HeadsetHost host, Action settingsChanged) public string Version { get; } = "Version " + (typeof(SettingsViewModel).Assembly.GetName().Version?.ToString(3) ?? "?") + L.Get("UnofficialSuffix"); + private string? _model; + public void Apply(Momentum4State state) { + _model = state.Device?.ModelId; Headset = state.Device?.ModelId ?? "–"; Firmware = state.Device?.Firmware.ToString() ?? "–"; Bluetooth = (_host.Address is { } address ? address.ToAnonymizedString() + " · " : string.Empty) + state.Connection switch @@ -158,6 +161,13 @@ public void Apply(Momentum4State state) private async Task RenameAsync() { var name = NewDeviceName.Trim(); + var limit = ProductName.MaxNameBytes(_model); + if (System.Text.Encoding.UTF8.GetByteCount(name) > limit) + { + DeviceNameHint = L.Get("NameTooLong", limit); + return; + } + if (_host.Service is not { } service || name.Length == 0 || name == CurrentDeviceName) { return; diff --git a/src/Momentum4.App/ViewModels/SpatialViewModel.cs b/src/Momentum4.App/ViewModels/SpatialViewModel.cs new file mode 100644 index 0000000..18df8a1 --- /dev/null +++ b/src/Momentum4.App/ViewModels/SpatialViewModel.cs @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: 2026 Ariazonaa +// SPDX-License-Identifier: MIT + +using CommunityToolkit.Mvvm.ComponentModel; +using Momentum4.App.Localization; +using Momentum4.Core.State; +using Momentum4.Protocol.Features; + +namespace Momentum4.App.ViewModels; + +/// +/// Raumklang des MOMENTUM 5 (FW 6.21.5): Immersive Audio und Head Tracking. Regeln wie im Core und im Linux-Frontend: +/// Head Tracking nur bei eingeschaltetem Immersive Audio, beides nicht im Klangmodus Sound Personalization. Sichtbar +/// nur, wenn der Core Immersive Audio für dieses Gerät freigibt. +/// +public sealed partial class SpatialViewModel(IActionRunner run) : ObservableObject +{ + private bool? _lastImmersive; + private bool? _lastTracking; + private bool _applying; + + [ObservableProperty] + public partial bool IsVisible { get; set; } + + [ObservableProperty] + public partial bool IsAvailable { get; set; } + + [ObservableProperty] + public partial bool ImmersiveAudio { get; set; } + + [ObservableProperty] + public partial bool HeadTracking { get; set; } + + [ObservableProperty] + public partial bool ImmersiveEnabled { get; set; } + + [ObservableProperty] + public partial bool HeadTrackingEnabled { get; set; } + + [ObservableProperty] + public partial string Hint { get; set; } = string.Empty; + + public void Apply(Momentum4State state, bool connected) + { + _lastImmersive = state.ImmersiveAudio; + _lastTracking = state.HeadTracking; + _applying = true; + try + { + var personalization = state.Equalizer?.SoundMode == SoundMode.SoundPersonalization; + IsVisible = state.CanWrite(HeadsetControl.ImmersiveAudio) && state.ImmersiveAudio is not null; + IsAvailable = connected && IsVisible; + ImmersiveAudio = state.ImmersiveAudio == true; + HeadTracking = state.HeadTracking == true; + ImmersiveEnabled = !personalization; + HeadTrackingEnabled = !personalization && state.ImmersiveAudio == true && state.CanWrite(HeadsetControl.HeadTracking); + Hint = personalization ? L.Get("SpatialPersonalizationHint") : string.Empty; + } + finally + { + _applying = false; + } + } + + partial void OnImmersiveAudioChanged(bool value) + { + if (_applying || _lastImmersive == value) + { + return; + } + + _ = run.RunAsync(L.Get("ActImmersive", L.Get(value ? "StateOn" : "StateOff")), (service, ct) => service.SetImmersiveAudioAsync(value, ct)); + } + + partial void OnHeadTrackingChanged(bool value) + { + if (_applying || _lastTracking == value) + { + return; + } + + _ = run.RunAsync(L.Get("ActHeadTracking", L.Get(value ? "StateOn" : "StateOff")), (service, ct) => service.SetHeadTrackingAsync(value, ct)); + } +} diff --git a/src/Momentum4.Core/Control/ControlCommands.cs b/src/Momentum4.Core/Control/ControlCommands.cs index 31e3c0a..eaf15f2 100644 --- a/src/Momentum4.Core/Control/ControlCommands.cs +++ b/src/Momentum4.Core/Control/ControlCommands.cs @@ -49,6 +49,12 @@ m4ctl autooff never|15|30|60 automatisch ausschalten nach Minuten m4ctl prompts voice|tones|off Töne & Sprachansagen (Töne und Stimme, nur Töne, aus) m4ctl connect NAME gekoppeltes Gerät verbinden (Name wie in der App) m4ctl rename NAME Headset umbenennen (localName) + m4ctl sidetone 0..5 Transparenz bei Anrufen (eigene Stimme hören), wo freigegeben + Nur MOMENTUM 5 (Firmware 6.21.5): + m4ctl immersive on|off Raumklang (Immersive Audio) + m4ctl headtracking on|off Head Tracking, nur bei eingeschaltetem Raumklang + m4ctl batteryprotect on|off Akkuschutz + m4ctl transparency 0..100 Transparenzstufe Läuft die App, führt sie den Befehl aus; sonst verbindet m4ctl selbst. Exit-Code: 0 ausgeführt, 1 Fehler, 2 falscher Aufruf. @@ -98,6 +104,18 @@ public static async Task ExecuteAsync(IReadOnlyList args, "prompts" when ParsePrompts(value) is { } prompts => ControlResult.Ok($"Töne & Sprachansagen: {PromptName(await service.SetAudioPromptModeAsync(prompts, cancellationToken))}"), "rename" when value is not null => ControlResult.Ok($"Headset heißt jetzt „{await service.SetDeviceNameAsync(value, cancellationToken)}“."), "connect" when value is not null => await ConnectAsync(service, value, cancellationToken), + "sidetone" when ParseLevel(value, 5) is { } sidetone => + ControlResult.Ok($"Transparenz bei Anrufen: {await service.SetSidetoneAsync(sidetone, cancellationToken)}"), + "transparency" when ParseLevel(value, 100) is { } level => + ControlResult.Ok($"Transparenzstufe: {await service.SetTransparencyLevelAsync(level, cancellationToken)}"), + "immersive" when ParseSwitch(value) is { } immersive => + ControlResult.Ok($"Raumklang: {OnOff(await service.SetImmersiveAudioAsync(immersive, cancellationToken))}"), + "headtracking" when ParseSwitch(value) is true && service.Store.Current.ImmersiveAudio != true => + ControlResult.Error("Nicht ausgeführt: Erst Raumklang einschalten (m4ctl immersive on)."), + "headtracking" when ParseSwitch(value) is { } tracking => + ControlResult.Ok($"Head Tracking: {OnOff(await service.SetHeadTrackingAsync(tracking, cancellationToken))}"), + "batteryprotect" when ParseSwitch(value) is { } protect => + ControlResult.Ok($"Akkuschutz: {OnOff(await service.SetBatteryProtectionAsync(protect, cancellationToken))}"), _ => ControlResult.Usage($"Unbekannter Befehl oder Wert: {string.Join(' ', args)}\n\n{Help}"), }; } @@ -111,6 +129,8 @@ public static async Task ExecuteAsync(IReadOnlyList args, public static string DescribeError(Exception exception) => exception switch { SettingNotAppliedException ex => ex.Message, + FeatureNotSupportedException ex when ex.Message.Contains("before head tracking", StringComparison.Ordinal) => "Erst Raumklang einschalten.", + FeatureNotSupportedException ex when ex.Message.Contains("Sound Personalization", StringComparison.Ordinal) => "Sound Personalization erst ausschalten.", HeadsetUnavailableException => "Headset nicht verbunden.", CommandNotAllowedException ex => $"nicht erlaubt ({ex.Message}).", GaiaErrorException ex => $"vom Headset abgelehnt{(ex.Reason is { } reason ? $" (Code 0x{reason:X2})" : string.Empty)}.", @@ -216,6 +236,32 @@ private static string Describe(Momentum4State s, EqPresetStore? presets) text.AppendLine(CultureInfo.InvariantCulture, $"Verhalten: On-Head {OnOff(b.OnHeadDetection)}, Smart Pause {OnOff(b.SmartPause)}, Touch {OnOff(b.TouchControl)}, Anrufe annehmen {OnOff(b.AutoAnswer)}, Comfort Call {OnOff(b.ComfortCall)}"); } + if (s.TransparencyLevel is { } transparencyLevel) + { + text.AppendLine(CultureInfo.InvariantCulture, $"Transparenzstufe: {transparencyLevel}"); + } + + if (s.ImmersiveAudio is { } immersive) + { + text.AppendLine(CultureInfo.InvariantCulture, $"Raumklang: {OnOff(immersive)}"); + } + + if (s.HeadTracking is { } tracking) + { + text.AppendLine(CultureInfo.InvariantCulture, $"Head Tracking: {OnOff(tracking)}"); + } + + if (s.BatteryProtection is { } protection) + { + text.AppendLine(CultureInfo.InvariantCulture, $"Akkuschutz: {OnOff(protection)}"); + } + + // Nur wo der Core Sidetone freigibt – am M4 ist die Wirkung nicht bestätigt, ein bloßer Lesewert hilft niemandem. + if (s.Sidetone is { } sidetone && s.CanWrite(HeadsetControl.Sidetone)) + { + text.AppendLine(CultureInfo.InvariantCulture, $"Transparenz bei Anrufen: {sidetone}"); + } + if (s.AutoPowerOffSeconds is { } autoOff) { text.AppendLine(CultureInfo.InvariantCulture, $"Auto-Aus: {AutoOffName(autoOff)}"); @@ -325,6 +371,9 @@ private static string Describe(Momentum4State s, EqPresetStore? presets) _ => "getrennt", }; + private static int? ParseLevel(string? value, int maximum) => + int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var level) && level <= maximum ? level : null; + private static string OnOff(bool? value) => value switch { true => "an", diff --git a/src/Momentum4.Core/Services/Momentum4Service.ControlSnapshot.cs b/src/Momentum4.Core/Services/Momentum4Service.ControlSnapshot.cs index 623a20a..32c4553 100644 --- a/src/Momentum4.Core/Services/Momentum4Service.ControlSnapshot.cs +++ b/src/Momentum4.Core/Services/Momentum4Service.ControlSnapshot.cs @@ -271,7 +271,7 @@ private async Task ReadControlSnapshotAsync(ControlGroup writable.ToFrozenSet(), choices.ToFrozenDictionary(), Array.AsReadOnly(notes.Distinct().Take(32).ToArray()), name, charging, wear, personalization, Array.AsReadOnly(peers.ToArray()), capacity, peersAvailable, true); _controlSnapshot = snapshot; - PublishControlSnapshot(snapshot); + PublishControlSnapshot(snapshot, group); return snapshot; } @@ -338,51 +338,92 @@ private async Task ReadControlReadbackAsync(HeadsetContr } } - private void PublishControlSnapshot(HeadsetControlSnapshot snapshot) + /// + /// Legt die Werte der tatsächlich gelesenen Gruppen im ab. Werte aus nicht gelesenen Gruppen + /// stammen aus dem vorigen Snapshot und können älter sein als ein Push oder Poll seitdem – sie werden nicht erneut + /// veröffentlicht. + /// + private void PublishControlSnapshot(HeadsetControlSnapshot snapshot, ControlGroup readGroups) { - if (snapshot.Battery is { } battery) + bool Read(ControlGroup part) => (readGroups & part) != 0; + + if (readGroups == ControlGroup.All && snapshot.Battery is { } battery) { Store.Apply(new BatteryChanged(battery)); } - if (snapshot.Settings is { AncEnabled: not null, AdaptiveAnc: not null, AncStrength: not null, AntiWind: not null, Transparency: not null }) + if (Read(ControlGroup.Noise)) { - Store.Apply(new NoiseControlChanged(NoiseState(snapshot.Settings))); - } + if (snapshot.Settings is { AncEnabled: not null, AdaptiveAnc: not null, AncStrength: not null, AntiWind: not null, Transparency: not null }) + { + Store.Apply(new NoiseControlChanged(NoiseState(snapshot.Settings))); + } - if (snapshot.EqGainsDb.Count > 0 && snapshot.EqFrequenciesHz.Count == snapshot.EqGainsDb.Count) - { - Store.Apply(new EqualizerChanged(EqualizerStateOf(snapshot))); + Store.Apply(new TransparencyLevelChanged(snapshot.Settings.TransparencyLevel)); } - if (snapshot.Settings is { OnHeadDetection: { } detection, SmartPause: { } pause, AutoAnswer: { } answer, ComfortCall: { } comfort, TouchControls: { } touch }) + if (Read(ControlGroup.Spatial)) { - Store.Apply(new BehaviorChanged(new BehaviorState(detection, pause, answer, comfort, touch))); + Store.Apply(new SpatialAudioChanged(snapshot.Settings.ImmersiveAudio, snapshot.Settings.HeadTracking)); } - if (snapshot.PeersAvailable) + if (Read(ControlGroup.Equalizer) && snapshot.EqGainsDb.Count > 0 && snapshot.EqFrequenciesHz.Count == snapshot.EqGainsDb.Count) { - Store.Apply(new MultipointChanged(MultipointStateOf(snapshot))); + Store.Apply(new EqualizerChanged(EqualizerStateOf(snapshot))); } - if (snapshot.DeviceName is { } name) + if (Read(ControlGroup.Behavior)) { - Store.Apply(new DeviceNameChanged(name)); - } + if (snapshot.Settings is { OnHeadDetection: { } detection, SmartPause: { } pause, AutoAnswer: { } answer, ComfortCall: { } comfort, TouchControls: { } touch }) + { + Store.Apply(new BehaviorChanged(new BehaviorState(detection, pause, answer, comfort, touch))); + } - if (snapshot.Settings.AutoPowerOff is { } seconds) - { - Store.Apply(new AutoPowerOffChanged(seconds)); + if (snapshot.Settings.AudioPrompts is { } prompts) + { + Store.Apply(new PromptModeChanged((AudioPromptMode)prompts)); + } } - if (snapshot.Settings.AudioPrompts is { } prompts) + if (Read(ControlGroup.Ancillary)) { - Store.Apply(new PromptModeChanged((AudioPromptMode)prompts)); + if (snapshot.Settings.AutoPowerOff is { } seconds) + { + Store.Apply(new AutoPowerOffChanged(seconds)); + } + + if (snapshot.Settings.PauseOnTransparency is { } autoPause) + { + Store.Apply(new AutoPauseChanged(autoPause)); + } + + Store.Apply(new SidetoneChanged(snapshot.Settings.Sidetone)); + Store.Apply(new BatteryProtectionChanged(snapshot.Settings.BatteryProtection)); } - if (snapshot.Settings.PauseOnTransparency is { } autoPause) + Store.Apply(new ControlCapabilitiesChanged(snapshot.Writable, snapshot.Choices)); + + if (Read(ControlGroup.Metadata)) { - Store.Apply(new AutoPauseChanged(autoPause)); + if (snapshot.PeersAvailable) + { + Store.Apply(new MultipointChanged(MultipointStateOf(snapshot))); + } + + if (snapshot.DeviceName is { } name) + { + Store.Apply(new DeviceNameChanged(name)); + } + + if (snapshot.Charging is { } charging) + { + Store.Apply(new ChargingChanged(charging)); + } + + if (snapshot.WearState is { } wear && Enum.IsDefined((WearState)wear)) + { + Store.Apply(new WearStateChanged((WearState)wear)); + } } } } diff --git a/src/Momentum4.Core/Services/Momentum4Service.Controls.cs b/src/Momentum4.Core/Services/Momentum4Service.Controls.cs index 522037b..368f2e8 100644 --- a/src/Momentum4.Core/Services/Momentum4Service.Controls.cs +++ b/src/Momentum4.Core/Services/Momentum4Service.Controls.cs @@ -196,7 +196,7 @@ public Task RenameControlAsync(string name, Cancellation EnsureActionPossible("Rename", [CommandCatalog.SetLocalName]); var before = await ReadControlSnapshotAsync(ControlGroup.Metadata, ct); RequireControl(before, HeadsetControl.Rename); - var payload = SharedHeadsetCodec.EncodeName(name, _gate.IsMomentum5 ? 16 : 30); + var payload = SharedHeadsetCodec.EncodeName(name, ProductName.MaxNameBytes(before.Model)); name = System.Text.Encoding.UTF8.GetString(payload); if (before.DeviceName == name) { diff --git a/src/Momentum4.Core/Services/Momentum4Service.cs b/src/Momentum4.Core/Services/Momentum4Service.cs index df41280..6f6a372 100644 --- a/src/Momentum4.Core/Services/Momentum4Service.cs +++ b/src/Momentum4.Core/Services/Momentum4Service.cs @@ -354,6 +354,26 @@ public Task SetDeviceNameAsync(string name, CancellationToken cancellati public Task SetAutoPauseAsync(bool on, CancellationToken cancellationToken) => LegacyControlAsync(() => SetBooleanControlAsync(HeadsetBooleanControl.PauseOnTransparency, on, cancellationToken), snapshot => snapshot.Settings.PauseOnTransparency!.Value, state => state.AutoPauseOnTransparency!.Value, "Auto pause"); + /// Immersive Audio (0x3604/0x3605), nur MOMENTUM 5 mit FW 6.21.5; nicht bei Sound Personalization. + public Task SetImmersiveAudioAsync(bool on, CancellationToken cancellationToken) => + LegacyControlAsync(() => SetBooleanControlAsync(HeadsetBooleanControl.ImmersiveAudio, on, cancellationToken), snapshot => snapshot.Settings.ImmersiveAudio!.Value, state => state.ImmersiveAudio == true, "Immersive audio"); + + /// Head Tracking (0x3602/0x3603), nur MOMENTUM 5 und nur bei eingeschaltetem Immersive Audio. + public Task SetHeadTrackingAsync(bool on, CancellationToken cancellationToken) => + LegacyControlAsync(() => SetBooleanControlAsync(HeadsetBooleanControl.HeadTracking, on, cancellationToken), snapshot => snapshot.Settings.HeadTracking!.Value, state => state.HeadTracking == true, "Head tracking"); + + /// Akkuschutz (0x060A/0x060B), nur MOMENTUM 5 – am M4 ungeprüft (0x06xx kann es offline nehmen). + public Task SetBatteryProtectionAsync(bool on, CancellationToken cancellationToken) => + LegacyControlAsync(() => SetBooleanControlAsync(HeadsetBooleanControl.BatteryProtection, on, cancellationToken), snapshot => snapshot.Settings.BatteryProtection!.Value, state => state.BatteryProtection == true, "Battery protection"); + + /// Transparenz bei Anrufen (Sidetone, 0x0805/0x0806), Stufe 0…5; freigegeben, wo der Core es erlaubt. + public Task SetSidetoneAsync(int level, CancellationToken cancellationToken) => + LegacyControlAsync(() => SetIntegerControlAsync(HeadsetIntegerControl.Sidetone, level, cancellationToken), snapshot => snapshot.Settings.Sidetone!.Value, state => state.Sidetone ?? 0, "Sidetone"); + + /// Transparenzstufe 0…100 (0x1802/0x1803), nur MOMENTUM 5 mit FW 6.21.5; koppelt an den ANC-Pegel. + public Task SetTransparencyLevelAsync(int level, CancellationToken cancellationToken) => + LegacyControlAsync(() => SetIntegerControlAsync(HeadsetIntegerControl.TransparencyLevel, level, cancellationToken), snapshot => snapshot.Settings.TransparencyLevel!.Value, state => state.TransparencyLevel ?? 0, "Transparency level"); + /// /// Gekoppeltes Gerät verbinden (docs/architecture.md §8.5). Vorher: Liste frisch lesen, am Platz /// muss stehen, das Ziel darf nicht dieser PC sein und die @@ -484,7 +504,17 @@ private async Task RunSessionAsync(CancellationToken session) _gate = new FeatureGate(firmware, model); Store.Apply(new DeviceIdentified(new DeviceInfo(model, firmware))); _logger.LogInformation("Headset: {Model}, Firmware {Firmware}.", model, firmware); - if (_options.ReadSerialNumber) + + // Ein MOMENTUM 5 läuft wie im am Gerät geprüften Linux-Ablauf: keine Seriennummer, keine Notification-Anmeldung, + // Refresh nur über den Shared-Snapshot (RefreshLockedAsync). Alles andere wurde am M5 nie gesendet. + var sharedSession = _gate.IsMomentum5; + _lastSharedRefresh = null; + if (sharedSession) + { + _logger.LogInformation("MOMENTUM 5: Sitzung ohne Notification-Anmeldung, Zustand per Snapshot im Abfrageintervall."); + } + + if (_options.ReadSerialNumber && !sharedSession) { try { @@ -496,7 +526,7 @@ private async Task RunSessionAsync(CancellationToken session) } } - if (_options.RegisterNotifications) + if (_options.RegisterNotifications && !sharedSession) { await RegisterNotificationsAsync(session); } @@ -612,6 +642,12 @@ private async Task RefreshAsync(RefreshScope scope, CancellationToken session) private async Task RefreshLockedAsync(RefreshScope scope, CancellationToken session) { + if (_gate.IsMomentum5) + { + await RefreshSharedSnapshotAsync(scope, session); + return; + } + await Step(RefreshScope.Battery, async () => Store.Apply(new BatteryChanged(await _client.GetBatteryLevelAsync(session)))); await Step(RefreshScope.NoiseControl, async () => Store.Apply(new NoiseControlChanged(await _client.ReadNoiseControlAsync(session)))); await Step(RefreshScope.NoiseControl, async () => Store.Apply(new AutoPauseChanged(await _client.ReadAutoPauseAsync(session)))); @@ -635,6 +671,10 @@ await Step(RefreshScope.Equalizer, async () => await Step(RefreshScope.Behavior, async () => Store.Apply(new CodecChanged(await _client.ReadCodecAsync(session)))); await Step(RefreshScope.Behavior, async () => Store.Apply(new PromptLanguageChanged(await _client.ReadPromptLanguageAsync(session)))); + // Sidetone und die Schreibfreigaben kommen aus dem Shared-Snapshot (am M4 nur die verifizierten Reads 0x1801, + // 0x0806, 0x0601; der erste Aufruf einer Sitzung liest alles). + await Step(RefreshScope.Behavior, () => ReadControlSnapshotAsync(ControlGroup.Ancillary, session)); + if (scope == RefreshScope.All) { Store.Apply(new FullRefreshCompleted(_time.GetUtcNow())); @@ -668,8 +708,55 @@ async Task Step(RefreshScope part, Func read) } } + /// + /// Refresh am MOMENTUM 5: immer der vollständige Shared-Snapshot (wie der Linux-Host). Timeouts zählen wie bei den + /// M4-Schritten; ein Formatfehler beendet die Sitzung, weil ein kaputter Frame die M5-Sitzung entwertet. + /// + /// Kürzester Abstand zwischen zwei M5-Snapshots aus dem Polling (Linux-Standard). + public static readonly TimeSpan SharedRefreshMinimumInterval = TimeSpan.FromSeconds(30); + + private DateTimeOffset? _lastSharedRefresh; + + private async Task RefreshSharedSnapshotAsync(RefreshScope scope, CancellationToken session) + { + // Ein M5-Snapshot liest jedes Mal alles (~40 Requests). Wie der Linux-Standard höchstens alle 30 s; ein + // vollständiger Refresh (jeder FullRefreshEvery-te Tick oder auf Anfrage) läuft immer. + if (scope != RefreshScope.All && _lastSharedRefresh is { } last && _time.GetUtcNow() - last < SharedRefreshMinimumInterval) + { + return; + } + + try + { + await ReadControlSnapshotAsync(ControlGroup.All, session); + _lastSharedRefresh = _time.GetUtcNow(); + _consecutiveTimeouts = 0; + } + catch (TimeoutException ex) + { + _consecutiveTimeouts++; + _logger.LogWarning("M5-Snapshot ohne Antwort ({Count}/{Max}): {Message}", _consecutiveTimeouts, _options.MaxConsecutiveTimeouts, ex.Message); + if (_consecutiveTimeouts >= _options.MaxConsecutiveTimeouts) + { + throw; + } + + return; + } + + if (scope == RefreshScope.All) + { + Store.Apply(new FullRefreshCompleted(_time.GetUtcNow())); + } + } + private void OnNotification(object? sender, GaiaFrame frame) { + if (_gate.IsMomentum5) + { + return; // am M5 nicht angemeldet und mit dem M4-Dispatcher nicht deutbar + } + if (_dispatcher.Translate(frame) is { } deviceEvent) { ApplyPushed(deviceEvent); @@ -687,6 +774,11 @@ private void ApplyPushed(DeviceEvent deviceEvent) private bool OnUnsolicitedResponse(GaiaFrame frame) { + if (_gate.IsMomentum5) + { + return false; + } + if (_dispatcher.TranslateUnsolicitedResponse(frame) is not { } deviceEvent) { return false; diff --git a/src/Momentum4.Core/State/DeviceEvents.cs b/src/Momentum4.Core/State/DeviceEvents.cs index 552a83e..65e6092 100644 --- a/src/Momentum4.Core/State/DeviceEvents.cs +++ b/src/Momentum4.Core/State/DeviceEvents.cs @@ -75,3 +75,19 @@ public sealed record PromptLanguageChanged(Protocol.Features.PromptLanguage Lang public sealed record AutoPauseChanged(bool On) : DeviceEvent; public sealed record FullRefreshCompleted(DateTimeOffset At) : DeviceEvent; + +/// Immersive Audio (0x3605) und Head Tracking (0x3603), nur MOMENTUM 5; null = unbekannt. +public sealed record SpatialAudioChanged(bool? ImmersiveAudio, bool? HeadTracking) : DeviceEvent; + +/// Akkuschutz (0x060B), nur MOMENTUM 5. +public sealed record BatteryProtectionChanged(bool? On) : DeviceEvent; + +/// Transparenzstufe 0…100 (0x1803), nur MOMENTUM 5 (FW 6.21.5). +public sealed record TransparencyLevelChanged(int? Level) : DeviceEvent; + +/// Sidetone / Transparenz bei Anrufen 0…5 (0x0806). +public sealed record SidetoneChanged(int? Level) : DeviceEvent; + +/// Was der Core laut letztem Shared-Snapshot schreiben würde, und die erlaubten Werte je Regler. +public sealed record ControlCapabilitiesChanged( + IReadOnlySet Writable, IReadOnlyDictionary> Choices) : DeviceEvent; diff --git a/src/Momentum4.Core/State/Momentum4State.cs b/src/Momentum4.Core/State/Momentum4State.cs index 1000933..d35739e 100644 --- a/src/Momentum4.Core/State/Momentum4State.cs +++ b/src/Momentum4.Core/State/Momentum4State.cs @@ -154,8 +154,21 @@ public sealed record Momentum4State( BluetoothCodec? Codec = null, string? SerialNumber = null, PromptLanguage? PromptLanguage = null, - bool? AutoPauseOnTransparency = null) + bool? AutoPauseOnTransparency = null, + bool? ImmersiveAudio = null, + bool? HeadTracking = null, + bool? BatteryProtection = null, + int? TransparencyLevel = null, + int? Sidetone = null, + IReadOnlySet? WritableControls = null, + IReadOnlyDictionary>? ControlChoices = null) { + /// + /// Ob der Core diese Einstellung für das verbundene Gerät schreiben würde (aus dem letzten Shared-Snapshot: + /// Modell-/Firmware-Gate und gelesener Wert). Unbekannt heißt nein. + /// + public bool CanWrite(HeadsetControl control) => WritableControls?.Contains(control) == true; + /// /// Werte für „Automatisch ausschalten“, die belegt sind: 0 = nie, 15 min (eigenes Gerät), 30 und 60 min ([DS]: so /// liest das Headset die Stufen der Smart-Control-App). Andere Werte schreibt die App nicht. diff --git a/src/Momentum4.Core/State/ProductName.cs b/src/Momentum4.Core/State/ProductName.cs new file mode 100644 index 0000000..af1b4c9 --- /dev/null +++ b/src/Momentum4.Core/State/ProductName.cs @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: 2026 Ariazonaa +// SPDX-License-Identifier: MIT + +using Momentum4.Core.Services; + +namespace Momentum4.Core.State; + +/// Anzeigename und Namensgrenze je Modell; die Modell-ID kommt vom Gerät (0x1206, z. B. „M4AEBT Black“). +public static class ProductName +{ + /// „MOMENTUM 4“, „MOMENTUM 5“ oder – unbekannt bzw. noch nicht verbunden – „MOMENTUM“. + public static string For(string? modelId) + { + var gate = new FeatureGate(null, modelId); + return gate.IsMomentum4 ? "MOMENTUM 4" : gate.IsMomentum5 ? "MOMENTUM 5" : "MOMENTUM"; + } + + /// Größte Länge des Gerätenamens in UTF-8-Bytes (localName, Feature 20): 16 am MOMENTUM 5, sonst 30. + public static int MaxNameBytes(string? modelId) => new FeatureGate(null, modelId).IsMomentum5 ? 16 : 30; +} diff --git a/src/Momentum4.Core/State/StateStore.cs b/src/Momentum4.Core/State/StateStore.cs index 572b1cb..f926069 100644 --- a/src/Momentum4.Core/State/StateStore.cs +++ b/src/Momentum4.Core/State/StateStore.cs @@ -60,6 +60,12 @@ public bool Apply(DeviceEvent deviceEvent) /// Reine Funktion: alter Zustand + Event → neuer Zustand. public static class StateReducer { + // Mengen vergleicht ein record nur per Referenz; inhaltlich gleiche Freigaben sollen keinen StateChanged auslösen. + private static bool SameCapabilities(Momentum4State state, ControlCapabilitiesChanged e) => + state.WritableControls is { } writable && writable.SetEquals(e.Writable) + && state.ControlChoices is { } choices && choices.Count == e.Choices.Count + && e.Choices.All(pair => choices.TryGetValue(pair.Key, out var values) && values.SequenceEqual(pair.Value)); + public static Momentum4State Apply(Momentum4State state, DeviceEvent deviceEvent) => deviceEvent switch { ConnectionChanged e => state with @@ -67,7 +73,24 @@ public static class StateReducer Connection = e.State, LastError = e.State == ConnectionState.Connected ? null : e.Error ?? state.LastError, }, - DeviceIdentified e => state with { Device = e.Device }, + DeviceIdentified e when e.Device == state.Device => state, + DeviceIdentified e => state with + { + Device = e.Device, + ImmersiveAudio = null, + HeadTracking = null, + BatteryProtection = null, + TransparencyLevel = null, + Sidetone = null, + WritableControls = null, + ControlChoices = null, + }, + SpatialAudioChanged e => state with { ImmersiveAudio = e.ImmersiveAudio, HeadTracking = e.HeadTracking }, + BatteryProtectionChanged e => state with { BatteryProtection = e.On }, + TransparencyLevelChanged e => state with { TransparencyLevel = e.Level }, + SidetoneChanged e => state with { Sidetone = e.Level }, + ControlCapabilitiesChanged e when SameCapabilities(state, e) => state, + ControlCapabilitiesChanged e => state with { WritableControls = e.Writable, ControlChoices = e.Choices }, BatteryChanged e => state with { BatteryPercent = e.Percent }, ChargingChanged e => state with { Charging = e.Charging }, NoiseControlChanged e => state with { NoiseControl = e.State }, diff --git a/tests/Momentum4.Core.Tests/ControlCommandsTests.cs b/tests/Momentum4.Core.Tests/ControlCommandsTests.cs index b36ec58..e695a24 100644 --- a/tests/Momentum4.Core.Tests/ControlCommandsTests.cs +++ b/tests/Momentum4.Core.Tests/ControlCommandsTests.cs @@ -179,6 +179,94 @@ public async Task Without_a_server_the_client_reports_no_app() Assert.Null(result); } + [Fact(Timeout = TestTimeoutMs)] + public async Task Sidetone_command_sets_and_reports_level() + { + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + + var result = await ControlCommands.ExecuteAsync(["sidetone", "4"], service, null, TestContext.Current.CancellationToken); + + Assert.Equal(0, result.ExitCode); + Assert.Contains("Transparenz bei Anrufen: 4", result.Output, StringComparison.Ordinal); + Assert.Equal(4, fixture.ExtraValues[0x0806]); + } + + [Fact(Timeout = TestTimeoutMs)] + public async Task M5_switch_and_level_commands_confirm_the_readback() + { + var ct = TestContext.Current.CancellationToken; + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + + var immersive = await ControlCommands.ExecuteAsync(["immersive", "on"], service, null, ct); + var tracking = await ControlCommands.ExecuteAsync(["headtracking", "on"], service, null, ct); + var protection = await ControlCommands.ExecuteAsync(["batteryprotect", "off"], service, null, ct); + var level = await ControlCommands.ExecuteAsync(["transparency", "40"], service, null, ct); + + Assert.Equal((0, 0, 0, 0), (immersive.ExitCode, tracking.ExitCode, protection.ExitCode, level.ExitCode)); + Assert.Contains("Raumklang: an", immersive.Output, StringComparison.Ordinal); + Assert.Contains("Head Tracking: an", tracking.Output, StringComparison.Ordinal); + Assert.Contains("Akkuschutz: aus", protection.Output, StringComparison.Ordinal); + Assert.Contains("Transparenzstufe: 40", level.Output, StringComparison.Ordinal); + } + + [Fact(Timeout = TestTimeoutMs)] + public async Task Status_lists_m5_values_when_known() + { + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + + var result = await ControlCommands.ExecuteAsync(["status"], service, null, TestContext.Current.CancellationToken); + + Assert.Contains("Raumklang: aus", result.Output, StringComparison.Ordinal); + Assert.Contains("Head Tracking: aus", result.Output, StringComparison.Ordinal); + Assert.Contains("Akkuschutz: an", result.Output, StringComparison.Ordinal); + Assert.Contains("Transparenzstufe: 100", result.Output, StringComparison.Ordinal); + Assert.Contains("Transparenz bei Anrufen: 3", result.Output, StringComparison.Ordinal); + } + + [Fact(Timeout = TestTimeoutMs)] + public async Task Status_omits_m5_values_on_m4() + { + await using var service = await StartAsync(TestContext.Current.CancellationToken); + + var result = await ControlCommands.ExecuteAsync(["status"], service, null, TestContext.Current.CancellationToken); + + Assert.DoesNotContain("Raumklang", result.Output, StringComparison.Ordinal); + Assert.DoesNotContain("Akkuschutz", result.Output, StringComparison.Ordinal); + Assert.DoesNotContain("Transparenzstufe", result.Output, StringComparison.Ordinal); + Assert.DoesNotContain("Transparenz bei Anrufen", result.Output, StringComparison.Ordinal); // am M4 gesperrt (Hörtest offen) + } + + [Fact(Timeout = TestTimeoutMs)] + public async Task Headtracking_without_immersive_is_rejected_without_write() + { + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + + var result = await ControlCommands.ExecuteAsync(["headtracking", "on"], service, null, TestContext.Current.CancellationToken); + + Assert.NotEqual(0, result.ExitCode); + Assert.Contains("Raumklang", result.Output, StringComparison.Ordinal); + Assert.Empty(fixture.Writes); + } + + [Theory(Timeout = TestTimeoutMs)] + [InlineData("9")] + [InlineData("-1")] + [InlineData("zwei")] + public async Task Out_of_range_sidetone_is_usage_error(string value) + { + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + + var result = await ControlCommands.ExecuteAsync(["sidetone", value], service, null, TestContext.Current.CancellationToken); + + Assert.Equal(2, result.ExitCode); + Assert.Empty(fixture.Writes); + } + private EqPresetStore Presets() => new(Path.Combine(_presetDirectory, "presets.json"), NullLogger.Instance); private async Task StartAsync(CancellationToken cancellationToken) diff --git a/tests/Momentum4.Core.Tests/SharedHeadsetControlTests.cs b/tests/Momentum4.Core.Tests/SharedHeadsetControlTests.cs index 4e8a8ee..8c1b341 100644 --- a/tests/Momentum4.Core.Tests/SharedHeadsetControlTests.cs +++ b/tests/Momentum4.Core.Tests/SharedHeadsetControlTests.cs @@ -203,10 +203,19 @@ public SharedHeadsetFixture() Transport.SetState(TransportState.Disconnected); } - public async Task StartAsync(bool polling = false) + public Task StartAsync(bool polling = false) => + StartWithAsync(new Momentum4ServiceOptions { RegisterNotifications = false, ReadSerialNumber = false, EnablePolling = polling, Reconnect = false, PeerConnectTimeout = PeerConnectTimeout }); + + /// Wie die Windows-App (HeadsetHost): Notifications, Seriennummer und Polling an, Uhr gefälscht. + public Task StartWindowsAsync() + { + Time ??= new Microsoft.Extensions.Time.Testing.FakeTimeProvider(); + return StartWithAsync(new Momentum4ServiceOptions { Reconnect = false, PeerConnectTimeout = PeerConnectTimeout }); + } + + private async Task StartWithAsync(Momentum4ServiceOptions options) { - var service = new Momentum4Service(Transport, CommandPolicy.Production, - new Momentum4ServiceOptions { RegisterNotifications = false, ReadSerialNumber = false, EnablePolling = polling, Reconnect = false, PeerConnectTimeout = PeerConnectTimeout }, NullLoggerFactory.Instance, Time); + var service = new Momentum4Service(Transport, CommandPolicy.Production, options, NullLoggerFactory.Instance, Time); service.Start(); for (var attempt = 0; attempt < 1000 && service.Store.Current.Connection != ConnectionState.Connected; attempt++) { diff --git a/tests/Momentum4.Core.Tests/SharedHeadsetParityTests.cs b/tests/Momentum4.Core.Tests/SharedHeadsetParityTests.cs index 26c685f..b094bed 100644 --- a/tests/Momentum4.Core.Tests/SharedHeadsetParityTests.cs +++ b/tests/Momentum4.Core.Tests/SharedHeadsetParityTests.cs @@ -229,7 +229,7 @@ public async Task Forced_windows_polling_cannot_interleave_shared_transaction() }; var operation = Task.Run(() => service.SetBooleanControlAsync(HeadsetBooleanControl.SmartPause, true, TestContext.Current.CancellationToken), TestContext.Current.CancellationToken); await blocked.Task.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken); - service.RequestRefresh(RefreshScope.Battery); + service.RequestRefresh(RefreshScope.All); // am M5 laufen Teil-Refreshes höchstens alle 30 s, ein voller immer await Task.Delay(30, TestContext.Current.CancellationToken); Assert.DoesNotContain(fixture.Requests, frame => frame.Command.Value == 0x0603); release.SetResult(); @@ -239,8 +239,10 @@ public async Task Forced_windows_polling_cannot_interleave_shared_transaction() await Task.Delay(5, TestContext.Current.CancellationToken); } + // Der Poll (am M5 ein voller Snapshot) beginnt erst nach dem Zurücklesen der Transaktion: Write 0x080c, dann 0x080d. var batteryIndex = fixture.Requests.FindIndex(frame => frame.Command.Value == 0x0603); - var lastBehaviorRead = fixture.Requests.FindLastIndex(frame => frame.Command.Value == 0x0802); - Assert.True(batteryIndex > lastBehaviorRead && lastBehaviorRead > fixture.Requests.FindIndex(frame => frame.Command.Value == 0x080c)); + var writeIndex = fixture.Requests.FindIndex(frame => frame.Command.Value == 0x080c); + var readbackIndex = fixture.Requests.FindIndex(writeIndex + 1, frame => frame.Command.Value == 0x080d); + Assert.True(writeIndex >= 0 && readbackIndex > writeIndex && batteryIndex > readbackIndex); } } diff --git a/tests/Momentum4.Core.Tests/SharedHeadsetTransactionTests.cs b/tests/Momentum4.Core.Tests/SharedHeadsetTransactionTests.cs index 8e0dd5d..c174906 100644 --- a/tests/Momentum4.Core.Tests/SharedHeadsetTransactionTests.cs +++ b/tests/Momentum4.Core.Tests/SharedHeadsetTransactionTests.cs @@ -338,5 +338,23 @@ public async Task Cached_noise_noop_rechecks_external_state_and_preserves_custom Assert.Equal(0x1a00, Assert.Single(fixture.Writes).Command.Value); } + [Fact(Timeout = 15000)] + public async Task Ancillary_write_does_not_republish_stale_noise_state() + { + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartAsync(); + var before = await service.GetControlSnapshotAsync(TestContext.Current.CancellationToken); + Assert.Equal(900, before.Settings.AutoPowerOff); + + // Neuer Noise-Stand, wie ihn Polling oder ein Push nach dem letzten Snapshot liefern würde. + var newer = new NoiseControlState(true, false, 40, AntiWindMode.Off, false); + service.Store.Apply(new NoiseControlChanged(newer)); + + await service.SetIntegerControlAsync(HeadsetIntegerControl.AutoPowerOff, 1800, TestContext.Current.CancellationToken); + + Assert.Equal(newer, service.Store.Current.NoiseControl); + Assert.Equal(1800, service.Store.Current.AutoPowerOffSeconds); + } + private static SharedHeadsetFixture M4() => new() { Model = "M4AEBT", Firmware = [0, 3, 0, 37, 0, 3] }; } diff --git a/tests/Momentum4.Core.Tests/SharedHeadsetWindowsSessionTests.cs b/tests/Momentum4.Core.Tests/SharedHeadsetWindowsSessionTests.cs new file mode 100644 index 0000000..64bf5fe --- /dev/null +++ b/tests/Momentum4.Core.Tests/SharedHeadsetWindowsSessionTests.cs @@ -0,0 +1,212 @@ +using System.Globalization; +using System.Text.Json; +using Momentum4.Core.Services; +using Momentum4.Core.State; +using Momentum4.Protocol; +using Momentum4.Protocol.Gaia; + +namespace Momentum4.Core.Tests; + +/// +/// Die Windows-App startet den Service mit Notifications, Seriennummer und Polling. Ein MOMENTUM 5 darf dabei nur +/// senden, was der am Gerät geprüfte Linux-Ablauf sendet. +/// +public sealed class SharedHeadsetWindowsSessionTests +{ + private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(10); + + [Fact(Timeout = 15000)] + public async Task M5_windows_session_sends_only_commands_seen_in_m5_captures() + { + var allowed = M5CaptureCommands(); + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + await RunPollsAsync(fixture, 2, TestContext.Current.CancellationToken); + + var unexpected = fixture.Requests.Select(Key).Where(key => !allowed.Contains(key)).Distinct().ToList(); + Assert.Empty(unexpected); + Assert.DoesNotContain(fixture.Requests, frame => frame.Command.Value == 0x0007); + Assert.DoesNotContain(fixture.Requests, frame => frame.Vendor == 0x001D && frame.Command.Value == 0x0003); + Assert.DoesNotContain(fixture.Requests, frame => frame.Command.Value is 0x0800 or 0x0807); + Assert.Empty(fixture.Writes); + } + + [Fact(Timeout = 15000)] + public async Task M5_other_firmware_windows_session_reads_only_shared_snapshot() + { + var fixture = new SharedHeadsetFixture { Firmware = [0, 6, 0, 21, 0, 6] }; + await using var service = await fixture.StartWindowsAsync(); + await RunPollsAsync(fixture, 1, TestContext.Current.CancellationToken); + + Assert.Equal(ConnectionState.Connected, service.Store.Current.Connection); + Assert.DoesNotContain(fixture.Requests, frame => frame.Command.Value is 0x0601 or 0x1801); + Assert.Empty(fixture.Writes); + } + + [Fact(Timeout = 15000)] + public async Task M5_windows_session_polls_at_most_every_30_seconds() + { + var ct = TestContext.Current.CancellationToken; + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + await RunPollsAsync(fixture, 0, ct); + var afterConnect = fixture.Requests.Count; + + await RunPollsAsync(fixture, 2, ct); // 20 s: wie der Linux-Standard noch kein neuer Snapshot + Assert.Equal(afterConnect, fixture.Requests.Count); + + await RunPollsAsync(fixture, 1, ct); // 30 s + Assert.True(fixture.Requests.Count > afterConnect); + } + + [Fact(Timeout = 15000)] + public async Task M5_session_ignores_unsolicited_frames() + { + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + Assert.False(service.Store.Current.Charging); + + fixture.Transport.Receive(GaiaFrameCodec.Encode(0x0495, new CommandWord(0x0682), new byte[] { 1 })); + await Task.Delay(100, TestContext.Current.CancellationToken); + + Assert.False(service.Store.Current.Charging); + } + + [Fact(Timeout = 15000)] + public async Task M4_windows_session_still_registers_notifications() + { + var fixture = new SharedHeadsetFixture { Model = "M4AEBT", Firmware = [0, 3, 0, 38, 0, 3] }; + await using var service = await fixture.StartWindowsAsync(); + await RunPollsAsync(fixture, 0, TestContext.Current.CancellationToken); + + Assert.Contains(fixture.Requests, frame => frame.Command.Value == 0x0007); + } + + [Fact(Timeout = 15000)] + public async Task M5_windows_session_exposes_extended_values() + { + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + await RunPollsAsync(fixture, 0, TestContext.Current.CancellationToken); + var state = service.Store.Current; + + Assert.False(state.ImmersiveAudio); + Assert.False(state.HeadTracking); + Assert.True(state.BatteryProtection); + Assert.Equal(100, state.TransparencyLevel); + Assert.Equal(3, state.Sidetone); + Assert.True(state.CanWrite(HeadsetControl.ImmersiveAudio)); + Assert.True(state.CanWrite(HeadsetControl.Sidetone)); + Assert.Equal(new[] { 0, 1 }, state.ControlChoices![HeadsetIntegerControl.AntiWind]); + } + + [Fact(Timeout = 15000)] + public async Task M4_windows_session_has_sidetone_value_but_no_m5_values() + { + var fixture = new SharedHeadsetFixture { Model = "M4AEBT", Firmware = [0, 3, 0, 38, 0, 3] }; + await using var service = await fixture.StartWindowsAsync(); + await RunPollsAsync(fixture, 0, TestContext.Current.CancellationToken); + var state = service.Store.Current; + + Assert.Equal(3, state.Sidetone); + Assert.Null(state.ImmersiveAudio); + Assert.Null(state.HeadTracking); + Assert.Null(state.BatteryProtection); + Assert.Null(state.TransparencyLevel); + Assert.False(state.CanWrite(HeadsetControl.Sidetone)); + Assert.False(state.CanWrite(HeadsetControl.ImmersiveAudio)); + Assert.True(state.CanWrite(HeadsetControl.SmartPause)); + Assert.DoesNotContain(fixture.Requests, frame => frame.Command.Value is 0x060b or 0x3603 or 0x3605 or 0x1803); + } + + [Fact(Timeout = 15000)] + public async Task Typed_setters_round_trip_on_m5() + { + var ct = TestContext.Current.CancellationToken; + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + + Assert.True(await service.SetImmersiveAudioAsync(true, ct)); + Assert.True(await service.SetHeadTrackingAsync(true, ct)); + Assert.False(await service.SetBatteryProtectionAsync(false, ct)); + Assert.Equal(1, await service.SetSidetoneAsync(1, ct)); + Assert.Equal(50, await service.SetTransparencyLevelAsync(50, ct)); + + var state = service.Store.Current; + Assert.True(state.ImmersiveAudio); + Assert.True(state.HeadTracking); + Assert.False(state.BatteryProtection); + Assert.Equal(1, state.Sidetone); + Assert.Equal(50, state.TransparencyLevel); + } + + [Fact(Timeout = 15000)] + public async Task Typed_setter_reports_rejection_with_confirmed_value() + { + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + fixture.Overrides[0x060b] = [1]; + + var failure = await Assert.ThrowsAsync>(() => service.SetBatteryProtectionAsync(false, TestContext.Current.CancellationToken)); + Assert.True(failure.Actual); + } + + [Fact(Timeout = 15000)] + public async Task Device_name_limit_is_counted_in_utf8_bytes() + { + Assert.Equal(16, ProductName.MaxNameBytes("M5AEBT Black")); + Assert.Equal(30, ProductName.MaxNameBytes("M4AEBT Black")); + var fixture = new SharedHeadsetFixture(); + await using var service = await fixture.StartWindowsAsync(); + + Assert.Equal("Ääääääää", await service.SetDeviceNameAsync("Ääääääää", TestContext.Current.CancellationToken)); + await Assert.ThrowsAsync(() => service.SetDeviceNameAsync("Äääääääää", TestContext.Current.CancellationToken)); + } + + [Theory] + [InlineData("M4AEBT Black", "MOMENTUM 4")] + [InlineData("M5AEBT", "MOMENTUM 5")] + [InlineData("Foreign", "MOMENTUM")] + [InlineData(null, "MOMENTUM")] + public void Product_name_follows_the_model(string? model, string expected) => Assert.Equal(expected, ProductName.For(model)); + + /// Dreht die Fake-Uhr Poll-Intervalle weiter und wartet, bis keine Requests mehr kommen. + private static async Task RunPollsAsync(SharedHeadsetFixture fixture, int polls, CancellationToken ct) + { + for (var poll = 0; poll < polls; poll++) + { + fixture.Time!.Advance(PollInterval); + var seen = -1; + while (seen != fixture.Requests.Count) + { + seen = fixture.Requests.Count; + await Task.Delay(50, ct); + } + } + } + + private static (ushort Vendor, ushort Command) Key(GaiaFrame frame) => (frame.Vendor, frame.Command.Value); + + /// Alle (Vendor, Command) aus den Requests der M5-Mitschnitte unter tests/CapturedPackets/M5. + private static HashSet<(ushort Vendor, ushort Command)> M5CaptureCommands() + { + var allowed = new HashSet<(ushort, ushort)>(); + foreach (var path in Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, "CapturedPackets", "M5"), "*.json")) + { + using var document = JsonDocument.Parse(File.ReadAllText(path)); + foreach (var row in document.RootElement.GetProperty("exchanges").EnumerateArray()) + { + if (row.TryGetProperty("tx", out var tx)) + { + allowed.Add(Key(new GaiaFrameReader().Push(Hex.Parse(tx.GetString()!)).Frames.Single())); + } + else if (row.TryGetProperty("command", out var command)) + { + allowed.Add((0x0495, ushort.Parse(command.GetString()!.Replace("0x", string.Empty, StringComparison.OrdinalIgnoreCase), NumberStyles.HexNumber, CultureInfo.InvariantCulture))); + } + } + } + + return allowed; + } +} diff --git a/tests/Momentum4.Core.Tests/StateStoreTests.cs b/tests/Momentum4.Core.Tests/StateStoreTests.cs index 4850f92..d914890 100644 --- a/tests/Momentum4.Core.Tests/StateStoreTests.cs +++ b/tests/Momentum4.Core.Tests/StateStoreTests.cs @@ -26,6 +26,44 @@ public void Raises_event_only_on_real_change() Assert.IsType(e.Cause); } + [Fact] + public void Identity_change_clears_extended_values_and_capabilities() + { + var store = new StateStore(); + store.Apply(new DeviceIdentified(new DeviceInfo("M5AEBT Black", new FirmwareVersion(6, 21, 5)))); + store.Apply(new SpatialAudioChanged(true, true)); + store.Apply(new BatteryProtectionChanged(true)); + store.Apply(new TransparencyLevelChanged(40)); + store.Apply(new SidetoneChanged(2)); + store.Apply(new ControlCapabilitiesChanged(new HashSet { HeadsetControl.ImmersiveAudio }, + new Dictionary> { [HeadsetIntegerControl.AntiWind] = [0, 1] })); + + // Gleiche Identität (jeder Snapshot meldet sie erneut) lässt die Werte stehen. + Assert.False(store.Apply(new DeviceIdentified(new DeviceInfo("M5AEBT Black", new FirmwareVersion(6, 21, 5))))); + Assert.True(store.Current.CanWrite(HeadsetControl.ImmersiveAudio)); + + store.Apply(new DeviceIdentified(new DeviceInfo("M4AEBT Black", new FirmwareVersion(3, 38, 3)))); + var state = store.Current; + Assert.Null(state.ImmersiveAudio); + Assert.Null(state.HeadTracking); + Assert.Null(state.BatteryProtection); + Assert.Null(state.TransparencyLevel); + Assert.Null(state.Sidetone); + Assert.Null(state.WritableControls); + Assert.Null(state.ControlChoices); + Assert.False(state.CanWrite(HeadsetControl.ImmersiveAudio)); + } + + [Fact] + public void Equal_capabilities_do_not_count_as_change() + { + var store = new StateStore(); + var choices = new Dictionary> { [HeadsetIntegerControl.AntiWind] = [0, 1] }; + Assert.True(store.Apply(new ControlCapabilitiesChanged(new HashSet { HeadsetControl.Sidetone }, choices))); + Assert.False(store.Apply(new ControlCapabilitiesChanged(new HashSet { HeadsetControl.Sidetone }, + new Dictionary> { [HeadsetIntegerControl.AntiWind] = [0, 1] }))); + } + [Fact] public void Equal_lists_do_not_count_as_change() { diff --git a/tools/Momentum4.Poc/Program.cs b/tools/Momentum4.Poc/Program.cs index 3f10232..68f7644 100644 --- a/tools/Momentum4.Poc/Program.cs +++ b/tools/Momentum4.Poc/Program.cs @@ -69,6 +69,7 @@ "setname" => await SetNameAsync(), "gesture" => await GestureAsync(), "autopause" => await AutoPauseAsync(), + "sidetone" => await SidetoneAsync(), "reasons" => await ReasonsAsync(), "winbattery" => await WinBatteryAsync(), "sdp" => await SdpAsync(), @@ -320,6 +321,69 @@ async Task Probe(string label, CommandDescriptor cmd, byte[] payload) return 0; } +// Sidetone (Transparenz bei Anrufen) am M4: 0x0806 lesen, optional 0x0805 [n] setzen und zuruecklesen (Write -> Verify). +// Nur fuer den Hardware-Test (Freigabe von Sidetone am M4 nur nach Hoerprobe); bricht bei anderem +// Modell als M4AEBT ab, bevor etwas geschrieben wird. +async Task SidetoneAsync() +{ + int? target = null; + if (options.SetValue.Length > 0) + { + if (!int.TryParse(options.SetValue, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var level) || level is < 0 or > 5) + { + Console.WriteLine($"Stufe '{options.SetValue}' ungültig – erlaubt sind 0 bis 5."); + return 2; + } + + target = level; + } + + var address = await ResolveAddressAsync(); + await using var transport = new RfcommTransport(address, loggerFactory.CreateLogger(), serviceIndex: options.ServiceIndex); + var policy = CommandPolicy.Only(CommandCatalog.GetModelId, CommandCatalog.GetFirmwareVersion, CommandCatalog.GetSidetone, CommandCatalog.SetSidetone); + using var queue = new GaiaCommandQueue(transport, policy, loggerFactory.CreateLogger()); + var client = new Momentum4Client(queue); + var ct = cancellation.Token; + var started = Stopwatch.StartNew(); + var exchange = new List(); + queue.Traffic += (_, t) => + { + lock (exchange) + { + exchange.Add(new { atMs = started.ElapsedMilliseconds, dir = t.Direction == TrafficDirection.Tx ? "TX" : "RX", hex = Hex.Format(t.Raw), command = t.CommandName }); + } + }; + + await transport.ConnectAsync(ct); + var model = await client.GetModelIdAsync(ct); + var firmware = await client.GetFirmwareVersionAsync(ct); + Console.WriteLine($"Headset: {model}, Firmware {firmware}"); + if (!new FeatureGate(firmware, model).IsMomentum4) + { + Console.WriteLine("Abbruch: sidetone ist nur für den MOMENTUM 4 (M4AEBT) gedacht."); + await transport.DisconnectAsync(); + return 1; + } + + async Task Read() => SharedHeadsetCodec.DecodeByte((await queue.SendAsync(CommandCatalog.GetSidetone, ct)).Payload, 5, "sidetone"); + + var before = await Read(); + Console.WriteLine($"Vorher: Stufe {before}"); + int? after = null; + if (target is { } value) + { + await queue.SendAsync(CommandCatalog.SetSidetone, new[] { (byte)value }, ct); + after = await Read(); + Console.WriteLine($"Nachher: Stufe {after}{(after == value ? string.Empty : $" – NICHT übernommen (gewünscht {value})")}"); + } + + await transport.DisconnectAsync(); + var path = Path.Combine(logDirectory, $"sidetone-{DateTime.Now:yyyyMMdd-HHmmss}.json"); + await File.WriteAllTextAsync(path, JsonSerializer.Serialize(new { tool = "m4poc sidetone", model, firmware = firmware.ToString(), before, target, after, exchange }, new JsonSerializerOptions { WriteIndented = true }), CancellationToken.None); + Console.WriteLine($"Mitschnitt: {path}"); + return target is null || after == target ? 0 : 1; +} + // Automatische Pause bei Transparenz (0x1800 setzen, 0x1801 zuruecklesen). Write -> Verify. async Task AutoPauseAsync() { @@ -1132,7 +1196,7 @@ internal sealed record PocOptions(string Command, BluetoothAddress? Address, int { public static PocOptions? Parse(string[] args) { - if (args.Length == 0 || args[0] is not ("list" or "sdp" or "listen" or "read" or "state" or "monitor" or "stage6" or "set" or "preset" or "peer" or "winbattery" or "features" or "probe20" or "setname" or "gesture" or "autopause" or "reasons")) + if (args.Length == 0 || args[0] is not ("list" or "sdp" or "listen" or "read" or "state" or "monitor" or "stage6" or "set" or "preset" or "peer" or "winbattery" or "features" or "probe20" or "setname" or "gesture" or "autopause" or "reasons" or "sidetone")) { return null; } @@ -1188,6 +1252,12 @@ internal sealed record PocOptions(string Command, BluetoothAddress? Address, int return null; } } + else if (args[0] == "sidetone") + { + (setWhat, setValue, first) = args.Length >= 2 && !args[1].StartsWith("--", StringComparison.Ordinal) + ? ("sidetone", args[1], 2) + : ("sidetone", string.Empty, 1); + } else if (args[0] == "setname") { if (args.Length < 2) @@ -1288,6 +1358,8 @@ m4poc monitor [--seconds N] [--poll 10] [--notifications] m4poc stage6 Hardware-Stufe 6–8: Anti-Wind mit beiden 0x1A00-Formaten ändern, nach jedem Versuch den gesamten Zustand wiederherstellen und vergleichen – ÄNDERT kurz Einstellungen (nur bei ANC an) + m4poc sidetone [0..5] nur M4: Sidetone (0x0806) lesen, mit Stufe setzen (0x0805) und + zurücklesen – Hardware-Test, Mitschnitt als JSON m4poc set mode transparency|adaptive|custom|off Noise-Control-Modus setzen (Write → Verify) m4poc set level 0..100 Pegel setzen (schaltet auf Custom)