diff --git a/AGENTS.md b/AGENTS.md index 10df90c..55652a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,9 +99,10 @@ Avalonia 12. Use the `avalonia-docs` MCP before reaching for an API from memory. ## Security The number arrives from a `tel:` link, which any web page or document can produce: it is -**hostile input**. It reaches the phone only after `TelUri` has reduced it to `0-9 * #` and a +**hostile input**. It reaches the phone only after `TelUri` has reduced it to digits and a length cap — never a `;`, `\r`, `\n` or letter, which would let a link append its own AT -commands. A security fix gets a test that replays the attack. Dialling always goes through the +commands, and never `*` or `#`, which on a landline would let it set up call forwarding +(`*21*#`) at the exchange. A security fix gets a test that replays the attack. Dialling always goes through the confirm window; nothing dials silently. ## Tests diff --git a/src/Waehlhilfe.AppLogic/DialMessages.cs b/src/Waehlhilfe.AppLogic/DialMessages.cs new file mode 100644 index 0000000..094aeda --- /dev/null +++ b/src/Waehlhilfe.AppLogic/DialMessages.cs @@ -0,0 +1,24 @@ +using Waehlhilfe.Modem; + +namespace Waehlhilfe.AppLogic; + +/// What the Lagebuchführer reads after a dial or a connection test. +public static class DialMessages +{ + public static string For(DialResult result, string portName) => result switch + { + DialResult.Dialled => "Gewählt. Gespräch am Telefon führen.", + DialResult.Answered => "Telefon antwortet. Alles bereit.", + DialResult.PortNotSet => "Kein Telefon eingerichtet – in Wählhilfe den Bluetooth-Port wählen.", + DialResult.PortMissing => $"Port {portName} nicht gefunden. Ist das Telefon mit diesem PC gekoppelt?", + DialResult.PortBusy => $"Port {portName} ist belegt oder gesperrt – läuft noch ein Anruf, oder nutzt ein anderes Programm den Port?", + DialResult.NoResponse => "Telefon antwortet nicht. Bluetooth am Telefon eingeschaltet? Ist es mit diesem PC als Audiogerät verbunden, diese Verbindung trennen.", + DialResult.Rejected => "Das Telefon hat die Wahl abgelehnt.", + DialResult.LineBusy => "Besetzt.", + DialResult.NoCarrier => "Keine Verbindung zustande gekommen.", + DialResult.NoDialTone => "Kein Freizeichen – ist die Telefonleitung angeschlossen?", + _ => "Unbekannte Antwort vom Telefon.", + }; + + public static bool IsError(DialResult result) => result is not (DialResult.Dialled or DialResult.Answered); +} diff --git a/src/Waehlhilfe.AppLogic/ISettingsStore.cs b/src/Waehlhilfe.AppLogic/ISettingsStore.cs new file mode 100644 index 0000000..38cf53c --- /dev/null +++ b/src/Waehlhilfe.AppLogic/ISettingsStore.cs @@ -0,0 +1,12 @@ +using Waehlhilfe.Domain; + +namespace Waehlhilfe.AppLogic; + +public interface ISettingsStore +{ + /// The saved settings, or when there are none or they are unreadable. + DialSettings Load(); + + /// The settings could not be written. + void Save(DialSettings settings); +} diff --git a/src/Waehlhilfe.AppLogic/ITelHandlerRegistration.cs b/src/Waehlhilfe.AppLogic/ITelHandlerRegistration.cs new file mode 100644 index 0000000..e8be287 --- /dev/null +++ b/src/Waehlhilfe.AppLogic/ITelHandlerRegistration.cs @@ -0,0 +1,13 @@ +namespace Waehlhilfe.AppLogic; + +/// Whether the OS opens tel: links with Wählhilfe, and the way to make it so. +public interface ITelHandlerRegistration +{ + bool IsDefaultHandler(); + + /// + /// Makes Wählhilfe the handler, or opens the OS dialog where the user does — Windows lets + /// no program set it on its own. Throws when neither is possible. + /// + Task MakeDefaultAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Waehlhilfe.AppLogic/JsonSettingsStore.cs b/src/Waehlhilfe.AppLogic/JsonSettingsStore.cs new file mode 100644 index 0000000..9ab883d --- /dev/null +++ b/src/Waehlhilfe.AppLogic/JsonSettingsStore.cs @@ -0,0 +1,80 @@ +using System.Text.Json; +using Waehlhilfe.Domain; + +namespace Waehlhilfe.AppLogic; + +/// The settings as a small JSON file in the user's profile. +public sealed class JsonSettingsStore : ISettingsStore +{ + /// A settings file is well under a kilobyte; anything this size was not written by Wählhilfe. + public const int MaxFileBytes = 16 * 1024; + + private static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web) { WriteIndented = true }; + + private readonly string _path; + + public JsonSettingsStore(string path) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + _path = path; + } + + /// + /// %APPDATA%\Waehlhilfe on Windows, ~/Library/Application Support/Waehlhilfe on + /// macOS, $XDG_CONFIG_HOME/Waehlhilfe on Linux. + /// + public static string DefaultPath() + { + var folder = OperatingSystem.IsMacOS() + ? Environment.SpecialFolder.LocalApplicationData + : Environment.SpecialFolder.ApplicationData; + return Path.Join(Environment.GetFolderPath(folder), "Waehlhilfe", "settings.json"); + } + + public DialSettings Load() + { + try + { + var file = new FileInfo(_path); + if (!file.Exists || file.Length > MaxFileBytes) + { + return DialSettings.Default; + } + + var stored = JsonSerializer.Deserialize(File.ReadAllText(_path), Options); + if (stored is null) + { + return DialSettings.Default; + } + + // A hand-edited value gets no further than the settings window would let it. + var defaults = DialSettings.Default; + return new DialSettings( + stored.PortName ?? defaults.PortName, + DialSettings.IsValidHomeCountryCode(stored.HomeCountryCode) ? stored.HomeCountryCode : defaults.HomeCountryCode, + DialSettings.IsValidOutsideLinePrefix(stored.OutsideLinePrefix) ? stored.OutsideLinePrefix : defaults.OutsideLinePrefix); + } + catch (Exception e) when (e is JsonException or IOException or UnauthorizedAccessException) + { + return DialSettings.Default; + } + } + + public void Save(DialSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + var directory = Path.GetDirectoryName(_path); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + // Write beside, then replace, so a crash mid-write never leaves half a file. + var temporary = _path + ".tmp"; + var stored = new StoredSettings(settings.PortName, settings.HomeCountryCode, settings.OutsideLinePrefix); + File.WriteAllText(temporary, JsonSerializer.Serialize(stored, Options)); + File.Move(temporary, _path, overwrite: true); + } + + private sealed record StoredSettings(string? PortName, string? HomeCountryCode, string? OutsideLinePrefix); +} diff --git a/src/Waehlhilfe.AppLogic/ViewModels/DialViewModel.cs b/src/Waehlhilfe.AppLogic/ViewModels/DialViewModel.cs new file mode 100644 index 0000000..1c2973f --- /dev/null +++ b/src/Waehlhilfe.AppLogic/ViewModels/DialViewModel.cs @@ -0,0 +1,133 @@ +using System.Diagnostics.CodeAnalysis; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Waehlhilfe.Domain; +using Waehlhilfe.Modem; + +namespace Waehlhilfe.AppLogic.ViewModels; + +/// +/// The confirm window a tel: click opens. Nothing is dialled until the Lagebuchführer +/// confirms: a link can come from any page or document, and a call is not something a page may +/// place on its own. +/// +public sealed partial class DialViewModel : ObservableObject +{ + /// Long enough to read „Gewählt“, short enough not to stand in the way. + public static readonly TimeSpan CloseDelay = TimeSpan.FromSeconds(2); + + /// + /// How long after opening the window ignores a confirm. A link can arrive while the + /// Lagebuchführer types elsewhere; the window takes focus, and an Enter meant for another + /// program must not place the call. + /// + public static readonly TimeSpan ArmDelay = TimeSpan.FromSeconds(1); + + private readonly IDialer _dialer; + private readonly TimeProvider _time; + private readonly string _portName; + private readonly DialNumber? _number; + private CancellationTokenSource? _dialing; + private bool _armed; + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(DialCommand))] + private bool _isBusy; + + [ObservableProperty] + private string _status; + + [ObservableProperty] + private bool _isError; + + public DialViewModel(string? link, DialSettings settings, IDialer dialer, TimeProvider? time = null) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(dialer); + _dialer = dialer; + _time = time ?? TimeProvider.System; + _portName = settings.PortName; + + if (TelUri.TryParse(link, out var uri)) + { + _number = DialNumber.From(uri, settings); + } + + Number = _number?.Digits ?? string.Empty; + (_status, _isError) = _number is null + ? ("Kein gültiger tel:-Link – es wird nicht gewählt.", true) + : string.IsNullOrWhiteSpace(_portName) + ? (DialMessages.For(DialResult.PortNotSet, _portName), true) + : ("Über das Telefon wählen?", false); + _ = ArmAfterDelayAsync(); + } + + public event EventHandler? CloseRequested; + + /// The digits that will follow ATD; empty for a link that was refused. + public string Number { get; } + + public bool CanDial => _number is not null && !string.IsNullOrWhiteSpace(_portName); + + private bool CanStartDial() => CanDial && _armed && !IsBusy; + + [RelayCommand(CanExecute = nameof(CanStartDial))] + [SuppressMessage("Design", "CA1031", Justification = "Any failure of the dial surfaces in Status; the window stays open to show it.")] + private async Task DialAsync() + { + if (!CanStartDial() || _number is null) + { + return; + } + + using var dialing = new CancellationTokenSource(); + _dialing = dialing; + IsBusy = true; + IsError = false; + Status = "Wähle …"; + try + { + var result = await _dialer.DialAsync(_portName, _number, dialing.Token); + Status = DialMessages.For(result, _portName); + IsError = DialMessages.IsError(result); + if (!IsError) + { + _ = CloseAfterDelayAsync(); + } + } + catch (OperationCanceledException) + { + Status = "Abgebrochen."; + } + catch (Exception) + { + Status = "Wählen fehlgeschlagen. Telefon und Bluetooth prüfen."; + IsError = true; + } + finally + { + _dialing = null; + IsBusy = false; + } + } + + [RelayCommand] + private void Cancel() + { + _dialing?.Cancel(); + CloseRequested?.Invoke(this, EventArgs.Empty); + } + + private async Task ArmAfterDelayAsync() + { + await Task.Delay(ArmDelay, _time); + _armed = true; + DialCommand.NotifyCanExecuteChanged(); + } + + private async Task CloseAfterDelayAsync() + { + await Task.Delay(CloseDelay, _time); + CloseRequested?.Invoke(this, EventArgs.Empty); + } +} diff --git a/src/Waehlhilfe.AppLogic/ViewModels/SettingsViewModel.cs b/src/Waehlhilfe.AppLogic/ViewModels/SettingsViewModel.cs new file mode 100644 index 0000000..3815d4c --- /dev/null +++ b/src/Waehlhilfe.AppLogic/ViewModels/SettingsViewModel.cs @@ -0,0 +1,193 @@ +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Waehlhilfe.Domain; +using Waehlhilfe.Modem; + +namespace Waehlhilfe.AppLogic.ViewModels; + +/// What Wählhilfe shows when started on its own: the phone's port, the dialling rules, the tests. +public sealed partial class SettingsViewModel : ObservableObject +{ + private readonly ISettingsStore _store; + private readonly IDialer _dialer; + private readonly Func> _listPorts; + private readonly ITelHandlerRegistration _registration; + + [ObservableProperty] + private string? _selectedPort; + + [ObservableProperty] + private string _homeCountryCode; + + [ObservableProperty] + private string _outsideLinePrefix; + + [ObservableProperty] + private string _testNumber = string.Empty; + + [ObservableProperty] + private string _status = string.Empty; + + [ObservableProperty] + private bool _isError; + + [ObservableProperty] + private bool _isDefaultHandler; + + [ObservableProperty] + private bool _isBusy; + + public SettingsViewModel(ISettingsStore store, IDialer dialer, Func> listPorts, ITelHandlerRegistration registration) + { + ArgumentNullException.ThrowIfNull(store); + ArgumentNullException.ThrowIfNull(dialer); + ArgumentNullException.ThrowIfNull(listPorts); + ArgumentNullException.ThrowIfNull(registration); + _store = store; + _dialer = dialer; + _listPorts = listPorts; + _registration = registration; + + var settings = store.Load(); + _homeCountryCode = settings.HomeCountryCode; + _outsideLinePrefix = settings.OutsideLinePrefix; + _selectedPort = string.IsNullOrEmpty(settings.PortName) ? null : settings.PortName; + RefreshPorts(); + _isDefaultHandler = registration.IsDefaultHandler(); + } + + public ObservableCollection Ports { get; } = []; + + [RelayCommand] + private void RefreshPorts() + { + var keep = SelectedPort; + Ports.Clear(); + foreach (var port in _listPorts()) + { + Ports.Add(port); + } + + // A stored port the OS does not list right now (phone switched off) is still shown. + if (!string.IsNullOrEmpty(keep) && !Ports.Contains(keep)) + { + Ports.Add(keep); + } + + SelectedPort = keep; + } + + [RelayCommand] + [SuppressMessage("Design", "CA1031", Justification = "A failed write surfaces in Status.")] + private void Save() + { + if (!TryCurrentSettings(out var settings)) + { + return; + } + + try + { + _store.Save(settings); + Show("Gespeichert.", isError: false); + } + catch (Exception) + { + Show("Speichern fehlgeschlagen.", isError: true); + } + } + + [RelayCommand] + private async Task TestConnectionAsync() + { + var port = SelectedPort ?? string.Empty; + await RunAsync(port, () => _dialer.ProbeAsync(port)); + } + + [RelayCommand] + private async Task TestCallAsync() + { + if (!TelUri.TryParse("tel:" + TestNumber, out var uri)) + { + Show("Bitte eine Rufnummer eingeben.", isError: true); + return; + } + + if (TryCurrentSettings(out var settings)) + { + var number = DialNumber.From(uri, settings); + await RunAsync(settings.PortName, () => _dialer.DialAsync(settings.PortName, number)); + } + } + + [RelayCommand] + [SuppressMessage("Design", "CA1031", Justification = "Whatever the OS refuses surfaces in Status.")] + private async Task MakeDefaultHandlerAsync() + { + try + { + await _registration.MakeDefaultAsync(); + IsDefaultHandler = _registration.IsDefaultHandler(); + Show( + IsDefaultHandler + ? "Wählhilfe öffnet jetzt tel:-Links." + : "Im Systemdialog Wählhilfe für tel:-Links auswählen und danach „Prüfen“ drücken.", + isError: false); + } + catch (Exception) + { + IsDefaultHandler = _registration.IsDefaultHandler(); + Show("Wählhilfe konnte nicht als Standard für tel:-Links eingetragen werden.", isError: true); + } + } + + [RelayCommand] + private void RefreshDefaultHandler() => IsDefaultHandler = _registration.IsDefaultHandler(); + + [SuppressMessage("Design", "CA1031", Justification = "Any failure of the test surfaces in Status.")] + private async Task RunAsync(string port, Func> test) + { + IsBusy = true; + Show("Verbinde …", isError: false); + try + { + var result = await test(); + Show(DialMessages.For(result, port), DialMessages.IsError(result)); + } + catch (Exception) + { + Show("Test fehlgeschlagen. Telefon und Bluetooth prüfen.", isError: true); + } + finally + { + IsBusy = false; + } + } + + private bool TryCurrentSettings([NotNullWhen(true)] out DialSettings? settings) + { + settings = null; + if (!DialSettings.IsValidHomeCountryCode(HomeCountryCode)) + { + Show("Ländervorwahl: eine bis drei Ziffern ohne führende 0, z. B. 49.", isError: true); + return false; + } + + if (!DialSettings.IsValidOutsideLinePrefix(OutsideLinePrefix)) + { + Show("Amtsholung: höchstens vier Ziffern, meist leer oder 0.", isError: true); + return false; + } + + settings = new DialSettings(SelectedPort ?? string.Empty, HomeCountryCode, OutsideLinePrefix); + return true; + } + + private void Show(string status, bool isError) + { + Status = status; + IsError = isError; + } +} diff --git a/src/Waehlhilfe.Domain/DialNumber.cs b/src/Waehlhilfe.Domain/DialNumber.cs new file mode 100644 index 0000000..5f4f3ea --- /dev/null +++ b/src/Waehlhilfe.Domain/DialNumber.cs @@ -0,0 +1,38 @@ +namespace Waehlhilfe.Domain; + +/// The exact string sent after ATD: digits only. +public sealed record DialNumber +{ + private DialNumber(string digits) => Digits = digits; + + public string Digits { get; } + + /// The settings carry an invalid country code or prefix. + public static DialNumber From(TelUri uri, DialSettings settings) + { + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(settings); + if (!DialSettings.IsValidHomeCountryCode(settings.HomeCountryCode)) + { + throw new ArgumentException("The home country code must be one to three digits.", nameof(settings)); + } + + if (!DialSettings.IsValidOutsideLinePrefix(settings.OutsideLinePrefix)) + { + throw new ArgumentException("The outside line prefix must be at most four digits.", nameof(settings)); + } + + var number = uri.Number; + if (uri.IsGlobal) + { + var national = number[1..]; + number = national.StartsWith(settings.HomeCountryCode, StringComparison.Ordinal) + ? "0" + national[settings.HomeCountryCode.Length..] + : "00" + national; + } + + return new DialNumber(settings.OutsideLinePrefix + number); + } + + public override string ToString() => Digits; +} diff --git a/src/Waehlhilfe.Domain/DialSettings.cs b/src/Waehlhilfe.Domain/DialSettings.cs new file mode 100644 index 0000000..35fc50d --- /dev/null +++ b/src/Waehlhilfe.Domain/DialSettings.cs @@ -0,0 +1,18 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Waehlhilfe.Domain; + +/// How numbers are dialled and through which port. +/// Serial port of the phone's Bluetooth SPP service; empty until chosen. +/// Country code that a global number is dialled nationally for. +/// Amtsholung, dialled before every number behind a PBX; usually empty. +public sealed record DialSettings(string PortName, string HomeCountryCode, string OutsideLinePrefix) +{ + public static DialSettings Default { get; } = new(string.Empty, "49", string.Empty); + + public static bool IsValidHomeCountryCode([NotNullWhen(true)] string? code) => + code is { Length: >= 1 and <= 3 } && code[0] != '0' && code.All(char.IsAsciiDigit); + + public static bool IsValidOutsideLinePrefix([NotNullWhen(true)] string? prefix) => + prefix is { Length: <= 4 } && prefix.All(char.IsAsciiDigit); +} diff --git a/src/Waehlhilfe.Domain/TelUri.cs b/src/Waehlhilfe.Domain/TelUri.cs new file mode 100644 index 0000000..5b230b4 --- /dev/null +++ b/src/Waehlhilfe.Domain/TelUri.cs @@ -0,0 +1,110 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text; + +namespace Waehlhilfe.Domain; + +/// +/// A tel: link (RFC 3966) reduced to the number it names. holds only +/// digits, with a leading + for a global number: the link comes from whatever page or +/// document the user clicked, and whatever reaches the phone after ATD is executed by it. +/// That rules out * and # too — on a landline *21*<number># sets up call +/// forwarding at the exchange. +/// +public sealed record TelUri +{ + public const int MaxDigits = 32; + + // Far above any real link; checked before decoding, so a huge argument costs nothing. + private const int MaxLinkLength = 256; + + private const string Scheme = "tel:"; + + private TelUri(string number) => Number = number; + + public string Number { get; } + + public bool IsGlobal => Number.StartsWith('+'); + + public static bool TryParse(string? link, [MaybeNullWhen(false)] out TelUri uri) + { + uri = null; + if (link is null || link.Length > MaxLinkLength) + { + return false; + } + + var text = link.Trim(); + if (!text.StartsWith(Scheme, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + text = text[Scheme.Length..]; + if (text.StartsWith("//", StringComparison.Ordinal)) + { + text = text[2..]; + } + + var separator = text.IndexOf(';', StringComparison.Ordinal); + var numberPart = separator < 0 ? text : text[..separator]; + if (separator >= 0 && !AreParametersClean(text[(separator + 1)..])) + { + return false; + } + + if (!TryClean(Uri.UnescapeDataString(numberPart), out var number)) + { + return false; + } + + uri = new TelUri(number); + return true; + } + + // Parameters (ext, isub, phone-context, …) never reach the phone, but a link carrying a + // control character anywhere is not one a person wrote, so it is refused as a whole. + private static bool AreParametersClean(string parameters) => + !Uri.UnescapeDataString(parameters).Any(char.IsControl); + + private static bool TryClean(string raw, [MaybeNullWhen(false)] out string number) + { + number = null; + var global = raw.StartsWith('+'); + if (global) + { + // "+49 (0)89 …" is how German numbers are often printed; the (0) is not dialled. + raw = raw[1..].Replace("(0)", string.Empty, StringComparison.Ordinal); + } + + var digits = new StringBuilder(raw.Length + 1); + if (global) + { + digits.Append('+'); + } + + foreach (var c in raw) + { + if (char.IsAsciiDigit(c)) + { + digits.Append(c); + } + else if (!IsVisualSeparator(c)) + { + return false; + } + } + + var count = digits.Length - (global ? 1 : 0); + if (count is 0 or > MaxDigits) + { + return false; + } + + number = digits.ToString(); + return true; + } + + // RFC 3966's visual separators, plus the space, no-break space and slash that German + // numbers are printed with ("089 / 1234567"). Never \r, \n or any other control character. + private static bool IsVisualSeparator(char c) => c is '-' or '.' or '(' or ')' or ' ' or ' ' or '/'; +} diff --git a/src/Waehlhilfe.Modem/AtDialer.cs b/src/Waehlhilfe.Modem/AtDialer.cs new file mode 100644 index 0000000..6619d34 --- /dev/null +++ b/src/Waehlhilfe.Modem/AtDialer.cs @@ -0,0 +1,139 @@ +using Waehlhilfe.Domain; + +namespace Waehlhilfe.Modem; + +/// +/// One dial is one connection: open the port, AT, ATD <number>, close. The +/// DL500A keeps the call up on the base once the link is gone, so nothing is held open. +/// +public sealed class AtDialer : IDialer +{ + /// Opening the port opens the Bluetooth link, which takes seconds. + public static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(10); + + public static readonly TimeSpan ResponseTimeout = TimeSpan.FromSeconds(15); + + /// How long to wait for CONNECT after OK before closing anyway. + public static readonly TimeSpan ConnectGrace = TimeSpan.FromSeconds(5); + + private readonly IAtChannelFactory _channels; + private readonly TimeProvider _time; + + public AtDialer(IAtChannelFactory channels, TimeProvider? time = null) + { + ArgumentNullException.ThrowIfNull(channels); + _channels = channels; + _time = time ?? TimeProvider.System; + } + + /// Checks that the phone answers, without placing a call. + public Task ProbeAsync(string portName, CancellationToken cancellationToken = default) => + RunAsync(portName, dial: null, cancellationToken); + + public Task DialAsync(string portName, DialNumber number, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(number); + return RunAsync(portName, number, cancellationToken); + } + + private async Task RunAsync(string portName, DialNumber? dial, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(portName)) + { + return DialResult.PortNotSet; + } + + try + { + using var connect = new CancellationTokenSource(ConnectTimeout, _time); + using var connectOrCancel = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, connect.Token); + await using var channel = await _channels.OpenAsync(portName, connectOrCancel.Token); + + var answer = await CommandAsync(channel, "AT", connectOrCancel.Token); + if (answer != DialResult.Answered || dial is null) + { + return answer; + } + + using var response = new CancellationTokenSource(ResponseTimeout, _time); + using var responseOrCancel = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, response.Token); + var result = await CommandAsync(channel, "ATD " + dial.Digits, responseOrCancel.Token); + if (result == DialResult.Answered) + { + await AwaitConnectAsync(channel, cancellationToken); + return DialResult.Dialled; + } + + return result; + } + catch (PortUnavailableException e) + { + return e.Failure switch + { + PortFailure.Busy => DialResult.PortBusy, + PortFailure.Unreachable => DialResult.NoResponse, + _ => DialResult.PortMissing, + }; + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return DialResult.NoResponse; + } + catch (IOException) + { + // The Bluetooth link went away after the port opened: phone switched off, out of + // range, or the OS dropped the RFCOMM channel. + return DialResult.NoResponse; + } + } + + // Sends one command and reads up to its final result code; OK and CONNECT come back as + // Answered. The echo, blank lines and unsolicited codes (RING, CLIP:…) are skipped. + private static async Task CommandAsync(IAtChannel channel, string command, CancellationToken cancellationToken) + { + await channel.WriteLineAsync(command, cancellationToken); + while (await channel.ReadLineAsync(cancellationToken) is { } line) + { + if (FinalResult(line.Trim()) is { } result) + { + return result; + } + } + + return DialResult.NoResponse; + } + + // After OK the base dials on its own; CONNECT confirms it. Closing earlier would most likely + // be fine too, but waiting a moment costs nothing and keeps the link until it is confirmed. + private async Task AwaitConnectAsync(IAtChannel channel, CancellationToken cancellationToken) + { + using var grace = new CancellationTokenSource(ConnectGrace, _time); + using var graceOrCancel = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, grace.Token); + try + { + while (await channel.ReadLineAsync(graceOrCancel.Token) is { } line) + { + if (FinalResult(line.Trim()) is not null) + { + return; + } + } + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + // The grace period ran out: the call was accepted with OK, so it still counts. + } + } + + private static DialResult? FinalResult(string line) => line switch + { + "OK" => DialResult.Answered, + "ERROR" => DialResult.Rejected, + "BUSY" => DialResult.LineBusy, + "NO CARRIER" or "NO ANSWER" => DialResult.NoCarrier, + "NO DIALTONE" => DialResult.NoDialTone, + _ when line.StartsWith("CONNECT", StringComparison.Ordinal) => DialResult.Answered, + _ when line.StartsWith("+CME ERROR", StringComparison.Ordinal) => DialResult.Rejected, + _ => null, + }; +} diff --git a/src/Waehlhilfe.Modem/DialResult.cs b/src/Waehlhilfe.Modem/DialResult.cs new file mode 100644 index 0000000..0336498 --- /dev/null +++ b/src/Waehlhilfe.Modem/DialResult.cs @@ -0,0 +1,32 @@ +namespace Waehlhilfe.Modem; + +public enum DialResult +{ + /// The phone accepted ATD and is setting up the call. + Dialled, + + /// The phone answered AT; returned by a probe only. + Answered, + + /// No port has been chosen yet. + PortNotSet, + + PortMissing, + + PortBusy, + + /// + /// The port opened but the phone never answered. With a DL500A this is what an audio + /// (Hands-Free) connection to the same PC does to the serial port. + /// + NoResponse, + + /// ERROR or +CME ERROR. + Rejected, + + LineBusy, + + NoCarrier, + + NoDialTone, +} diff --git a/src/Waehlhilfe.Modem/IAtChannel.cs b/src/Waehlhilfe.Modem/IAtChannel.cs new file mode 100644 index 0000000..49caaed --- /dev/null +++ b/src/Waehlhilfe.Modem/IAtChannel.cs @@ -0,0 +1,16 @@ +namespace Waehlhilfe.Modem; + +/// A line-oriented connection to the phone's AT command interpreter. +public interface IAtChannel : IAsyncDisposable +{ + Task WriteLineAsync(string line, CancellationToken cancellationToken = default); + + /// The next line without its terminator, or null once the link has dropped. + Task ReadLineAsync(CancellationToken cancellationToken = default); +} + +public interface IAtChannelFactory +{ + /// The port does not exist or another program holds it. + Task OpenAsync(string portName, CancellationToken cancellationToken = default); +} diff --git a/src/Waehlhilfe.Modem/IDialer.cs b/src/Waehlhilfe.Modem/IDialer.cs new file mode 100644 index 0000000..6d8dcd2 --- /dev/null +++ b/src/Waehlhilfe.Modem/IDialer.cs @@ -0,0 +1,11 @@ +using Waehlhilfe.Domain; + +namespace Waehlhilfe.Modem; + +public interface IDialer +{ + Task DialAsync(string portName, DialNumber number, CancellationToken cancellationToken = default); + + /// Checks that the phone answers, without placing a call. + Task ProbeAsync(string portName, CancellationToken cancellationToken = default); +} diff --git a/src/Waehlhilfe.Modem/PortUnavailableException.cs b/src/Waehlhilfe.Modem/PortUnavailableException.cs new file mode 100644 index 0000000..02fde82 --- /dev/null +++ b/src/Waehlhilfe.Modem/PortUnavailableException.cs @@ -0,0 +1,41 @@ +namespace Waehlhilfe.Modem; + +public enum PortFailure +{ + /// No such port: the phone is not paired, or the port name is stale. + Missing, + + /// Another program, or another dial still in progress, holds the port. + Busy, + + /// The port exists but the link behind it did not come up: the phone is off or out of range. + Unreachable, +} + +public sealed class PortUnavailableException : Exception +{ + public PortUnavailableException() + { + } + + public PortUnavailableException(string message) + : base(message) + { + } + + public PortUnavailableException(string message, Exception innerException) + : base(message, innerException) + { + } + + public PortUnavailableException(string portName, PortFailure failure, Exception? innerException = null) + : base($"Port {portName} is unavailable: {failure}.", innerException) + { + PortName = portName; + Failure = failure; + } + + public string PortName { get; } = string.Empty; + + public PortFailure Failure { get; } +} diff --git a/src/Waehlhilfe.Modem/SerialPorts.cs b/src/Waehlhilfe.Modem/SerialPorts.cs new file mode 100644 index 0000000..9423d31 --- /dev/null +++ b/src/Waehlhilfe.Modem/SerialPorts.cs @@ -0,0 +1,95 @@ +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO.Ports; + +namespace Waehlhilfe.Modem; + +/// +/// The phone's Bluetooth SPP service as the OS exposes it: an outgoing COM port on Windows, +/// /dev/cu.* on macOS, /dev/rfcomm* (after rfcomm bind) on Linux. Opening +/// the port is what makes the OS bring up the RFCOMM link. +/// +public sealed class SerialPorts : IAtChannelFactory +{ + private const int BaudRate = 115200; + + public static IReadOnlyList List() + { + IEnumerable names = SerialPort.GetPortNames(); + if (OperatingSystem.IsMacOS()) + { + names = names.Concat(Directory.EnumerateFiles("/dev", "cu.*")); + } + else if (OperatingSystem.IsLinux()) + { + names = names.Concat(Directory.EnumerateFiles("/dev", "rfcomm*")); + } + + return Filter(names, OperatingSystem.IsMacOS()); + } + + internal static IReadOnlyList Filter(IEnumerable names, bool isMacOS) + { + var ports = names.Distinct(StringComparer.Ordinal); + if (isMacOS) + { + // The callout device (cu.*) opens without waiting for carrier detect; the tty.* twin + // blocks. The two built-in ports are never a phone. + ports = ports.Where(p => p.StartsWith("/dev/cu.", StringComparison.Ordinal) + && !p.EndsWith("Bluetooth-Incoming-Port", StringComparison.Ordinal) + && !p.EndsWith("debug-console", StringComparison.Ordinal)); + } + + return [.. ports + .OrderBy(p => p.Contains("rfcomm", StringComparison.Ordinal) ? 0 : 1) + .ThenBy(p => p.TrimEnd("0123456789".ToCharArray()), StringComparer.Ordinal) + .ThenBy(TrailingNumber)]; + } + + /// Why the port did not open, or null for an exception that is not about the port. + internal static PortFailure? Classify(Exception error) => error switch + { + FileNotFoundException or ArgumentException => PortFailure.Missing, + UnauthorizedAccessException => PortFailure.Busy, + IOException or TimeoutException => PortFailure.Unreachable, + _ => null, + }; + + [SuppressMessage("Reliability", "CA2000", Justification = "Ownership of the port passes to the returned channel, or it is disposed here when opening fails.")] + public async Task OpenAsync(string portName, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(portName); + var port = new SerialPort(portName, BaudRate) + { + DtrEnable = true, + RtsEnable = true, + WriteTimeout = (int)AtDialer.ConnectTimeout.TotalMilliseconds, + }; + + // Open blocks while the OS sets up the Bluetooth link, so it runs off the caller's + // thread. If the caller gives up first, the port is closed once Open has returned. + var open = Task.Run(port.Open, CancellationToken.None); + try + { + await open.WaitAsync(cancellationToken); + } + catch (OperationCanceledException) + { + _ = open.ContinueWith(_ => port.Dispose(), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); + throw; + } + catch (Exception e) when (Classify(e) is { } failure) + { + port.Dispose(); + throw new PortUnavailableException(portName, failure, e); + } + + return new StreamAtChannel(port.BaseStream, port); + } + + private static int TrailingNumber(string name) + { + var digits = name[name.TrimEnd("0123456789".ToCharArray()).Length..]; + return digits.Length == 0 ? 0 : int.Parse(digits, CultureInfo.InvariantCulture); + } +} diff --git a/src/Waehlhilfe.Modem/StreamAtChannel.cs b/src/Waehlhilfe.Modem/StreamAtChannel.cs new file mode 100644 index 0000000..df860ce --- /dev/null +++ b/src/Waehlhilfe.Modem/StreamAtChannel.cs @@ -0,0 +1,48 @@ +using System.Text; + +namespace Waehlhilfe.Modem; + +/// AT lines over a byte stream: commands end in CR LF, answers end in CR, LF or both. +public sealed class StreamAtChannel : IAtChannel +{ + private readonly Stream _stream; + private readonly IDisposable? _owner; + private readonly StreamReader _reader; + + /// The connection to the phone. + /// What else to dispose with the channel, such as the serial port. + public StreamAtChannel(Stream stream, IDisposable? owner = null) + { + ArgumentNullException.ThrowIfNull(stream); + _stream = stream; + _owner = owner; + _reader = new StreamReader(stream, Encoding.ASCII, detectEncodingFromByteOrderMarks: false, leaveOpen: true); + } + + public async Task WriteLineAsync(string line, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(line); + + // Defence in depth behind TelUri: a second line here would be a second AT command. + if (!line.All(c => c is >= ' ' and <= '~')) + { + throw new ArgumentException("An AT command is one line of printable ASCII.", nameof(line)); + } + + var bytes = Encoding.ASCII.GetBytes(line + "\r\n"); + await _stream.WriteAsync(bytes, cancellationToken); + await _stream.FlushAsync(cancellationToken); + } + + // WaitAsync on top: a serial stream does not always honour cancellation of a pending read, + // and the dialer's timeouts must hold regardless. Disposing the port ends the read. + public async Task ReadLineAsync(CancellationToken cancellationToken = default) => + await _reader.ReadLineAsync(cancellationToken).AsTask().WaitAsync(cancellationToken); + + public async ValueTask DisposeAsync() + { + _reader.Dispose(); + await _stream.DisposeAsync(); + _owner?.Dispose(); + } +} diff --git a/tests/Waehlhilfe.AppLogic.Tests/DialMessagesTests.cs b/tests/Waehlhilfe.AppLogic.Tests/DialMessagesTests.cs new file mode 100644 index 0000000..a75483e --- /dev/null +++ b/tests/Waehlhilfe.AppLogic.Tests/DialMessagesTests.cs @@ -0,0 +1,39 @@ +using Waehlhilfe.Modem; + +namespace Waehlhilfe.AppLogic.Tests; + +public sealed class DialMessagesTests +{ + [Fact] + public void Every_result_has_a_german_message() + { + foreach (var result in Enum.GetValues()) + { + Assert.False(string.IsNullOrWhiteSpace(DialMessages.For(result, "COM7"))); + } + } + + [Fact] + public void No_response_names_the_audio_connection_trap() + { + Assert.Contains("Audiogerät", DialMessages.For(DialResult.NoResponse, "COM7"), StringComparison.Ordinal); + } + + [Theory] + [InlineData(DialResult.PortMissing)] + [InlineData(DialResult.PortBusy)] + public void Port_failures_name_the_port(DialResult result) + { + Assert.Contains("COM7", DialMessages.For(result, "COM7"), StringComparison.Ordinal); + } + + [Theory] + [InlineData(DialResult.Dialled, false)] + [InlineData(DialResult.Answered, false)] + [InlineData(DialResult.NoResponse, true)] + [InlineData(DialResult.LineBusy, true)] + public void Tells_success_from_failure(DialResult result, bool isError) + { + Assert.Equal(isError, DialMessages.IsError(result)); + } +} diff --git a/tests/Waehlhilfe.AppLogic.Tests/DialViewModelTests.cs b/tests/Waehlhilfe.AppLogic.Tests/DialViewModelTests.cs new file mode 100644 index 0000000..2c0744e --- /dev/null +++ b/tests/Waehlhilfe.AppLogic.Tests/DialViewModelTests.cs @@ -0,0 +1,197 @@ +using Microsoft.Extensions.Time.Testing; +using Waehlhilfe.AppLogic.ViewModels; +using Waehlhilfe.Domain; +using Waehlhilfe.Modem; + +namespace Waehlhilfe.AppLogic.Tests; + +public sealed class DialViewModelTests +{ + private static readonly DialSettings Settings = DialSettings.Default with { PortName = "COM7" }; + + private readonly FakeDialer _dialer = new(); + private readonly FakeTimeProvider _time = new(); + + private DialViewModel ViewModel(string link, DialSettings? settings = null) + { + var vm = new DialViewModel(link, settings ?? Settings, _dialer, _time); + _time.Advance(DialViewModel.ArmDelay); + return vm; + } + + // A tel: link can arrive while the Lagebuchführer is typing elsewhere. The window comes to + // the front and takes focus, so an Enter meant for another program would confirm the call. + [Fact] + public async Task Ignores_a_confirm_that_arrives_before_the_window_is_armed() + { + var vm = new DialViewModel("tel:0891234567", Settings, _dialer, _time); + + Assert.False(vm.DialCommand.CanExecute(null)); + await vm.DialCommand.ExecuteAsync(null); + _time.Advance(DialViewModel.ArmDelay - TimeSpan.FromMilliseconds(1)); + await vm.DialCommand.ExecuteAsync(null); + + Assert.Empty(_dialer.Dialled); + } + + [Fact] + public async Task Dials_once_armed() + { + var vm = new DialViewModel("tel:0891234567", Settings, _dialer, _time); + var changed = 0; + vm.DialCommand.CanExecuteChanged += (_, _) => changed++; + + _time.Advance(DialViewModel.ArmDelay); + await vm.DialCommand.ExecuteAsync(null); + + Assert.True(changed > 0); + Assert.Single(_dialer.Dialled); + } + + [Fact] + public void Shows_the_number_that_will_be_dialled() + { + var vm = ViewModel("tel:+49 89 1234567"); + + Assert.Equal("0891234567", vm.Number); + Assert.True(vm.CanDial); + Assert.True(vm.DialCommand.CanExecute(null)); + } + + [Fact] + public void Does_not_dial_until_confirmed() + { + _ = ViewModel("tel:0891234567"); + + Assert.Empty(_dialer.Dialled); + } + + [Fact] + public async Task Dials_on_the_configured_port_when_confirmed() + { + var vm = ViewModel("tel:0891234567"); + + await vm.DialCommand.ExecuteAsync(null); + + Assert.Equal([("COM7", "0891234567")], _dialer.Dialled); + Assert.Equal("Gewählt. Gespräch am Telefon führen.", vm.Status); + Assert.False(vm.IsError); + } + + [Fact] + public async Task Closes_itself_a_moment_after_dialling() + { + var vm = ViewModel("tel:0891234567"); + var closed = 0; + vm.CloseRequested += (_, _) => closed++; + + await vm.DialCommand.ExecuteAsync(null); + Assert.Equal(0, closed); + _time.Advance(DialViewModel.CloseDelay); + + Assert.Equal(1, closed); + } + + [Fact] + public async Task Stays_open_and_shows_why_when_dialling_failed() + { + _dialer.Result = DialResult.NoResponse; + var vm = ViewModel("tel:0891234567"); + var closed = 0; + vm.CloseRequested += (_, _) => closed++; + + await vm.DialCommand.ExecuteAsync(null); + _time.Advance(DialViewModel.CloseDelay); + + Assert.Equal(0, closed); + Assert.True(vm.IsError); + Assert.Equal(DialMessages.For(DialResult.NoResponse, "COM7"), vm.Status); + Assert.True(vm.DialCommand.CanExecute(null)); + } + + [Fact] + public async Task Cannot_dial_twice_while_a_dial_is_running() + { + _dialer.Hold(); + var vm = ViewModel("tel:0891234567"); + + var dial = vm.DialCommand.ExecuteAsync(null); + + Assert.True(vm.IsBusy); + Assert.Equal("Wähle …", vm.Status); + Assert.False(vm.DialCommand.CanExecute(null)); + _dialer.Complete(DialResult.Dialled); + await dial; + Assert.False(vm.IsBusy); + } + + [Fact] + public void Cancel_closes_without_dialling() + { + var vm = ViewModel("tel:0891234567"); + var closed = 0; + vm.CloseRequested += (_, _) => closed++; + + vm.CancelCommand.Execute(null); + + Assert.Equal(1, closed); + Assert.Empty(_dialer.Dialled); + } + + [Fact] + public async Task Cancel_during_a_dial_stops_it() + { + _dialer.Hold(); + var vm = ViewModel("tel:0891234567"); + var dial = vm.DialCommand.ExecuteAsync(null); + + vm.CancelCommand.Execute(null); + await dial; + + Assert.True(_dialer.LastToken.IsCancellationRequested); + Assert.False(vm.IsBusy); + } + + [Theory] + [InlineData("tel:0891234567%0D%0AATH")] + [InlineData("tel:*21*015112345678%23")] + [InlineData("mailto:someone@example.org")] + [InlineData("")] + public async Task Never_dials_a_link_that_is_not_a_plain_number(string link) + { + var vm = ViewModel(link); + + Assert.False(vm.CanDial); + Assert.False(vm.DialCommand.CanExecute(null)); + Assert.True(vm.IsError); + Assert.Equal("Kein gültiger tel:-Link – es wird nicht gewählt.", vm.Status); + await vm.DialCommand.ExecuteAsync(null); + Assert.Empty(_dialer.Dialled); + } + + [Fact] + public void Shows_no_number_for_a_rejected_link() + { + var vm = ViewModel("tel:0891234567%0D%0AATH"); + + Assert.Equal(string.Empty, vm.Number); + } + + [Fact] + public void Says_where_to_set_the_phone_up_when_no_port_is_chosen() + { + var vm = ViewModel("tel:0891234567", DialSettings.Default); + + Assert.False(vm.CanDial); + Assert.True(vm.IsError); + Assert.Equal(DialMessages.For(DialResult.PortNotSet, string.Empty), vm.Status); + } + + [Fact] + public void Applies_the_outside_line_prefix_to_the_shown_number() + { + var vm = ViewModel("tel:0891234567", Settings with { OutsideLinePrefix = "0" }); + + Assert.Equal("00891234567", vm.Number); + } +} diff --git a/tests/Waehlhilfe.AppLogic.Tests/FakeDialer.cs b/tests/Waehlhilfe.AppLogic.Tests/FakeDialer.cs new file mode 100644 index 0000000..8dbab53 --- /dev/null +++ b/tests/Waehlhilfe.AppLogic.Tests/FakeDialer.cs @@ -0,0 +1,80 @@ +using Waehlhilfe.Domain; +using Waehlhilfe.Modem; + +namespace Waehlhilfe.AppLogic.Tests; + +internal sealed class FakeDialer : IDialer +{ + private TaskCompletionSource? _pending; + + public DialResult Result { get; set; } = DialResult.Dialled; + + public List<(string Port, string Digits)> Dialled { get; } = []; + + public List Probed { get; } = []; + + public CancellationToken LastToken { get; private set; } + + /// Makes the next dial or probe wait until . + public void Hold() => _pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + public void Complete(DialResult result) => _pending?.TrySetResult(result); + + public Task DialAsync(string portName, DialNumber number, CancellationToken cancellationToken = default) + { + Dialled.Add((portName, number.Digits)); + return ResultAsync(cancellationToken); + } + + public Task ProbeAsync(string portName, CancellationToken cancellationToken = default) + { + Probed.Add(portName); + return ResultAsync(cancellationToken); + } + + private Task ResultAsync(CancellationToken cancellationToken) + { + LastToken = cancellationToken; + return _pending is null ? Task.FromResult(Result) : _pending.Task.WaitAsync(cancellationToken); + } +} + +internal sealed class FakeSettingsStore(DialSettings settings) : ISettingsStore +{ + public DialSettings Stored { get; private set; } = settings; + + public int Saves { get; private set; } + + public DialSettings Load() => Stored; + + public void Save(DialSettings settings) + { + Stored = settings; + Saves++; + } +} + +internal sealed class FakeRegistration : ITelHandlerRegistration +{ + public bool IsDefault { get; set; } + + public bool BecomesDefault { get; set; } = true; + + public Exception? Failure { get; set; } + + public int Requests { get; private set; } + + public bool IsDefaultHandler() => IsDefault; + + public Task MakeDefaultAsync(CancellationToken cancellationToken = default) + { + Requests++; + if (Failure is not null) + { + throw Failure; + } + + IsDefault = BecomesDefault; + return Task.CompletedTask; + } +} diff --git a/tests/Waehlhilfe.AppLogic.Tests/JsonSettingsStoreTests.cs b/tests/Waehlhilfe.AppLogic.Tests/JsonSettingsStoreTests.cs new file mode 100644 index 0000000..9c4b38e --- /dev/null +++ b/tests/Waehlhilfe.AppLogic.Tests/JsonSettingsStoreTests.cs @@ -0,0 +1,63 @@ +using Waehlhilfe.Domain; + +namespace Waehlhilfe.AppLogic.Tests; + +public sealed class JsonSettingsStoreTests : IDisposable +{ + private readonly string _directory = Path.Join(Path.GetTempPath(), "waehlhilfe-tests-" + Guid.NewGuid().ToString("N")); + + private string File => Path.Join(_directory, "settings.json"); + + public void Dispose() + { + if (Directory.Exists(_directory)) + { + Directory.Delete(_directory, recursive: true); + } + } + + [Fact] + public void Starts_from_the_defaults_when_nothing_was_saved() + { + Assert.Equal(DialSettings.Default, new JsonSettingsStore(File).Load()); + } + + [Fact] + public void Round_trips_saved_settings() + { + var settings = new DialSettings("/dev/cu.DL500A", "43", "0"); + + new JsonSettingsStore(File).Save(settings); + + Assert.Equal(settings, new JsonSettingsStore(File).Load()); + } + + [Fact] + public void Falls_back_to_the_defaults_for_a_damaged_file() + { + Directory.CreateDirectory(_directory); + System.IO.File.WriteAllText(File, "{ not json"); + + Assert.Equal(DialSettings.Default, new JsonSettingsStore(File).Load()); + } + + // The file is plain JSON in the user's profile; a value edited by hand must not get past + // the rules the settings window enforces. + [Fact] + public void Drops_hand_edited_values_the_settings_window_would_refuse() + { + Directory.CreateDirectory(_directory); + System.IO.File.WriteAllText(File, """{ "portName": "COM7", "homeCountryCode": "4;", "outsideLinePrefix": "*21*" }"""); + + Assert.Equal(DialSettings.Default with { PortName = "COM7" }, new JsonSettingsStore(File).Load()); + } + + [Fact] + public void Ignores_an_oversized_file() + { + Directory.CreateDirectory(_directory); + System.IO.File.WriteAllText(File, """{ "portName": "COM7" }""" + new string(' ', JsonSettingsStore.MaxFileBytes)); + + Assert.Equal(DialSettings.Default, new JsonSettingsStore(File).Load()); + } +} diff --git a/tests/Waehlhilfe.AppLogic.Tests/SettingsViewModelTests.cs b/tests/Waehlhilfe.AppLogic.Tests/SettingsViewModelTests.cs new file mode 100644 index 0000000..d207141 --- /dev/null +++ b/tests/Waehlhilfe.AppLogic.Tests/SettingsViewModelTests.cs @@ -0,0 +1,172 @@ +using Waehlhilfe.AppLogic.ViewModels; +using Waehlhilfe.Domain; +using Waehlhilfe.Modem; + +namespace Waehlhilfe.AppLogic.Tests; + +public sealed class SettingsViewModelTests +{ + private readonly FakeDialer _dialer = new(); + private readonly FakeRegistration _registration = new(); + private readonly FakeSettingsStore _store = new(DialSettings.Default with { PortName = "COM7" }); + private IReadOnlyList _ports = ["COM3", "COM7"]; + + private SettingsViewModel ViewModel() => new(_store, _dialer, () => _ports, _registration); + + [Fact] + public void Shows_the_stored_settings() + { + var vm = ViewModel(); + + Assert.Equal(["COM3", "COM7"], vm.Ports); + Assert.Equal("COM7", vm.SelectedPort); + Assert.Equal("49", vm.HomeCountryCode); + Assert.Equal(string.Empty, vm.OutsideLinePrefix); + } + + [Fact] + public void Keeps_showing_a_stored_port_that_is_not_present_now() + { + _ports = ["COM3"]; + + var vm = ViewModel(); + + Assert.Equal("COM7", vm.SelectedPort); + Assert.Contains("COM7", vm.Ports); + } + + [Fact] + public void Picks_up_ports_that_appeared_after_pairing() + { + var vm = ViewModel(); + _ports = ["COM3", "COM7", "COM9"]; + + vm.RefreshPortsCommand.Execute(null); + + Assert.Equal(["COM3", "COM7", "COM9"], vm.Ports); + Assert.Equal("COM7", vm.SelectedPort); + } + + [Fact] + public void Saves_valid_settings() + { + var vm = ViewModel(); + vm.SelectedPort = "COM3"; + vm.HomeCountryCode = "43"; + vm.OutsideLinePrefix = "0"; + + vm.SaveCommand.Execute(null); + + Assert.Equal(new DialSettings("COM3", "43", "0"), _store.Stored); + Assert.Equal("Gespeichert.", vm.Status); + Assert.False(vm.IsError); + } + + [Theory] + [InlineData("4;", "")] + [InlineData("49", "0;ATH")] + [InlineData("", "")] + [InlineData("49", "*21*")] + public void Refuses_to_save_invalid_settings(string country, string prefix) + { + var vm = ViewModel(); + vm.HomeCountryCode = country; + vm.OutsideLinePrefix = prefix; + + vm.SaveCommand.Execute(null); + + Assert.Equal(0, _store.Saves); + Assert.True(vm.IsError); + } + + [Fact] + public async Task Test_connection_only_probes() + { + var vm = ViewModel(); + _dialer.Result = DialResult.Answered; + + await vm.TestConnectionCommand.ExecuteAsync(null); + + Assert.Equal(["COM7"], _dialer.Probed); + Assert.Empty(_dialer.Dialled); + Assert.Equal("Telefon antwortet. Alles bereit.", vm.Status); + } + + [Fact] + public async Task Test_connection_uses_the_port_shown_even_before_saving() + { + var vm = ViewModel(); + vm.SelectedPort = "COM3"; + + await vm.TestConnectionCommand.ExecuteAsync(null); + + Assert.Equal(["COM3"], _dialer.Probed); + } + + [Fact] + public async Task Test_call_dials_the_entered_number_with_the_shown_settings() + { + var vm = ViewModel(); + vm.OutsideLinePrefix = "0"; + vm.TestNumber = "0151 1234567"; + + await vm.TestCallCommand.ExecuteAsync(null); + + Assert.Equal([("COM7", "001511234567")], _dialer.Dialled); + Assert.Equal(DialMessages.For(DialResult.Dialled, "COM7"), vm.Status); + } + + [Theory] + [InlineData("")] + [InlineData("abc")] + [InlineData("*21*0151#")] + public async Task Test_call_refuses_what_is_not_a_number(string number) + { + var vm = ViewModel(); + vm.TestNumber = number; + + await vm.TestCallCommand.ExecuteAsync(null); + + Assert.Empty(_dialer.Dialled); + Assert.True(vm.IsError); + Assert.Equal("Bitte eine Rufnummer eingeben.", vm.Status); + } + + [Fact] + public async Task Makes_waehlhilfe_the_tel_handler() + { + var vm = ViewModel(); + Assert.False(vm.IsDefaultHandler); + + await vm.MakeDefaultHandlerCommand.ExecuteAsync(null); + + Assert.Equal(1, _registration.Requests); + Assert.True(vm.IsDefaultHandler); + } + + [Fact] + public async Task Reports_when_the_os_did_not_make_it_the_handler() + { + _registration.Failure = new InvalidOperationException("denied"); + var vm = ViewModel(); + + await vm.MakeDefaultHandlerCommand.ExecuteAsync(null); + + Assert.True(vm.IsError); + Assert.False(vm.IsDefaultHandler); + Assert.Equal("Wählhilfe konnte nicht als Standard für tel:-Links eingetragen werden.", vm.Status); + } + + [Fact] + public async Task Re_reads_the_handler_state_after_the_user_returns_from_the_os_dialog() + { + _registration.BecomesDefault = false; + var vm = ViewModel(); + + await vm.MakeDefaultHandlerCommand.ExecuteAsync(null); + _registration.IsDefault = true; + vm.RefreshDefaultHandlerCommand.Execute(null); + + Assert.True(vm.IsDefaultHandler); + } +} diff --git a/tests/Waehlhilfe.Domain.Tests/DialNumberTests.cs b/tests/Waehlhilfe.Domain.Tests/DialNumberTests.cs new file mode 100644 index 0000000..81bc38d --- /dev/null +++ b/tests/Waehlhilfe.Domain.Tests/DialNumberTests.cs @@ -0,0 +1,82 @@ +namespace Waehlhilfe.Domain.Tests; + +public sealed class DialNumberTests +{ + private static readonly DialSettings Germany = DialSettings.Default; + + private static DialNumber Dial(string link, DialSettings settings) + { + Assert.True(TelUri.TryParse(link, out var uri)); + return DialNumber.From(uri, settings); + } + + [Fact] + public void Dials_a_national_number_as_written() + { + Assert.Equal("0891234567", Dial("tel:0891234567", Germany).Digits); + } + + [Fact] + public void Turns_plus_49_into_a_leading_zero() + { + Assert.Equal("0891234567", Dial("tel:+49891234567", Germany).Digits); + } + + [Fact] + public void Turns_a_foreign_plus_into_double_zero() + { + Assert.Equal("0043121234", Dial("tel:+43121234", Germany).Digits); + } + + [Fact] + public void Uses_the_configured_home_country() + { + var austria = Germany with { HomeCountryCode = "43" }; + + Assert.Equal("0121234", Dial("tel:+43121234", austria).Digits); + Assert.Equal("0049891234567", Dial("tel:+49891234567", austria).Digits); + } + + [Fact] + public void Prepends_the_outside_line_prefix() + { + var behindPbx = Germany with { OutsideLinePrefix = "0" }; + + Assert.Equal("00891234567", Dial("tel:0891234567", behindPbx).Digits); + Assert.Equal("00891234567", Dial("tel:+49891234567", behindPbx).Digits); + } + + [Theory] + [InlineData("0;ATH")] + [InlineData("0\r")] + [InlineData("12345")] + [InlineData("a")] + [InlineData("*")] + [InlineData("#")] + public void Refuses_an_outside_line_prefix_that_is_not_up_to_four_digits(string prefix) + { + Assert.False(DialSettings.IsValidOutsideLinePrefix(prefix)); + Assert.Throws(() => Dial("tel:0891234567", Germany with { OutsideLinePrefix = prefix })); + } + + [Theory] + [InlineData("")] + [InlineData("0")] + [InlineData("04")] + [InlineData("1234")] + [InlineData("+49")] + [InlineData("4;")] + public void Refuses_a_home_country_code_that_is_not_one_to_three_digits(string code) + { + Assert.False(DialSettings.IsValidHomeCountryCode(code)); + Assert.Throws(() => Dial("tel:+49891234567", Germany with { HomeCountryCode = code })); + } + + [Fact] + public void Default_settings_are_for_germany_without_an_outside_line() + { + Assert.Equal("49", DialSettings.Default.HomeCountryCode); + Assert.Equal(string.Empty, DialSettings.Default.OutsideLinePrefix); + Assert.Equal(string.Empty, DialSettings.Default.PortName); + } +} diff --git a/tests/Waehlhilfe.Domain.Tests/TelUriTests.cs b/tests/Waehlhilfe.Domain.Tests/TelUriTests.cs new file mode 100644 index 0000000..c6d4555 --- /dev/null +++ b/tests/Waehlhilfe.Domain.Tests/TelUriTests.cs @@ -0,0 +1,137 @@ +namespace Waehlhilfe.Domain.Tests; + +public sealed class TelUriTests +{ + [Theory] + [InlineData("tel:0891234567", "0891234567")] + [InlineData("TEL:0891234567", "0891234567")] + [InlineData(" tel:0891234567 ", "0891234567")] + [InlineData("tel://0891234567", "0891234567")] + public void Parses_a_plain_tel_link(string link, string expected) + { + Assert.True(TelUri.TryParse(link, out var uri)); + Assert.Equal(expected, uri.Number); + Assert.False(uri.IsGlobal); + } + + [Theory] + [InlineData("tel:089-123-4567")] + [InlineData("tel:089.123.4567")] + [InlineData("tel:(089) 1234567")] + [InlineData("tel:089%201234567")] + [InlineData("tel:089 / 1234567")] + [InlineData("tel:089 1234567")] + public void Drops_visual_separators(string link) + { + Assert.True(TelUri.TryParse(link, out var uri)); + Assert.Equal("0891234567", uri.Number); + } + + [Theory] + [InlineData("tel:+49891234567", "+49891234567")] + [InlineData("tel:+49-89-1234567", "+49891234567")] + [InlineData("tel:%2B49891234567", "+49891234567")] + public void Parses_a_global_number(string link, string expected) + { + Assert.True(TelUri.TryParse(link, out var uri)); + Assert.Equal(expected, uri.Number); + Assert.True(uri.IsGlobal); + } + + [Fact] + public void Drops_the_bracketed_zero_of_a_global_number() + { + Assert.True(TelUri.TryParse("tel:+49 (0)89 1234567", out var uri)); + Assert.Equal("+49891234567", uri.Number); + } + + [Theory] + [InlineData("tel:0891234567;ext=12")] + [InlineData("tel:0891234567;isub=12")] + [InlineData("tel:0891234567;phone-context=+49")] + public void Keeps_parameters_off_the_number(string link) + { + Assert.True(TelUri.TryParse(link, out var uri)); + Assert.Equal("0891234567", uri.Number); + } + + // On a landline a code such as *21*# sets up call forwarding at the exchange: a + // link carrying one would divert every call to the Feuerwehr's line to a number of its + // choosing, behind a confirm window that shows something that looks like a number. + [Theory] + [InlineData("tel:*21*015112345678%23")] + [InlineData("tel:%2A21%2A015112345678%23")] + [InlineData("tel:##002#")] + [InlineData("tel:*31#0891234567")] + [InlineData("tel:0891234567#")] + [InlineData("tel:089*1234567")] + public void Rejects_a_service_code_that_would_reconfigure_the_line(string link) + { + Assert.False(TelUri.TryParse(link, out _)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("tel:")] + [InlineData("tel:+")] + [InlineData("0891234567")] + [InlineData("mailto:0891234567")] + [InlineData("https://example.org/?tel:0891234567")] + [InlineData("tel:089abc")] + [InlineData("tel:+49*31")] + [InlineData("tel:08+91234567")] + public void Rejects_what_is_not_a_dialable_tel_link(string? link) + { + Assert.False(TelUri.TryParse(link, out var uri)); + Assert.Null(uri); + } + + // A tel: link is produced by whatever web page or document the user clicked. Anything that + // reaches the phone after `ATD` is executed by it, so a smuggled line break or semicolon + // would let a link run AT commands of its own. + [Theory] + [InlineData("tel:0891234567%0D%0AATH")] + [InlineData("tel:0891234567%0AATZ")] + [InlineData("tel:0891234567\r\nATH")] + [InlineData("tel:0891234567%0D")] + [InlineData("tel:0891234567%00")] + public void Rejects_a_line_break_smuggled_in_by_percent_encoding(string link) + { + Assert.False(TelUri.TryParse(link, out _)); + } + + [Theory] + [InlineData("tel:0891234567%3BATH")] + [InlineData("tel:0891234567%3B")] + public void Rejects_a_semicolon_command(string link) + { + Assert.False(TelUri.TryParse(link, out _)); + } + + [Theory] + [InlineData("tel:0891234567;ext=1%0D%0AATH")] + [InlineData("tel:0891234567;foo\nbar")] + public void Rejects_a_line_break_in_a_parameter(string link) + { + Assert.False(TelUri.TryParse(link, out _)); + } + + [Fact] + public void Accepts_thirty_two_digits() + { + Assert.True(TelUri.TryParse("tel:+" + new string('1', 32), out _)); + } + + [Fact] + public void Rejects_more_than_thirty_two_digits() + { + Assert.False(TelUri.TryParse("tel:" + new string('1', 33), out _)); + } + + [Fact] + public void Rejects_an_oversized_link_before_decoding_it() + { + Assert.False(TelUri.TryParse("tel:1" + new string('-', 10_000), out _)); + } +} diff --git a/tests/Waehlhilfe.Modem.Tests/AtDialerTests.cs b/tests/Waehlhilfe.Modem.Tests/AtDialerTests.cs new file mode 100644 index 0000000..19c30cb --- /dev/null +++ b/tests/Waehlhilfe.Modem.Tests/AtDialerTests.cs @@ -0,0 +1,235 @@ +using Microsoft.Extensions.Time.Testing; +using Waehlhilfe.Domain; + +namespace Waehlhilfe.Modem.Tests; + +public sealed class AtDialerTests +{ + private const string Port = "COM7"; + + private readonly FakeTimeProvider _time = new(); + + private static DialNumber Number(string link = "tel:0891234567") + { + Assert.True(TelUri.TryParse(link, out var uri)); + return DialNumber.From(uri, DialSettings.Default); + } + + private AtDialer Dialer(IAtChannel channel) => new(new FakeChannelFactory(channel), _time); + + [Fact] + public async Task Dials_the_number_the_way_the_dl500a_answered_it() + { + var phone = ScriptedAtChannel.Dl500a(); + + var result = await Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + + Assert.Equal(DialResult.Dialled, result); + Assert.Equal(["AT", "ATD 0891234567"], phone.Written); + } + + [Fact] + public async Task Opens_the_configured_port() + { + var factory = new FakeChannelFactory(ScriptedAtChannel.Dl500a()); + + await new AtDialer(factory, _time).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + + Assert.Equal([Port], factory.Opened); + } + + [Fact] + public async Task Closes_the_port_after_dialling() + { + var phone = ScriptedAtChannel.Dl500a(); + + await Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + + Assert.True(phone.IsDisposed); + } + + [Fact] + public async Task Counts_the_call_as_dialled_when_connect_never_follows_ok() + { + var phone = new ScriptedAtChannel().Answer("AT", "OK").Answer("ATD 0891234567", "OK"); + + var dial = Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + _time.Advance(AtDialer.ConnectGrace); + + Assert.Equal(DialResult.Dialled, await dial); + Assert.True(phone.IsDisposed); + } + + [Fact] + public async Task Never_sends_ATD_before_the_phone_answered_AT() + { + var phone = new ScriptedAtChannel(); + + var dial = Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + _time.Advance(AtDialer.ConnectTimeout); + + Assert.Equal(DialResult.NoResponse, await dial); + Assert.Equal(["AT"], phone.Written); + Assert.True(phone.IsDisposed); + } + + [Fact] + public async Task Waits_the_full_connect_timeout_for_the_bluetooth_link() + { + var phone = new ScriptedAtChannel(); + + var dial = Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + _time.Advance(AtDialer.ConnectTimeout - TimeSpan.FromMilliseconds(1)); + + Assert.False(dial.IsCompleted); + _time.Advance(TimeSpan.FromMilliseconds(1)); + Assert.Equal(DialResult.NoResponse, await dial); + } + + [Fact] + public async Task Reports_no_response_when_the_phone_never_answers_the_dial() + { + var phone = new ScriptedAtChannel().Answer("AT", "OK"); + + var dial = Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + _time.Advance(AtDialer.ResponseTimeout); + + Assert.Equal(DialResult.NoResponse, await dial); + } + + [Fact] + public async Task Reports_no_response_when_the_link_drops() + { + var phone = new ScriptedAtChannel(); + phone.Hangup(); + + var result = await Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + + Assert.Equal(DialResult.NoResponse, result); + } + + [Fact] + public async Task Reports_no_response_when_the_link_breaks_while_reading() + { + var phone = new ScriptedAtChannel().Answer("AT", "OK"); + phone.Break(new IOException("The device is not connected.")); + + var result = await Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + + Assert.Equal(DialResult.NoResponse, result); + Assert.True(phone.IsDisposed); + } + + [Fact] + public async Task Reports_no_response_when_the_link_breaks_while_writing() + { + var phone = new ScriptedAtChannel { WriteFailure = new IOException("The semaphore timeout period has expired.") }; + + var result = await Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + + Assert.Equal(DialResult.NoResponse, result); + Assert.True(phone.IsDisposed); + } + + [Theory] + [InlineData("ERROR", DialResult.Rejected)] + [InlineData("+CME ERROR: 3", DialResult.Rejected)] + [InlineData("BUSY", DialResult.LineBusy)] + [InlineData("NO CARRIER", DialResult.NoCarrier)] + [InlineData("NO DIALTONE", DialResult.NoDialTone)] + [InlineData("NO ANSWER", DialResult.NoCarrier)] + public async Task Maps_the_phones_final_answer(string answer, DialResult expected) + { + var phone = new ScriptedAtChannel().Answer("AT", "OK").Answer("ATD 0891234567", "ATD 0891234567", answer); + + var result = await Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + + Assert.Equal(expected, result); + Assert.True(phone.IsDisposed); + } + + [Fact] + public async Task Skips_unsolicited_lines_while_waiting() + { + var phone = new ScriptedAtChannel() + .Answer("AT", string.Empty, "RING", "CLIP:EXTERN", "OK") + .Answer("ATD 0891234567", "OK", "CONNECT"); + + var result = await Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + + Assert.Equal(DialResult.Dialled, result); + } + + [Fact] + public async Task Rejects_when_the_phone_refuses_AT() + { + var phone = new ScriptedAtChannel().Answer("AT", "ERROR"); + + var result = await Dialer(phone).DialAsync(Port, Number(), TestContext.Current.CancellationToken); + + Assert.Equal(DialResult.Rejected, result); + Assert.Equal(["AT"], phone.Written); + } + + [Theory] + [InlineData(PortFailure.Missing, DialResult.PortMissing)] + [InlineData(PortFailure.Busy, DialResult.PortBusy)] + [InlineData(PortFailure.Unreachable, DialResult.NoResponse)] + public async Task Reports_a_port_that_cannot_be_opened(PortFailure failure, DialResult expected) + { + var dialer = new AtDialer(new FakeChannelFactory(new PortUnavailableException(Port, failure)), _time); + + var result = await dialer.DialAsync(Port, Number(), TestContext.Current.CancellationToken); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public async Task Reports_a_missing_port_without_opening_anything(string port) + { + var factory = new FakeChannelFactory(ScriptedAtChannel.Dl500a()); + + var result = await new AtDialer(factory, _time).DialAsync(port, Number(), TestContext.Current.CancellationToken); + + Assert.Equal(DialResult.PortNotSet, result); + Assert.Empty(factory.Opened); + } + + [Fact] + public async Task Cancelling_closes_the_port_and_throws() + { + var phone = new ScriptedAtChannel(); + using var cancel = new CancellationTokenSource(); + + var dial = Dialer(phone).DialAsync(Port, Number(), cancel.Token); + await cancel.CancelAsync(); + + await Assert.ThrowsAnyAsync(() => dial); + Assert.True(phone.IsDisposed); + } + + [Fact] + public async Task Probe_sends_only_AT() + { + var phone = ScriptedAtChannel.Dl500a(); + + var result = await Dialer(phone).ProbeAsync(Port, TestContext.Current.CancellationToken); + + Assert.Equal(DialResult.Answered, result); + Assert.Equal(["AT"], phone.Written); + Assert.True(phone.IsDisposed); + } + + [Fact] + public async Task Probe_reports_no_response_from_a_silent_phone() + { + var phone = new ScriptedAtChannel(); + + var probe = Dialer(phone).ProbeAsync(Port, TestContext.Current.CancellationToken); + _time.Advance(AtDialer.ConnectTimeout); + + Assert.Equal(DialResult.NoResponse, await probe); + } +} diff --git a/tests/Waehlhilfe.Modem.Tests/ScriptedAtChannel.cs b/tests/Waehlhilfe.Modem.Tests/ScriptedAtChannel.cs new file mode 100644 index 0000000..5f37bdd --- /dev/null +++ b/tests/Waehlhilfe.Modem.Tests/ScriptedAtChannel.cs @@ -0,0 +1,87 @@ +using System.Threading.Channels; + +namespace Waehlhilfe.Modem.Tests; + +/// +/// A phone that answers each command with scripted lines. A command without a script stays +/// silent, which is what the DL500A does while the PC holds its audio connection. +/// +internal sealed class ScriptedAtChannel : IAtChannel +{ + private readonly Dictionary _script = new(StringComparer.Ordinal); + private readonly Channel _incoming = Channel.CreateUnbounded(); + + public List Written { get; } = []; + + public bool IsDisposed { get; private set; } + + public ScriptedAtChannel Answer(string command, params string[] lines) + { + _script[command] = lines; + return this; + } + + // The DL500A echoes every command before answering it. + public static ScriptedAtChannel Dl500a() => new ScriptedAtChannel() + .Answer("AT", "AT", "OK") + .Answer("ATD 0891234567", "ATD 0891234567", "OK", string.Empty, "CLIP:EXTERN", string.Empty, "CONNECT"); + + public Task WriteLineAsync(string line, CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(IsDisposed, this); + if (WriteFailure is not null) + { + throw WriteFailure; + } + + Written.Add(line); + if (_script.TryGetValue(line, out var lines)) + { + foreach (var answer in lines) + { + _incoming.Writer.TryWrite(answer); + } + } + + return Task.CompletedTask; + } + + public async Task ReadLineAsync(CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(IsDisposed, this); + return await _incoming.Reader.WaitToReadAsync(cancellationToken) && _incoming.Reader.TryRead(out var line) + ? line + : null; + } + + public void Hangup() => _incoming.Writer.TryComplete(); + + /// The Bluetooth link breaks: every later read throws, as a serial stream does. + public void Break(Exception error) => _incoming.Writer.TryComplete(error); + + /// The link is already gone when the next command is written. + public Exception? WriteFailure { get; set; } + + public ValueTask DisposeAsync() + { + IsDisposed = true; + return ValueTask.CompletedTask; + } +} + +internal sealed class FakeChannelFactory : IAtChannelFactory +{ + private readonly Func _open; + + public FakeChannelFactory(IAtChannel channel) => _open = () => channel; + + public FakeChannelFactory(Exception failure) => _open = () => throw failure; + + public List Opened { get; } = []; + + public Task OpenAsync(string portName, CancellationToken cancellationToken = default) + { + Opened.Add(portName); + return Task.FromResult(_open()); + } +} diff --git a/tests/Waehlhilfe.Modem.Tests/SerialPortsTests.cs b/tests/Waehlhilfe.Modem.Tests/SerialPortsTests.cs new file mode 100644 index 0000000..9e912ce --- /dev/null +++ b/tests/Waehlhilfe.Modem.Tests/SerialPortsTests.cs @@ -0,0 +1,49 @@ +namespace Waehlhilfe.Modem.Tests; + +public sealed class SerialPortsTests +{ + [Fact] + public void Lists_bluetooth_ports_on_macos_by_their_callout_device() + { + var ports = SerialPorts.Filter( + ["/dev/cu.DL500A", "/dev/tty.DL500A", "/dev/cu.Bluetooth-Incoming-Port", "/dev/cu.debug-console", "/dev/tty.Bluetooth-Incoming-Port"], + isMacOS: true); + + Assert.Equal(["/dev/cu.DL500A"], ports); + } + + [Fact] + public void Lists_windows_com_ports_in_numeric_order() + { + var ports = SerialPorts.Filter(["COM10", "COM3", "COM7", "COM3"], isMacOS: false); + + Assert.Equal(["COM3", "COM7", "COM10"], ports); + } + + [Fact] + public void Lists_linux_rfcomm_ports_first() + { + var ports = SerialPorts.Filter(["/dev/ttyS0", "/dev/rfcomm0", "/dev/ttyUSB0"], isMacOS: false); + + Assert.Equal(["/dev/rfcomm0", "/dev/ttyS0", "/dev/ttyUSB0"], ports); + } + + [Theory] + [InlineData(typeof(FileNotFoundException), PortFailure.Missing)] + [InlineData(typeof(ArgumentException), PortFailure.Missing)] + [InlineData(typeof(UnauthorizedAccessException), PortFailure.Busy)] + [InlineData(typeof(IOException), PortFailure.Unreachable)] + [InlineData(typeof(TimeoutException), PortFailure.Unreachable)] + public void Classifies_why_a_port_did_not_open(Type exception, PortFailure expected) + { + var error = (Exception)Activator.CreateInstance(exception)!; + + Assert.Equal(expected, SerialPorts.Classify(error)); + } + + [Fact] + public void Leaves_unrelated_exceptions_alone() + { + Assert.Null(SerialPorts.Classify(new InvalidOperationException())); + } +} diff --git a/tests/Waehlhilfe.Modem.Tests/StreamAtChannelTests.cs b/tests/Waehlhilfe.Modem.Tests/StreamAtChannelTests.cs new file mode 100644 index 0000000..d719d3f --- /dev/null +++ b/tests/Waehlhilfe.Modem.Tests/StreamAtChannelTests.cs @@ -0,0 +1,115 @@ +using System.Text; + +namespace Waehlhilfe.Modem.Tests; + +public sealed class StreamAtChannelTests +{ + private static (StreamAtChannel Channel, DuplexStream Stream) Over(string phoneSays) + { + var stream = new DuplexStream(Encoding.ASCII.GetBytes(phoneSays)); + return (new StreamAtChannel(stream), stream); + } + + [Fact] + public async Task Terminates_a_command_with_cr_lf() + { + var (channel, stream) = Over(string.Empty); + await using var _ = channel; + + await channel.WriteLineAsync("ATD 0891234567", TestContext.Current.CancellationToken); + + Assert.Equal("ATD 0891234567\r\n", stream.Written); + } + + [Theory] + [InlineData("ATD 089\r\nATH")] + [InlineData("ATD 089\n")] + [InlineData("ATD 089\0")] + [InlineData("ATD 08ä9")] + public async Task Refuses_to_send_anything_but_one_printable_ascii_line(string line) + { + var (channel, stream) = Over(string.Empty); + await using var _ = channel; + + await Assert.ThrowsAsync(() => channel.WriteLineAsync(line, TestContext.Current.CancellationToken)); + Assert.Equal(string.Empty, stream.Written); + } + + [Fact] + public async Task Splits_the_dl500a_answer_into_lines() + { + var (channel, _) = Over("ATD 0891234567\r\nOK\r\n\r\nCLIP:EXTERN\r\n\r\nCONNECT\r\n"); + await using var __ = channel; + var lines = new List(); + + for (var i = 0; i < 7; i++) + { + lines.Add(await channel.ReadLineAsync(TestContext.Current.CancellationToken)); + } + + Assert.Equal(["ATD 0891234567", "OK", string.Empty, "CLIP:EXTERN", string.Empty, "CONNECT", null], lines); + } + + [Fact] + public async Task Accepts_a_bare_cr_as_line_end() + { + var (channel, _) = Over("AT\rOK\r"); + await using var __ = channel; + + Assert.Equal("AT", await channel.ReadLineAsync(TestContext.Current.CancellationToken)); + Assert.Equal("OK", await channel.ReadLineAsync(TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task Disposes_the_port_it_owns() + { + var owner = new DisposeProbe(); + var channel = new StreamAtChannel(new DuplexStream([]), owner); + + await channel.DisposeAsync(); + + Assert.True(owner.IsDisposed); + } + + private sealed class DisposeProbe : IDisposable + { + public bool IsDisposed { get; private set; } + + public void Dispose() => IsDisposed = true; + } +} + +/// Reads what the phone "says" and records what was written to it. +internal sealed class DuplexStream(byte[] incoming) : Stream +{ + private readonly MemoryStream _in = new(incoming); + private readonly MemoryStream _out = new(); + + public string Written => Encoding.ASCII.GetString(_out.ToArray()); + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override int Read(byte[] buffer, int offset, int count) => _in.Read(buffer, offset, count); + + public override void Write(byte[] buffer, int offset, int count) => _out.Write(buffer, offset, count); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); +}