diff --git a/app/src/androidTest/java/com/neodesktop/dmodem/NativeModemTest.kt b/app/src/androidTest/java/com/neodesktop/dmodem/NativeModemTest.kt index a854445..dcf44fd 100644 --- a/app/src/androidTest/java/com/neodesktop/dmodem/NativeModemTest.kt +++ b/app/src/androidTest/java/com/neodesktop/dmodem/NativeModemTest.kt @@ -30,18 +30,21 @@ class NativeModemTest { private val exits = CopyOnWriteArrayList() private val exited = CountDownLatch(1) + /** the modem stopped and the listener gone after each test */ @After fun tearDown() { NativeModem.stop() NativeModem.listener = null } + /** a SIP account at nowhere (no call is made), the modem's data in the app's files */ private fun config() = NativeModem.Config( user = "test", password = "x", domain = "127.0.0.1:5999", sipPort = 15060, dns = listOf("127.0.0.1"), logLevel = 1, sipLogLevel = 3, dataFile = File(InstrumentationRegistry.getInstrumentation().targetContext.filesDir, "test_dsp").path, ) + /** [cmd] sent on [dte]: what came back by the time [expect] matched or [secs] passed */ private fun command(dte: ParcelFileDescriptor, cmd: String, expect: Regex, secs: Int = 10): String { val out = ParcelFileDescriptor.AutoCloseOutputStream(dte.dup()) out.write("$cmd\r".toByteArray()) @@ -64,10 +67,13 @@ class NativeModemTest { return buf.toString() } + /** the modem starts (once at a time), answers AT, ATI3 and ATX3, and stops with 0, SIP's log through the hook */ @Test fun startsAnswersAndStops() { NativeModem.listener = object : NativeModem.Listener { + /** the line kept */ override fun onLog(line: String) { logs.add(line) } + /** the result kept, the test woken */ override fun onExit(result: Int) { exits.add(result); exited.countDown() } } val dte = NativeModem.start(config()) @@ -90,9 +96,11 @@ class NativeModemTest { dte.close() } + /** closing the DTE stops the modem, with 0 */ @Test fun closingTheDteStopsTheModem() { NativeModem.listener = object : NativeModem.Listener { + /** the result kept, the test woken */ override fun onExit(result: Int) { exits.add(result); exited.countDown() } } val dte = NativeModem.start(config()) diff --git a/app/src/main/cpp/dmodem_engine.cpp b/app/src/main/cpp/dmodem_engine.cpp index 0dfc1e4..834b815 100644 --- a/app/src/main/cpp/dmodem_engine.cpp +++ b/app/src/main/cpp/dmodem_engine.cpp @@ -22,12 +22,14 @@ namespace { std::mutex mu; dmodem_callbacks cbs; +/* the callbacks set, copied under the lock */ dmodem_callbacks callbacks() { std::lock_guard lk(mu); return cbs; } +/* s, or "" for NULL */ const char *str(const char *s) { return s ? s : ""; @@ -35,6 +37,7 @@ const char *str(const char *s) } // namespace +/* see dmodem_engine.h */ extern "C" void dmodem_config_init(dmodem_config *c) { *c = dmodem_config(); @@ -44,6 +47,7 @@ extern "C" void dmodem_config_init(dmodem_config *c) c->peer_lead_ms = 100; } +/* see dmodem_engine.h */ extern "C" void dmodem_set_callbacks(const dmodem_callbacks *cb) { { @@ -65,6 +69,7 @@ extern "C" void dmodem_set_callbacks(const dmodem_callbacks *cb) }) : nullptr); } +/* see dmodem_engine.h */ extern "C" int dmodem_start(const dmodem_config *c) { Config cfg; @@ -101,16 +106,19 @@ extern "C" int dmodem_start(const dmodem_config *c) }); } +/* see dmodem_engine.h */ extern "C" void dmodem_stop(void) { Engine::instance().stop(); } +/* see dmodem_engine.h */ extern "C" int dmodem_running(void) { return Engine::instance().running(); } +/* see dmodem_engine.h */ extern "C" void dmodem_peer_event(const char *line) { Engine::instance().peer_event(str(line)); diff --git a/app/src/main/cpp/engine.cpp b/app/src/main/cpp/engine.cpp index adb6e21..3ce4680 100644 --- a/app/src/main/cpp/engine.cpp +++ b/app/src/main/cpp/engine.cpp @@ -38,6 +38,7 @@ const int RATE = 8000; std::mutex log_mu; Engine::LogFn log_fn; +/* a log line to the app's function, if it set one */ void log_hook(const char *line) { std::lock_guard lk(log_mu); @@ -45,6 +46,7 @@ void log_hook(const char *line) log_fn(line); } +/* the app's link state for the core's */ Status::Link link_of(dcore::LinkState s) { switch (s) { diff --git a/app/src/main/cpp/jni.cpp b/app/src/main/cpp/jni.cpp index 3968b5c..1d64f18 100644 --- a/app/src/main/cpp/jni.cpp +++ b/app/src/main/cpp/jni.cpp @@ -37,12 +37,14 @@ int speaker_fd[2] = { -1, -1 }; struct Attached { JNIEnv *env = nullptr; bool ours = false; + /* the thread detached, if attached here */ ~Attached() { if (ours) vm->DetachCurrentThread(); } }; +/* this thread's JNIEnv, attaching it if need be (nullptr if that fails) */ JNIEnv *env_now() { thread_local Attached a; @@ -84,6 +86,7 @@ std::string printable(const char *line) return s; } +/* a log line to NativeModem.onLog() */ void log_line(const char *line) { JNIEnv *env = env_now(); @@ -99,6 +102,7 @@ void log_line(const char *line) env->DeleteLocalRef(s); } +/* the call's state to NativeModem.onStatus() */ void status_changed(const Status &st) { JNIEnv *env = env_now(); @@ -110,6 +114,7 @@ void status_changed(const Status &st) clear(env); } +/* the modem's end to NativeModem.onExit() */ void exited(int result) { JNIEnv *env = env_now(); @@ -138,6 +143,7 @@ void line_started(bool caller, const char *dial, int fd) env->DeleteLocalRef(d); } +/* the speaker's level to NativeModem.onSpeaker() */ void speaker_level(int level) { JNIEnv *env = env_now(); @@ -157,6 +163,7 @@ void speaker_sound(const int16_t *pcm, int n) } } +/* s as a std::string ("" for null) */ std::string str(JNIEnv *env, jstring s) { if (!s) @@ -196,11 +203,13 @@ jint native_start(JNIEnv *env, jclass, jstring user, jstring password, line_started); } +/* NativeModem.nativeStop(): the engine stopped */ void native_stop(JNIEnv *, jclass) { Engine::instance().stop(); } +/* NativeModem.nativePeerEvent(): a peer line's event to the engine */ void native_peer_event(JNIEnv *env, jclass, jstring line) { Engine::instance().peer_event(str(env, line).c_str()); @@ -215,6 +224,7 @@ jint native_speaker_fd(JNIEnv *, jclass) return fd; } +/* NativeModem.nativeRunning(): whether the engine runs */ jboolean native_running(JNIEnv *, jclass) { return Engine::instance().running(); diff --git a/app/src/main/cpp/peer_modem.cpp b/app/src/main/cpp/peer_modem.cpp index f0890a8..ea0cf71 100644 --- a/app/src/main/cpp/peer_modem.cpp +++ b/app/src/main/cpp/peer_modem.cpp @@ -75,20 +75,27 @@ bool send_all(int fd, const void *buf, size_t n) app's while off hook */ class PeerLine final : public dcore::Host { public: + /* on dte, lead_ms of silence ahead of the modem's samples */ PeerLine(dmd::Dte &dte, int lead_ms) : dte_(dte), lead_ms_(lead_ms) {} + /* the app's end of the line closed, if off hook */ ~PeerLine() { hang_up(); } s16 start(dcore::Modem &m) override; + /* on hook: the line closed */ s16 stop(dcore::Modem &) override { DBG("on hook\n"); hang_up(); return 0; } + /* the driver's name, for the log */ const char *driver_name() override { return "peer"; } + /* the app's line says when the far end answers (ANSWERED) */ bool signals_answer(dcore::Modem &) override { return true; } + /* the modem's output to the DTE */ s32 dte_write(dcore::Modem &, const char *buf, s32 n) override { return dte_.write(buf, n); } + /* the core's clock: the monotonic ms */ u64 now_ms() override { return dcore::monotonic_ms(); } /* ATM, ATL */ void speaker(dcore::Modem &, s16 volume) override { @@ -100,6 +107,7 @@ public: PeerModem::LineFn line_fn; dmd::SipModem::Speaker speaker_to; + /* the line's socket, -1 on hook */ int fd() const { return fd_; } /* the ms until the line may take samples again (0: now) */ long wait_ms(); @@ -108,6 +116,7 @@ public: int audio(dcore::Modem &m); private: + /* the line's socket closed, if open */ void hang_up() { if (fd_ >= 0) { close(fd_); @@ -257,16 +266,19 @@ PeerModem::~PeerModem() close(fd); } +/* the core up and the event pipe made */ bool PeerModem::ok() const { return m_ && m_->ok() && ev_[0] >= 0; } +/* where an off hook's line goes (before run()) */ void PeerModem::on_line(LineFn fn) { line_->line_fn = std::move(fn); } +/* see peer_modem.h */ void PeerModem::on_speaker(dmd::SipModem::Speaker s) { line_->speaker_to = std::move(s); @@ -313,6 +325,7 @@ void PeerModem::act(const char *s) } } +/* the call's state to status_fn_, when it changed */ void PeerModem::report() { Status s; diff --git a/app/src/main/cpp/peer_modem.h b/app/src/main/cpp/peer_modem.h index 6bbac25..096eb75 100644 --- a/app/src/main/cpp/peer_modem.h +++ b/app/src/main/cpp/peer_modem.h @@ -53,6 +53,7 @@ public: PeerModem &operator=(const PeerModem &) = delete; bool ok() const; + /* the core */ dcore::Modem &modem() { return *m_; } /* before run() */ diff --git a/app/src/main/cpp/pty.c b/app/src/main/cpp/pty.c index d013dce..05646bb 100644 --- a/app/src/main/cpp/pty.c +++ b/app/src/main/cpp/pty.c @@ -21,6 +21,7 @@ #include #include +/* an IOException thrown: what, and errno's message */ static void throw_io(JNIEnv *env, const char *what) { char msg[256]; @@ -45,6 +46,7 @@ static char **strings(JNIEnv *env, jobjectArray a) return out; } +/* what strings() made, freed */ static void free_strings(char **s) { for (char **p = s; p && *p; p++) @@ -146,6 +148,7 @@ Java_com_neodesktop_dmodem_local_Pty_start(JNIEnv *env, jclass cls, jstring jpat return master; } +/* resize(fd, rows, cols): the pty's window size set */ JNIEXPORT void JNICALL Java_com_neodesktop_dmodem_local_Pty_resize(JNIEnv *env, jclass cls, jint fd, jint rows, jint cols) { @@ -258,6 +261,7 @@ Java_com_neodesktop_dmodem_local_Pty_signalSession(JNIEnv *env, jclass cls, jint return count; } +/* close(fd): the fd closed */ JNIEXPORT void JNICALL Java_com_neodesktop_dmodem_local_Pty_close(JNIEnv *env, jclass cls, jint fd) { diff --git a/app/src/main/cpp/usb/usb_android.cpp b/app/src/main/cpp/usb/usb_android.cpp index 0656cef..d8d00f5 100644 --- a/app/src/main/cpp/usb/usb_android.cpp +++ b/app/src/main/cpp/usb/usb_android.cpp @@ -20,6 +20,7 @@ libusb_device_handle *wrapped_ = nullptr; namespace dmodem_android { +/* see usb_android.h */ void usb_use_fd(int fd) { fd_ = fd; diff --git a/app/src/main/cpp/usb/usb_modem.cpp b/app/src/main/cpp/usb/usb_modem.cpp index 0cac8f9..9604d37 100644 --- a/app/src/main/cpp/usb/usb_modem.cpp +++ b/app/src/main/cpp/usb/usb_modem.cpp @@ -60,11 +60,13 @@ UsbModem::~UsbModem() close(e); } +/* the core up, the device open and the wake pipe made */ bool UsbModem::ok() const { return m_ && m_->ok() && open_ && ev_[0] >= 0; } +/* see usb_modem.h: stopped_ set and run()'s poll woken */ void UsbModem::stop() { stopped_ = true; diff --git a/app/src/main/cpp/usb/usb_modem.h b/app/src/main/cpp/usb/usb_modem.h index 1c6c543..3f37d88 100644 --- a/app/src/main/cpp/usb/usb_modem.h +++ b/app/src/main/cpp/usb/usb_modem.h @@ -37,6 +37,7 @@ public: UsbModem &operator=(const UsbModem &) = delete; bool ok() const; + /* the core */ dcore::Modem &modem() { return *m_; } /* before run(): the call's state each time it changes */ diff --git a/app/src/main/cpp/usb/usb_transfers.cpp b/app/src/main/cpp/usb/usb_transfers.cpp index 8aaa603..3fc4195 100644 --- a/app/src/main/cpp/usb/usb_transfers.cpp +++ b/app/src/main/cpp/usb/usb_transfers.cpp @@ -30,6 +30,7 @@ Way in_, out_; std::unordered_map sent_at_; uint64_t trips_ = 0, trip_us_ = 0, trip_max_us_ = 0, gap_max_us_ = 0, last_back_us_ = 0; +/* the monotonic clock, in microseconds */ uint64_t now_us() { struct timespec ts; @@ -43,11 +44,13 @@ int in_said_ = 0; /* each transfer's own callback, called after it's counted */ std::unordered_map callbacks_; +/* whether t is an IN transfer */ bool is_in(const libusb_transfer *t) { return t->endpoint & LIBUSB_ENDPOINT_IN; } +/* t's callback in libusb: t counted (and its round trip, the first few logged), then its own callback */ void LIBUSB_CALL counted(libusb_transfer *t) { Way &w = is_in(t) ? in_ : out_; @@ -105,6 +108,7 @@ void LIBUSB_CALL counted(libusb_transfer *t) namespace dmodem_android { +/* see usb_android.h */ void usb_transfers_reset() { in_ = Way(); @@ -115,6 +119,7 @@ void usb_transfers_reset() trips_ = trip_us_ = trip_max_us_ = gap_max_us_ = last_back_us_ = 0; } +/* see usb_android.h (the round trips' and gaps' counts started again) */ void usb_transfer_stats(char *buf, size_t len) { snprintf(buf, len, diff --git a/app/src/main/java/com/neodesktop/dmodem/DModemApp.kt b/app/src/main/java/com/neodesktop/dmodem/DModemApp.kt index e8bc4d2..6102cda 100644 --- a/app/src/main/java/com/neodesktop/dmodem/DModemApp.kt +++ b/app/src/main/java/com/neodesktop/dmodem/DModemApp.kt @@ -15,6 +15,7 @@ class DModemApp : Application() { const val CHANNEL_CALLS = "calls" } + /** the notification channels made; the terminal, fax and dial-in set up; the log and the DTE's console started */ override fun onCreate() { super.onCreate() val ch = NotificationChannel( diff --git a/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt b/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt index 080476e..d4c1cde 100644 --- a/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt +++ b/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt @@ -67,7 +67,9 @@ object NativeModem { ) interface Listener { + /** a line of the modem's or SIP's log */ fun onLog(line: String) {} + /** the call's state, as it changes */ fun onStatus(status: Status) {} /** The modem stopped: 0 by [stop] or the DTE closed, -1 on an error. */ fun onExit(result: Int) {} @@ -110,6 +112,7 @@ object NativeModem { /** A peer line's event to the modem: RING, CANCEL, ANSWERED, FAILED , DROPPED. */ fun peerEvent(line: String) = nativePeerEvent(line) + /** the modem started (jni.cpp): the app's end of its DTE's socket, or -1 */ @JvmStatic private external fun nativeStart( user: String, password: String, domain: String, sipPort: Int, @@ -118,31 +121,38 @@ object NativeModem { peer: Boolean, peerLeadMs: Int, usbFd: Int, usbRate: Int, ): Int + /** a peer line's event to the engine */ @JvmStatic private external fun nativePeerEvent(line: String) + /** the speaker sound's socket, -1 after the first call */ @JvmStatic private external fun nativeSpeakerFd(): Int + /** the modem stopped, waiting for it */ @JvmStatic private external fun nativeStop() + /** whether the modem runs */ @JvmStatic private external fun nativeRunning(): Boolean // the native library's callbacks (jni.cpp) + /** a log line, to the listener */ @JvmStatic private fun onLog(line: String) { listener?.onLog(line) } + /** the call's state, to the listener as a [Status] */ @JvmStatic private fun onStatus(link: Int, offhook: Boolean, txRate: Int, rxRate: Int) { val l = Link.entries.getOrElse(link) { Link.IDLE } listener?.onStatus(Status(l, offhook, txRate, rxRate)) } + /** a peer line's call to the listener (its descriptor closed if there is none) */ @JvmStatic private fun onLine(caller: Boolean, dial: String, fd: Int) { val pfd = ParcelFileDescriptor.adoptFd(fd) @@ -150,11 +160,13 @@ object NativeModem { if (l == null) pfd.close() else l.onLine(caller, dial, pfd) } + /** the speaker's level, to the listener */ @JvmStatic private fun onSpeaker(level: Int) { listener?.onSpeaker(level) } + /** the modem's end, to the listener */ @JvmStatic private fun onExit(result: Int) { listener?.onExit(result) diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/BluetoothBridge.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/BluetoothBridge.kt index 05d4789..8aa98b1 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/BluetoothBridge.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/BluetoothBridge.kt @@ -55,6 +55,7 @@ class BluetoothBridge( private val adapter: BluetoothAdapter? get() = context.getSystemService(BluetoothManager::class.java)?.adapter + /** the bridge's thread started (true), or why not in [state] (false) */ fun start(): Boolean { if (running) return true val a = adapter @@ -79,6 +80,7 @@ class BluetoothBridge( return true } + /** the bridge stopped: its sockets closed, its thread joined */ fun stop() { running = false runCatching { server?.close() } @@ -88,6 +90,7 @@ class BluetoothBridge( _state.value = State.Stopped } + /** [why] in [state]; false, for [start] */ private fun fail(why: String): Boolean { _state.value = State.Failed(why) return false @@ -144,6 +147,7 @@ class BluetoothBridge( } } + /** [c] served by the bridge until it closes, or told BUSY if the modem's in use; [known] its name */ private fun serveSocket(c: BluetoothSocket, known: String? = null) { val d = c.remoteDevice val name = known ?: runCatching { d?.name }.getOrNull() ?: d?.address ?: "a device" @@ -174,6 +178,7 @@ class BluetoothBridge( fun permissions(): Array = if (Build.VERSION.SDK_INT >= 31) arrayOf(Manifest.permission.BLUETOOTH_CONNECT) else emptyArray() + /** whether the app has [permissions] */ fun hasPermission(context: Context): Boolean = permissions().all { context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED } diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/Bridges.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/Bridges.kt index 3c6a03b..5d7f001 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/Bridges.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/Bridges.kt @@ -61,6 +61,7 @@ object Bridges { /** "RING" from the modem: RI on for a while */ @Volatile private var ringUntil = 0L + /** the line signals kept up with the modem's state and its RINGs (once) */ private fun watch() { if (watching) return watching = true @@ -79,6 +80,7 @@ object Bridges { }) } + /** the line signals for [r] and [s]: DSR running, DCD online, RI while a RING is recent and on hook */ private fun update(r: ModemState.Run, s: NativeModem.Status) { signals.value = LineSignals( ready = r == ModemState.Run.RUNNING, @@ -144,6 +146,7 @@ object Bridges { } } + /** every bridge stopped, the settings forgotten */ @Synchronized fun stopAll() { stopTcp() @@ -153,6 +156,7 @@ object Bridges { applied = null } + /** the TCP bridge stopped */ private fun stopTcp() { tcp?.stop() tcp = null @@ -166,6 +170,7 @@ object Bridges { scope.launch { u.withBoard(f) } } + /** the USB bridge stopped, its board gone */ private fun stopUsb() { usb?.stop() usb = null @@ -175,6 +180,7 @@ object Bridges { _usb.value = UsbBridge.State.Stopped } + /** the USB gadget stopped (in the background) */ private fun stopGadget() { val g = gadget gadget = null @@ -196,6 +202,7 @@ object Bridges { return if (m == null) SerialFormat(baud) else SerialFormat(baud, m.groupValues[1].toInt(), m.groupValues[2][0], m.groupValues[3].toInt()) } + /** the Bluetooth bridge stopped */ private fun stopBt() { bt?.stop() bt = null diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/HostService.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/HostService.kt index db2ddae..d768829 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/HostService.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/HostService.kt @@ -33,8 +33,10 @@ class HostService : Service() { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private var watching = false + /** not bound: started only */ override fun onBind(intent: Intent?): IBinder? = null + /** in the foreground; the bridges kept as the settings are (stopped with the service when internet mode or every bridge is off), the notification saying who's online */ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { ServiceCompat.startForeground( this, NOTIFICATION_ID, notification("Starting"), @@ -57,12 +59,14 @@ class HostService : Service() { return START_STICKY } + /** the watch cancelled, the bridges stopped */ override fun onDestroy() { scope.cancel() Bridges.stopAll() super.onDestroy() } + /** the ongoing notification, saying [text], opening the app */ private fun notification(text: String): Notification { val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE) return NotificationCompat.Builder(this, DModemApp.CHANNEL_MODEM) diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/ModemTty.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/ModemTty.kt index c515769..ba692be 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/ModemTty.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/ModemTty.kt @@ -81,11 +81,13 @@ class ModemTty( /** the program's octets: -1 once it has closed the port (or the bridge let it go) */ private inner class Input(private val fd: Int) : InputStream() { + /** one octet, or -1 at the end */ override fun read(): Int { val b = ByteArray(1) return if (read(b, 0, 1) <= 0) -1 else b[0].toInt() and 0xff } + /** what the program sent into [b], waiting for it; -1 once it closed the port or was let go */ override fun read(b: ByteArray, off: Int, len: Int): Int { while (true) { if (kicked) return -1 @@ -98,8 +100,10 @@ class ModemTty( /** the modem's octets to the program */ private class Output(private val fd: Int) : OutputStream() { + /** one octet to the program */ override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1) + /** [len] octets of [b] to the pty; an IOException if the write fails */ override fun write(b: ByteArray, off: Int, len: Int) { if (!Pty.write(fd, b, off, len)) throw IOException("ttyDM0: the write failed") } diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/PicoSerial.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/PicoSerial.kt index 6da9181..5222f5d 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/PicoSerial.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/PicoSerial.kt @@ -126,11 +126,14 @@ object PicoSerialProtocol { val roleChanges: Long, ) + /** [b]'s byte at [i], unsigned */ private fun u8(b: ByteArray, i: Int) = b[i].toInt() and 0xff + /** [b]'s little-endian u32 at [i] */ private fun u32(b: ByteArray, i: Int): Long = (u8(b, i).toLong()) or (u8(b, i + 1).toLong() shl 8) or (u8(b, i + 2).toLong() shl 16) or (u8(b, i + 3).toLong() shl 24) + /** GET_INFO's reply as an [Info], or null when it's short or no protocol */ fun info(b: ByteArray): Info? { if (b.size < 14 || u8(b, 0) < 1) return null return Info( @@ -146,11 +149,13 @@ object PicoSerialProtocol { ) } + /** GET_INPUTS' reply as [Inputs], or null when it's short */ fun inputs(b: ByteArray): Inputs? { if (b.size < 5) return null return Inputs(Role.of(u8(b, 0)), u8(b, 1), u8(b, 2), u8(b, 3), u8(b, 4)) } + /** GET_STATS' reply as [Stats], or null when it's short */ fun stats(b: ByteArray): Stats? { if (b.size < 32) return null val v = LongArray(8) { u32(b, it * 4) } @@ -178,29 +183,38 @@ interface UsbControl { /** [UsbControl] on Android's USB host: vendor requests to [itf] on [conn] */ class AndroidUsbControl(private val conn: UsbDeviceConnection, private val itf: Int) : UsbControl { + /** a vendor IN request to [itf]: its data, null if it failed */ override fun read(request: Int, value: Int, length: Int): ByteArray? { val buf = ByteArray(length) val n = conn.controlTransfer(0xC1, request, value, itf, buf, length, 500) return if (n < 0) null else buf.copyOf(n) } + /** a vendor OUT request to [itf], no data: whether it went */ override fun write(request: Int, value: Int): Boolean = conn.controlTransfer(0x41, request, value, itf, null, 0, 500) >= 0 } /** A pico-serial board, by its control requests. */ class PicoSerial(private val control: UsbControl) { + /** the board's info (GET_INFO), or null */ fun info(): PicoSerialProtocol.Info? = control.read(PicoSerialProtocol.GET_INFO, 0, 64)?.let(PicoSerialProtocol::info) + /** the board's lines now (GET_INPUTS), or null */ fun inputs(): PicoSerialProtocol.Inputs? = control.read(PicoSerialProtocol.GET_INPUTS, 0, 5)?.let(PicoSerialProtocol::inputs) + /** the board's counts (GET_STATS), or null */ fun stats(): PicoSerialProtocol.Stats? = control.read(PicoSerialProtocol.GET_STATS, 0, 32)?.let(PicoSerialProtocol::stats) /** (saved in the board's flash) */ fun setMode(m: PicoSerialProtocol.Mode) = control.write(PicoSerialProtocol.SET_MODE, m.code) + /** the board's flow control (saved in the board's flash) */ fun setFlow(f: PicoSerialProtocol.Flow) = control.write(PicoSerialProtocol.SET_FLOW, f.code) + /** where the board's speed comes from (saved in the board's flash) */ fun setBaudMode(b: PicoSerialProtocol.BaudMode) = control.write(PicoSerialProtocol.SET_BAUD_MODE, b.code) /** (not saved) */ fun setOutputs(mask: Int, value: Int) = control.write(PicoSerialProtocol.SET_OUTPUTS, PicoSerialProtocol.outputs(mask, value)) + /** the board's counts zeroed */ fun clearStats() = control.write(PicoSerialProtocol.CLEAR_STATS, 0) + /** the board's speed learned from the computer again */ fun relearnBaud() = control.write(PicoSerialProtocol.AUTOBAUD_RESTART, 0) companion object { @@ -224,6 +238,7 @@ interface AdapterLines { /** the computer's DTR, or null when it isn't known */ fun computerDtr(): Boolean? + /** whatever the adapter holds let go (nothing, by default) */ fun close() {} } @@ -275,6 +290,7 @@ class PicoSerialLines(val pico: PicoSerial, private val clock: () -> Long = Syst return true } + /** the computer's DTR from the inputs the last [drive] read, or null when the board isn't DCE */ override fun computerDtr(): Boolean? { val i = last ?: return null if (i.role != PicoSerialProtocol.Role.DCE) return null @@ -312,12 +328,16 @@ class CdcLineState(private val read: (ByteArray, Int) -> Int) : AdapterLines { } }, "cdc-notify").apply { isDaemon = true } + /** the notifications read, on a thread of their own */ fun start(): CdcLineState = apply { thread.start() } + /** nothing driven: false, the port's DTR does DCD */ override fun drive(dcd: Boolean, dsr: Boolean, ri: Boolean) = false + /** the computer's DTR: the adapter's DSR, from the last notification */ override fun computerDtr(): Boolean? = state?.dsr + /** the notifications' thread stopped */ override fun close() { open = false thread.interrupt() diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt index 894a1b0..4a372ab 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt @@ -182,6 +182,7 @@ class Telnet { /** the modem's lines as last told */ @Volatile private var lines = LineSignals() + /** [s] as RFC 2217's modem state bits: DCD, RI, DSR and CTS */ private fun lineBits(s: LineSignals) = (if (s.carrier) 0x80 else 0) or (if (s.ringing) 0x40 else 0) or (if (s.ready) 0x30 else 0) private var lastModem = -1 @@ -246,6 +247,7 @@ class Telnet { return o.toByteArray() } + /** the client's WILL, WONT, DO or DONT of [opt] answered: the options we offer or accept agreed to, the rest refused */ private fun negotiate(cmd: Int, opt: Int) { when (cmd) { DO_I -> if (opt in OFFER) { @@ -261,13 +263,16 @@ class Telnet { } } + /** IAC [verb] [opt] to the client */ private fun send(verb: Byte, opt: Int) = reply(byteArrayOf(IAC, verb, opt.toByte())) + /** an RFC 2217 subnegotiation acted on and answered; any other option's ignored */ private fun subnegotiation(s: ByteArray) { if (s.isEmpty() || (s[0].toInt() and 0xff) != COM_PORT || s.size < 2) return comPort = true val c = s[1].toInt() and 0xff val v = s.copyOfRange(2, s.size) + /** the value's first octet, or 0 */ fun u8() = if (v.isNotEmpty()) v[0].toInt() and 0xff else 0 when (c) { SIGNATURE -> answer(c, "D-Modem".toByteArray()) @@ -308,8 +313,10 @@ class Telnet { } } + /** RFC 2217's answer to command [c]: [v] back */ private fun answer(c: Int, v: ByteArray) = reply(subneg(c + 100, v)) + /** a COM-PORT-OPTION subnegotiation of [c] with [v], IAC doubled */ private fun subneg(c: Int, v: ByteArray): ByteArray { val o = java.io.ByteArrayOutputStream() o.write(0xff); o.write(SB_I); o.write(COM_PORT); o.write(c) diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/TcpBridge.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/TcpBridge.kt index ae0c892..670c988 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/TcpBridge.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/TcpBridge.kt @@ -61,6 +61,7 @@ class TcpBridge( /** the port the server got (when [port] was 0: any) */ val localPort: Int get() = server?.localPort ?: -1 + /** the server closed, its thread joined */ fun stop() { val s = server ?: return server = null @@ -69,6 +70,7 @@ class TcpBridge( _state.value = State.Stopped } + /** each connection to [s] served on a thread of its own, until it's closed */ private fun accept(s: ServerSocket) { while (!s.isClosed) { val c = try { s.accept() } catch (_: IOException) { break } @@ -76,6 +78,7 @@ class TcpBridge( } } + /** [c] served: Telnet started, the password asked for, then the modem if no other client has it (else BUSY) */ private fun client(c: Socket) { c.tcpNoDelay = true val name = c.inetAddress.hostAddress ?: "?" @@ -141,6 +144,7 @@ class TcpBridge( return null } + /** whether [a] and [b] are the same, compared in constant time (by their SHA-256) */ private fun same(a: String, b: String): Boolean { val d = MessageDigest.getInstance("SHA-256") return MessageDigest.isEqual(d.digest(a.toByteArray()), d.digest(b.toByteArray())) diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/UsbBridge.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbBridge.kt index 91221dc..0d0f2cb 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/UsbBridge.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbBridge.kt @@ -21,6 +21,7 @@ import java.io.OutputStream /** a serial line's character format and speed */ data class SerialFormat(val baud: Int = 115200, val dataBits: Int = 8, val parity: Char = 'N', val stopBits: Int = 1) { + /** as "115200 8N1" */ override fun toString() = "$baud $dataBits$parity$stopBits" val parityCode: Int get() = when (parity) { @@ -55,6 +56,7 @@ class UsbPortLink( ) { @Volatile private var open = true + /** the link ended: the adapter's extra lines and its port closed */ fun close() { open = false runCatching { extra?.close() } @@ -66,11 +68,13 @@ class UsbPortLink( private var have = 0 private var at = 0 + /** one octet, or -1 once closed */ override fun read(): Int { val one = ByteArray(1) return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 0xff } + /** what the port has into [b], polling it until there is some; -1 once closed or failed */ override fun read(b: ByteArray, off: Int, len: Int): Int { while (open) { if (at < have) { @@ -88,7 +92,9 @@ class UsbPortLink( } private val output = object : OutputStream() { + /** one octet to the port */ override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1) + /** [len] octets of [b] to the port; an IOException once closed */ override fun write(b: ByteArray, off: Int, len: Int) { if (!open) throw IOException("the adapter is closed") port.write(b.copyOfRange(off, off + len), 2000) @@ -184,6 +190,7 @@ class UsbBridge( @Volatile private var running = false private val receiver = object : BroadcastReceiver() { + /** an adapter plugged in or allowed: looked for, if none is served; unplugged: the link closed */ override fun onReceive(c: Context, i: Intent) { when (i.action) { UsbManager.ACTION_USB_DEVICE_ATTACHED, ACTION_PERMISSION -> if (link == null) Thread { find() }.start() @@ -194,6 +201,7 @@ class UsbBridge( } } + /** watching for adapters plugged in, and the first one there served */ fun start() { if (running) return if (usb == null) { @@ -211,6 +219,7 @@ class UsbBridge( Thread { find() }.start() } + /** the watch stopped, the link closed */ fun stop() { if (!running) return running = false @@ -224,6 +233,7 @@ class UsbBridge( fun adapters(): List> = usb?.let { m -> UsbSerialAdapters.prober.findAllDrivers(m).map { label(it.device) to it.device } }.orEmpty() + /** the first adapter there served on a thread of its own (Android's permission asked for first), or [state] saying why not */ @Synchronized private fun find() { if (!running || link != null) return @@ -300,6 +310,7 @@ class UsbBridge( return CdcLineState { buf, ms -> conn.bulkTransfer(ep, buf, buf.size, ms) }.start() } + /** [d]'s maker and product, else its USB IDs */ private fun label(d: UsbDevice): String = (listOfNotNull(d.manufacturerName, d.productName).joinToString(" ").ifBlank { null }) ?: "USB %04x:%04x".format(d.vendorId, d.productId) diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/UsbGadget.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbGadget.kt index 5a9af42..4b3663f 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/UsbGadget.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbGadget.kt @@ -38,6 +38,7 @@ class UsbGadget( private var thread: Thread? = null @Volatile private var input: FileInputStream? = null + /** the ACM function added (as root) and the tty served on a thread of its own; false, [state] saying why, if root couldn't */ fun start(): Boolean { if (running) return true val (status, out) = root(ENABLE) @@ -51,6 +52,7 @@ class UsbGadget( return true } + /** the tty let go, its thread joined, the function taken out again */ fun stop() { if (!running) return running = false diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/UsbSerialAdapters.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbSerialAdapters.kt index ebeb246..040b1f4 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/UsbSerialAdapters.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbSerialAdapters.kt @@ -19,6 +19,7 @@ object UsbSerialAdapters { /** finds them among what's plugged in */ val prober: UsbSerialProber by lazy { UsbSerialProber(table()) } + /** usb-serial-for-android's table, with the adapters' IDs Linux knows and Exar's chips added */ internal fun table(): ProbeTable = UsbSerialProber.getDefaultProbeTable().apply { add(UsbSerialIds.FTDI, FtdiSerialDriver::class.java) add(UsbSerialIds.CP210X, Cp21xxSerialDriver::class.java) @@ -28,6 +29,7 @@ object UsbSerialAdapters { for (pid in XrChip.products) addProduct(XrChip.VENDOR, pid, XrSerialDriver::class.java) } + /** [driver] for each of [ids] (vendor << 16 | product) */ private fun ProbeTable.add(ids: IntArray, driver: Class) { for (id in ids) addProduct(id ushr 16, id and 0xffff, driver) } diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/XrSerialDriver.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/XrSerialDriver.kt index d85766b..9c8c106 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/XrSerialDriver.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/XrSerialDriver.kt @@ -27,6 +27,7 @@ import java.util.EnumSet /** a control transfer on endpoint 0: the bytes moved, or < 0 */ fun interface XrControl { + /** the transfer done, [data] (up to [length]) out or in: the bytes moved, or < 0 */ fun transfer(requestType: Int, request: Int, value: Int, index: Int, data: ByteArray?, length: Int): Int } @@ -94,11 +95,13 @@ class XrUart(val chip: XrChip, private val control: XrControl, val itf: Int) { private val recipient = if (chip.toDevice) 0 else 1 + /** register [reg] of this channel set to [value]; an IOException if the request fails */ fun write(reg: Int, value: Int) { val n = control.transfer(0x40 or recipient, chip.setRequest, value and 0xffff, (channel shl 8) or reg, null, 0) if (n < 0) throw IOException("register 0x%x write failed".format(reg)) } + /** register [reg] of this channel (1 byte for 8-bit chips, else 2); an IOException if the read fails */ fun read(reg: Int): Int { val len = if (chip.width == 8) 1 else 2 val buf = ByteArray(len) @@ -138,8 +141,10 @@ class XrUart(val chip: XrChip, private val control: XrControl, val itf: Int) { enable() } + /** the UART off */ fun close() = disable() + /** the UART on, TX and RX (on the V141x its FIFOs too, in the datasheet's order) */ fun enable() { if (chip == XrChip.V141X) { // (the order the datasheet asks: TX FIFO, the UART, then RX FIFO) @@ -151,11 +156,13 @@ class XrUart(val chip: XrChip, private val control: XrControl, val itf: Int) { } } + /** the UART off (on the V141x its FIFOs too) */ fun disable() { write(chip.uartEnable, 0) if (chip == XrChip.V141X) manager(UM_FIFO_ENABLE, 0) } + /** the TX and/or RX FIFOs emptied */ fun resetFifos(tx: Boolean, rx: Boolean) { if (chip == XrChip.V141X) { if (tx) manager(UM_TX_FIFO_RESET, 1) @@ -174,6 +181,7 @@ class XrUart(val chip: XrChip, private val control: XrControl, val itf: Int) { enable() } + /** [baud] and the format checked for this chip: IllegalArgumentException if invalid, UnsupportedOperationException if the chip can't */ private fun check(baud: Int, dataBits: Int, stopBits: Int, parity: Int) { if (baud <= 0) throw IllegalArgumentException("Invalid baud rate: $baud") if (chip == XrChip.V141X && (baud < V141X_MIN || baud > OSC_HZ)) throw UnsupportedOperationException("Unsupported baud rate: $baud") @@ -190,6 +198,7 @@ class XrUart(val chip: XrChip, private val control: XrControl, val itf: Int) { if (parity !in UsbSerialPort.PARITY_NONE..UsbSerialPort.PARITY_SPACE) throw IllegalArgumentException("Invalid parity: $parity") } + /** the speed and format written: the V141x's own registers, the others' by CDC's SET_LINE_CODING */ private fun line(baud: Int, dataBits: Int, stopBits: Int, parity: Int) { if (chip == XrChip.V141X) { val c = v141xClock(baud) @@ -215,6 +224,7 @@ class XrUart(val chip: XrChip, private val control: XrControl, val itf: Int) { } } + /** GPIO_MODE's value: RTS/CTS on the pins for hardware flow, the activity toggles on chips that keep them */ private fun gpioMode(): Int { val sel = if (flow == UsbSerialPort.FlowControl.RTS_CTS) GPIO_SEL_RTS_CTS else 0 return sel or (if (chip.toggles) GPIO_TX_TOGGLE or GPIO_RX_TOGGLE else 0) @@ -231,6 +241,7 @@ class XrUart(val chip: XrChip, private val control: XrControl, val itf: Int) { enable() } + /** the chip's FLOW_CONTROL mode for [f] */ private fun flowMode(f: UsbSerialPort.FlowControl) = when (f) { UsbSerialPort.FlowControl.NONE -> FLOW_NONE UsbSerialPort.FlowControl.RTS_CTS -> FLOW_HW @@ -238,6 +249,7 @@ class XrUart(val chip: XrChip, private val control: XrControl, val itf: Int) { else -> throw UnsupportedOperationException("Unsupported flow control: $f") } + /** the XON and XOFF characters set, for software flow */ private fun flowChars() { if (flow != UsbSerialPort.FlowControl.XON_XOFF) return write(chip.xonChar, UsbSerialPort.CHAR_XON.code) @@ -322,6 +334,7 @@ class XrUart(val chip: XrChip, private val control: XrControl, val itf: Int) { 0xaaa, 0x5aa, 0x55a, 0xb56, 0x6d6, 0xdb6, 0xbb6, 0x76e, 0xeee, 0xdde, 0x7de, 0xf7e, 0xefe, 0x7fe, 0xffe, 0xffd, ) + /** the V141x's divisor and clock masks for [baud] */ fun v141xClock(baud: Int): Clock { val divisor = OSC_HZ / baud val fraction = ((32L * OSC_HZ) / baud).toInt() and 0x1f @@ -359,8 +372,10 @@ class XrSerialDriver(private val device: UsbDevice) : UsbSerialDriver { XrUart.pairs(itfs.map { it.id to it.interfaceClass }).mapIndexed { n, (c, d) -> XrSerialPort(n, itfs[c], itfs[d]) } } + /** the device the ports are on */ override fun getDevice(): UsbDevice = device + /** its ports, one per communications/data interface pair */ override fun getPorts(): List = ports inner class XrSerialPort(n: Int, private val comm: UsbInterface, private val data: UsbInterface) : @@ -370,10 +385,13 @@ class XrSerialDriver(private val device: UsbDevice) : UsbSerialDriver { private var dtr = false private var rts = false + /** the driver the port is of */ override fun getDriver(): UsbSerialDriver = this@XrSerialDriver + /** the open port's UART; an IOException when closed */ private fun uart(): XrUart = uart ?: throw IOException("Port not open") + /** the port opened: its interfaces claimed, its bulk endpoints found, the UART set up with DTR, RTS and flow as set before */ override fun openInt() { val conn = mConnection if (!conn.claimInterface(comm, true)) throw IOException("Could not claim interface ${comm.id}") @@ -390,6 +408,7 @@ class XrSerialDriver(private val device: UsbDevice) : UsbSerialDriver { uart = u } + /** the UART off, its interfaces let go */ override fun closeInt() { runCatching { uart?.close() } uart = null @@ -397,26 +416,36 @@ class XrSerialDriver(private val device: UsbDevice) : UsbSerialDriver { runCatching { mConnection.releaseInterface(comm) } } + /** the UART's speed and character format */ override fun setParameters(baudRate: Int, dataBits: Int, stopBits: Int, parity: Int) = uart().setLine(baudRate, dataBits, stopBits, parity) + /** CD, from the UART's status */ override fun getCD() = uart().status().cd + /** CTS, from the UART's status */ override fun getCTS() = uart().status().cts + /** DSR, from the UART's status */ override fun getDSR() = uart().status().dsr + /** RI, from the UART's status */ override fun getRI() = uart().status().ri + /** DTR as last set */ override fun getDTR() = dtr + /** RTS as last set */ override fun getRTS() = rts + /** DTR set, kept for the next open if closed */ override fun setDTR(value: Boolean) { uart?.lines(value, rts) dtr = value } + /** RTS set, kept for the next open if closed */ override fun setRTS(value: Boolean) { uart?.lines(dtr, value) rts = value } + /** the lines: DTR and RTS as set, the rest from the UART's status */ override fun getControlLines(): EnumSet { val s = uart().status() val l = EnumSet.noneOf(UsbSerialPort.ControlLine::class.java) @@ -429,28 +458,34 @@ class XrSerialDriver(private val device: UsbDevice) : UsbSerialDriver { return l } + /** all of them: the chip has every line */ override fun getSupportedControlLines(): EnumSet = EnumSet.allOf(UsbSerialPort.ControlLine::class.java) + /** flow control done by the chip (kept for the next open if closed) */ override fun setFlowControl(flowControl: UsbSerialPort.FlowControl) { if (flowControl !in supportedFlowControl) throw UnsupportedOperationException("Unsupported flow control: $flowControl") uart?.setFlow(flowControl) mFlowControl = flowControl } + /** none, RTS/CTS and XON/XOFF */ override fun getSupportedFlowControl(): EnumSet = EnumSet.of( UsbSerialPort.FlowControl.NONE, UsbSerialPort.FlowControl.RTS_CTS, UsbSerialPort.FlowControl.XON_XOFF, ) + /** the chip's FIFOs emptied, either way */ override fun purgeHwBuffers(purgeWriteBuffers: Boolean, purgeReadBuffers: Boolean) = uart().resetFifos(tx = purgeWriteBuffers, rx = purgeReadBuffers) + /** a break held on the line, or ended */ override fun setBreak(value: Boolean) = uart().setBreak(value) } companion object { private const val TIMEOUT = 5000 + /** usb-serial-for-android's table: Exar's products this driver takes */ @JvmStatic fun getSupportedDevices(): Map = mapOf(XrChip.VENDOR to XrChip.products) } diff --git a/app/src/main/java/com/neodesktop/dmodem/cell/CallAudio.kt b/app/src/main/java/com/neodesktop/dmodem/cell/CallAudio.kt index 41ee64d..83957cb 100644 --- a/app/src/main/java/com/neodesktop/dmodem/cell/CallAudio.kt +++ b/app/src/main/java/com/neodesktop/dmodem/cell/CallAudio.kt @@ -40,6 +40,7 @@ class AndroidCallAudio(context: Context) : CallAudio { private val app = context.applicationContext private val audio = app.getSystemService(AudioManager::class.java) + /** why the call's sound can't be had (Android before 13, not privileged, the phone's audio not interceptable), or null */ override fun unavailable(): String? = when { Build.VERSION.SDK_INT < 33 -> "needs Android 13 or later" app.checkSelfPermission(PERMISSION) != PackageManager.PERMISSION_GRANTED -> @@ -48,10 +49,12 @@ class AndroidCallAudio(context: Context) : CallAudio { else -> null } + /** whether the phone's audio says mobile calls' sound can be intercepted (false if it can't be asked) */ private fun interceptable(): Boolean = runCatching { AudioManager::class.java.getMethod("isPstnCallAudioInterceptable").invoke(audio) as Boolean }.getOrDefault(false) + /** the downlink's AudioRecord and the uplink's AudioTrack, started, as the call's streams; an IOException if unavailable */ @SuppressLint("MissingPermission") override fun open(): CallStreams { unavailable()?.let { throw IOException(it) } @@ -83,12 +86,14 @@ class AndroidCallAudio(context: Context) : CallAudio { return object : CallStreams { @Volatile private var open = true override val input = object : InputStream() { + /** one octet of the far end's sound, or -1 once closed */ override fun read(): Int { val b = ByteArray(1) return if (read(b, 0, 1) < 0) -1 else b[0].toInt() and 0xff } private val two = ByteArray(2) private var odd = -1 + /** the far end's sound: whole samples where [len] allows, an odd octet kept for the next read; -1 once closed */ override fun read(b: ByteArray, off: Int, len: Int): Int { if (!open) return -1 if (len == 0) return 0 @@ -110,7 +115,9 @@ class AndroidCallAudio(context: Context) : CallAudio { } } override val output = object : OutputStream() { + /** one octet to the call */ override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1) + /** our sound to the call, all of it; an IOException once closed */ override fun write(b: ByteArray, off: Int, len: Int) { if (!open) throw IOException("the call is over") var at = off @@ -121,6 +128,7 @@ class AndroidCallAudio(context: Context) : CallAudio { } } } + /** the record and track stopped and released (once) */ override fun close() { if (!open) return open = false diff --git a/app/src/main/java/com/neodesktop/dmodem/cell/CellPhone.kt b/app/src/main/java/com/neodesktop/dmodem/cell/CellPhone.kt index ee826ad..be63709 100644 --- a/app/src/main/java/com/neodesktop/dmodem/cell/CellPhone.kt +++ b/app/src/main/java/com/neodesktop/dmodem/cell/CellPhone.kt @@ -31,6 +31,7 @@ interface CellPhone { fun hangUp() /** the microphone muted (a modem call: only the modem's sound on it) or not */ fun muteMic(on: Boolean) {} + /** whatever it holds let go (nothing, by default) */ fun close() {} } @@ -53,6 +54,7 @@ class AndroidCellPhone(context: Context) : CellPhone { init { if (missing().isEmpty() && Build.VERSION.SDK_INT >= 31) { val cb = object : TelephonyCallback(), TelephonyCallback.CallStateListener { + /** Telephony's call state as [state] */ override fun onCallStateChanged(s: Int) { _state.value = when (s) { TelephonyManager.CALL_STATE_RINGING -> CellPhone.State.RINGING @@ -68,6 +70,7 @@ class AndroidCellPhone(context: Context) : CellPhone { /** the runtime permissions the line needs and hasn't got */ fun missing(): List = PERMISSIONS.filter { app.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED } + /** a call to [number] placed through Telecom; an IOException if the app may not */ override fun dial(number: String) { if (missing().isNotEmpty()) throw IOException("calls aren't allowed (the app's permissions)") try { @@ -77,15 +80,18 @@ class AndroidCellPhone(context: Context) : CellPhone { } } + /** the ringing call answered through Telecom (quietly not, if it can't be) */ override fun answer() { runCatching { telecom.acceptRingingCall() } } + /** the call ended through Telecom (Android 9 on; else nothing) */ override fun hangUp() { @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= 28) runCatching { telecom.endCall() } } + /** the microphone muted, its state before kept; unmuted: as it was before */ override fun muteMic(on: Boolean) { if (on) { if (micWas == null) micWas = audio.isMicrophoneMute @@ -96,6 +102,7 @@ class AndroidCellPhone(context: Context) : CellPhone { } } + /** Telephony's callback unregistered, its thread stopped */ override fun close() { if (Build.VERSION.SDK_INT >= 31) { (callback as? TelephonyCallback)?.let { runCatching { telephony.unregisterTelephonyCallback(it) } } diff --git a/app/src/main/java/com/neodesktop/dmodem/cell/CellTransport.kt b/app/src/main/java/com/neodesktop/dmodem/cell/CellTransport.kt index 5f08e56..782e927 100644 --- a/app/src/main/java/com/neodesktop/dmodem/cell/CellTransport.kt +++ b/app/src/main/java/com/neodesktop/dmodem/cell/CellTransport.kt @@ -51,9 +51,11 @@ class CellTransport( throw last ?: IOException("no sound from the call") } + /** whether the phone's call state came to [s] within [ms] */ private fun waitFor(s: CellPhone.State, ms: Long): Boolean = runBlocking { withTimeoutOrNull(ms) { phone.state.first { it == s } } } != null + /** a mobile call placed to the digits of [address], up and its sound had (the mic muted), as a connection already answered; an IOException, hung up, if not */ override fun connect(address: String): Duplex { audio.unavailable()?.let { throw IOException(it) } val number = address.filter { it.isDigit() || it in "+*#" } @@ -76,6 +78,7 @@ class CellTransport( return CellDuplex(number, "ANSWER\n".toByteArray(), streams).also { call = it; it.watchEnd() } } + /** each call ringing here, while there's none, to [accept] as a connection saying RING */ override fun listen(accept: (Duplex) -> Unit) { audio.unavailable()?.let { throw IOException(it) } listening = Thread({ @@ -95,6 +98,7 @@ class CellTransport( }, "cell-listen").apply { isDaemon = true; start() } } + /** listening stopped, the call there is hung up */ override fun close() { listening?.interrupt() listening = null @@ -129,6 +133,7 @@ class CellTransport( }, "cell-end").apply { isDaemon = true; start() } override val input: Source = object : Source { + /** the hello first, then the call's sound once it's there; -1 once closed */ override fun read(b: ByteArray, off: Int, len: Int): Int { if (helloAt < hello.size) { val n = minOf(len, hello.size - helloAt) @@ -146,8 +151,10 @@ class CellTransport( } override val output: Sink = object : Sink { + /** one octet to the call */ override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1) + /** the handshake's line first (ANSWER takes the call), then our sound to the call: kept until it's taken */ override fun write(b: ByteArray, off: Int, len: Int) { var at = off // the handshake's line (RING from a caller: nothing to do; ANSWER: the call taken) @@ -194,6 +201,7 @@ class CellTransport( } }, "cell-answer").apply { isDaemon = true; start() } + /** the call's sound closed, the mic as it was, the call hung up (once) */ override fun close() { val s = synchronized(lock) { if (closed) return diff --git a/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt b/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt index 2b8114b..fb42183 100644 --- a/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt +++ b/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt @@ -39,10 +39,12 @@ data class FaxRecord( /** the received fax's file in Downloads (its name) */ val file: String = "", ) { + /** the record as JSON, for the history's file */ fun toJson(): JSONObject = JSONObject().put("id", id).put("time", time).put("sending", sending).put("number", number) .put("remote", remote).put("pages", pages).put("result", result).put("file", file) companion object { + /** a record from its JSON */ fun fromJson(o: JSONObject) = FaxRecord( o.getString("id"), o.getLong("time"), o.getBoolean("sending"), o.optString("number"), o.optString("remote"), o.optInt("pages"), o.optString("result"), o.optString("file"), @@ -80,6 +82,7 @@ object Fax { private var history: JsonListStore? = null private var watching = false + /** the faxes sent and received, kept in the app's faxes.json */ fun history(context: Context): JsonListStore = synchronized(this) { history ?: JsonListStore(File(context.applicationContext.filesDir, "faxes.json"), FaxRecord::toJson, FaxRecord::fromJson, FaxRecord::id) .also { history = it } @@ -180,16 +183,19 @@ object Fax { _state.value = s } + /** the last call's state cleared, once it's over */ fun dismiss() { if (!running) _state.value = null } private var rates: List = emptyList() + /** the call's progress shown as [p] */ private fun update(p: FaxProgress) { _state.value = _state.value?.copy(progress = p) } + /** a dial's result (null: none came) as the reason the fax didn't go */ private fun dialResult(r: String?) = when (r) { null -> "no answer" "BUSY" -> "busy" @@ -268,7 +274,9 @@ object Fax { @android.annotation.SuppressLint("StaticFieldLeak") private var app: Context? = null + /** the application's context; a FaxException before init */ private fun contextOrThrow(): Context = app ?: throw FaxException("not set up") + /** the application's context, or null before init */ private fun contextOrNull(): Context? = app /** adaptive answer's word for a fax call (ATV1), its line alone */ @@ -295,6 +303,7 @@ object Fax { }) } + /** [pages] saved as a PDF in Downloads/D-Modem: its file's name */ private fun save(context: Context, pages: List): String { val name = "fax-" + SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date()) + ".pdf" val into = DownloadsIncoming(context) @@ -309,6 +318,7 @@ object Fax { return actual } + /** the call put in the history */ private fun record(context: Context, sending: Boolean, number: String, p: FaxProgress, result: String, file: String) { history(context).put( FaxRecord(java.util.UUID.randomUUID().toString(), System.currentTimeMillis(), sending, number, p.remote, p.pages, result, file), diff --git a/app/src/main/java/com/neodesktop/dmodem/fax/FaxDocuments.kt b/app/src/main/java/com/neodesktop/dmodem/fax/FaxDocuments.kt index 0ea157b..ca35182 100644 --- a/app/src/main/java/com/neodesktop/dmodem/fax/FaxDocuments.kt +++ b/app/src/main/java/com/neodesktop/dmodem/fax/FaxDocuments.kt @@ -42,6 +42,7 @@ object FaxDocuments { } } + /** each page of the PDF at [uri] rendered at the fax's width, black and white */ private fun pdf(context: Context, uri: Uri, fine: Boolean): List { val fd = context.contentResolver.openFileDescriptor(uri, "r") ?: throw IOException("can't open the PDF") return fd.use { pfd -> @@ -60,6 +61,7 @@ object FaxDocuments { } } + /** the fax's lines per inch: fine 196, else 98 */ private fun lpi(fine: Boolean) = if (fine) 196 else 98 /** an image decoded no bigger than it need be for a fax page */ @@ -82,8 +84,10 @@ object FaxDocuments { return (if (dither) dither(s, fine) else threshold(s, fine)).also { s.recycle() } } + /** [p]'s brightness, 0..255 */ private fun luma(p: Int): Int = (Color.red(p) * 299 + Color.green(p) * 587 + Color.blue(p) * 114) / 1000 + /** [b] as a page: each pixel black where it's opaque and dark */ private fun threshold(b: Bitmap, fine: Boolean): FaxPage { val page = FaxPage(b.width, b.height, fine) val row = IntArray(b.width) diff --git a/app/src/main/java/com/neodesktop/dmodem/local/Distros.kt b/app/src/main/java/com/neodesktop/dmodem/local/Distros.kt index 61a8147..81e170d 100644 --- a/app/src/main/java/com/neodesktop/dmodem/local/Distros.kt +++ b/app/src/main/java/com/neodesktop/dmodem/local/Distros.kt @@ -22,6 +22,7 @@ data class Rootfs( /** The phone's processor, as each source names it. */ data class Machine(val abi: String, val alpine: String, val lxc: String, val ubuntu: String?) { companion object { + /** the processor of Android ABI [abi] as the sources name it, or null if none has it */ fun forAbi(abi: String): Machine? = when (abi) { "arm64-v8a" -> Machine(abi, "aarch64", "arm64", "arm64") "armeabi-v7a" -> Machine(abi, "armv7", "armhf", "armhf") @@ -45,16 +46,19 @@ sealed class Distro( /** a line for the list: its package manager, how big */ val about: String, ) { + /** the root file system to download for [m]: its URL, checksum and size, looked up with [http] */ abstract fun resolve(m: Machine, http: Http): Rootfs class Alpine(private val mirror: String = ALPINE_MIRROR, private val branch: String = ALPINE_BRANCH) : Distro("alpine", "Alpine Linux", "apk · about 3 MB · musl, small and quick") { + /** the minirootfs in Alpine's latest-releases.yaml for [m]'s processor */ override fun resolve(m: Machine, http: Http): Rootfs { val base = "$mirror/$branch/releases/${m.alpine}" val yaml = http.text("$base/latest-releases.yaml") // (a list of releases, one per flavour: the minirootfs one's fields) val b = yaml.split(Regex("\n-\\s*\n|\n- ")).firstOrNull { it.contains("flavor: alpine-minirootfs") } ?: throw IOException("no Alpine for ${m.alpine}") + /** field [k]'s value in the release's entry, or null */ fun field(k: String) = Regex("(?m)^\\s*$k:\\s*(\\S+)").find(b)?.groupValues?.get(1) val version = field("version") ?: "?" return Rootfs( @@ -69,6 +73,7 @@ sealed class Distro( /** Ubuntu's base image (its own, ~30 MB): the newest point release of [release] */ class Ubuntu(private val release: String = "24.04", private val mirror: String = UBUNTU_MIRROR) : Distro("ubuntu", "Ubuntu $release LTS", "apt · about 30 MB") { + /** the newest point release's base tarball for [m] in the release's SHA256SUMS */ override fun resolve(m: Machine, http: Http): Rootfs { val arch = m.ubuntu ?: throw IOException("no Ubuntu for ${m.abi}") val base = "$mirror/$release/release" @@ -87,6 +92,7 @@ sealed class Distro( */ class Lxc(id: String, name: String, about: String, private val distro: String, private val release: String? = null) : Distro(id, name, about) { + /** the image's rootfs.tar.xz from the Linux Containers index for [m], its checksum from its SHA256SUMS */ override fun resolve(m: Machine, http: Http): Rootfs { val rows = lxcIndex(http).filter { it.distro == distro && it.arch == m.lxc && it.variant == "default" } val row = (if (release != null) rows.firstOrNull { it.release == release } else newest(rows)) @@ -103,6 +109,7 @@ sealed class Distro( fun availableFor(m: Machine, index: List): Boolean = index.any { it.distro == distro && it.arch == m.lxc && it.variant == "default" && (release == null || it.release == release) } + /** the newest of [rows]: "current", "tumbleweed", else the highest numbered release, else the first */ private fun newest(rows: List): LxcRow? = rows.firstOrNull { it.release == "current" } ?: rows.firstOrNull { it.release == "tumbleweed" } ?: rows.filter { it.release.firstOrNull()?.isDigit() == true }.maxByOrNull { versionKey(it.release) } @@ -112,6 +119,7 @@ sealed class Distro( /** any root file system tarball (.tar, .tar.gz or .tar.xz) by its URL */ class Custom(id: String, name: String, private val url: String, private val sha256: String?) : Distro(id, name, url) { + /** the tarball at its URL, its checksum as given (if any) */ override fun resolve(m: Machine, http: Http): Rootfs = Rootfs(url, sha256?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }, http.size(url), name, "custom") } @@ -138,11 +146,13 @@ sealed class Distro( Lxc("devuan", "Devuan", "apt · about 80 MB · Debian without systemd", "devuan"), ) + /** the catalog's distribution with [id], or null */ fun byId(id: String): Distro? = CATALOG.firstOrNull { it.id == id } /** the Linux Containers images' index: distro;release;arch;variant;build;path */ fun lxcIndex(http: Http): List = parseLxcIndex(http.text("$LXC_MIRROR/meta/1.0/index-system")) + /** the index's rows: distro;release;arch;variant;build;path (other lines skipped) */ fun parseLxcIndex(text: String): List = text.lineSequence().mapNotNull { l -> val f = l.trim().split(';') if (f.size >= 6) LxcRow(f[0], f[1], f[2], f[3], f[4], f[5]) else null @@ -159,6 +169,7 @@ sealed class Distro( /** What the systems are fetched with. */ open class Http { + /** a GET of [url], redirects followed; an IOException unless it's 200 */ open fun open(url: String): HttpURLConnection { val c = URL(url).openConnection() as HttpURLConnection c.connectTimeout = 20_000 @@ -169,6 +180,7 @@ open class Http { return c } + /** [url]'s body as text */ open fun text(url: String): String = open(url).let { c -> c.inputStream.use { it.readBytes().decodeToString() } } /** its size from a HEAD request, or -1 */ diff --git a/app/src/main/java/com/neodesktop/dmodem/local/Linux.kt b/app/src/main/java/com/neodesktop/dmodem/local/Linux.kt index 2ffd127..293b01f 100644 --- a/app/src/main/java/com/neodesktop/dmodem/local/Linux.kt +++ b/app/src/main/java/com/neodesktop/dmodem/local/Linux.kt @@ -59,6 +59,7 @@ object Linux { var place: (Context) -> Place = { ctx -> phonePlace(ctx) } + /** where the systems live on the phone: the app's files, its programs, its cache, shared storage when allowed, the phone's DNS */ private fun phonePlace(app: Context) = Place( root = File(app.filesDir, "linux"), programDir = File(app.applicationInfo.nativeLibraryDir ?: app.filesDir.path), @@ -71,6 +72,7 @@ object Linux { /** this phone's processor, or null where no Linux is built for it */ fun machine(): Machine? = Build.SUPPORTED_ABIS.firstNotNullOfOrNull { Machine.forAbi(it) } + /** the system with [id] (installed or not), where [place] has it */ fun system(context: Context, id: String): LinuxSystem { val p = place(context.applicationContext) return LinuxSystem(File(p.root, id), p.programDir, p.tmpDir, p.storage, p.nameServers, p.extraEnv) @@ -127,6 +129,7 @@ object Linux { } } + /** the system with [id] removed (in the background), unless work is going on */ fun remove(context: Context, id: String) { if (_work.value is Work.Busy) return if (_done.value == id) _done.value = null @@ -143,6 +146,7 @@ object Linux { } } + /** a failed install's or removal's word cleared */ fun clearFailure() { if (_work.value is Work.Failed) _work.value = Work.Idle } diff --git a/app/src/main/java/com/neodesktop/dmodem/local/LocalLink.kt b/app/src/main/java/com/neodesktop/dmodem/local/LocalLink.kt index e109ed2..5c424d8 100644 --- a/app/src/main/java/com/neodesktop/dmodem/local/LocalLink.kt +++ b/app/src/main/java/com/neodesktop/dmodem/local/LocalLink.kt @@ -38,10 +38,12 @@ class LocalLink( @Volatile var exitStatus: Int? = null private set + /** [l] given the program's output from now */ override fun addListener(l: TerminalLink.Listener) { listeners.add(l) } + /** [l] given no more of it */ override fun removeListener(l: TerminalLink.Listener) { listeners.remove(l) } @@ -75,6 +77,7 @@ class LocalLink( return true } + /** the program's output to the listeners, until the pty's end */ private fun read() { val buf = ByteArray(16384) while (true) { @@ -84,6 +87,7 @@ class LocalLink( } } + /** closed, saying [reason] (once): the writer stopped, the pty's master closed */ private fun closed(reason: String?) { synchronized(this) { if (_state.value is TerminalLink.State.Closed) return @@ -97,6 +101,7 @@ class LocalLink( } } + /** [length] octets of [data] to the program, on the writer's thread; false when it isn't open */ override fun write(data: ByteArray, offset: Int, length: Int): Boolean { val f = fd if (f < 0 || _state.value !is TerminalLink.State.Open) return false @@ -109,6 +114,7 @@ class LocalLink( } } + /** the window's size kept and given the pty */ override fun resize(cols: Int, rows: Int) { this.cols = cols this.rows = rows