diff --git a/src/Waehlhilfe.Modem/AtDialer.cs b/src/Waehlhilfe.Modem/AtDialer.cs
new file mode 100644
index 0000000..908e562
--- /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
+{
+ /// 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/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.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();
+}