diff --git a/Makefile b/Makefile index c63452f..90da49c 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,9 @@ SLN := Freizeichen.slnx APP := src/Freizeichen.App/Freizeichen.App.csproj +SCENARIO ?= ok +PHONE_PORT ?= /dev/rfcomm9 -.PHONY: help restore build test ci format format-check run clean +.PHONY: help restore build test ci format format-check run fake-phone clean help: ## Show this help @grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}' @@ -29,5 +31,8 @@ format-check: ## Fail if dotnet format would change anything run: ## Run the app (ARGS=tel:0891234567 to open the dial window) dotnet run --project $(APP) -- $(ARGS) +fake-phone: ## Play a DL500A on /dev/rfcomm9 (SCENARIO=ok|error|busy|nocarrier|nodialtone|silent; Linux) + python3 tools/fake-dl500a.py --link $(PHONE_PORT) --scenario $(SCENARIO) + clean: ## Remove build output find src tests -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + diff --git a/README.md b/README.md index 9cb0128..a8c9033 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,20 @@ auf; das Gespräch wird am Telefon geführt. Das DL500A stellt über Bluetooth eine serielle Schnittstelle (SPP) bereit und versteht dort AT-Befehle. Freizeichen öffnet diese Schnittstelle, sendet `ATD ` und schließt sie wieder. +## Ohne Telefon testen + +Unter Linux spielt `tools/fake-dl500a.py` ein DL500A auf einem Pseudo-Terminal und zeigt jede +Zeile, die Freizeichen sendet: + +```sh +make fake-phone # legt /dev/rfcomm9 an (fragt per sudo), SCENARIO=ok +make run # Einstellungen: /dev/rfcomm9 wählen, „Verbindung testen“ +make run ARGS=tel:0891234567 # Wählfenster +``` + +`SCENARIO` steuert die Antwort auf `ATD`: `ok`, `error`, `busy`, `nocarrier`, `nodialtone` oder +`silent` – Letzteres antwortet gar nicht, wie das DL500A bei bestehender Audioverbindung. + ## Status In Entwicklung. Hintergrund: CodeForFire/lagebuch#617. diff --git a/src/Freizeichen.Modem/SerialPorts.cs b/src/Freizeichen.Modem/SerialPorts.cs index 9d4900b..2908aae 100644 --- a/src/Freizeichen.Modem/SerialPorts.cs +++ b/src/Freizeichen.Modem/SerialPorts.cs @@ -61,8 +61,6 @@ public async Task OpenAsync(string portName, CancellationToken cance ArgumentException.ThrowIfNullOrWhiteSpace(portName); var port = new SerialPort(portName, BaudRate) { - DtrEnable = true, - RtsEnable = true, WriteTimeout = (int)AtDialer.ConnectTimeout.TotalMilliseconds, }; @@ -84,9 +82,26 @@ public async Task OpenAsync(string portName, CancellationToken cance throw new PortUnavailableException(portName, failure, e); } + RaiseModemLines(port); return new StreamAtChannel(port.BaseStream, port); } + // DTR and RTS are raised once the port is open, and only where the device has them: a + // pseudo-terminal, such as the one tools/fake-dl500a.py plays the phone on, has no modem + // control lines, and asking for them before Open made Open itself fail. + private static void RaiseModemLines(SerialPort port) + { + try + { + port.DtrEnable = true; + port.RtsEnable = true; + } + catch (IOException) + { + // No modem control lines on this device: talk without them. + } + } + private static int TrailingNumber(string name) { var digits = name[name.TrimEnd("0123456789".ToCharArray()).Length..]; diff --git a/tests/Freizeichen.Modem.Tests/Freizeichen.Modem.Tests.csproj b/tests/Freizeichen.Modem.Tests/Freizeichen.Modem.Tests.csproj index 6afe610..d63e72a 100644 --- a/tests/Freizeichen.Modem.Tests/Freizeichen.Modem.Tests.csproj +++ b/tests/Freizeichen.Modem.Tests/Freizeichen.Modem.Tests.csproj @@ -3,6 +3,8 @@ false true + + true diff --git a/tests/Freizeichen.Modem.Tests/PseudoTerminal.cs b/tests/Freizeichen.Modem.Tests/PseudoTerminal.cs new file mode 100644 index 0000000..e4001a5 --- /dev/null +++ b/tests/Freizeichen.Modem.Tests/PseudoTerminal.cs @@ -0,0 +1,63 @@ +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.Win32.SafeHandles; + +namespace Freizeichen.Modem.Tests; + +/// +/// A Unix pseudo-terminal: a serial device with no modem control lines, like the one +/// tools/fake-dl500a.py plays the phone on. is the far end. +/// +internal sealed partial class PseudoTerminal : IDisposable +{ + private const int ReadWrite = 2; + + private PseudoTerminal(FileStream phone, string port) + { + Phone = phone; + Port = port; + } + + /// The device a program opens, as it would open /dev/rfcomm0. + public string Port { get; } + + public FileStream Phone { get; } + + public static PseudoTerminal Open() + { + var fd = PosixOpenpt(ReadWrite | NoControllingTerminal()); + if (fd < 0 || Grantpt(fd) != 0 || Unlockpt(fd) != 0) + { + throw new IOException($"No pseudo-terminal: errno {Marshal.GetLastPInvokeError()}."); + } + + var name = new byte[128]; + if (PtsnameR(fd, name, name.Length) != 0) + { + throw new IOException($"No pseudo-terminal name: errno {Marshal.GetLastPInvokeError()}."); + } + + var phone = new FileStream(new SafeFileHandle(fd, ownsHandle: true), FileAccess.ReadWrite, bufferSize: 0); + return new PseudoTerminal(phone, Encoding.ASCII.GetString(name, 0, Array.IndexOf(name, (byte)0))); + } + + public void Dispose() => Phone.Dispose(); + + private static int NoControllingTerminal() => OperatingSystem.IsMacOS() ? 0x20000 : 0x100; + + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + [LibraryImport("libc", EntryPoint = "posix_openpt", SetLastError = true)] + private static partial int PosixOpenpt(int flags); + + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + [LibraryImport("libc", EntryPoint = "grantpt", SetLastError = true)] + private static partial int Grantpt(int fd); + + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + [LibraryImport("libc", EntryPoint = "unlockpt", SetLastError = true)] + private static partial int Unlockpt(int fd); + + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + [LibraryImport("libc", EntryPoint = "ptsname_r", SetLastError = true)] + private static partial int PtsnameR(int fd, [Out] byte[] buffer, nint length); +} diff --git a/tests/Freizeichen.Modem.Tests/SerialPortsTests.cs b/tests/Freizeichen.Modem.Tests/SerialPortsTests.cs index b48ddcc..04c66fa 100644 --- a/tests/Freizeichen.Modem.Tests/SerialPortsTests.cs +++ b/tests/Freizeichen.Modem.Tests/SerialPortsTests.cs @@ -1,3 +1,5 @@ +using System.Text; + namespace Freizeichen.Modem.Tests; public sealed class SerialPortsTests @@ -46,4 +48,17 @@ public void Leaves_unrelated_exceptions_alone() { Assert.Null(SerialPorts.Classify(new InvalidOperationException())); } + + [Fact] + public async Task Talks_to_a_port_without_modem_control_lines() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "Pseudo-terminals are Unix only."); + var cancellationToken = TestContext.Current.CancellationToken; + using var terminal = PseudoTerminal.Open(); + + await using var channel = await new SerialPorts().OpenAsync(terminal.Port, cancellationToken); + await terminal.Phone.WriteAsync(Encoding.ASCII.GetBytes("OK\r\n"), cancellationToken); + + Assert.Equal("OK", await channel.ReadLineAsync(cancellationToken)); + } } diff --git a/tools/fake-dl500a.py b/tools/fake-dl500a.py new file mode 100755 index 0000000..6c9142a --- /dev/null +++ b/tools/fake-dl500a.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""A fake Gigaset DL500A on a pseudo-terminal, for trying Freizeichen without the phone. + +It answers the AT commands Freizeichen sends the way the DL500A does over Bluetooth SPP, and +prints every line it receives, so you can see exactly what a tel: link put on the wire. + + python3 tools/fake-dl500a.py # prints the port to choose in Freizeichen + python3 tools/fake-dl500a.py --link /dev/rfcomm9 --scenario silent + +--link makes the port appear in Freizeichen's port list (Linux lists /dev/rfcomm*, macOS +/dev/cu.*). Linking into /dev needs root, so the script calls sudo for that step alone. +Tried on Linux only. +""" + +import argparse +import os +import re +import subprocess +import sys +import tty + +# What the phone answers to ATD, per scenario. "silent" answers nothing at all, not even AT: that +# is what the DL500A does while the PC also holds its Hands-Free audio connection. +DIAL_ANSWERS = { + "ok": ["OK", "CLIP:EXTERN", "CONNECT"], + "error": ["ERROR"], + "busy": ["BUSY"], + "nocarrier": ["NO CARRIER"], + "nodialtone": ["NO DIALTONE"], + "silent": [], +} + + +def answer(command, scenario): + if scenario == "silent": + return [] + if command == "AT": + return ["OK"] + if command == "AT+CGMI": + return ["Gigaset Communications GmbH", "OK"] + if command.startswith("ATD"): + return DIAL_ANSWERS[scenario] + return ["ERROR"] + + +def check(command): + # Anything after ATD other than digits is what TelUri must never let through. + if command.startswith("ATD") and not re.fullmatch(r"ATD \d+", command): + print(f"!!! not just digits after ATD: {command!r}", flush=True) + elif not command.startswith("AT"): + print(f"!!! not an AT command: {command!r}", flush=True) + + +def link(target, name): + try: + if os.path.lexists(name): + os.remove(name) + os.symlink(target, name) + except PermissionError: + subprocess.run(["sudo", "ln", "-sfn", target, name], check=True) + + +def unlink(name): + try: + os.remove(name) + except PermissionError: + subprocess.run(["sudo", "rm", "-f", name], check=False) + except FileNotFoundError: + pass + + +def serve(master, scenario): + pending = b"" + while True: + try: + chunk = os.read(master, 1024) + except OSError: + # Every slave fd closed; cannot happen while we hold ours, but end cleanly if it does. + return + pending += chunk + *lines, pending = re.split(rb"\r\n|\r|\n", pending) + for raw in lines: + if not raw: + continue + command = raw.decode("ascii", errors="backslashreplace") + print(f"<- {command!r}", flush=True) + check(command) + for reply in answer(command.strip(), scenario): + print(f"-> {reply}", flush=True) + os.write(master, f"\r\n{reply}\r\n".encode("ascii")) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--scenario", choices=DIAL_ANSWERS, default="ok", help="how the phone answers ATD (default: ok)") + parser.add_argument("--link", metavar="PATH", help="also expose the port under this name, e.g. /dev/rfcomm9") + args = parser.parse_args() + + master, slave = os.openpty() + # Holding the slave open keeps the pty alive between dials, and raw mode stops it echoing. + tty.setraw(slave) + port = os.ttyname(slave) + if args.link: + link(port, args.link) + port = args.link + + print(f"Fake DL500A ({args.scenario}) on {port} – choose it in Freizeichen. Ctrl+C ends.", flush=True) + try: + serve(master, args.scenario) + except KeyboardInterrupt: + pass + finally: + if args.link: + unlink(args.link) + + +if __name__ == "__main__": + sys.exit(main())