diff --git a/app/src/main/java/com/neodesktop/dmodem/DModemApp.kt b/app/src/main/java/com/neodesktop/dmodem/DModemApp.kt index b908072..e8bc4d2 100644 --- a/app/src/main/java/com/neodesktop/dmodem/DModemApp.kt +++ b/app/src/main/java/com/neodesktop/dmodem/DModemApp.kt @@ -42,6 +42,10 @@ class DModemApp : Application() { // dial-in: callers given the internet when the settings say so (after the fax's watch: its calls first) com.neodesktop.dmodem.ppp.DialIn.init(this) + // the log's first lines: which build, when; the USB modems plugged in, and as they're plugged in and out + ModemState.log.add("app: ${BuildInfo.described}, started ${com.neodesktop.dmodem.modem.LogFormat.now()}") + com.neodesktop.dmodem.modem.UsbModems.watch(this) { ModemState.log.add("app: $it") } + // what the modem sends its DTE, as text, for the status screen's console ModemState.dte.addListener { data, length -> ModemState.console.append(String(data, 0, length, Charsets.ISO_8859_1)) diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/LogFormat.kt b/app/src/main/java/com/neodesktop/dmodem/modem/LogFormat.kt new file mode 100644 index 0000000..f88b19e --- /dev/null +++ b/app/src/main/java/com/neodesktop/dmodem/modem/LogFormat.kt @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.modem + +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.TimeZone + +/** The log as it's shown, copied and saved: each line after its time stamp, a line between the days. */ +object LogFormat { + /** the time stamp's pattern unless the settings say otherwise: "[04:12:03.417]" */ + const val DEFAULT = "[HH:mm:ss.SSS]" + + /** whether [pattern] is one (SimpleDateFormat's; empty for no time stamp) */ + fun valid(pattern: String): Boolean = pattern.isEmpty() || runCatching { SimpleDateFormat(pattern, Locale.US) }.isSuccess + + /** "---- Monday 26 October 2026 ----": before a day's first line */ + fun day(ms: Long, zone: TimeZone = TimeZone.getDefault()): String = + "---- " + SimpleDateFormat("EEEE d MMMM yyyy", Locale.US).apply { timeZone = zone }.format(Date(ms)) + " ----" + + /** the lines, each after its time stamp in [pattern] ([DEFAULT] if it isn't one; none if empty), the days between */ + fun render(lines: List, pattern: String = DEFAULT, zone: TimeZone = TimeZone.getDefault()): List { + val stamp = if (pattern.isEmpty()) null + else SimpleDateFormat(if (valid(pattern)) pattern else DEFAULT, Locale.US).apply { timeZone = zone } + val key = SimpleDateFormat("yyyyMMdd", Locale.US).apply { timeZone = zone } + val out = ArrayList(lines.size + 2) + var last: String? = null + for (l in lines) { + val d = Date(l.ms) + val k = key.format(d) + if (k != last) { + out += day(l.ms, zone) + last = k + } + out += if (stamp == null) l.text else stamp.format(d) + " " + l.text + } + return out + } + + /** "2026-10-26 04:12:03 PDT": when the app started, in its first line */ + fun now(ms: Long = System.currentTimeMillis(), zone: TimeZone = TimeZone.getDefault()): String = + SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz", Locale.US).apply { timeZone = zone }.format(Date(ms)) +} 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 dba9f7b..d809ec1 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt @@ -263,7 +263,6 @@ class ModemService : Service() { ?: com.neodesktop.dmodem.tones.CountryTones.find("")!! watchProgress() ModemState.line = settings.line - if (settings.usb) watchUsb() // (the speaker's sound: one socket for the process, read for good once started) NativeModem.speakerSound()?.let { s -> speakerSocket = s @@ -320,33 +319,6 @@ class ModemService : Service() { } } - /** a USB modem as the line: Android's word when it goes from the bus, or comes back (a reset shows as both) */ - private var usbWatch: android.content.BroadcastReceiver? = null - - private fun watchUsb() { - if (usbWatch != null) return - val r = object : android.content.BroadcastReceiver() { - override fun onReceive(c: Context, i: Intent) { - @Suppress("DEPRECATION") - val d = i.getParcelableExtra(android.hardware.usb.UsbManager.EXTRA_DEVICE) ?: return - val kind = UsbModems.kindOf(d) ?: return - val gone = i.action == android.hardware.usb.UsbManager.ACTION_USB_DEVICE_DETACHED - log("USB: the ${kind.label} " + if (gone) "has gone from the bus (unplugged, or it reset)" else "is on the bus again") - } - } - val f = android.content.IntentFilter().apply { - addAction(android.hardware.usb.UsbManager.ACTION_USB_DEVICE_DETACHED) - addAction(android.hardware.usb.UsbManager.ACTION_USB_DEVICE_ATTACHED) - } - androidx.core.content.ContextCompat.registerReceiver(this, r, f, androidx.core.content.ContextCompat.RECEIVER_EXPORTED) - usbWatch = r - } - - private fun unwatchUsb() { - usbWatch?.let { runCatching { unregisterReceiver(it) } } - usbWatch = null - } - /** the native modem stopped: the call hung up, SIP gone, the DTE's socket closed */ private fun stopNative() { stopping = true @@ -359,7 +331,6 @@ class ModemService : Service() { ModemState.speaker.setLevel(0) com.neodesktop.dmodem.peer.Peers.stop() NativeModem.stop() - unwatchUsb() // (the device let go once the modem has) usbModem?.connection?.close() usbModem = null diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt b/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt index e6bd982..465dd93 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt @@ -76,22 +76,32 @@ object ModemState { private const val MAX_CONSOLE = 16 * 1024 } -/** The last [max] lines, as a flow of snapshots (each line added makes a new one). */ -class LineBuffer(private val max: Int) { - private val lines = ArrayDeque() +/** a log line, and when it came ([System.currentTimeMillis]) */ +data class LogLine(val ms: Long, val text: String) + +/** + * The last [max] lines, as flows of snapshots (each line added makes a new one): their texts, and + * [entries], with when each came (as [clock] has it). + */ +class LineBuffer(private val max: Int, private val clock: () -> Long = System::currentTimeMillis) { + private val lines = ArrayDeque() private val _flow = MutableStateFlow>(emptyList()) val flow: StateFlow> = _flow.asStateFlow() + private val _entries = MutableStateFlow>(emptyList()) + val entries: StateFlow> = _entries.asStateFlow() @Synchronized fun add(line: String) { - lines.addLast(line) + lines.addLast(LogLine(clock(), line)) while (lines.size > max) lines.removeFirst() - _flow.value = lines.toList() + _entries.value = lines.toList() + _flow.value = _entries.value.map { it.text } } @Synchronized fun clear() { lines.clear() + _entries.value = emptyList() _flow.value = emptyList() } } diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt b/app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt index 2ff2062..3de6a11 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/UsbModems.kt @@ -54,6 +54,35 @@ object UsbModems { if (p.isEmpty()) "none" else p.joinToString(", ") { it.second.label } } + /** "the Agere USB 2.0 modem (USB 047e:2892) at /dev/bus/usb/001/002" */ + private fun said(d: UsbDevice, kind: Kind): String = + "the ${kind.label} (USB %04x:%04x) at ${d.deviceName}".format(d.vendorId, d.productId) + + /** + * The ones plugged in said to [log] now, and each as it's plugged in or goes (unplugged, or a reset of + * its own: Android says so as it goes from the bus and comes back), for as long as the app runs. + */ + fun watch(context: Context, log: (String) -> Unit) { + for ((d, kind) in plugged(context)) log("USB: ${said(d, kind)}: plugged in") + val r = object : BroadcastReceiver() { + override fun onReceive(c: Context, i: Intent) { + @Suppress("DEPRECATION") + val d = i.getParcelableExtra(UsbManager.EXTRA_DEVICE) ?: return + val kind = kindOf(d) ?: return + log( + "USB: ${said(d, kind)}: " + if (i.action == UsbManager.ACTION_USB_DEVICE_DETACHED) "gone from the bus (unplugged, or it reset)" + else "plugged in", + ) + } + } + val f = IntentFilter().apply { + addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED) + addAction(UsbManager.ACTION_USB_DEVICE_DETACHED) + } + // (the system's broadcasts) + ContextCompat.registerReceiver(context, r, f, ContextCompat.RECEIVER_EXPORTED) + } + /** an opened modem, or why there's none */ sealed interface Opened { class Device(val kind: Kind, val connection: UsbDeviceConnection) : Opened 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 095e9ac..200bf53 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt @@ -10,6 +10,7 @@ import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore +import com.neodesktop.dmodem.modem.LogFormat import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map @@ -33,6 +34,8 @@ data class ModemSettings( /** the modem's log level (0 errors .. 5), SIP's (0 none .. 4 the SIP messages) */ val logLevel: Int = 0, val sipLogLevel: Int = 1, + /** the log's time stamp before each line, a date pattern (SimpleDateFormat's; empty: none) */ + val logTimestamp: String = LogFormat.DEFAULT, /** the modem's line: a SIP account, or another phone with the app over Wi-Fi or Bluetooth */ val line: String = LINE_SIP, /** the other phone to call: host[:port] on Wi-Fi, a paired phone's address on Bluetooth */ @@ -128,6 +131,7 @@ class SettingsStore(private val context: Context) { val initCommands = stringPreferencesKey("init_commands") val logLevel = intPreferencesKey("log_level") val sipLogLevel = intPreferencesKey("sip_log_level") + val logTimestamp = stringPreferencesKey("log_timestamp") val line = stringPreferencesKey("line") val peerAddress = stringPreferencesKey("peer_address") val peerName = stringPreferencesKey("peer_name") @@ -152,6 +156,7 @@ class SettingsStore(private val context: Context) { initCommands = p[Keys.initCommands] ?: d.initCommands, logLevel = p[Keys.logLevel] ?: d.logLevel, sipLogLevel = p[Keys.sipLogLevel] ?: d.sipLogLevel, + logTimestamp = p[Keys.logTimestamp] ?: d.logTimestamp, line = p[Keys.line] ?: d.line, peerAddress = p[Keys.peerAddress] ?: d.peerAddress, peerName = p[Keys.peerName] ?: d.peerName, @@ -178,6 +183,7 @@ class SettingsStore(private val context: Context) { p[Keys.initCommands] = s.initCommands.trim() p[Keys.logLevel] = s.logLevel p[Keys.sipLogLevel] = s.sipLogLevel + p[Keys.logTimestamp] = s.logTimestamp p[Keys.line] = s.line p[Keys.peerAddress] = s.peerAddress.trim() p[Keys.peerName] = s.peerName diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/LogScreen.kt b/app/src/main/java/com/neodesktop/dmodem/ui/LogScreen.kt index ff7862c..dd6a773 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/LogScreen.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/LogScreen.kt @@ -30,8 +30,14 @@ import com.neodesktop.dmodem.modem.ModemState /** The modem's and SIP's log, the last lines (their levels in the settings): cleared, copied, or saved to a file. */ @Composable fun LogScreen(modifier: Modifier = Modifier) { - val lines by ModemState.log.flow.collectAsStateWithLifecycle() val context = androidx.compose.ui.platform.LocalContext.current + val entries by ModemState.log.entries.collectAsStateWithLifecycle() + val store = androidx.compose.runtime.remember { com.neodesktop.dmodem.settings.SettingsStore(context.applicationContext) } + val settings by store.settings.collectAsStateWithLifecycle(com.neodesktop.dmodem.settings.ModemSettings()) + // (each after its time stamp, the days between) + val lines = androidx.compose.runtime.remember(entries, settings.logTimestamp) { + com.neodesktop.dmodem.modem.LogFormat.render(entries, settings.logTimestamp) + } // (where it's saved: the user's pick, the system's file picker; the lines as they were when Save was pressed) var toSave by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf>(emptyList()) } val save = androidx.activity.compose.rememberLauncherForActivityResult( 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 6a38d4b..b42978a 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt @@ -211,6 +211,19 @@ 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)) } + Field("Log time stamp", s.logTimestamp) { s = s.copy(logTimestamp = it) } + Text( + if (com.neodesktop.dmodem.modem.LogFormat.valid(s.logTimestamp)) { + "Before each line of the log: a date pattern (HH:mm:ss.SSS the time to the millisecond, " + + "yyyy-MM-dd the date), empty for none. Each day starts with a line of its own." + } else { + "Not a date pattern: the log keeps ${com.neodesktop.dmodem.modem.LogFormat.DEFAULT}. " + + "Letters other than the pattern's go in quotes ('at')." + }, + style = MaterialTheme.typography.bodySmall, + color = if (com.neodesktop.dmodem.modem.LogFormat.valid(s.logTimestamp)) androidx.compose.ui.graphics.Color.Unspecified + else MaterialTheme.colorScheme.error, + ) SaveRow() } SettingsPage.BRIDGES -> BridgeSection() diff --git a/app/src/test/java/com/neodesktop/dmodem/modem/LogFormatTest.kt b/app/src/test/java/com/neodesktop/dmodem/modem/LogFormatTest.kt new file mode 100644 index 0000000..e0d89e0 --- /dev/null +++ b/app/src/test/java/com/neodesktop/dmodem/modem/LogFormatTest.kt @@ -0,0 +1,51 @@ +// 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.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.util.TimeZone + +class LogFormatTest { + private val utc = TimeZone.getTimeZone("UTC") + + // 2026-10-26 04:12:03.417 UTC, and 23:59:59.999 that day, and the next day's first second + private val t = 1792987923417L + private val lastOfDay = 1793059199999L + + @Test + fun stampedWithADayLine() = assertEquals( + listOf("---- Monday 26 October 2026 ----", "[04:12:03.417] app: one", "[23:59:59.999] app: two", + "---- Tuesday 27 October 2026 ----", "[00:00:00.000] app: three"), + LogFormat.render(listOf(LogLine(t, "app: one"), LogLine(lastOfDay, "app: two"), LogLine(lastOfDay + 1, "app: three")), LogFormat.DEFAULT, utc), + ) + + @Test + fun noStamp() = assertEquals( + listOf("---- Monday 26 October 2026 ----", "app: one"), + LogFormat.render(listOf(LogLine(t, "app: one")), "", utc), + ) + + @Test + fun otherPatternsAndBadOnes() { + assertEquals("2026-10-26T04:12:03 app: one", LogFormat.render(listOf(LogLine(t, "app: one")), "yyyy-MM-dd'T'HH:mm:ss", utc)[1]) + assertFalse(LogFormat.valid("HH:mm:ss.msec")) + assertTrue(LogFormat.valid("[HH:mm:ss.SSS]")) + // (one that isn't a pattern: the default's) + assertEquals("[04:12:03.417] app: one", LogFormat.render(listOf(LogLine(t, "app: one")), "HH:mm:ss.msec", utc)[1]) + } + + @Test + fun theBufferTimesItsLines() { + var now = t + val b = LineBuffer(2) { now } + b.add("a") + now += 5 + b.add("b") + b.add("c") + assertEquals(listOf("b", "c"), b.flow.value) + assertEquals(listOf(LogLine(t + 5, "b"), LogLine(t + 5, "c")), b.entries.value) + } +}