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
7 changes: 6 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -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}'
Expand Down Expand Up @@ -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 {} +
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Nummer>` 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.
19 changes: 17 additions & 2 deletions src/Freizeichen.Modem/SerialPorts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,6 @@ public async Task<IAtChannel> OpenAsync(string portName, CancellationToken cance
ArgumentException.ThrowIfNullOrWhiteSpace(portName);
var port = new SerialPort(portName, BaudRate)
{
DtrEnable = true,
RtsEnable = true,
WriteTimeout = (int)AtDialer.ConnectTimeout.TotalMilliseconds,
};

Expand All @@ -84,9 +82,26 @@ public async Task<IAtChannel> 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..];
Expand Down
2 changes: 2 additions & 0 deletions tests/Freizeichen.Modem.Tests/Freizeichen.Modem.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<!-- LibraryImport opens the pseudo-terminal that stands in for the phone. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
Expand Down
63 changes: 63 additions & 0 deletions tests/Freizeichen.Modem.Tests/PseudoTerminal.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;

namespace Freizeichen.Modem.Tests;

/// <summary>
/// A Unix pseudo-terminal: a serial device with no modem control lines, like the one
/// <c>tools/fake-dl500a.py</c> plays the phone on. <see cref="Phone"/> is the far end.
/// </summary>
internal sealed partial class PseudoTerminal : IDisposable
{
private const int ReadWrite = 2;

private PseudoTerminal(FileStream phone, string port)
{
Phone = phone;
Port = port;
}

/// <summary>The device a program opens, as it would open <c>/dev/rfcomm0</c>.</summary>
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);
}
15 changes: 15 additions & 0 deletions tests/Freizeichen.Modem.Tests/SerialPortsTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Text;

namespace Freizeichen.Modem.Tests;

public sealed class SerialPortsTests
Expand Down Expand Up @@ -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));
}
}
118 changes: 118 additions & 0 deletions tools/fake-dl500a.py
Original file line number Diff line number Diff line change
@@ -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())
Loading