Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 139 additions & 0 deletions src/Waehlhilfe.Modem/AtDialer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
using Waehlhilfe.Domain;

namespace Waehlhilfe.Modem;

/// <summary>
/// One dial is one connection: open the port, <c>AT</c>, <c>ATD &lt;number&gt;</c>, close. The
/// DL500A keeps the call up on the base once the link is gone, so nothing is held open.
/// </summary>
public sealed class AtDialer
{
/// <summary>Opening the port opens the Bluetooth link, which takes seconds.</summary>
public static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(10);

public static readonly TimeSpan ResponseTimeout = TimeSpan.FromSeconds(15);

/// <summary>How long to wait for <c>CONNECT</c> after <c>OK</c> before closing anyway.</summary>
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;
}

/// <summary>Checks that the phone answers, without placing a call.</summary>
public Task<DialResult> ProbeAsync(string portName, CancellationToken cancellationToken = default) =>
RunAsync(portName, dial: null, cancellationToken);

public Task<DialResult> DialAsync(string portName, DialNumber number, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(number);
return RunAsync(portName, number, cancellationToken);
}

private async Task<DialResult> 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<DialResult> 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,
};
}
32 changes: 32 additions & 0 deletions src/Waehlhilfe.Modem/DialResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace Waehlhilfe.Modem;

public enum DialResult
{
/// <summary>The phone accepted <c>ATD</c> and is setting up the call.</summary>
Dialled,

/// <summary>The phone answered <c>AT</c>; returned by a probe only.</summary>
Answered,

/// <summary>No port has been chosen yet.</summary>
PortNotSet,

PortMissing,

PortBusy,

/// <summary>
/// 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.
/// </summary>
NoResponse,

/// <summary><c>ERROR</c> or <c>+CME ERROR</c>.</summary>
Rejected,

LineBusy,

NoCarrier,

NoDialTone,
}
16 changes: 16 additions & 0 deletions src/Waehlhilfe.Modem/IAtChannel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace Waehlhilfe.Modem;

/// <summary>A line-oriented connection to the phone's AT command interpreter.</summary>
public interface IAtChannel : IAsyncDisposable
{
Task WriteLineAsync(string line, CancellationToken cancellationToken = default);

/// <returns>The next line without its terminator, or <c>null</c> once the link has dropped.</returns>
Task<string?> ReadLineAsync(CancellationToken cancellationToken = default);
}

public interface IAtChannelFactory
{
/// <exception cref="PortUnavailableException">The port does not exist or another program holds it.</exception>
Task<IAtChannel> OpenAsync(string portName, CancellationToken cancellationToken = default);
}
41 changes: 41 additions & 0 deletions src/Waehlhilfe.Modem/PortUnavailableException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
namespace Waehlhilfe.Modem;

public enum PortFailure
{
/// <summary>No such port: the phone is not paired, or the port name is stale.</summary>
Missing,

/// <summary>Another program, or another dial still in progress, holds the port.</summary>
Busy,

/// <summary>The port exists but the link behind it did not come up: the phone is off or out of range.</summary>
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; }
}
95 changes: 95 additions & 0 deletions src/Waehlhilfe.Modem/SerialPorts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO.Ports;

namespace Waehlhilfe.Modem;

/// <summary>
/// The phone's Bluetooth SPP service as the OS exposes it: an outgoing COM port on Windows,
/// <c>/dev/cu.*</c> on macOS, <c>/dev/rfcomm*</c> (after <c>rfcomm bind</c>) on Linux. Opening
/// the port is what makes the OS bring up the RFCOMM link.
/// </summary>
public sealed class SerialPorts : IAtChannelFactory
{
private const int BaudRate = 115200;

public static IReadOnlyList<string> List()
{
IEnumerable<string> 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<string> Filter(IEnumerable<string> 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)];
}

/// <returns>Why the port did not open, or <c>null</c> for an exception that is not about the port.</returns>
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<IAtChannel> 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);
}
}
48 changes: 48 additions & 0 deletions src/Waehlhilfe.Modem/StreamAtChannel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Text;

namespace Waehlhilfe.Modem;

/// <summary>AT lines over a byte stream: commands end in CR LF, answers end in CR, LF or both.</summary>
public sealed class StreamAtChannel : IAtChannel
{
private readonly Stream _stream;
private readonly IDisposable? _owner;
private readonly StreamReader _reader;

/// <param name="stream">The connection to the phone.</param>
/// <param name="owner">What else to dispose with the channel, such as the serial port.</param>
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<string?> ReadLineAsync(CancellationToken cancellationToken = default) =>
await _reader.ReadLineAsync(cancellationToken).AsTask().WaitAsync(cancellationToken);

public async ValueTask DisposeAsync()
{
_reader.Dispose();
await _stream.DisposeAsync();
_owner?.Dispose();
}
}
Loading
Loading