From d353ae2b025eeaf5a1d790bbd629bb7432f8f7c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 19:16:22 +0000 Subject: [PATCH] USB modems as the modem's line: SmartUSB56 and pico-serial Line A new line, "A phone line, through a USB modem": the phone runs the modem, a Smart Link SmartUSB56 (0483:7554) or a pico-serial Line stick (1209:0002) plugged into it carries its samples to a real phone line, with D-Modem-RE's usb_line.cpp as dmodemd --usb drives them (the stick's caller ID and the country's DAA settings too). - libusb 1.0.27 (D-Modem-RE's pinned release) built for Android (usb/libusb.cmake); usb_line.cpp built with libusb_init, libusb_get_device_list and libusb_open renamed to usb_android.cpp's, which start libusb without device discovery and give it the descriptor Android opened for the app, wrapped, as the only device. - usb_modem.cpp: the core on that line, the run loop of dmodemd's run_line() with a stop pipe and the engine's status; Engine::Config usb_fd and usb_rate, through JNI. - UsbModems: the devices by their IDs, Android's permission asked when the modem starts, the connection held while it runs; ModemSettings LINE_USB (no SIP account, not a peer line); the settings, Home and the notifications say so; Android offers the app when one is plugged in. - native-test: usb_host (the engine on D-Modem-RE's fake stick, linked in as libusb) and usb_line_test.py: two of them through its simulated exchange: caller ID, CONNECT 33600, data each way, hang up, unplugged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs --- README.md | 29 +++- app/src/main/cpp/CMakeLists.txt | 14 ++ app/src/main/cpp/engine.cpp | 29 +++- app/src/main/cpp/engine.h | 8 + app/src/main/cpp/jni.cpp | 6 +- app/src/main/cpp/usb/libusb.cmake | 66 ++++++++ app/src/main/cpp/usb/usb_android.cpp | 77 +++++++++ app/src/main/cpp/usb/usb_android.h | 38 +++++ app/src/main/cpp/usb/usb_modem.cpp | 146 +++++++++++++++++ app/src/main/cpp/usb/usb_modem.h | 68 ++++++++ .../java/com/neodesktop/dmodem/NativeModem.kt | 10 +- .../neodesktop/dmodem/modem/ModemService.kt | 28 +++- .../com/neodesktop/dmodem/modem/UsbModems.kt | 92 +++++++++++ .../dmodem/settings/ModemSettings.kt | 11 +- .../neodesktop/dmodem/ui/DashboardScreen.kt | 9 ++ .../com/neodesktop/dmodem/ui/MainActivity.kt | 1 + .../com/neodesktop/dmodem/ui/PeerLineUi.kt | 26 ++- .../neodesktop/dmodem/ui/SettingsScreen.kt | 4 +- app/src/main/res/xml/usb_serial_adapters.xml | 5 +- .../neodesktop/dmodem/modem/UsbModemsTest.kt | 25 +++ .../dmodem/settings/ModemSettingsTest.kt | 15 ++ .../com/neodesktop/dmodem/ui/PeerShotsTest.kt | 13 ++ native-test/CMakeLists.txt | 32 ++++ native-test/usb_fake_device.cpp | 16 ++ native-test/usb_host.cpp | 87 ++++++++++ native-test/usb_line_test.py | 150 ++++++++++++++++++ 26 files changed, 990 insertions(+), 15 deletions(-) create mode 100644 app/src/main/cpp/usb/libusb.cmake create mode 100644 app/src/main/cpp/usb/usb_android.cpp create mode 100644 app/src/main/cpp/usb/usb_android.h create mode 100644 app/src/main/cpp/usb/usb_modem.cpp create mode 100644 app/src/main/cpp/usb/usb_modem.h create mode 100644 app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt create mode 100644 app/src/test/java/com/neodesktop/dmodem/modem/UsbModemsTest.kt create mode 100644 native-test/usb_fake_device.cpp create mode 100644 native-test/usb_host.cpp create mode 100644 native-test/usb_line_test.py diff --git a/README.md b/README.md index e68fe6c..f6fc9dc 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,30 @@ and uses its lines and settings (its firmware/PROTOCOL.md): Any other CDC-ACM adapter's line notifications (`SERIAL_STATE`) are read too, so the computer dropping DTR hangs up there as well. +## A real phone line: USB modems + +The modem's line can also be a telephone line, through a USB modem that +carries the modem's sound (D-Modem-RE's `usb_line.cpp`, as +`dmodemd --usb` drives them): a Smart Link SmartUSB56 (USB 0483:7554), or +a [pico-serial](https://github.com/Neo-Desktop/pico-serial) Line stick +(1209:0002, a Si3056 DAA: caller ID on hook, and the country's line +settings in its registers). The phone runs the modem; plugged into it +(USB OTG) the stick is its line, with no SIP account or network. Settings, +Line, "A phone line, through a USB modem"; Android asks once whether +D-Modem may use it, and offers the app when one is plugged in. + +An app can't list the USB devices itself: Android opens the one the user +allowed and gives its descriptor. libusb is built for Android in the app +(`app/src/main/cpp/usb/libusb.cmake`, D-Modem-RE's pinned release) and +`usb_line.cpp` built with its three calls that look for the device +renamed to `usb/usb_android.cpp`'s, which start libusb without its device +discovery and give it that descriptor, wrapped, as the only device on the +bus. Tested on the build host on D-Modem-RE's fake pico-serial Line +sticks and simulated exchange (`native-test/usb_line_test.py`: dialling, +caller ID, answering, CONNECT 33600, data each way, hanging up, unplugged); +not yet on a phone with a real stick. The phone's speaker isn't fed on +this line. + ## The app - **Home**: what the modem is doing (off, ready, connecting, online with @@ -146,7 +170,8 @@ no `/etc/resolv.conf` for libre to read. `libdmodem_sip`, the modem on a SIP line as a library. - `app/src/main/cpp`: the native library, `libdmodem_jni.so`: `engine.cpp` runs the modem in a thread of its own with its DTE on a - socket pair whose other end is the app's; `jni.cpp` binds it to + socket pair whose other end is the app's, on SIP, a peer line + (`peer_modem.cpp`) or a USB modem (`usb/`); `jni.cpp` binds it to `com.neodesktop.dmodem.NativeModem`. - `app/src/main/java/com/neodesktop/dmodem`: `modem/` the service, the state the UI observes and `DteHub`, the modem's DTE shared by the @@ -157,7 +182,7 @@ no `/etc/resolv.conf` for libre to read. `BoxDrawing`, `Themes`, the directory and snippets. - `native-test`: the engine on the build host, against a dmodemd over loopback SIP (dialling out, data both ways, restarting, a call coming - in, the app closing its end). + in, the app closing its end), and on fake USB modems (`usb_line_test.py`). ## Building diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index c61b647..5fce384 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -34,6 +34,20 @@ target_compile_options(dmodem_engine PRIVATE -Wall -Wextra) set_target_properties(dmodem_engine PROPERTIES POSITION_INDEPENDENT_CODE ON) if(ANDROID) + # the USB modems (D-Modem-RE's usb_line.cpp: a SmartUSB56, a + # pico-serial Line stick) on the device Android opened for the app: + # libusb built here, and usb_line.cpp's three calls that look for the + # device renamed to usb/usb_android.cpp's, which give it that one + include(usb/libusb.cmake) + target_sources(dmodem_engine PRIVATE usb/usb_modem.cpp + usb/usb_android.cpp ${DMODEM_RE_DIR}/dmodemd/usb_line.cpp + ${DMODEM_RE_DIR}/dmodemd/si3056.cpp) + set_source_files_properties(${DMODEM_RE_DIR}/dmodemd/usb_line.cpp + PROPERTIES COMPILE_DEFINITIONS + "libusb_init=dmodem_libusb_init;libusb_get_device_list=dmodem_libusb_get_device_list;libusb_open=dmodem_libusb_open") + target_compile_definitions(dmodem_engine PUBLIC DMODEM_ENGINE_USB) + target_link_libraries(dmodem_engine PUBLIC dmodem_android_libusb) + add_library(dmodem_jni SHARED jni.cpp) target_link_libraries(dmodem_jni PRIVATE dmodem_engine log) target_compile_options(dmodem_jni PRIVATE -Wall -Wextra) diff --git a/app/src/main/cpp/engine.cpp b/app/src/main/cpp/engine.cpp index 2a8735e..adb6e21 100644 --- a/app/src/main/cpp/engine.cpp +++ b/app/src/main/cpp/engine.cpp @@ -23,6 +23,9 @@ #include "engine.h" #include "peer_modem.h" +#ifdef DMODEM_ENGINE_USB +#include "usb/usb_modem.h" +#endif namespace dmodem_android { @@ -115,6 +118,10 @@ void Engine::stop() modem_->stop(); if (peer_) peer_->stop(); +#ifdef DMODEM_ENGINE_USB + if (usb_) + usb_->stop(); +#endif std::thread t = std::move(thread_); lk.unlock(); t.join(); @@ -223,7 +230,27 @@ void Engine::run(Config cfg, int dte_fd, StatusFn status, ExitFn done, { dmd::FdDte dte(dte_fd); - if (cfg.peer) { + if (cfg.usb_fd >= 0) { +#ifdef DMODEM_ENGINE_USB + mo.rate = cfg.usb_rate; + UsbModem um(dte, mo, cfg.usb_fd); + if (um.ok()) { + if (status) + um.on_status(report); + { + std::lock_guard lk(mu_); + usb_ = &um; + if (stopping_) + um.stop(); + } + serve(um.modem(), [&um] { return um.run(); }); + std::lock_guard lk(mu_); + usb_ = nullptr; + } +#else + dcore::log_printf(0, "error: a USB modem: not in this build\n"); +#endif + } else if (cfg.peer) { PeerModem pm(dte, mo, cfg.peer_lead_ms); if (pm.ok()) { if (status) diff --git a/app/src/main/cpp/engine.h b/app/src/main/cpp/engine.h index 752de72..6fff2db 100644 --- a/app/src/main/cpp/engine.h +++ b/app/src/main/cpp/engine.h @@ -28,6 +28,7 @@ namespace dmd { class SipModem; } namespace dmodem_android { class PeerModem; +class UsbModem; struct Config { /* the SIP account: user, password, the registrar's or proxy's @@ -54,6 +55,12 @@ struct Config { not SIP: the account above unused; its lead silence (ms) */ bool peer = false; int peer_lead_ms = 100; + /* the line a USB modem's (usb/usb_modem.h: a SmartUSB56 or a + pico-serial Line stick), the device Android opened for the app + (its descriptor, the caller's: open while the modem runs), not + SIP or a peer; its rate (8000 or 9600 Hz). -1: none */ + int usb_fd = -1; + int usb_rate = 9600; }; /* what the modem's call is doing (dmd::SipModem::Status) */ @@ -114,6 +121,7 @@ private: std::thread thread_; dmd::SipModem *modem_ = nullptr; /* while run() has one */ PeerModem *peer_ = nullptr; /* or this one */ + UsbModem *usb_ = nullptr; /* or this one */ SpeakerFn speaker_; SoundFn sound_; bool active_ = false; /* run() hasn't ended */ diff --git a/app/src/main/cpp/jni.cpp b/app/src/main/cpp/jni.cpp index b624356..3968b5c 100644 --- a/app/src/main/cpp/jni.cpp +++ b/app/src/main/cpp/jni.cpp @@ -173,7 +173,7 @@ jint native_start(JNIEnv *env, jclass, jstring user, jstring password, jstring domain, jint sip_port, jboolean listen, jboolean t38, jstring dns, jstring country, jstring data_file, jint log_level, jint sip_log_level, jboolean peer, - jint peer_lead_ms) + jint peer_lead_ms, jint usb_fd, jint usb_rate) { Config cfg; @@ -190,6 +190,8 @@ jint native_start(JNIEnv *env, jclass, jstring user, jstring password, cfg.sip_log_level = sip_log_level; cfg.peer = peer; cfg.peer_lead_ms = peer_lead_ms; + cfg.usb_fd = usb_fd; + cfg.usb_rate = usb_rate; return Engine::instance().start(cfg, status_changed, exited, line_started); } @@ -221,7 +223,7 @@ jboolean native_running(JNIEnv *, jclass) const JNINativeMethod methods[] = { { "nativeStart", "(Ljava/lang/String;Ljava/lang/String;" "Ljava/lang/String;IZZLjava/lang/String;Ljava/lang/String;" - "Ljava/lang/String;IIZI)I", + "Ljava/lang/String;IIZIII)I", reinterpret_cast(native_start) }, { "nativeStop", "()V", reinterpret_cast(native_stop) }, { "nativeRunning", "()Z", reinterpret_cast(native_running) }, diff --git a/app/src/main/cpp/usb/libusb.cmake b/app/src/main/cpp/usb/libusb.cmake new file mode 100644 index 0000000..77db4a4 --- /dev/null +++ b/app/src/main/cpp/usb/libusb.cmake @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright (C) 2026 Neo-Desktop +# libusb-1.0 for Android, as the static library `dmodem_android_libusb` +# (the build host's tests take its libusb.h alone, DMODEM_LIBUSB_SRC): +# D-Modem-RE's pinned release (its cmake/libusb.cmake: the same version +# and SHA-256), downloaded once while configuring into the build tree, +# its core and Linux backend (usbfs) built with the NDK, with the config.h +# it ships for Android. An app can't list the USB devices itself: the +# device comes from Android (UsbManager) as a descriptor, which libusb +# wraps (usb_android.cpp). +# +# libusb is LGPL-2.1-or-later. +set(DMODEM_LIBUSB_VERSION "1.0.27" CACHE STRING "libusb release to fetch") +set(DMODEM_LIBUSB_URL + "https://github.com/libusb/libusb/releases/download/v${DMODEM_LIBUSB_VERSION}/libusb-${DMODEM_LIBUSB_VERSION}.tar.bz2" + CACHE STRING "libusb release tarball") +set(DMODEM_LIBUSB_SHA256 + "ffaa41d741a8a3bee244ac8e54a72ea05bf2879663c098c82fc5757853441575" + CACHE STRING "the tarball's SHA-256") +set(DMODEM_LIBUSB_DIR "" CACHE PATH "a libusb source tree (else fetched)") + +set(_usb_src ${DMODEM_LIBUSB_DIR}) +if(NOT _usb_src) + set(_deps ${CMAKE_BINARY_DIR}/_deps) + set(_usb_tar ${_deps}/libusb-${DMODEM_LIBUSB_VERSION}.tar.bz2) + set(_usb_src ${_deps}/libusb-${DMODEM_LIBUSB_VERSION}) + if(NOT EXISTS ${_usb_src}/libusb/libusb.h) + message(STATUS "libusb: fetching ${DMODEM_LIBUSB_VERSION}") + file(DOWNLOAD ${DMODEM_LIBUSB_URL} ${_usb_tar} + EXPECTED_HASH SHA256=${DMODEM_LIBUSB_SHA256} + STATUS _st TLS_VERIFY ON) + list(GET _st 0 _code) + if(NOT _code EQUAL 0) + message(FATAL_ERROR "libusb: can't fetch ${DMODEM_LIBUSB_URL}: ${_st} " + "(or give -DDMODEM_LIBUSB_DIR=)") + endif() + file(ARCHIVE_EXTRACT INPUT ${_usb_tar} DESTINATION ${_deps}) + endif() +endif() +if(NOT EXISTS ${_usb_src}/libusb/os/linux_usbfs.c) + message(FATAL_ERROR "libusb: no source tree in ${_usb_src}") +endif() +set(DMODEM_LIBUSB_SRC ${_usb_src}) +if(NOT ANDROID) + return() +endif() + +add_library(dmodem_android_libusb STATIC + ${_usb_src}/libusb/core.c + ${_usb_src}/libusb/descriptor.c + ${_usb_src}/libusb/hotplug.c + ${_usb_src}/libusb/io.c + ${_usb_src}/libusb/strerror.c + ${_usb_src}/libusb/sync.c + ${_usb_src}/libusb/os/events_posix.c + ${_usb_src}/libusb/os/threads_posix.c + ${_usb_src}/libusb/os/linux_usbfs.c + ${_usb_src}/libusb/os/linux_netlink.c) +# (its Android config.h, as its own ndk-build has it) +target_include_directories(dmodem_android_libusb PRIVATE ${_usb_src}/android + ${_usb_src}/libusb/os) +target_include_directories(dmodem_android_libusb SYSTEM PUBLIC ${_usb_src}/libusb) +target_compile_options(dmodem_android_libusb PRIVATE -w -fvisibility=hidden -pthread) +set_target_properties(dmodem_android_libusb PROPERTIES C_STANDARD 11 + POSITION_INDEPENDENT_CODE ON) +target_link_libraries(dmodem_android_libusb PUBLIC log) diff --git a/app/src/main/cpp/usb/usb_android.cpp b/app/src/main/cpp/usb/usb_android.cpp new file mode 100644 index 0000000..b9808cc --- /dev/null +++ b/app/src/main/cpp/usb/usb_android.cpp @@ -0,0 +1,77 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + * + * usb_android.cpp - the device Android opened, as libusb's only one + * (usb_android.h) + * + */ +#include "usb_android.h" + +#include + +namespace { + +/* (one modem in the process: its thread alone uses these) */ +int fd_ = -1; +libusb_device_handle *wrapped_ = nullptr; + +} // namespace + +namespace dmodem_android { + +void usb_use_fd(int fd) +{ + fd_ = fd; +} + +} // namespace dmodem_android + +/* libusb without its device discovery, the descriptor wrapped */ +int dmodem_libusb_init(libusb_context **ctx) +{ + struct libusb_init_option opt[1]; + int err; + + opt[0].option = LIBUSB_OPTION_NO_DEVICE_DISCOVERY; + opt[0].value.ival = 0; + err = libusb_init_context(ctx, opt, 1); + if (err < 0) + return err; + wrapped_ = nullptr; + if (fd_ >= 0) { + err = libusb_wrap_sys_device(*ctx, (intptr_t)fd_, &wrapped_); + if (err < 0) { + libusb_exit(*ctx); + *ctx = nullptr; + wrapped_ = nullptr; + return err; + } + } + return 0; +} + +/* the wrapped device alone (none if there is none) */ +ssize_t dmodem_libusb_get_device_list(libusb_context *, + libusb_device ***list) +{ + libusb_device **l = static_cast( + calloc(2, sizeof(libusb_device *))); + if (!l) + return LIBUSB_ERROR_NO_MEM; + if (wrapped_) + l[0] = libusb_ref_device(libusb_get_device(wrapped_)); + *list = l; + return wrapped_ ? 1 : 0; +} + +/* the wrapped device: its handle (open already) */ +int dmodem_libusb_open(libusb_device *dev, libusb_device_handle **h) +{ + if (wrapped_ && dev == libusb_get_device(wrapped_)) { + *h = wrapped_; + wrapped_ = nullptr; + return 0; + } + return libusb_open(dev, h); +} diff --git a/app/src/main/cpp/usb/usb_android.h b/app/src/main/cpp/usb/usb_android.h new file mode 100644 index 0000000..366653f --- /dev/null +++ b/app/src/main/cpp/usb/usb_android.h @@ -0,0 +1,38 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + * + * usb_android.h - D-Modem-RE's USB line (usb_line.cpp) on a device + * Android has opened for the app + * + * An app can't list the USB devices (no /dev/bus/usb to read): Android + * gives it the one the user allowed, as a descriptor (UsbManager's + * UsbDeviceConnection). usb_line.cpp finds its modem as dmodemd does, + * with libusb_init(), libusb_get_device_list() and libusb_open(): it is + * built here with those three renamed to the ones below + * (CMakeLists.txt), which start libusb without its device discovery, + * wrap the descriptor given (libusb_wrap_sys_device()) and give that + * device as the only one on the bus, already open. + * + */ +#ifndef DMODEM_ANDROID_USB_ANDROID_H +#define DMODEM_ANDROID_USB_ANDROID_H + +#include + +namespace dmodem_android { + +/* the device's descriptor for the next libusb_init() of usb_line.cpp + (-1: none); the caller's, kept open while it is used */ +void usb_use_fd(int fd); + +} // namespace dmodem_android + +extern "C" { +int dmodem_libusb_init(libusb_context **ctx); +ssize_t dmodem_libusb_get_device_list(libusb_context *ctx, + libusb_device ***list); +int dmodem_libusb_open(libusb_device *dev, libusb_device_handle **h); +} + +#endif diff --git a/app/src/main/cpp/usb/usb_modem.cpp b/app/src/main/cpp/usb/usb_modem.cpp new file mode 100644 index 0000000..0fec907 --- /dev/null +++ b/app/src/main/cpp/usb/usb_modem.cpp @@ -0,0 +1,146 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + * + * usb_modem.cpp - the modem core on a USB modem's line (usb_modem.h) + * + */ +#include "usb_modem.h" + +#include +#include +#include +#include + +#include +#include +#include + +#include "usb_android.h" + +#define ERR(fmt, ...) dcore::log_printf(0, "error: " fmt, ##__VA_ARGS__) + +namespace dmodem_android { + +/* see usb_modem.h: the core first (its country to the line), then the + device (the country's settings into its DAA) */ +UsbModem::UsbModem(dmd::Dte &dte, const dcore::Options &opt, int fd) + : dte_(dte), line_(new dmd::UsbLine(dte)) +{ + m_.reset(new dcore::Modem(*line_, opt)); + if (!m_->ok()) + return; + if (pipe(ev_) < 0) { + ERR("pipe: %s\n", strerror(errno)); + ev_[0] = ev_[1] = -1; + return; + } + for (int e : ev_) { + fcntl(e, F_SETFD, FD_CLOEXEC); + fcntl(e, F_SETFL, fcntl(e, F_GETFL) | O_NONBLOCK); + } + usb_use_fd(fd); + open_ = line_->open("auto", (unsigned)opt.rate); + usb_use_fd(-1); +} + +/* the core first: it may still hang up on the line */ +UsbModem::~UsbModem() +{ + m_.reset(); + line_.reset(); + for (int e : ev_) + if (e >= 0) + close(e); +} + +bool UsbModem::ok() const +{ + return m_ && m_->ok() && open_ && ev_[0] >= 0; +} + +void UsbModem::stop() +{ + stopped_ = true; + if (ev_[1] >= 0 && write(ev_[1], "", 1) < 0) { + /* (full: it wakes anyway) */ + } +} + +/* the status to status_fn_ if it changed (as SipModem's) */ +void UsbModem::report() +{ + Status s; + + if (!status_fn_) + return; + s.link = m_->link_state(); + s.offhook = m_->started(); + if (s.link == dcore::LinkState::Online) { + s.tx_rate = m_->tx_rate(); + s.rx_rate = m_->rx_rate(); + } + if (s != status_) { + status_ = s; + status_fn_(s); + } +} + +/* each turn (dmodemd's run_line()): the modem's timers, then select() + on libusb's descriptors, the stop pipe and the DTE, then the samples + that came */ +int UsbModem::run() +{ + dcore::Modem &m = *m_; + dcore::Modem *const modems[] = { &m }; + dmd::RunLoop loop; + int ret = 0; + + while (!stopped_) { + long wait = dmd::RunLoop::poll(modems, 1); + int dte = dte_.fd(); + + report(); + loop.clear(); + line_->watch(loop); + loop.watch(ev_[0]); + if (dte >= 0 && dte_.want_read(m)) + loop.watch(dte); + if (dte >= 0 && dte_.want_write()) + loop.watch_write(dte); + int n = loop.wait(wait); + if (n < 0 && errno != EINTR) { + ERR("select: %s\n", strerror(errno)); + ret = -1; + break; + } + if (line_->pump(m) < 0) { + ret = -1; + break; + } + if (n <= 0) + continue; + if (loop.ready(ev_[0])) { + char buf[64]; + while (read(ev_[0], buf, sizeof(buf)) > 0) { + } + } + if (loop.ready_write(dte)) + dte_.flush(); + if (loop.ready(dte)) { + int r = dte_.serve(m); + if (r < 0) { + ret = -1; + break; + } + if (r > 0) + break; + } + } + if (m.link_state() != dcore::LinkState::Idle) + m.hangup_now(); + dte_.flush(); + return ret; +} + +} // namespace dmodem_android diff --git a/app/src/main/cpp/usb/usb_modem.h b/app/src/main/cpp/usb/usb_modem.h new file mode 100644 index 0000000..1c6c543 --- /dev/null +++ b/app/src/main/cpp/usb/usb_modem.h @@ -0,0 +1,68 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + * + * usb_modem.h - the modem core on a telephone line through a USB + * modem (D-Modem-RE's UsbLine: a Smart Link SmartUSB56, + * or a pico-serial Line stick), its DTE a descriptor + * + * As dmodemd --usb runs it (its run_line()), on the device Android + * gave the app (usb_android.h), until stop() or the DTE gone. + * + */ +#ifndef DMODEM_ANDROID_USB_MODEM_H +#define DMODEM_ANDROID_USB_MODEM_H + +#include +#include +#include + +#include +#include + +namespace dmd { class UsbLine; } + +namespace dmodem_android { + +class UsbModem { +public: + using Status = dmd::SipModem::Status; + + /* the core as opt has it (its rate the device's: 8000 or 9600) on + dte, the device fd (Android's, kept open by the caller) opened; + ok() if all of it is */ + UsbModem(dmd::Dte &dte, const dcore::Options &opt, int fd); + ~UsbModem(); + UsbModem(const UsbModem &) = delete; + UsbModem &operator=(const UsbModem &) = delete; + + bool ok() const; + dcore::Modem &modem() { return *m_; } + + /* before run(): the call's state each time it changes */ + void on_status(std::function fn) { + status_fn_ = std::move(fn); + } + + /* until stop() (0), the DTE gone (0) or an error, the device + unplugged among them (-1) */ + int run(); + /* run() returns (any thread) */ + void stop(); + +private: + void report(); + + dmd::Dte &dte_; + std::unique_ptr line_; + std::unique_ptr m_; + bool open_ = false; + int ev_[2] = { -1, -1 }; + std::atomic stopped_{ false }; + std::function status_fn_; + Status status_; +}; + +} // namespace dmodem_android + +#endif diff --git a/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt b/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt index 1eb01a8..080476e 100644 --- a/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt +++ b/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt @@ -58,6 +58,12 @@ object NativeModem { val peer: Boolean = false, /** a peer line's silence ahead of our samples (ms): their room on the way */ val peerLeadMs: Int = 100, + /** + * The line a USB modem's (a SmartUSB56 or a pico-serial Line stick): its descriptor from + * the device's UsbDeviceConnection, open while the modem runs (-1: none); its rate (Hz) + */ + val usbFd: Int = -1, + val usbRate: Int = 9600, ) interface Listener { @@ -84,7 +90,7 @@ object NativeModem { config.user, config.password, config.domain, config.sipPort, config.listen, config.t38, config.dns.joinToString(","), config.country, config.dataFile, config.logLevel, config.sipLogLevel, - config.peer, config.peerLeadMs, + config.peer, config.peerLeadMs, config.usbFd, config.usbRate, ) return if (fd >= 0) ParcelFileDescriptor.adoptFd(fd) else null } @@ -109,7 +115,7 @@ object NativeModem { user: String, password: String, domain: String, sipPort: Int, listen: Boolean, t38: Boolean, dns: String, country: String, dataFile: String, logLevel: Int, sipLogLevel: Int, - peer: Boolean, peerLeadMs: Int, + peer: Boolean, peerLeadMs: Int, usbFd: Int, usbRate: Int, ): Int @JvmStatic diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt b/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt index 6e93ce5..e694796 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt @@ -87,6 +87,8 @@ class ModemService : Service() { /** we are stopping the modem (its exit is ours, not an error) */ @Volatile private var stopping = false + /** the USB modem that's the line (LINE_USB), open while the modem runs */ + private var usbModem: UsbModems.Opened.Device? = null /** the network changed during a call: start again once on hook */ @Volatile @@ -186,7 +188,20 @@ class ModemService : Service() { } ModemState.setError(null) // (not a failure: the SIP server may be on the internet, which needs no leave) - if (!settings.peer && !localNetworkAllowed()) log(NO_LOCAL_NETWORK) + if (settings.sip && !localNetworkAllowed()) log(NO_LOCAL_NETWORK) + // a USB modem: Android's leave to use it (asked now if need be), the device opened while the modem runs + if (settings.usb) { + when (val o = UsbModems.open(this)) { + is UsbModems.Opened.Failed -> { + fail(o.why) + return + } + is UsbModems.Opened.Device -> { + usbModem = o + log("line: the ${o.kind.described}") + } + } + } ModemState.setRun(ModemState.Run.STARTING) if (!startNative()) { fail(ModemState.error.value ?: "the modem didn't start") @@ -194,7 +209,7 @@ class ModemService : Service() { } acquireLocks() // (a line to another phone doesn't care which network: nothing to start again for) - if (!settings.peer) watchNetwork() + if (settings.sip) watchNetwork() ModemState.setRun(ModemState.Run.RUNNING) } @@ -203,7 +218,7 @@ class ModemService : Service() { val cm = getSystemService(ConnectivityManager::class.java) val net = cm.activeNetwork val lp = net?.let { cm.getLinkProperties(it) } - if (lp == null && !settings.peer) { + if (lp == null && settings.sip) { ModemState.setError("no network") return false } @@ -224,6 +239,8 @@ class ModemService : Service() { logLevel = settings.logLevel, sipLogLevel = settings.sipLogLevel, peer = settings.peer, + usbFd = usbModem?.connection?.fileDescriptor ?: -1, + usbRate = UsbModems.RATE, // (Bluetooth's way is slower: more room for the samples on it) peerLeadMs = when (settings.line) { ModemSettings.LINE_BLUETOOTH -> 200 @@ -313,6 +330,9 @@ class ModemService : Service() { ModemState.speaker.setLevel(0) com.neodesktop.dmodem.peer.Peers.stop() NativeModem.stop() + // (the device let go once the modem has) + usbModem?.connection?.close() + usbModem = null ModemState.dte.detach() ModemState.setStatus(ModemState.IDLE) } @@ -471,6 +491,7 @@ class ModemService : Service() { ModemSettings.LINE_BLUETOOTH -> " (line: another phone on Bluetooth)" ModemSettings.LINE_CELL -> " (line: mobile calls)" ModemSettings.LINE_NONE -> " (no line)" + ModemSettings.LINE_USB -> " (line: the ${usbModem?.kind?.label ?: "USB modem"})" else -> "" } } @@ -497,6 +518,7 @@ class ModemService : Service() { private fun callerOfLine(): String = when (settings.line) { ModemSettings.LINE_WIFI, ModemSettings.LINE_BLUETOOTH -> "The other phone" ModemSettings.LINE_CELL -> "A mobile call" + ModemSettings.LINE_USB -> "A call on the phone line" else -> "A SIP call" } diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt b/app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt new file mode 100644 index 0000000..426b14b --- /dev/null +++ b/app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.modem + +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.hardware.usb.UsbDevice +import android.hardware.usb.UsbDeviceConnection +import android.hardware.usb.UsbManager +import android.os.Build +import androidx.core.content.ContextCompat +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withTimeoutOrNull +import kotlin.coroutines.resume + +/** + * The USB modems that can be the modem's line (D-Modem-RE's usb_line.cpp, + * on the device Android opens for the app): a Smart Link SmartUSB56 + * (ST7554) and a pico-serial Line stick (a Si3056 DAA on a phone line). + * The app runs the modem itself: they carry its samples to the line. + */ +object UsbModems { + enum class Kind(val vendor: Int, val product: Int, val label: String) { + SMART_USB56(0x0483, 0x7554, "SmartUSB56"), + PICO_LINE(0x1209, 0x0002, "pico-serial Line"), + ; + + /** "SmartUSB56 (USB 0483:7554)" */ + val described: String get() = "$label (USB %04x:%04x)".format(vendor, product) + } + + /** the modems' rate (Hz): both take 9600, the Si3056's default (dmodemd's too) */ + const val RATE = 9600 + + /** which of them a USB device with these IDs is, or null */ + fun kindOf(vendor: Int, product: Int): Kind? = Kind.entries.firstOrNull { it.vendor == vendor && it.product == product } + + fun kindOf(d: UsbDevice): Kind? = kindOf(d.vendorId, d.productId) + + /** the ones plugged in, and which each is */ + fun plugged(context: Context): List> { + val m = context.getSystemService(UsbManager::class.java) ?: return emptyList() + return m.deviceList.values.mapNotNull { d -> kindOf(d)?.let { d to it } } + } + + /** what the line setting says of what's plugged in */ + fun describe(context: Context): String = plugged(context).let { p -> + if (p.isEmpty()) "none" else p.joinToString(", ") { it.second.label } + } + + /** an opened modem, or why there's none */ + sealed interface Opened { + class Device(val kind: Kind, val connection: UsbDeviceConnection) : Opened + class Failed(val why: String) : Opened + } + + private const val ACTION_PERMISSION = "com.neodesktop.dmodem.USB_MODEM_PERMISSION" + + /** + * The first one plugged in, opened: Android asked first if the app may + * use it (the user has [askMs] to say), unless it has said so already. + */ + suspend fun open(context: Context, askMs: Long = 60_000): Opened { + val m = context.getSystemService(UsbManager::class.java) ?: return Opened.Failed("this phone has no USB host") + val (dev, kind) = plugged(context).firstOrNull() + ?: return Opened.Failed("no USB modem plugged in: a ${Kind.SMART_USB56.described} or a ${Kind.PICO_LINE.described}") + if (!m.hasPermission(dev)) { + val allowed = withTimeoutOrNull(askMs) { ask(context, m, dev) } ?: false + if (!allowed) return Opened.Failed("the ${kind.label} wasn't allowed: allow D-Modem to use it, then start the modem again") + } + val conn = m.openDevice(dev) ?: return Opened.Failed("can't open the ${kind.label}") + return Opened.Device(kind, conn) + } + + /** Android's question for [dev]: whether it was allowed */ + private suspend fun ask(context: Context, m: UsbManager, dev: UsbDevice): Boolean = + suspendCancellableCoroutine { cont -> + val receiver = object : BroadcastReceiver() { + override fun onReceive(c: Context, i: Intent) { + runCatching { context.unregisterReceiver(this) } + if (cont.isActive) cont.resume(i.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) + } + } + ContextCompat.registerReceiver(context, receiver, IntentFilter(ACTION_PERMISSION), ContextCompat.RECEIVER_NOT_EXPORTED) + cont.invokeOnCancellation { runCatching { context.unregisterReceiver(receiver) } } + val flags = if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0 + m.requestPermission(dev, PendingIntent.getBroadcast(context, 2, Intent(ACTION_PERMISSION).setPackage(context.packageName), flags)) + } +} diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt index 2608452..095e9ac 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt @@ -59,13 +59,19 @@ data class ModemSettings( val cellSpeed: String = CELL_VCVM, ) { /** the line is another phone (or this phone's mobile calls, or none), not SIP: the app carries its samples */ - val peer: Boolean get() = line != LINE_SIP + val peer: Boolean get() = line != LINE_SIP && line != LINE_USB + + /** the line is a SIP account's */ + val sip: Boolean get() = line == LINE_SIP + + /** the line is a phone line, through a USB modem (UsbModems): the modem dials it itself */ + val usb: Boolean get() = line == LINE_USB /** no line at all: the modem on its own (AT commands, the terminal, the bridges); a dial gets NO DIALTONE */ val noLine: Boolean get() = line == LINE_NONE /** Enough to start: an account (or the line another phone's). */ - val complete: Boolean get() = peer || (user.isNotBlank() && domain.isNotBlank()) + val complete: Boolean get() = !sip || (user.isNotBlank() && domain.isNotBlank()) /** the commands sent as the modem starts: the init commands, on mobile calls the modulation first */ fun startCommands(): String { @@ -86,6 +92,7 @@ data class ModemSettings( const val LINE_BLUETOOTH = "bluetooth" const val LINE_CELL = "cell" const val LINE_NONE = "none" + const val LINE_USB = "usb" /** the mobile-call line's V.cvm (D-Modem-RE's +MS=V_CVM) */ const val CELL_VCVM = "V_CVM" diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/DashboardScreen.kt b/app/src/main/java/com/neodesktop/dmodem/ui/DashboardScreen.kt index dbe5283..d1932e5 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/DashboardScreen.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/DashboardScreen.kt @@ -307,6 +307,15 @@ private fun LineCard(s: ModemSettings, run: ModemState.Run, network: String?, on PeerLineRows(s, run, network) return@Column } + if (s.usb) { + val context = androidx.compose.ui.platform.LocalContext.current + InfoRow("Via", "a phone line, through a USB modem") + InfoRow("Plugged in", remember(run) { com.neodesktop.dmodem.modem.UsbModems.describe(context) }) + if (run == ModemState.Run.RUNNING) { + Text("Calls ring in the terminal (RING); ATS0=1 answers them", style = MaterialTheme.typography.bodySmall) + } + return@Column + } InfoRow("SIP", if (s.complete) "${s.user}@${s.domain}" else "not set up") InfoRow("Calls in", if (s.listen) "answered (registered)" else "off") InfoRow("Network", network ?: "none") diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt b/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt index 6f541be..c96a61b 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt @@ -187,6 +187,7 @@ class MainActivity : ComponentActivity() { private fun callerOfLine(): String = when (com.neodesktop.dmodem.modem.ModemState.line) { com.neodesktop.dmodem.settings.ModemSettings.LINE_WIFI, com.neodesktop.dmodem.settings.ModemSettings.LINE_BLUETOOTH -> "The other phone" com.neodesktop.dmodem.settings.ModemSettings.LINE_CELL -> "A mobile call" + com.neodesktop.dmodem.settings.ModemSettings.LINE_USB -> "A call on the phone line" else -> "A SIP call" } diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/PeerLineUi.kt b/app/src/main/java/com/neodesktop/dmodem/ui/PeerLineUi.kt index c858077..9a3ee44 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/PeerLineUi.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/PeerLineUi.kt @@ -54,6 +54,7 @@ fun LineChoice(s: ModemSettings, onChange: (ModemSettings) -> Unit) { ModemSettings.LINE_WIFI to "Another phone with D-Modem, on Wi-Fi", ModemSettings.LINE_BLUETOOTH to "Another phone with D-Modem, on Bluetooth", ModemSettings.LINE_CELL to "This phone's mobile calls (slow; root)", + ModemSettings.LINE_USB to "A phone line, through a USB modem", ModemSettings.LINE_NONE to "No line (the modem on its own)", ) var open by remember { mutableStateOf(false) } @@ -74,7 +75,8 @@ fun LineChoice(s: ModemSettings, onChange: (ModemSettings) -> Unit) { onClick = { open = false when (line) { - ModemSettings.LINE_SIP, ModemSettings.LINE_CELL, ModemSettings.LINE_NONE -> onChange(s.copy(line = line)) + ModemSettings.LINE_SIP, ModemSettings.LINE_CELL, ModemSettings.LINE_NONE, ModemSettings.LINE_USB -> + onChange(s.copy(line = line)) ModemSettings.LINE_WIFI -> onChange( s.copy(line = line, peerAddress = if (s.line == line) s.peerAddress else "", peerName = ""), ) @@ -92,6 +94,28 @@ fun LineChoice(s: ModemSettings, onChange: (ModemSettings) -> Unit) { } } +/** A phone line through a USB modem: which ones there are, what's plugged in */ +@Composable +fun UsbLineFields() { + val context = LocalContext.current + // (looked at again when the screen is: plugging one in brings the app up) + val plugged = remember { com.neodesktop.dmodem.modem.UsbModems.describe(context) } + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + "The modem dials and answers a real phone line through a USB modem: a Smart Link SmartUSB56, or a " + + "pico-serial Line stick (with caller ID, and the country's line settings). The phone runs the modem; " + + "the USB one is its line. No SIP account or network needed. Android asks once whether D-Modem may use it.", + style = MaterialTheme.typography.bodySmall, + ) + Text("Plugged in: $plugged", style = MaterialTheme.typography.bodyMedium) + Text( + "Incoming calls ring in the terminal (RING); ATS0=1 answers them. The modem's country (below) sets " + + "the tones it listens for and, on the pico-serial Line, the line's electrical settings. The phone's speaker stays quiet on this line.", + style = MaterialTheme.typography.bodySmall, + ) + } +} + /** * A line to another phone: which one to call, whether this one takes * calls. The two modems connect as over a perfect phone line (V.90/V.91 diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt b/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt index 637274a..b28e3c5 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt @@ -66,6 +66,8 @@ fun SettingsScreen(modifier: Modifier = Modifier, onOpenTerminal: () -> Unit = { LineChoice(s) { s = it } if (s.peer) { PeerLineFields(s) { s = it } + } else if (s.usb) { + UsbLineFields() } else { Text("SIP account (saved with the button below)", style = MaterialTheme.typography.titleSmall) OutlinedTextField( @@ -118,7 +120,7 @@ fun SettingsScreen(modifier: Modifier = Modifier, onOpenTerminal: () -> Unit = { style = MaterialTheme.typography.bodySmall, ) NumberField("Modem log level (0-5)", s.logLevel) { s = s.copy(logLevel = it.coerceIn(0, 5)) } - if (!s.peer) NumberField("SIP log level (0-4)", s.sipLogLevel) { s = s.copy(sipLogLevel = it.coerceIn(0, 4)) } + if (s.sip) NumberField("SIP log level (0-4)", s.sipLogLevel) { s = s.copy(sipLogLevel = it.coerceIn(0, 4)) } Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { Button(onClick = { diff --git a/app/src/main/res/xml/usb_serial_adapters.xml b/app/src/main/res/xml/usb_serial_adapters.xml index 3d165a2..6a0f4ba 100644 --- a/app/src/main/res/xml/usb_serial_adapters.xml +++ b/app/src/main/res/xml/usb_serial_adapters.xml @@ -1,5 +1,5 @@ - + @@ -9,6 +9,9 @@ + + + diff --git a/app/src/test/java/com/neodesktop/dmodem/modem/UsbModemsTest.kt b/app/src/test/java/com/neodesktop/dmodem/modem/UsbModemsTest.kt new file mode 100644 index 0000000..300d150 --- /dev/null +++ b/app/src/test/java/com/neodesktop/dmodem/modem/UsbModemsTest.kt @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.modem + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class UsbModemsTest { + + @Test + fun theTwoModemsByTheirIds() { + assertEquals(UsbModems.Kind.SMART_USB56, UsbModems.kindOf(0x0483, 0x7554)) + assertEquals(UsbModems.Kind.PICO_LINE, UsbModems.kindOf(0x1209, 0x0002)) + // (the pico-serial board, an STM32's other devices: not modems) + assertNull(UsbModems.kindOf(0x1209, 0x0001)) + assertNull(UsbModems.kindOf(0x0483, 0x5740)) + } + + @Test + fun describedWithTheirIds() { + assertEquals("SmartUSB56 (USB 0483:7554)", UsbModems.Kind.SMART_USB56.described) + assertEquals("pico-serial Line (USB 1209:0002)", UsbModems.Kind.PICO_LINE.described) + } +} diff --git a/app/src/test/java/com/neodesktop/dmodem/settings/ModemSettingsTest.kt b/app/src/test/java/com/neodesktop/dmodem/settings/ModemSettingsTest.kt index 6aff5c6..686556c 100644 --- a/app/src/test/java/com/neodesktop/dmodem/settings/ModemSettingsTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/settings/ModemSettingsTest.kt @@ -27,4 +27,19 @@ class ModemSettingsTest { assertFalse(ModemSettings(user = "u").complete) assertTrue(ModemSettings(user = "u", domain = "h").complete) } + + @Test + fun aUsbModemNeedsNoAccountAndIsNoPeer() { + val s = ModemSettings(line = ModemSettings.LINE_USB) + assertTrue(s.complete) + assertTrue(s.usb) + assertFalse(s.peer) + assertFalse(s.sip) + assertFalse(s.noLine) + // (the others as they were) + assertTrue(ModemSettings(line = ModemSettings.LINE_WIFI).peer) + assertTrue(ModemSettings(line = ModemSettings.LINE_NONE).peer) + assertTrue(ModemSettings().sip) + assertFalse(ModemSettings().usb) + } } diff --git a/app/src/test/java/com/neodesktop/dmodem/ui/PeerShotsTest.kt b/app/src/test/java/com/neodesktop/dmodem/ui/PeerShotsTest.kt index 6d882d8..f4e09c0 100644 --- a/app/src/test/java/com/neodesktop/dmodem/ui/PeerShotsTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/ui/PeerShotsTest.kt @@ -76,6 +76,19 @@ class PeerShotsTest { shot("peer-4-no-line") } + @Test + fun aUsbModem() { + save(ModemSettings(line = ModemSettings.LINE_SIP)) + compose.onNodeWithText("Settings").performClick() + compose.onNodeWithText("A SIP account (calls over the internet)").performScrollTo().performClick() + compose.onNodeWithText("A phone line, through a USB modem").performClick() + compose.onNodeWithText("pico-serial Line stick", substring = true).assertExists() + // (none on Robolectric's bus) + compose.onNodeWithText("Plugged in: none").assertExists() + compose.onNodeWithText("SIP account (saved with the button below)").assertDoesNotExist() + shot("peer-5-usb-modem") + } + @Test fun homeOnACall() { save(ModemSettings(line = ModemSettings.LINE_WIFI, peerAddress = "192.168.1.20:5070", peerName = "D-Modem on Pixel 8", listen = true)) diff --git a/native-test/CMakeLists.txt b/native-test/CMakeLists.txt index 359e86e..36551d1 100644 --- a/native-test/CMakeLists.txt +++ b/native-test/CMakeLists.txt @@ -78,3 +78,35 @@ target_compile_options(c_api_test PRIVATE -Wall -Wextra) set_target_properties(c_api_test PROPERTIES LINKER_LANGUAGE CXX) add_test(NAME c_api COMMAND c_api_test) set_tests_properties(c_api PROPERTIES TIMEOUT 120) + +# usb_line_test: the engine on a USB modem's line (usb/usb_modem.h), two +# of them on D-Modem-RE's fake pico-serial Line sticks (its +# test/fake_pico_line.cpp linked in as libusb, so usb_line.cpp finds the +# stick by libusb's own calls: usb_fake_device.cpp) calling each other +# through its simulated exchange (test/line_exchange.cpp); libusb.h from +# the release the app builds +include(${CMAKE_CURRENT_SOURCE_DIR}/../app/src/main/cpp/usb/libusb.cmake) +set(_app ${CMAKE_CURRENT_SOURCE_DIR}/../app/src/main/cpp) +set(_dmd ${DMODEM_RE_DIR}/dmodemd) +add_library(dmodem_engine_usb STATIC ${_app}/engine.cpp + ${_app}/peer_modem.cpp ${_app}/dmodem_engine.cpp + ${_app}/usb/usb_modem.cpp ${_dmd}/usb_line.cpp ${_dmd}/si3056.cpp + usb_fake_device.cpp ${_dmd}/test/fake_pico_line.cpp) +target_include_directories(dmodem_engine_usb PUBLIC ${_app}) +target_include_directories(dmodem_engine_usb SYSTEM PUBLIC + ${DMODEM_LIBUSB_SRC}/libusb) +target_compile_definitions(dmodem_engine_usb PUBLIC DMODEM_ENGINE_USB) +target_link_libraries(dmodem_engine_usb PUBLIC dmodem_sip) + +add_executable(usb_host usb_host.cpp) +target_link_libraries(usb_host PRIVATE dmodem_engine_usb Threads::Threads) +target_compile_options(usb_host PRIVATE -Wall -Wextra) + +add_executable(usb_exchange ${_dmd}/test/line_exchange.cpp) +target_link_libraries(usb_exchange PRIVATE dmodem_core dmodem_dsp + dmodem_link m Threads::Threads) + +add_test(NAME usb_line COMMAND python3 + ${CMAKE_CURRENT_SOURCE_DIR}/usb_line_test.py $ + $) +set_tests_properties(usb_line PROPERTIES TIMEOUT 300) diff --git a/native-test/usb_fake_device.cpp b/native-test/usb_fake_device.cpp new file mode 100644 index 0000000..ec151e1 --- /dev/null +++ b/native-test/usb_fake_device.cpp @@ -0,0 +1,16 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + * + * usb_fake_device.cpp - the build host's usb_android.h: the fake + * stick (fake_pico_line.cpp) is found by + * libusb's own calls, no descriptor to wrap + * + */ +#include "usb/usb_android.h" + +namespace dmodem_android { + +void usb_use_fd(int) {} + +} // namespace dmodem_android diff --git a/native-test/usb_host.cpp b/native-test/usb_host.cpp new file mode 100644 index 0000000..77c1e57 --- /dev/null +++ b/native-test/usb_host.cpp @@ -0,0 +1,87 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + * + * usb_host.cpp - the app's engine on a USB modem's line (engine.h, + * usb_modem.h) as a program, for usb_line_test.py: the + * device D-Modem-RE's fake pico-serial Line stick + * (test/fake_pico_line.cpp, linked in as libusb), its + * line the simulated exchange's at $FAKE_PICO_LINE_SOCKET + * + * The modem's DTE on stdin and stdout; on stderr the log, and + * STATUS and EXIT lines. + * + * usb_host [rate] + * + */ +#include +#include +#include +#include +#include + +#include + +#include "engine.h" + +using namespace dmodem_android; + +namespace { + +std::atomic exited{ false }; + +/* what came on from to to, false at from's end (or to's) */ +bool pass(int from, int to) +{ + char buf[4096]; + ssize_t n = read(from, buf, sizeof(buf)); + if (n <= 0) + return false; + for (ssize_t o = 0; o < n;) { + ssize_t w = write(to, buf + o, n - o); + if (w <= 0) + return false; + o += w; + } + return true; +} + +} // namespace + +int main(int argc, char *argv[]) +{ + Config cfg; + Engine &e = Engine::instance(); + + signal(SIGPIPE, SIG_IGN); + setvbuf(stderr, nullptr, _IOLBF, 0); + cfg.usb_fd = 0; /* (the fake has its own: any will do) */ + cfg.usb_rate = argc > 1 ? atoi(argv[1]) : 9600; + cfg.log_level = getenv("USB_LOG") ? atoi(getenv("USB_LOG")) : 1; + cfg.country = getenv("USB_COUNTRY") ? getenv("USB_COUNTRY") : ""; + int dte = e.start(cfg, + [](const Status &s) { + fprintf(stderr, "STATUS %d %d %u %u\n", (int)s.link, + s.offhook ? 1 : 0, s.tx_rate, s.rx_rate); + }, + [](int result) { + fprintf(stderr, "EXIT %d\n", result); + exited = true; + }); + if (dte < 0) { + fprintf(stderr, "EXIT -1\n"); + return 1; + } + struct pollfd p[2] = { { 0, POLLIN, 0 }, { dte, POLLIN, 0 } }; + while (!exited) { + if (poll(p, 2, 200) < 0) + break; + if ((p[0].revents & (POLLIN | POLLHUP)) && !pass(0, dte)) + break; + if ((p[1].revents & (POLLIN | POLLHUP)) && !pass(dte, 1)) + break; + } + e.stop(); + close(dte); + return 0; +} diff --git a/native-test/usb_line_test.py b/native-test/usb_line_test.py new file mode 100644 index 0000000..d92cc48 --- /dev/null +++ b/native-test/usb_line_test.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright (C) 2026 Neo-Desktop +# +# usb_line_test.py : the app's engine on a USB +# modem's line (usb_modem.h), two of them (usb_host) on D-Modem-RE's fake +# pico-serial Line sticks whose lines are the simulated exchange's, 1001 +# and 1002 (as D-Modem-RE's pico_line_test.py runs dmodemd --usb): +# +# - each says it's on a pico-serial Line (ATI3); +# - 1001 dials 1002 (ATX4: after the dial tone, in DTMF); 1002 rings, +# shows the caller ID (AT#CID=1), answers at the second ring (ATS0=2); +# both CONNECT, and the engine's status says online; a line of text +# goes each way; 1001 hangs up (+++ ATH), 1002 NO CARRIER; +# - the exchange gone (the sticks unplugged): both engines stop with an +# error (EXIT -1), as the app's modem does when the stick is pulled. +import os, re, shutil, subprocess, sys, tempfile, threading, time + +host, exchange = sys.argv[1], sys.argv[2] +rate = "9600" +tmp = tempfile.mkdtemp(prefix="dmodem-usb-line-") + +procs = [] +events = [] +ex = subprocess.Popen([exchange, rate, tmp, "1001", "1002"], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, text=True) +procs.append(ex) +threading.Thread(target=lambda: [events.append(l.strip()) for l in ex.stdout], daemon=True).start() +t0 = time.time() +while "ready" not in events and time.time() - t0 < 5: + time.sleep(0.05) + + +class Modem: + """the engine (usb_host) on line 's fake stick: its DTE, its log""" + def __init__(self, n): + self.n = n + env = dict(os.environ, FAKE_PICO_LINE_SOCKET=os.path.join(tmp, n + ".sock")) + self.p = subprocess.Popen([host, rate], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, env=env) + procs.append(self.p) + self.buf = b"" + self.log = [] + self.lock = threading.Lock() + threading.Thread(target=self._dte, daemon=True).start() + threading.Thread(target=self._log, daemon=True).start() + + def _dte(self): + while True: + d = os.read(self.p.stdout.fileno(), 4096) + if not d: + return + with self.lock: + self.buf += d + + def _log(self): + for l in self.p.stderr: + self.log.append(l.decode(errors="replace").rstrip()) + + def write(self, b): + self.p.stdin.write(b) + self.p.stdin.flush() + + def expect(self, pat, t): + end = time.time() + t + while time.time() < end: + with self.lock: + m = re.search(pat, self.buf) + if m: + self.buf = self.buf[m.end():] + return m + time.sleep(0.05) + return None + + def cmd(self, c, pat=rb"OK\r\n", t=5): + self.write(c + b"\r") + return self.expect(pat, t) + + def logged(self, pat, t): + end = time.time() + t + while time.time() < end: + if any(re.search(pat, l) for l in list(self.log)): + return True + time.sleep(0.1) + return False + + +ok = True +def check(what, cond): + global ok + print("%s: %s" % (what, "yes" if cond else "NO")) + ok = ok and bool(cond) + + +try: + a = Modem("1001") + b = Modem("1002") + for m in (a, b): + check("%s ATE0" % m.n, m.cmd(b"ATE0", t=15)) + check("%s ATI3: pico-serial Line" % m.n, + m.cmd(b"ATI3", rb"pico-serial Line \(Si3056\)\r\n(\r\n)?OK\r\n")) + check("1002 answers at the 2nd ring", b.cmd(b"ATS0=2")) + check("1002 caller ID on", b.cmd(b"AT#CID=1")) + check("1001 waits for the dial tone", a.cmd(b"ATX4")) + + t = time.time() + a.write(b"ATD1002\r") + check("1002 RING", b.expect(rb"RING\r\n", 15)) + cid = b.expect(rb"NMBR = (\d+)\r\n", 6) + check("1002 caller ID 1001", cid and cid.group(1) == b"1001") + ca = a.expect(rb"(CONNECT[^\r]*|NO CARRIER|BUSY|NO DIALTONE)\r\n", 50) + cb = b.expect(rb"(CONNECT[^\r]*|NO CARRIER)\r\n", 10) + print("1001: %s, 1002: %s, %.1f s" % (ca and ca.group(1).decode(), + cb and cb.group(1).decode(), time.time() - t)) + check("both CONNECT", ca and cb and ca.group(1).startswith(b"CONNECT") + and cb.group(1).startswith(b"CONNECT")) + check("the exchange heard 1002 dialled", "1001 dialled 1002" in events) + check("1001's status: online, off hook", a.logged(r"^STATUS 2 1 [1-9]\d* [1-9]\d*$", 5)) + a.write(b"hello from 1001\r\n") + check("1002 gets 1001's line", b.expect(rb"hello from 1001", 10)) + b.write(b"hello from 1002\r\n") + check("1001 gets 1002's line", a.expect(rb"hello from 1002", 10)) + time.sleep(1.2) + a.write(b"+++") + check("1001 +++ OK", a.expect(rb"OK\r\n", 5)) + check("1001 ATH", a.cmd(b"ATH")) + check("1002 NO CARRIER", b.expect(rb"NO CARRIER\r\n", 30)) + check("1001's status: idle, on hook", a.logged(r"^STATUS 0 0 0 0$", 5)) + + ex.terminate() + ex.wait(5) + for m in (a, b): + check("%s stops once unplugged (EXIT -1)" % m.n, m.logged(r"^EXIT -1$", 15)) +finally: + for p in reversed(procs): + if p.poll() is None: + p.terminate() + for p in procs: + try: + p.wait(5) + except subprocess.TimeoutExpired: + p.kill() + if not ok: + for m in ("a", "b"): + if m in globals(): + print("--- %s's log" % globals()[m].n) + print("\n".join(globals()[m].log[-60:])) + shutil.rmtree(tmp, ignore_errors=True) +print("PASS" if ok else "FAIL") +sys.exit(0 if ok else 1)