diff --git a/crates/rns-interface/src/android_usb.rs b/crates/rns-interface/src/android_usb.rs index 8919372..d690b76 100644 --- a/crates/rns-interface/src/android_usb.rs +++ b/crates/rns-interface/src/android_usb.rs @@ -37,6 +37,7 @@ const USB_STARTUP_ACK_DEADLINE: Duration = Duration::from_secs(2); const USB_CAPABILITY_RESPONSE_DEADLINE: Duration = Duration::from_secs(5); const USB_DETACH_ACK_DEADLINE: Duration = Duration::from_millis(500); const USB_WORKER_JOIN_DEADLINE: Duration = Duration::from_millis(1_250); +const USB_RECONNECT_DELAY: Duration = Duration::from_secs(rnode::RECONNECT_WAIT); /// USB VIDs of serial chipsets commonly used by RNode hardware. pub const KNOWN_VIDS: &[(u16, &str)] = &[ @@ -391,7 +392,12 @@ pub async fn enumerate_usb_devices() -> Result, String> { .map_err(|e| format!("{e}"))? } -pub async fn request_usb_permission(device_name: &str) -> Result { +/// Return whether Android has already granted this app access to `device_name`. +/// +/// This is deliberately a probe only. Android permission prompts are owned by +/// the Activity bridge because JNI cannot safely create the required +/// `PendingIntent`/`BroadcastReceiver` interaction here. +pub async fn has_usb_permission(device_name: &str) -> Result { let dev_name = device_name.to_string(); tokio::task::spawn_blocking(move || { with_env(|env| { @@ -444,6 +450,13 @@ pub async fn request_usb_permission(device_name: &str) -> Result { .map_err(|e| format!("{e}"))? } +/// Backwards-compatible name retained for downstream callers. This function +/// has never requested permission; use [`has_usb_permission`] in new code. +#[deprecated(note = "this is a permission probe; use has_usb_permission")] +pub async fn request_usb_permission(device_name: &str) -> Result { + has_usb_permission(device_name).await +} + fn clear_pending_jni_exception(env: &jni::JNIEnv) { if env.exception_check().unwrap_or(false) { let _ = env.exception_clear(); @@ -1144,68 +1157,22 @@ async fn shutdown_failed_android_usb_startup( .err() } -/// Same shape as the serial/BLE RNode interfaces, but over Android USB. -pub async fn spawn_android_usb_rnode_interface( - config: AndroidUsbConfig, - id: InterfaceId, - transport_tx: mpsc::Sender, -) -> Result { - Ok( - spawn_android_usb_rnode_interface_with_driver(config, id, transport_tx) - .await? - .interface, - ) +struct AndroidUsbGeneration { + usb: OwnedUsbIo, + protocol_state: Option, } -/// Spawn Android USB with the same privacy-safe RNode observation surface as -/// the serial, TCP, and BLE drivers. -pub async fn spawn_android_usb_rnode_interface_with_driver( - config: AndroidUsbConfig, - id: InterfaceId, - transport_tx: mpsc::Sender, -) -> Result { - spawn_android_usb_rnode_interface_with_driver_and_options( - config, - id, - transport_tx, - RNodeStartupOptions::default(), - ) - .await - .map_err(RNodeSpawnError::into_legacy_interface_error) -} - -/// Spawn Android USB with an explicit startup policy and local observation. -/// -/// [`RNodeStartupOptions::default`] preserves the historical two-write startup -/// sequence exactly. Strict admission inserts one bounded ROM_READ(0) on the -/// same owned session between Detect and Init and preserves deterministic -/// capability failures as [`RNodeSpawnError::CapabilityAdmission`]. -pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( - config: AndroidUsbConfig, - id: InterfaceId, - transport_tx: mpsc::Sender, +/// Open and initialise exactly one physical USB generation. Every failure +/// path resolves Java ownership before returning, so the logical interface can +/// retry without leaking a claim or racing another opener. +async fn start_android_usb_generation( + config: &AndroidUsbConfig, options: RNodeStartupOptions, -) -> Result { - config.validate().map_err(|error| { - InterfaceError::SendFailed(format!("rnode config {}: {error}", error.field())) - })?; - let (mut usb, connected) = open_usb_serial(&config.device_name, config.baud_rate).await?; - - let name = config.name.clone(); - let protocol_target = RNodeProtocolTarget::new( - config.frequency, - config.bandwidth, - config.spreading_factor, - config.coding_rate, - config.tx_power, - ); - - // Detect and initialization are distinct, physically acknowledged startup - // phases. The radio remains disabled until the exact existing init - // sequence reaches the device. - let rnode_cfg = rnode_config_from_android_usb_config(&config); +) -> Result { + let (mut usb, _worker_online) = open_usb_serial(&config.device_name, config.baud_rate).await?; + let rnode_cfg = rnode_config_from_android_usb_config(config); let init_bytes = rnode::build_init_sequence(&rnode_cfg); - let capability_admission = if options.requires_capability_admission() { + let protocol_state = if options.requires_capability_admission() { match run_usb_rnode_capability_startup( &mut usb, rnode::RNodeRadioSettings::from(&rnode_cfg), @@ -1268,7 +1235,10 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( ) .await { - let cleanup = shutdown_failed_android_usb_startup(usb, false).await; + // The legacy startup helper can enqueue part of the initialisation + // sequence before reporting failure. Always attempt the terminal + // detach here so a retry does not inherit an active radio session. + let cleanup = shutdown_failed_android_usb_startup(usb, true).await; let cleanup = cleanup .map(|cleanup| format!("; cleanup: {cleanup}")) .unwrap_or_default(); @@ -1279,28 +1249,80 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( None }; + Ok(AndroidUsbGeneration { + usb, + protocol_state, + }) +} + +/// Same shape as the serial/BLE RNode interfaces, but over Android USB. +pub async fn spawn_android_usb_rnode_interface( + config: AndroidUsbConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + Ok( + spawn_android_usb_rnode_interface_with_driver(config, id, transport_tx) + .await? + .interface, + ) +} + +/// Spawn Android USB with the same privacy-safe RNode observation surface as +/// the serial, TCP, and BLE drivers. +pub async fn spawn_android_usb_rnode_interface_with_driver( + config: AndroidUsbConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, +) -> Result { + spawn_android_usb_rnode_interface_with_driver_and_options( + config, + id, + transport_tx, + RNodeStartupOptions::default(), + ) + .await + .map_err(RNodeSpawnError::into_legacy_interface_error) +} + +/// Spawn Android USB with an explicit startup policy and local observation. +/// +/// [`RNodeStartupOptions::default`] preserves the historical two-write startup +/// sequence exactly. Strict admission inserts one bounded ROM_READ(0) on the +/// same owned session between Detect and Init and preserves deterministic +/// capability failures as [`RNodeSpawnError::CapabilityAdmission`]. +pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( + config: AndroidUsbConfig, + id: InterfaceId, + transport_tx: mpsc::Sender, + options: RNodeStartupOptions, +) -> Result { + config.validate().map_err(|error| { + InterfaceError::SendFailed(format!("rnode config {}: {error}", error.field())) + })?; + let initial_generation = start_android_usb_generation(&config, options).await?; + + let name = config.name.clone(); + let protocol_target = RNodeProtocolTarget::new( + config.frequency, + config.bandwidth, + config.spreading_factor, + config.coding_rate, + config.tx_power, + ); + let shared_txb = Arc::new(AtomicU64::new(0)); let shared_rxb = Arc::new(AtomicU64::new(0)); - let (tx, app_rx) = mpsc::channel::(64); + // Match the serial and BLE RNode application queue. The queue is logical + // interface state and survives physical Android USB reconnects. + let (tx, app_rx) = mpsc::channel::(256); + let app_rx = Arc::new(tokio::sync::Mutex::new(app_rx)); let (stop_tx, mut stop_rx) = mpsc::channel::<()>(1); - let (mut snapshot_publisher, driver) = rnode::new_rnode_driver_observation_with_shutdown( + let (snapshot_publisher, driver) = rnode::new_rnode_driver_observation_with_shutdown( RNodeTransportClass::Usb, RNodeDriverShutdown::from_stop_sender(stop_tx.clone()), ); - let initial_protocol_state = match capability_admission { - Some(UsbRNodeCapabilityAdmission { - protocol_state, - admission, - }) => { - snapshot_publisher.capability_connection_established(&protocol_state, admission); - Some(protocol_state) - } - None => { - snapshot_publisher.connection_established(); - None - } - }; let (shutdown_status_tx, shutdown_status_rx) = watch::channel(AndroidUsbShutdownStatus::Running); let stop_guard = register_android_usb_rnode_stop(id, stop_tx, shutdown_status_rx); @@ -1308,205 +1330,311 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( let read_name = name.clone(); let txb = shared_txb.clone(); let rxb = shared_rxb.clone(); - let online = connected.clone(); + let online = Arc::new(AtomicBool::new(true)); + let online_task = online.clone(); + let reconnect_config = config.clone(); let read_task = tokio::spawn(async move { let _stop_guard = stop_guard; - let (tx_pump_stop_tx, tx_pump_stop_rx) = tokio::sync::oneshot::channel(); - let (tx_pump_exit_tx, mut tx_pump_exit_rx) = tokio::sync::oneshot::channel(); - let pump_writer = usb.writer.clone(); - let pump_txb = txb.clone(); - let mut tx_pump = tokio::spawn(async move { - let exit = run_usb_tx_pump(app_rx, pump_writer, pump_txb, tx_pump_stop_rx).await; - let _ = tx_pump_exit_tx.send(exit); - }); - let mut inbound = match initial_protocol_state { - Some(protocol_state) => { - UsbInboundState::projected_with_protocol_state(protocol_state, snapshot_publisher) - } - None => UsbInboundState::projected(protocol_target, snapshot_publisher), - }; - let mut stop_requested = false; - let mut drain_reader_tail = false; - let mut terminal_reason = RNodeRuntimeReason::DriverTerminated; + let mut snapshot_publisher = Some(snapshot_publisher); + let mut next_generation = Some(initial_generation); + let mut last_report: Option> = None; loop { - tokio::select! { - biased; - stop = stop_rx.recv() => { - stop_requested = stop.is_some(); - if stop_requested { - terminal_reason = RNodeRuntimeReason::StopRequested; - } - break; - } - pump = &mut tx_pump_exit_rx => { - match pump { - Ok(UsbTxPumpExit::WriterRejected(error)) => { - terminal_reason = RNodeRuntimeReason::ConnectionLost; + let generation = match next_generation.take() { + Some(generation) => generation, + None => { + let publisher = snapshot_publisher + .as_mut() + .expect("Android USB reconnect publisher missing"); + publisher.reconnect_started(); + match start_android_usb_generation(&reconnect_config, options).await { + Ok(generation) => generation, + Err(RNodeSpawnError::CapabilityAdmission(error)) => { tracing::warn!( name = %read_name, - error = %error, - "Android USB packet could not be queued" + class = error.log_class(), + "Android USB reconnect capability admission rejected" ); - drain_reader_tail = true; - } - Ok(UsbTxPumpExit::ApplicationClosed) => { - terminal_reason = RNodeRuntimeReason::TransportConsumerClosed; - } - Ok(UsbTxPumpExit::StopRequested) => { - stop_requested = true; - terminal_reason = RNodeRuntimeReason::StopRequested; + publisher.stopped(RNodeRuntimeReason::CapabilityAdmissionRejected); + if let Some(report) = last_report.take() { + shutdown_status_tx + .send_replace(AndroidUsbShutdownStatus::Complete(report)); + } + return; } Err(error) => { + online_task.store(false, Ordering::SeqCst); + publisher.connection_attempt_failed(); tracing::warn!( name = %read_name, error = %error, - "Android USB TX pump ended without an outcome" + "Android USB RNode reconnect failed" ); - drain_reader_tail = true; + tokio::select! { + _ = stop_rx.recv() => { + publisher.shutting_down(RNodeRuntimeReason::StopRequested); + publisher.stopped(RNodeRuntimeReason::StopRequested); + if let Some(report) = last_report.take() { + shutdown_status_tx.send_replace( + AndroidUsbShutdownStatus::Complete(report), + ); + } + return; + } + _ = tokio::time::sleep(USB_RECONNECT_DELAY) => {} + } + continue; } } - break; } - event = usb.events.recv() => { - match event { - Some(UsbIoEvent::Writer(exit)) => { - terminal_reason = RNodeRuntimeReason::ConnectionLost; - tracing::debug!( - name = %read_name, - worker = ?exit, - "Android USB writer ended" - ); - drain_reader_tail = true; - break; - } - Some(UsbIoEvent::Reader(exit)) => { - terminal_reason = RNodeRuntimeReason::ConnectionLost; - tracing::debug!( - name = %read_name, - worker = ?exit, - "Android USB reader ended" - ); - break; - } - Some(UsbIoEvent::Read(bytes)) => { - match forward_usb_read_chunk( - &mut inbound, - &bytes, - id, - rxb.as_ref(), - &transport_tx, - &mut stop_rx, - ).await { - UsbInboundOutcome::Complete => {} - UsbInboundOutcome::StopRequested => { - stop_requested = true; - terminal_reason = RNodeRuntimeReason::StopRequested; - break; - } - UsbInboundOutcome::TransportClosed => { - terminal_reason = - RNodeRuntimeReason::TransportConsumerClosed; - tracing::warn!( - name = %read_name, - "transport channel closed" - ); - break; - } - UsbInboundOutcome::DeadlineElapsed => break, + }; + + let AndroidUsbGeneration { + mut usb, + protocol_state, + } = generation; + let mut publisher = snapshot_publisher + .take() + .expect("Android USB generation publisher missing"); + let mut inbound = match protocol_state { + Some(UsbRNodeCapabilityAdmission { + protocol_state, + admission, + }) => { + publisher.capability_connection_established(&protocol_state, admission); + UsbInboundState::projected_with_protocol_state(protocol_state, publisher) + } + None => { + publisher.connection_established(); + UsbInboundState::projected(protocol_target, publisher) + } + }; + online_task.store(true, Ordering::SeqCst); + + let (tx_pump_stop_tx, tx_pump_stop_rx) = tokio::sync::oneshot::channel(); + let (tx_pump_exit_tx, mut tx_pump_exit_rx) = tokio::sync::oneshot::channel(); + let pump_writer = usb.writer.clone(); + let pump_txb = txb.clone(); + let pump_rx = app_rx.clone(); + let mut tx_pump = tokio::spawn(async move { + let exit = run_usb_tx_pump(pump_rx, pump_writer, pump_txb, tx_pump_stop_rx).await; + let _ = tx_pump_exit_tx.send(exit); + }); + let mut stop_requested = false; + let mut drain_reader_tail = false; + let mut terminal_reason = RNodeRuntimeReason::ConnectionLost; + + loop { + tokio::select! { + biased; + stop = stop_rx.recv() => { + stop_requested = stop.is_some(); + terminal_reason = if stop_requested { + RNodeRuntimeReason::StopRequested + } else { + // Losing every stop sender means the logical + // interface has been abandoned. Do not reopen a + // physical device after its owner is gone. + RNodeRuntimeReason::DriverTerminated + }; + break; + } + pump = &mut tx_pump_exit_rx => { + match pump { + Ok(UsbTxPumpExit::WriterRejected(error)) => { + tracing::warn!( + name = %read_name, + error = %error, + "Android USB packet could not be queued" + ); + drain_reader_tail = true; + } + Ok(UsbTxPumpExit::ApplicationClosed) => { + terminal_reason = RNodeRuntimeReason::TransportConsumerClosed; + } + Ok(UsbTxPumpExit::StopRequested) => { + stop_requested = true; + terminal_reason = RNodeRuntimeReason::StopRequested; + } + Err(error) => { + tracing::warn!( + name = %read_name, + error = %error, + "Android USB TX pump ended without an outcome" + ); + drain_reader_tail = true; } } - None => { - terminal_reason = RNodeRuntimeReason::ConnectionLost; - break; + break; + } + event = usb.events.recv() => { + match event { + Some(UsbIoEvent::Writer(exit)) => { + tracing::debug!( + name = %read_name, + worker = ?exit, + "Android USB writer ended" + ); + drain_reader_tail = true; + break; + } + Some(UsbIoEvent::Reader(exit)) => { + tracing::debug!( + name = %read_name, + worker = ?exit, + "Android USB reader ended" + ); + break; + } + Some(UsbIoEvent::Read(bytes)) => { + match forward_usb_read_chunk( + &mut inbound, + &bytes, + id, + rxb.as_ref(), + &transport_tx, + &mut stop_rx, + ).await { + UsbInboundOutcome::Complete => {} + UsbInboundOutcome::StopRequested => { + stop_requested = true; + terminal_reason = RNodeRuntimeReason::StopRequested; + break; + } + UsbInboundOutcome::TransportClosed => { + terminal_reason = + RNodeRuntimeReason::TransportConsumerClosed; + tracing::warn!( + name = %read_name, + "transport channel closed" + ); + break; + } + UsbInboundOutcome::DeadlineElapsed => break, + } + } + None => break, } } } } - } - inbound.shutting_down(terminal_reason); - - let _ = tx_pump_stop_tx.send(()); - if tokio::time::timeout(USB_WORKER_JOIN_DEADLINE, &mut tx_pump) - .await - .is_err() - { - tx_pump.abort(); - let _ = tx_pump.await; - tracing::warn!(name = %read_name, "Android USB TX pump join timed out"); - } - - if drain_reader_tail { - usb.request_worker_stop(); - match drain_usb_reader_tail( - &mut usb.events, - &mut inbound, - id, - rxb.as_ref(), - &transport_tx, - &mut stop_rx, - tokio::time::Instant::now() + USB_WORKER_JOIN_DEADLINE, - ) - .await + let _ = tx_pump_stop_tx.send(()); + if tokio::time::timeout(USB_WORKER_JOIN_DEADLINE, &mut tx_pump) + .await + .is_err() { - UsbReadDrainOutcome::Drained => {} - UsbReadDrainOutcome::StopRequested => { - stop_requested = true; - terminal_reason = RNodeRuntimeReason::StopRequested; - inbound.shutting_down(terminal_reason); - } - UsbReadDrainOutcome::TransportClosed => { - terminal_reason = RNodeRuntimeReason::TransportConsumerClosed; - inbound.shutting_down(terminal_reason); - tracing::warn!( + tx_pump.abort(); + let _ = tx_pump.await; + tracing::warn!(name = %read_name, "Android USB TX pump join timed out"); + } + + if drain_reader_tail { + usb.request_worker_stop(); + match drain_usb_reader_tail( + &mut usb.events, + &mut inbound, + id, + rxb.as_ref(), + &transport_tx, + &mut stop_rx, + tokio::time::Instant::now() + USB_WORKER_JOIN_DEADLINE, + ) + .await + { + UsbReadDrainOutcome::Drained => {} + UsbReadDrainOutcome::StopRequested => { + stop_requested = true; + terminal_reason = RNodeRuntimeReason::StopRequested; + } + UsbReadDrainOutcome::TransportClosed => { + terminal_reason = RNodeRuntimeReason::TransportConsumerClosed; + tracing::warn!( + name = %read_name, + "transport channel closed while draining Android USB reader tail" + ); + } + UsbReadDrainOutcome::DeadlineElapsed => tracing::warn!( name = %read_name, - "transport channel closed while draining Android USB reader tail" - ); + "Android USB reader tail did not finish before shutdown deadline" + ), } - UsbReadDrainOutcome::DeadlineElapsed => tracing::warn!( + } + + let terminal = stop_requested + || matches!( + terminal_reason, + RNodeRuntimeReason::TransportConsumerClosed + | RNodeRuntimeReason::DriverTerminated + ); + if terminal { + inbound.shutting_down(terminal_reason); + } + let shutdown = usb + .shutdown( + Some(rnode::build_detach_sequence()), + USB_DETACH_ACK_DEADLINE, + USB_WORKER_JOIN_DEADLINE, + ) + .await; + let report = Arc::new(shutdown.report); + if let Err(error) = report.as_result() { + tracing::warn!( name = %read_name, - "Android USB reader tail did not finish before shutdown deadline" - ), + error = %error, + stop_requested, + "Android USB owner shutdown completed with errors" + ); + } else { + tracing::info!( + name = %read_name, + stop_requested, + "Android USB owner shutdown complete" + ); + } + online_task.store(false, Ordering::SeqCst); + + if terminal { + inbound.stopped(terminal_reason); + shutdown_status_tx.send_replace(AndroidUsbShutdownStatus::Complete(report)); + return; + } + + let mut publisher = inbound + .into_publisher() + .expect("Android USB reconnect publisher missing after generation"); + if report.is_quarantined() { + publisher.stopped(RNodeRuntimeReason::DriverTerminated); + shutdown_status_tx.send_replace(AndroidUsbShutdownStatus::Complete(report)); + return; + } + publisher.connection_lost(); + snapshot_publisher = Some(publisher); + last_report = Some(report); + tracing::info!(name = %read_name, "Android USB RNode reconnecting"); + tokio::select! { + _ = stop_rx.recv() => { + let publisher = snapshot_publisher + .as_mut() + .expect("Android USB stop publisher missing"); + publisher.shutting_down(RNodeRuntimeReason::StopRequested); + publisher.stopped(RNodeRuntimeReason::StopRequested); + if let Some(report) = last_report.take() { + shutdown_status_tx + .send_replace(AndroidUsbShutdownStatus::Complete(report)); + } + return; + } + _ = tokio::time::sleep(USB_RECONNECT_DELAY) => {} } } - - let shutdown = usb - .shutdown( - Some(rnode::build_detach_sequence()), - USB_DETACH_ACK_DEADLINE, - USB_WORKER_JOIN_DEADLINE, - ) - .await; - let report = Arc::new(shutdown.report); - match &report.detach { - Some(Ok(())) => tracing::info!(name = %read_name, "Android USB detach sequence sent"), - Some(Err(error)) => tracing::warn!( - name = %read_name, - error = %error, - "Android USB detach sequence failed" - ), - None => {} - } - if let Err(error) = report.as_result() { - tracing::warn!( - name = %read_name, - error = %error, - stop_requested, - "Android USB owner shutdown completed with errors" - ); - } else { - tracing::info!( - name = %read_name, - stop_requested, - "Android USB owner shutdown complete" - ); - } - online.store(false, Ordering::SeqCst); - inbound.stopped(terminal_reason); - shutdown_status_tx.send_replace(AndroidUsbShutdownStatus::Complete(report)); }); + let bitrate = rnode::calculate_bitrate( + config.spreading_factor, + config.coding_rate, + config.bandwidth, + ); let interface = InterfaceHandle { id, parent_id: None, @@ -1515,12 +1643,12 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( direction: InterfaceDirection { inbound: true, outbound: true, - forward: true, + forward: false, repeat: false, }, - bitrate: BAUD_RATE as u64, - mtu: 500, - online: connected, + bitrate, + mtu: 508, + online, txb: Some(shared_txb), rxb: Some(shared_rxb), inspection: None, diff --git a/crates/rns-interface/src/android_usb_lifecycle.rs b/crates/rns-interface/src/android_usb_lifecycle.rs index 30ef992..ff92c6d 100644 --- a/crates/rns-interface/src/android_usb_lifecycle.rs +++ b/crates/rns-interface/src/android_usb_lifecycle.rs @@ -571,6 +571,18 @@ impl UsbInboundState { projection.publisher.stopped(reason); } } + + /// Return the lifecycle publisher after one physical USB generation ends. + /// + /// Framing and protocol evidence are intentionally generation-local, but + /// the privacy-safe observation stream belongs to the stable logical + /// interface and must survive an unplug/replug cycle. + #[cfg_attr(not(target_os = "android"), allow(dead_code))] + pub(crate) fn into_publisher(mut self) -> Option { + self.projection + .take() + .map(|projection| projection.publisher) + } } #[derive(Clone, Debug, Eq, PartialEq)] @@ -1191,11 +1203,15 @@ pub(crate) enum UsbTxPumpExit { /// stall writer admission, and a full writer queue cannot stall inbound /// forwarding in the driver task. pub(crate) async fn run_usb_tx_pump( - mut application_rx: mpsc::Receiver, + application_rx: Arc>>, writer: UsbWriterHandle, transmitted_bytes: Arc, mut stop: oneshot::Receiver<()>, ) -> UsbTxPumpExit { + // A fresh physical USB generation borrows the same application queue. + // The lock is released when that generation's pump exits, preserving the + // stable InterfaceHandle across reconnects without duplicating queues. + let mut application_rx = application_rx.lock().await; loop { let payload = tokio::select! { biased; @@ -3134,6 +3150,7 @@ mod tests { }); let (application_tx, application_rx) = mpsc::channel(1); + let application_rx = Arc::new(tokio::sync::Mutex::new(application_rx)); let (pump_stop_tx, pump_stop_rx) = oneshot::channel(); let transmitted = Arc::new(AtomicU64::new(0)); let expected_frame_length = kiss::frame(&[4, 5, 6]).len() as u64; @@ -3168,9 +3185,62 @@ mod tests { assert_eq!(pump.await.expect("pump join"), UsbTxPumpExit::StopRequested); } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn application_queue_survives_sequential_usb_generations() { + let (application_tx, application_rx) = mpsc::channel(2); + let application_rx = Arc::new(tokio::sync::Mutex::new(application_rx)); + let transmitted = Arc::new(AtomicU64::new(0)); + + let (first_stop_tx, first_stop_rx) = oneshot::channel(); + let first_pump = tokio::spawn(run_usb_tx_pump( + application_rx.clone(), + UsbWriterHandle { + queue: UsbWriteQueue::new(1), + }, + transmitted.clone(), + first_stop_rx, + )); + first_stop_tx.send(()).expect("stop first generation"); + assert_eq!( + first_pump.await.expect("first pump join"), + UsbTxPumpExit::StopRequested + ); + + let payload = Bytes::from_static(&[4, 2, 4, 2]); + let expected_frame_length = kiss::frame(&payload).len() as u64; + application_tx + .send(payload) + .await + .expect("queue payload between generations"); + + let (second_stop_tx, second_stop_rx) = oneshot::channel(); + let second_pump = tokio::spawn(run_usb_tx_pump( + application_rx, + UsbWriterHandle { + queue: UsbWriteQueue::new(1), + }, + transmitted.clone(), + second_stop_rx, + )); + tokio::time::timeout(Duration::from_secs(1), async { + while transmitted.load(Ordering::Relaxed) != expected_frame_length { + tokio::task::yield_now().await; + } + }) + .await + .expect("second generation did not receive the queued payload"); + + second_stop_tx.send(()).expect("stop second generation"); + assert_eq!( + second_pump.await.expect("second pump join"), + UsbTxPumpExit::StopRequested + ); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn blocked_tx_admission_does_not_stall_inbound_forwarding() { let (application_tx, application_rx) = mpsc::channel(1); + let application_rx = Arc::new(tokio::sync::Mutex::new(application_rx)); let (pump_stop_tx, pump_stop_rx) = oneshot::channel(); let transmitted = Arc::new(AtomicU64::new(0)); let pump = tokio::spawn(run_usb_tx_pump( diff --git a/crates/rns-interface/src/rnode.rs b/crates/rns-interface/src/rnode.rs index fb2cdab..48d05ea 100644 --- a/crates/rns-interface/src/rnode.rs +++ b/crates/rns-interface/src/rnode.rs @@ -839,7 +839,12 @@ impl RNodeSnapshotPublisher { }); } - #[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))] + #[cfg(any( + feature = "serial", + feature = "rnode-tcp", + feature = "ble", + target_os = "android" + ))] pub(crate) fn reconnect_started(&self) { self.update(|snapshot| { snapshot.phase = RNodeRuntimePhase::Connecting; @@ -851,7 +856,12 @@ impl RNodeSnapshotPublisher { }); } - #[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))] + #[cfg(any( + feature = "serial", + feature = "rnode-tcp", + feature = "ble", + target_os = "android" + ))] pub(crate) fn connection_attempt_failed(&self) { self.update(|snapshot| { snapshot.phase = RNodeRuntimePhase::ReconnectBackoff; @@ -861,7 +871,12 @@ impl RNodeSnapshotPublisher { }); } - #[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))] + #[cfg(any( + feature = "serial", + feature = "rnode-tcp", + feature = "ble", + target_os = "android" + ))] pub(crate) fn connection_lost(&self) { self.update(|snapshot| { snapshot.phase = RNodeRuntimePhase::ReconnectBackoff; diff --git a/crates/rns-interface/src/rnode_multi.rs b/crates/rns-interface/src/rnode_multi.rs index f007067..27047dd 100644 --- a/crates/rns-interface/src/rnode_multi.rs +++ b/crates/rns-interface/src/rnode_multi.rs @@ -1,10 +1,13 @@ //! Multi-radio RNode: up to 11 sub-interfaces on one serial connection. -//! One read task demuxes by per-vport command byte; one write task prepends -//! `CMD_SEL_INT` so the device picks the right radio. +//! One read task demuxes canonical `CMD_DATA` frames by the most recently +//! selected virtual port; one write task prepends `CMD_SEL_INT` so the device +//! picks the right radio. +use std::collections::HashSet; +use std::io::Write; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::time::Duration; +use std::time::{Duration, Instant}; use bytes::Bytes; use tokio::sync::mpsc; @@ -29,8 +32,12 @@ pub const CMD_ERROR: u8 = 0x90; pub const ERROR_INITRADIO: u8 = 0x01; pub const ERROR_TXFAILED: u8 = 0x02; -/// Per-sub-interface data command bytes. NOT port-nibble; some collide -/// (e.g. `CMD_INT5_DATA == CMD_ERROR`) — demux by vport index, not byte. +/// Legacy per-interface constants exposed by the firmware protocol. +/// +/// Live RNodeMulti traffic is not demultiplexed with this table. The canonical +/// wire form selects a vport with [`CMD_SEL_INT`] and then sends one ordinary +/// [`kiss::CMD_DATA`] frame. Treating these values as inbound data commands +/// makes `0x90` indistinguishable from [`CMD_ERROR`]. pub const CMD_INT_DATA: [u8; 12] = [ 0x00, 0x10, 0x20, 0x70, 0x75, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, ]; @@ -83,7 +90,7 @@ impl RadioType { #[derive(Debug, Clone)] pub struct SubInterfaceConfig { pub name: String, - /// vport index on RNode (0..MAX_SUBINTERFACES). + /// vport index on RNode (`0..MAX_SUBINTERFACES`). pub vport: u8, pub frequency: u32, pub bandwidth: u32, @@ -158,10 +165,12 @@ impl SubInterfaceConfig { )); } } - if self.vport as usize > MAX_SUBINTERFACES { + if self.vport as usize >= MAX_SUBINTERFACES { return Err(format!( - "Virtual port {} exceeds max {} for sub-interface {}", - self.vport, MAX_SUBINTERFACES, self.name + "Virtual port {} is outside 0..{} for sub-interface {}", + self.vport, + MAX_SUBINTERFACES - 1, + self.name )); } Ok(()) @@ -249,6 +258,14 @@ pub fn build_subinterface_data_frame(index: u8, data: &[u8]) -> Vec { out } +/// Map a legacy `CMD_INTn_DATA` constant to its nominal vport. +/// +/// This helper is retained for protocol inspection and compatibility only. +/// It must not be used to route live RNodeMulti input; use `CMD_SEL_INT` +/// followed by `CMD_DATA` instead. +#[deprecated( + note = "legacy constants collide with control commands; route CMD_DATA by CMD_SEL_INT" +)] pub fn command_to_subinterface(cmd_byte: u8) -> Option { for (i, &port_cmd) in CMD_INT_DATA.iter().enumerate() { if cmd_byte == port_cmd { @@ -258,6 +275,345 @@ pub fn command_to_subinterface(cmd_byte: u8) -> Option { None } +const RNODE_HW_MTU: u32 = 508; +const RNODE_OPEN_SETTLE: Duration = Duration::from_secs(2); +const RNODE_SUBINTERFACE_SETTLE: Duration = Duration::from_secs(2); +const RNODE_SUBINTERFACE_READY_SETTLE: Duration = Duration::from_millis(300); +const RNODE_DISCOVERY_DEADLINE: Duration = Duration::from_secs(2); +const RNODE_CONFIGURATION_DEADLINE: Duration = Duration::from_secs(2); + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +struct RadioEvidence { + frequency: Option, + bandwidth: Option, + spreading_factor: Option, + coding_rate: Option, + tx_power: Option, + radio_state: Option, +} + +impl RadioEvidence { + fn complete(self) -> bool { + self.frequency.is_some() + && self.bandwidth.is_some() + && self.spreading_factor.is_some() + && self.coding_rate.is_some() + && self.tx_power.is_some() + && self.radio_state.is_some() + } + + fn validate(self, config: &SubInterfaceConfig) -> Result<(), String> { + let frequency = self + .frequency + .ok_or_else(|| format!("{} did not report frequency", config.name))?; + if frequency.abs_diff(config.frequency) > crate::rnode_protocol::FREQUENCY_TOLERANCE_HZ { + return Err(format!("{} reported a different frequency", config.name)); + } + if self.bandwidth != Some(config.bandwidth) { + return Err(format!("{} reported a different bandwidth", config.name)); + } + if self.spreading_factor != Some(config.spreading_factor) { + return Err(format!( + "{} reported a different spreading factor", + config.name + )); + } + if self.coding_rate != Some(config.coding_rate) { + return Err(format!("{} reported a different coding rate", config.name)); + } + if self.tx_power != Some(config.tx_power) { + return Err(format!("{} reported a different TX power", config.name)); + } + if self.radio_state != Some(rnode::RADIO_STATE_ON) { + return Err(format!("{} did not report its radio online", config.name)); + } + Ok(()) + } +} + +#[derive(Debug)] +struct StartupEvidence { + detected: bool, + firmware: Option<(u8, u8)>, + interfaces: [Option; MAX_SUBINTERFACES], + selected_vport: Option, + radios: [RadioEvidence; MAX_SUBINTERFACES], +} + +impl Default for StartupEvidence { + fn default() -> Self { + Self { + detected: false, + firmware: None, + interfaces: [None; MAX_SUBINTERFACES], + selected_vport: None, + radios: [RadioEvidence::default(); MAX_SUBINTERFACES], + } + } +} + +impl StartupEvidence { + fn apply_frame(&mut self, command: u8, payload: &[u8]) -> Result<(), String> { + match command { + rnode::CMD_DETECT => { + if payload.len() != 1 { + return Err("RNodeMulti returned malformed detection evidence".into()); + } + self.detected = payload[0] == rnode::DETECT_RESP; + } + rnode::CMD_FW_VERSION => { + if payload.len() != 2 { + return Err("RNodeMulti returned malformed firmware evidence".into()); + } + self.firmware = Some((payload[0], payload[1])); + } + CMD_INTERFACES => { + if payload.is_empty() { + return Ok(()); + } + if payload.len() % 2 != 0 { + return Err("RNodeMulti returned a malformed interface list".into()); + } + for pair in payload.chunks_exact(2) { + let vport = pair[0] as usize; + if vport >= MAX_SUBINTERFACES { + return Err(format!( + "RNodeMulti reported unsupported virtual port {}", + pair[0] + )); + } + let radio_type = RadioType::from_u8(pair[1]).ok_or_else(|| { + format!( + "RNodeMulti reported unknown radio type 0x{:02X} on virtual port {}", + pair[1], pair[0] + ) + })?; + if self.interfaces[vport].is_some_and(|known| known != radio_type) { + return Err(format!( + "RNodeMulti changed the radio type reported for virtual port {}", + pair[0] + )); + } + self.interfaces[vport] = Some(radio_type); + } + } + CMD_SEL_INT => { + if payload.len() != 1 || payload[0] as usize >= MAX_SUBINTERFACES { + self.selected_vport = None; + return Err("RNodeMulti returned an invalid virtual-port selection".into()); + } + self.selected_vport = Some(payload[0]); + } + rnode::CMD_FREQUENCY => { + if payload.len() != 4 { + return Err("RNodeMulti returned malformed frequency evidence".into()); + } + if let Some(radio) = self.selected_radio_mut() { + radio.frequency = Some(u32::from_be_bytes( + payload.try_into().expect("length checked"), + )); + } + } + rnode::CMD_BANDWIDTH => { + if payload.len() != 4 { + return Err("RNodeMulti returned malformed bandwidth evidence".into()); + } + if let Some(radio) = self.selected_radio_mut() { + radio.bandwidth = Some(u32::from_be_bytes( + payload.try_into().expect("length checked"), + )); + } + } + rnode::CMD_SF => { + let value = one_byte(payload, "spreading factor")?; + if let Some(radio) = self.selected_radio_mut() { + radio.spreading_factor = Some(value); + } + } + rnode::CMD_CR => { + let value = one_byte(payload, "coding rate")?; + if let Some(radio) = self.selected_radio_mut() { + radio.coding_rate = Some(value); + } + } + rnode::CMD_TXPOWER => { + let value = one_byte(payload, "TX power")?; + if let Some(radio) = self.selected_radio_mut() { + radio.tx_power = Some(value); + } + } + rnode::CMD_RADIO_STATE => { + let value = one_byte(payload, "radio state")?; + if let Some(radio) = self.selected_radio_mut() { + radio.radio_state = Some(value); + } + } + CMD_ERROR => { + let class = match payload.first().copied() { + Some(ERROR_INITRADIO) => "radio initialisation", + Some(ERROR_TXFAILED) => "radio transmission", + _ => "unknown hardware", + }; + return Err(format!("RNodeMulti reported a {class} error")); + } + rnode::CMD_RESET if payload.first().copied() == Some(0xF8) => { + return Err("RNodeMulti reset during startup".into()); + } + _ => {} + } + Ok(()) + } + + fn selected_radio_mut(&mut self) -> Option<&mut RadioEvidence> { + self.selected_vport + .and_then(|vport| self.radios.get_mut(vport as usize)) + } + + fn discovery_complete(&self, config: &RNodeMultiConfig) -> bool { + self.detected + && self.firmware.is_some() + && config + .subinterfaces + .iter() + .all(|sub| self.interfaces[sub.vport as usize].is_some()) + } + + fn validate_discovery(&self, config: &RNodeMultiConfig) -> Result<(), String> { + if !self.detected { + return Err("RNodeMulti device did not answer detection".into()); + } + let (major, minor) = self + .firmware + .ok_or_else(|| "RNodeMulti did not report its firmware version".to_string())?; + if (major, minor) < (REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN) { + return Err(format!( + "RNodeMulti firmware {major}.{minor} is below required {}.{}", + REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN + )); + } + for sub in &config.subinterfaces { + let radio_type = self.interfaces[sub.vport as usize].ok_or_else(|| { + format!( + "virtual port {} for {} was not reported by the RNodeMulti device", + sub.vport, sub.name + ) + })?; + if !radio_type.validate_frequency(sub.frequency) { + return Err(format!( + "frequency {} is outside the {} range reported for {}", + sub.frequency, + radio_type.family_name(), + sub.name + )); + } + } + Ok(()) + } + + fn reset_radio(&mut self, vport: u8) { + self.radios[vport as usize] = RadioEvidence::default(); + self.selected_vport = None; + } + + fn radio_complete(&self, vport: u8) -> bool { + self.radios[vport as usize].complete() + } +} + +fn one_byte(payload: &[u8], field: &str) -> Result { + if payload.len() != 1 { + return Err(format!("RNodeMulti returned malformed {field} evidence")); + } + Ok(payload[0]) +} + +fn read_startup_until( + port: &mut dyn serialport::SerialPort, + deframer: &mut kiss::RawKissDeframer, + evidence: &mut StartupEvidence, + deadline: Instant, + ready: impl Fn(&StartupEvidence) -> bool, +) -> Result<(), String> { + let mut buffer = [0u8; 1024]; + while Instant::now() < deadline { + match port.read(&mut buffer) { + Ok(0) => {} + Ok(read) => { + for (command, payload) in deframer.feed(&buffer[..read]) { + evidence.apply_frame(command, &payload)?; + if ready(evidence) { + return Ok(()); + } + } + } + Err(error) if error.kind() == std::io::ErrorKind::TimedOut => {} + Err(error) => return Err(format!("RNodeMulti startup read failed: {error}")), + } + } + Err("RNodeMulti startup validation timed out".into()) +} + +fn initialise_rnode_multi( + mut port: Box, + config: &RNodeMultiConfig, +) -> Result, String> { + std::thread::sleep(RNODE_OPEN_SETTLE); + let mut deframer = kiss::RawKissDeframer::new(); + let mut evidence = StartupEvidence::default(); + + port.write_all(&build_detect_sequence()) + .map_err(|error| format!("RNodeMulti detect write failed: {error}"))?; + port.flush() + .map_err(|error| format!("RNodeMulti detect flush failed: {error}"))?; + read_startup_until( + port.as_mut(), + &mut deframer, + &mut evidence, + Instant::now() + RNODE_DISCOVERY_DEADLINE, + |state| state.discovery_complete(config), + )?; + evidence.validate_discovery(config)?; + + for sub in &config.subinterfaces { + // RNode firmware configures one physical radio at a time. Match the + // established RNodeMulti startup cadence and let the selected radio + // settle before sending its reset/init sequence. + std::thread::sleep(RNODE_SUBINTERFACE_SETTLE); + evidence.reset_radio(sub.vport); + port.write_all(&build_subinterface_init(sub.vport, sub)) + .map_err(|error| format!("RNodeMulti {} init write failed: {error}", sub.name))?; + port.flush() + .map_err(|error| format!("RNodeMulti {} init flush failed: {error}", sub.name))?; + read_startup_until( + port.as_mut(), + &mut deframer, + &mut evidence, + Instant::now() + RNODE_CONFIGURATION_DEADLINE, + |state| state.radio_complete(sub.vport), + )?; + evidence.radios[sub.vport as usize].validate(sub)?; + // Match upstream's brief post-validation pause before exposing this + // radio or beginning configuration of the next physical radio. + std::thread::sleep(RNODE_SUBINTERFACE_READY_SETTLE); + } + + Ok(port) +} + +fn selected_data_target( + command: u8, + selected_vport: Option, + vport_map: &[Option; MAX_SUBINTERFACES], +) -> Option { + if command != kiss::CMD_DATA { + return None; + } + selected_vport + .and_then(|vport| vport_map.get(vport as usize)) + .copied() + .flatten() +} + struct WriteRequest { index: u8, /// Raw payload, not yet KISS-escaped. @@ -334,6 +690,15 @@ pub async fn spawn_rnode_multi_interface( sub.validate() .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti config: {}", e)))?; } + let mut configured_vports = HashSet::with_capacity(config.subinterfaces.len()); + for sub in &config.subinterfaces { + if !configured_vports.insert(sub.vport) { + return Err(InterfaceError::SendFailed(format!( + "RNodeMulti config: virtual port {} is configured more than once", + sub.vport + ))); + } + } let port = serialport::new(&config.port, config.baud_rate) .timeout(Duration::from_millis(RNODE_READ_TIMEOUT_MS)) @@ -347,36 +712,13 @@ pub async fn spawn_rnode_multi_interface( "RNodeMulti interface opened" ); - { - let mut detect_port = port - .try_clone() - .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti clone: {}", e)))?; - let detect_seq = build_detect_sequence(); - use std::io::Write; - detect_port - .write_all(&detect_seq) - .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti detect write: {}", e)))?; - detect_port - .flush() - .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti detect flush: {}", e)))?; - } - - { - let mut init_port = port - .try_clone() - .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti clone: {}", e)))?; - let mut init_seq = Vec::new(); - for sub in &config.subinterfaces { - init_seq.extend_from_slice(&build_subinterface_init(sub.vport, sub)); - } - use std::io::Write; - init_port - .write_all(&init_seq) - .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti init write: {}", e)))?; - init_port - .flush() - .map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti init flush: {}", e)))?; - } + let startup_config = config.clone(); + let port = tokio::task::spawn_blocking(move || initialise_rnode_multi(port, &startup_config)) + .await + .map_err(|error| { + InterfaceError::SendFailed(format!("RNodeMulti startup worker failed: {error}")) + })? + .map_err(|error| InterfaceError::SendFailed(format!("RNodeMulti startup: {error}")))?; let online = Arc::new(AtomicBool::new(true)); @@ -478,7 +820,7 @@ pub async fn spawn_rnode_multi_interface( repeat: false, }, bitrate, - mtu: rns_wire::constants::MTU as u32, + mtu: RNODE_HW_MTU, online: sub_onlines[i].clone(), rxb: Some(rxb), txb: Some(txb), @@ -602,13 +944,11 @@ pub async fn spawn_rnode_multi_interface( let parent_name = config.name.clone(); // `vport_map[vport] -> Some(local_index)` for configured sub-interfaces. - let mut vport_map: [Option; 12] = [None; 12]; + let mut vport_map: [Option; MAX_SUBINTERFACES] = [None; MAX_SUBINTERFACES]; let mut sub_ids: Vec = Vec::with_capacity(num_subs); for (i, sub_cfg) in config.subinterfaces.iter().enumerate() { let vp = sub_cfg.vport as usize; - if vp < 12 { - vport_map[vp] = Some(i); - } + vport_map[vp] = Some(i); sub_ids.push(ids[i]); } @@ -622,10 +962,8 @@ pub async fn spawn_rnode_multi_interface( .collect(); // Which sub-interface the device is currently addressing via - // CMD_SEL_INT; status commands below target this index. - let mut selected_index: usize = 0; - - let mut interfaces_buf: Vec = Vec::new(); + // CMD_SEL_INT; status and canonical CMD_DATA frames target this vport. + let mut selected_vport: Option = Some(0); loop { if !flags_r.device_running() { @@ -641,11 +979,13 @@ pub async fn spawn_rnode_multi_interface( } for (raw_cmd, frame) in deframer.feed(&buf[..n]) { - if let Some(vport) = command_to_subinterface(raw_cmd) { + if raw_cmd == kiss::CMD_DATA { if frame.is_empty() { continue; } - if let Some(local_idx) = vport_map[vport] { + if let Some(local_idx) = + selected_data_target(raw_cmd, selected_vport, &vport_map) + { sub_rxb[local_idx].fetch_add(frame.len() as u64, Ordering::Relaxed); let rssi = signals[local_idx].last_rssi.take(); @@ -669,7 +1009,7 @@ pub async fn spawn_rnode_multi_interface( } else { tracing::debug!( parent = %parent_name, - vport, + vport = ?selected_vport, "data for unconfigured sub-interface, dropping" ); } @@ -681,7 +1021,15 @@ pub async fn spawn_rnode_multi_interface( // Device echoes selection before emitting any // status/config responses for that sub-interface. if let Some(&idx) = frame.first() { - selected_index = idx as usize; + selected_vport = + ((idx as usize) < MAX_SUBINTERFACES).then_some(idx); + if selected_vport.is_none() { + tracing::warn!( + parent = %parent_name, + vport = idx, + "RNodeMulti selected an invalid virtual port" + ); + } } } @@ -689,7 +1037,7 @@ pub async fn spawn_rnode_multi_interface( if !frame.is_empty() { let rssi = rnode::decode_rssi_byte(frame[0]); if let Some(local_idx) = - vport_map.get(selected_index).copied().flatten() + selected_vport.and_then(|vport| vport_map[vport as usize]) { signals[local_idx].last_rssi = Some(rssi); } @@ -699,7 +1047,7 @@ pub async fn spawn_rnode_multi_interface( if !frame.is_empty() { let snr = rnode::decode_snr_byte(frame[0]); if let Some(local_idx) = - vport_map.get(selected_index).copied().flatten() + selected_vport.and_then(|vport| vport_map[vport as usize]) { signals[local_idx].last_snr = Some(snr); } @@ -746,20 +1094,20 @@ pub async fn spawn_rnode_multi_interface( rnode::CMD_RADIO_STATE => { if let Some(local_idx) = - vport_map.get(selected_index).copied().flatten() + selected_vport.and_then(|vport| vport_map[vport as usize]) { if frame.first().copied() == Some(rnode::RADIO_STATE_ON) { tracing::info!( parent = %parent_name, subinterface = local_idx, - vport = selected_index, + vport = ?selected_vport, "RNodeMulti sub-interface radio online" ); } else { tracing::warn!( parent = %parent_name, subinterface = local_idx, - vport = selected_index, + vport = ?selected_vport, "RNodeMulti sub-interface radio offline" ); } @@ -773,7 +1121,7 @@ pub async fn spawn_rnode_multi_interface( ]); tracing::debug!( parent = %parent_name, - vport = selected_index, + vport = ?selected_vport, freq_mhz = format!("{:.3}", freq as f64 / 1_000_000.0), "Radio reporting frequency" ); @@ -787,7 +1135,7 @@ pub async fn spawn_rnode_multi_interface( ]); tracing::debug!( parent = %parent_name, - vport = selected_index, + vport = ?selected_vport, bw_khz = format!("{:.1}", bw as f64 / 1000.0), "Radio reporting bandwidth" ); @@ -798,7 +1146,7 @@ pub async fn spawn_rnode_multi_interface( if !frame.is_empty() { tracing::debug!( parent = %parent_name, - vport = selected_index, + vport = ?selected_vport, sf = frame[0], "Radio reporting spreading factor" ); @@ -809,7 +1157,7 @@ pub async fn spawn_rnode_multi_interface( if !frame.is_empty() { tracing::debug!( parent = %parent_name, - vport = selected_index, + vport = ?selected_vport, cr = frame[0], "Radio reporting coding rate" ); @@ -821,7 +1169,7 @@ pub async fn spawn_rnode_multi_interface( let txp = frame[0] as i8; tracing::debug!( parent = %parent_name, - vport = selected_index, + vport = ?selected_vport, txpower_dbm = txp, "Radio reporting TX power" ); @@ -834,7 +1182,7 @@ pub async fn spawn_rnode_multi_interface( let pct = at as f32 / 100.0; tracing::debug!( parent = %parent_name, - vport = selected_index, + vport = ?selected_vport, "RNodeMulti short-term airtime limit: {:.2}%", pct, ); } @@ -846,7 +1194,7 @@ pub async fn spawn_rnode_multi_interface( let pct = at as f32 / 100.0; tracing::debug!( parent = %parent_name, - vport = selected_index, + vport = ?selected_vport, "RNodeMulti long-term airtime limit: {:.2}%", pct, ); } @@ -873,12 +1221,10 @@ pub async fn spawn_rnode_multi_interface( } CMD_INTERFACES => { - // Reply is a stream of 2-byte `[vport, radio_type]` - // pairs, one per radio module; accumulate then pop. - interfaces_buf.extend_from_slice(&frame); - if interfaces_buf.len() >= 2 { - let vp = interfaces_buf[0]; - let rt = interfaces_buf[1]; + // Reply is one or more `[vport, radio_type]` pairs. + for pair in frame.chunks_exact(2) { + let vp = pair[0]; + let rt = pair[1]; let rtype = RadioType::from_u8(rt) .map(|r| r.family_name().to_string()) .unwrap_or_else(|| format!("unknown(0x{:02X})", rt)); @@ -888,13 +1234,30 @@ pub async fn spawn_rnode_multi_interface( radio_type = %rtype, "RNodeMulti radio module reported" ); - interfaces_buf.clear(); + } + if frame.len() % 2 != 0 { + tracing::warn!( + parent = %parent_name, + "RNodeMulti returned a malformed interface list" + ); } } - // No CMD_ERROR arm: 0x90 collides with CMD_INT5_DATA - // and is consumed by the vport demux above — same - // collision as Python RNodeMultiInterface. + CMD_ERROR => { + let class = match frame.first().copied() { + Some(ERROR_INITRADIO) => "radio initialisation", + Some(ERROR_TXFAILED) => "radio transmission", + _ => "unknown hardware", + }; + tracing::error!( + parent = %parent_name, + class, + "RNodeMulti hardware error" + ); + flags_r.trip_device(); + return; + } + rnode::CMD_RESET => { if frame.first().copied() == Some(0xF8) { tracing::error!( @@ -1019,25 +1382,6 @@ mod tests { assert_eq!(frames.len(), 9); } - #[test] - fn test_command_to_subinterface() { - assert_eq!(command_to_subinterface(0x00), Some(0)); - assert_eq!(command_to_subinterface(0x10), Some(1)); - assert_eq!(command_to_subinterface(0x20), Some(2)); - assert_eq!(command_to_subinterface(0x70), Some(3)); - assert_eq!(command_to_subinterface(0x75), Some(4)); - assert_eq!(command_to_subinterface(0x90), Some(5)); - assert_eq!(command_to_subinterface(0xA0), Some(6)); - assert_eq!(command_to_subinterface(0xB0), Some(7)); - assert_eq!(command_to_subinterface(0xC0), Some(8)); - assert_eq!(command_to_subinterface(0xD0), Some(9)); - assert_eq!(command_to_subinterface(0xE0), Some(10)); - assert_eq!(command_to_subinterface(0xF0), Some(11)); - assert_eq!(command_to_subinterface(0x55), None); - assert_eq!(command_to_subinterface(0xFF), None); - assert_eq!(command_to_subinterface(0x01), None); - } - #[test] fn test_radio_type() { assert_eq!(RadioType::from_u8(0x00), Some(RadioType::SX127X)); @@ -1068,7 +1412,12 @@ mod tests { #[test] fn test_max_subinterfaces() { assert_eq!(MAX_SUBINTERFACES, 11); - assert_eq!(CMD_INT_DATA.len(), 12); + assert_eq!(RNODE_HW_MTU, 508); + + let highest = SubInterfaceConfig::new("radio10", 10, 868_000_000); + assert!(highest.validate().is_ok()); + let outside = SubInterfaceConfig::new("radio11", 11, 868_000_000); + assert!(outside.validate().is_err()); } #[test] @@ -1099,9 +1448,9 @@ mod tests { #[test] fn test_raw_kiss_deframer_preserves_command() { - // CMD_INT5_DATA = 0x90 collides with CMD_ERROR after masking; the raw - // deframer must keep the high nibble intact. - let payload = b"test data"; + // CMD_ERROR is 0x90. The raw deframer must retain that exact command + // so it can never be mistaken for vport-5 packet data. + let payload = &[ERROR_INITRADIO]; let mut raw_frame = Vec::new(); raw_frame.push(kiss::FEND); raw_frame.push(0x90); @@ -1111,10 +1460,12 @@ mod tests { let mut deframer = kiss::RawKissDeframer::new(); let frames = deframer.feed(&raw_frame); assert_eq!(frames.len(), 1); - assert_eq!(frames[0].0, 0x90); + assert_eq!(frames[0].0, CMD_ERROR); assert_eq!(frames[0].1, payload); - assert_eq!(command_to_subinterface(0x90), Some(5)); + let mut vport_map = [None; MAX_SUBINTERFACES]; + vport_map[5] = Some(0); + assert_eq!(selected_data_target(CMD_ERROR, Some(5), &vport_map), None); } #[test] @@ -1214,7 +1565,7 @@ mod tests { bad.st_alock = Some(101.0); assert!(bad.validate().is_err()); - let bad = SubInterfaceConfig::new("radio0", 12, 868_000_000); + let bad = SubInterfaceConfig::new("radio0", 11, 868_000_000); assert!(bad.validate().is_err()); } @@ -1284,55 +1635,118 @@ mod tests { } #[test] - fn test_all_subinterface_data_commands_unique() { - for (i, lhs) in CMD_INT_DATA.iter().enumerate() { - for (j, rhs) in CMD_INT_DATA.iter().enumerate().skip(i + 1) { - assert_ne!( - lhs, rhs, - "CMD_INT_DATA[{}] == CMD_INT_DATA[{}] == 0x{:02X}", - i, j, *lhs - ); - } - } + fn canonical_data_routing_uses_selected_vport_only() { + let mut vport_map = [None; MAX_SUBINTERFACES]; + vport_map[0] = Some(0); + vport_map[5] = Some(1); + + assert_eq!( + selected_data_target(kiss::CMD_DATA, Some(5), &vport_map), + Some(1) + ); + assert_eq!( + selected_data_target(kiss::CMD_DATA, Some(0), &vport_map), + Some(0) + ); + assert_eq!( + selected_data_target(kiss::CMD_DATA, Some(4), &vport_map), + None + ); + assert_eq!(selected_data_target(CMD_ERROR, Some(5), &vport_map), None); + assert_eq!(selected_data_target(0xA0, Some(5), &vport_map), None); } #[test] - fn test_data_commands_dont_collide_with_control_commands() { - let control_cmds = [ - CMD_SEL_INT, - rnode::CMD_STAT_RSSI, - rnode::CMD_STAT_SNR, - rnode::CMD_READY, - rnode::CMD_DETECT, - rnode::CMD_FW_VERSION, - rnode::CMD_RADIO_STATE, - rnode::CMD_FREQUENCY, - rnode::CMD_BANDWIDTH, - rnode::CMD_SF, - rnode::CMD_CR, - rnode::CMD_TXPOWER, - rnode::CMD_ST_ALOCK, - rnode::CMD_LT_ALOCK, - rnode::CMD_PLATFORM, - rnode::CMD_MCU, - CMD_INTERFACES, - rnode::CMD_RESET, - ]; + fn startup_discovery_validates_firmware_interface_types_and_ranges() { + let mut config = RNodeMultiConfig::new("multi0", "/dev/null"); + config + .subinterfaces + .push(SubInterfaceConfig::new("low", 0, 868_000_000)); + config + .subinterfaces + .push(SubInterfaceConfig::new("high", 3, 2_400_000_000)); - for &data_cmd in &CMD_INT_DATA { - for &ctrl_cmd in &control_cmds { - // CMD_INT0_DATA == CMD_DATA (0x00) and CMD_INT5_DATA == - // CMD_ERROR (0x90) are known, intentional overlaps; the read - // loop disambiguates by checking data commands first. - if data_cmd == 0x00 || data_cmd == 0x90 { - continue; - } - assert_ne!( - data_cmd, ctrl_cmd, - "CMD_INT_DATA 0x{:02X} collides with control cmd 0x{:02X}", - data_cmd, ctrl_cmd - ); - } - } + let mut state = StartupEvidence::default(); + state + .apply_frame(rnode::CMD_DETECT, &[rnode::DETECT_RESP]) + .unwrap(); + // Lexicographic comparison accepts newer major versions. + state.apply_frame(rnode::CMD_FW_VERSION, &[2, 0]).unwrap(); + state + .apply_frame( + CMD_INTERFACES, + &[0, RadioType::SX1276 as u8, 3, RadioType::SX1280 as u8], + ) + .unwrap(); + + assert!(state.discovery_complete(&config)); + assert!(state.validate_discovery(&config).is_ok()); + + config.subinterfaces[1].frequency = 915_000_000; + assert!(state.validate_discovery(&config).is_err()); + } + + #[test] + fn startup_discovery_rejects_malformed_or_unknown_interfaces() { + let mut state = StartupEvidence::default(); + assert!(state.apply_frame(CMD_INTERFACES, &[0]).is_err()); + assert!(state.apply_frame(CMD_INTERFACES, &[0, 0xFF]).is_err()); + assert!( + state + .apply_frame(CMD_INTERFACES, &[MAX_SUBINTERFACES as u8, 0x00]) + .is_err() + ); + assert!(state.apply_frame(CMD_ERROR, &[ERROR_INITRADIO]).is_err()); + } + + #[test] + fn startup_requires_matching_echoes_before_radio_is_ready() { + let config = SubInterfaceConfig::new("radio0", 0, 868_000_000); + let mut state = StartupEvidence::default(); + state.apply_frame(CMD_SEL_INT, &[0]).unwrap(); + state + .apply_frame(rnode::CMD_FREQUENCY, &config.frequency.to_be_bytes()) + .unwrap(); + state + .apply_frame(rnode::CMD_BANDWIDTH, &config.bandwidth.to_be_bytes()) + .unwrap(); + state + .apply_frame(rnode::CMD_SF, &[config.spreading_factor]) + .unwrap(); + state + .apply_frame(rnode::CMD_CR, &[config.coding_rate]) + .unwrap(); + state + .apply_frame(rnode::CMD_TXPOWER, &[config.tx_power]) + .unwrap(); + assert!(!state.radio_complete(0)); + state + .apply_frame(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON]) + .unwrap(); + + assert!(state.radio_complete(0)); + assert!(state.radios[0].validate(&config).is_ok()); + + let mut mismatch = state.radios[0]; + mismatch.coding_rate = Some(config.coding_rate + 1); + assert!(mismatch.validate(&config).is_err()); + } + + #[tokio::test] + async fn duplicate_vports_are_rejected_before_opening_serial() { + let mut config = RNodeMultiConfig::new("multi0", "/does/not/exist"); + config + .subinterfaces + .push(SubInterfaceConfig::new("first", 0, 868_000_000)); + config + .subinterfaces + .push(SubInterfaceConfig::new("second", 0, 915_000_000)); + let (transport_tx, _transport_rx) = mpsc::channel(1); + let result = spawn_rnode_multi_interface(config, &[1, 2], transport_tx).await; + let error = match result { + Ok(_) => panic!("duplicate vports must fail before serial open"), + Err(error) => error, + }; + assert!(error.to_string().contains("configured more than once")); } } diff --git a/crates/rns-runtime/src/interface_factory.rs b/crates/rns-runtime/src/interface_factory.rs index 43c3c6c..1059436 100644 --- a/crates/rns-runtime/src/interface_factory.rs +++ b/crates/rns-runtime/src/interface_factory.rs @@ -32,7 +32,7 @@ pub enum InterfaceConfig { #[cfg(feature = "serial")] KissSerial(KissSerialConfig), Auto(AutoInterfaceConfig), - #[cfg(any(feature = "serial", feature = "rnode-tcp"))] + #[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] RNode(RNodeInterfaceConfig), Local(LocalInterfaceConfig), I2P(I2PInterfaceConfig), @@ -94,11 +94,12 @@ pub struct AutoInterfaceConfig { pub mode: InterfaceMode, } -#[cfg(any(feature = "serial", feature = "rnode-tcp"))] +#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] #[derive(Debug, Clone)] pub struct RNodeInterfaceConfig { pub name: String, pub port: String, + pub baud_rate: u32, pub frequency: u32, pub bandwidth: u32, pub spreading_factor: u8, @@ -116,7 +117,7 @@ pub struct RNodeInterfaceConfig { pub id_callsign: Option, } -#[cfg(any(feature = "serial", feature = "rnode-tcp"))] +#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] impl RNodeInterfaceConfig { /// Convert runtime configuration into the lower driver type while /// preserving signed-value and RF-range validation. @@ -129,6 +130,7 @@ impl RNodeInterfaceConfig { message: format!("{} is outside 0..=37 dBm", self.tx_power), })?; let mut config = rns_interface::rnode::RNodeConfig::new(&self.name, &self.port); + config.baud_rate = self.baud_rate; config.frequency = self.frequency; config.bandwidth = self.bandwidth; config.spreading_factor = self.spreading_factor; @@ -476,12 +478,20 @@ pub fn synthesize_interface( ))); } } - // Android USB-OTG ports vanish on replug; add them at runtime after - // the device is present. if port.starts_with("androidusb://") { - return Err(InterfaceFactoryError::Disabled(format!( - "RNodeInterface '{name}' is an Android USB-OTG entry — skipped at startup; re-add from the UI after plugging the device in" - ))); + #[cfg(target_os = "android")] + { + // Keep Android USB entries in the same persisted + // RNodeInterface schema as serial, TCP and BLE. The + // runtime selects the JNI transport from the URI. + return synthesize_rnode(name, section, mode); + } + #[cfg(not(target_os = "android"))] + { + return Err(InterfaceFactoryError::Disabled(format!( + "RNodeInterface '{name}' uses an Android USB-OTG port on a non-Android build" + ))); + } } #[cfg(any(feature = "serial", feature = "rnode-tcp"))] { @@ -769,7 +779,7 @@ fn synthesize_auto( })) } -#[cfg(any(feature = "serial", feature = "rnode-tcp"))] +#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] fn synthesize_rnode( name: &str, section: &ConfigSection, @@ -783,6 +793,11 @@ fn synthesize_rnode( })? .to_string(); + let baud_rate = section + .get_uint("speed") + .or_else(|| section.get_uint("baud_rate")) + .unwrap_or(115200) as u32; + let (frequency, bandwidth, spreading_factor, coding_rate, tx_power) = require_generic_rnode_radio_params(name, section)?; @@ -791,6 +806,7 @@ fn synthesize_rnode( let config = RNodeInterfaceConfig { name: name.to_string(), port, + baud_rate, frequency, bandwidth, spreading_factor, @@ -810,7 +826,7 @@ fn synthesize_rnode( Ok(InterfaceConfig::RNode(config)) } -#[cfg(any(feature = "serial", feature = "rnode-tcp"))] +#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] fn require_generic_rnode_radio_params( name: &str, section: &ConfigSection, @@ -872,7 +888,7 @@ fn require_generic_rnode_radio_params( )) } -#[cfg(any(feature = "serial", feature = "rnode-tcp"))] +#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] fn required_rnode_scalar<'a>( name: &str, section: &'a ConfigSection, @@ -889,7 +905,7 @@ fn required_rnode_scalar<'a>( }) } -#[cfg(any(feature = "serial", feature = "rnode-tcp"))] +#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] fn parse_required_rnode_unsigned( name: &str, section: &ConfigSection, @@ -912,7 +928,7 @@ where Ok((key, value)) } -#[cfg(any(feature = "serial", feature = "rnode-tcp"))] +#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] fn parse_required_rnode_signed( name: &str, section: &ConfigSection, @@ -935,7 +951,7 @@ where Ok((key, value)) } -#[cfg(any(feature = "serial", feature = "rnode-tcp"))] +#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] fn validate_parsed_rnode_integer( name: &str, key: &str, @@ -956,7 +972,7 @@ where Ok(value) } -#[cfg(any(feature = "serial", feature = "rnode-tcp"))] +#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] fn parse_generic_rnode_airtime( name: &str, section: &ConfigSection, @@ -969,7 +985,7 @@ fn parse_generic_rnode_airtime( Ok((flow_control, st_alock, lt_alock)) } -#[cfg(any(feature = "serial", feature = "rnode-tcp"))] +#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] fn parse_generic_rnode_airtime_value( name: &str, section: &ConfigSection, @@ -1215,13 +1231,13 @@ fn synthesize_rnode_multi( name: format!("{name}/{sub_name}"), field: "vport".to_string(), })? as u8; - if vport as usize > rns_interface::rnode_multi::MAX_SUBINTERFACES { + if vport as usize >= rns_interface::rnode_multi::MAX_SUBINTERFACES { return Err(InterfaceFactoryError::InvalidValue { field: format!("{sub_name}.vport"), message: format!( - "virtual port {} exceeds max {}", + "virtual port {} is outside 0..{}", vport, - rns_interface::rnode_multi::MAX_SUBINTERFACES + rns_interface::rnode_multi::MAX_SUBINTERFACES - 1 ), }); } @@ -1605,7 +1621,7 @@ pub fn default_ifac_size_for(config: &InterfaceConfig) -> usize { | InterfaceConfig::KissSerial(_) | InterfaceConfig::RNodeMulti(_) | InterfaceConfig::AX25KISS(_) => 8, - #[cfg(any(feature = "serial", feature = "rnode-tcp"))] + #[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] InterfaceConfig::RNode(_) => 8, InterfaceConfig::Local(_) | InterfaceConfig::Pipe(_) => 8, #[cfg(feature = "ble")] @@ -2229,6 +2245,7 @@ mod tests { InterfaceConfig::RNode(c) => { assert_eq!(c.name, "test_rnode"); assert_eq!(c.port, "/dev/ttyACM0"); + assert_eq!(c.baud_rate, 115200); assert_eq!(c.frequency, 868000000); assert_eq!(c.bandwidth, 125000); assert_eq!(c.spreading_factor, 7); @@ -2456,6 +2473,7 @@ mod tests { section.set("type", "RNodeInterface"); section.set("port", "tcp://rnode.local"); section.set("frequency", "915000000"); + section.set("speed", "230400"); set_rnode_radio_params(&mut section); let config = synthesize_interface("rnode_tcp", §ion).unwrap(); @@ -2463,12 +2481,28 @@ mod tests { InterfaceConfig::RNode(c) => { assert_eq!(c.name, "rnode_tcp"); assert_eq!(c.port, "tcp://rnode.local"); + assert_eq!(c.baud_rate, 230400); assert_eq!(c.frequency, 915000000); } _ => panic!("expected RNode"), } } + #[cfg(all( + not(target_os = "android"), + any(feature = "serial", feature = "rnode-tcp") + ))] + #[test] + fn test_android_usb_rnode_is_not_synthesized_off_android() { + let mut section = complete_rnode_section(); + section.set("port", "androidusb:///dev/bus/usb/001/002"); + assert!(matches!( + synthesize_interface("android_usb", §ion), + Err(InterfaceFactoryError::Disabled(message)) + if message.contains("non-Android build") + )); + } + #[cfg(any(feature = "serial", feature = "rnode-tcp"))] #[test] fn test_synthesize_rnode_missing_port() { @@ -2576,6 +2610,7 @@ mod tests { let _rnode = InterfaceConfig::RNode(RNodeInterfaceConfig { name: "r".to_string(), port: "/dev/ttyACM0".to_string(), + baud_rate: 115200, frequency: 868000000, bandwidth: 125000, spreading_factor: 7, @@ -3076,6 +3111,31 @@ mod tests { } } + #[cfg(feature = "serial")] + #[test] + fn test_synthesize_rnode_multi_rejects_first_out_of_range_vport() { + let mut section = ConfigSection::new(); + section.set("type", "RNodeMultiInterface"); + section.set("port", "/dev/ttyACM0"); + + let mut sub = ConfigSection::new(); + sub.set( + "vport", + &rns_interface::rnode_multi::MAX_SUBINTERFACES.to_string(), + ); + sub.set("frequency", "865600000"); + sub.set("bandwidth", "125000"); + sub.set("txpower", "14"); + sub.set("spreadingfactor", "7"); + sub.set("codingrate", "5"); + section.subsections.insert("Invalid".to_string(), sub); + + assert!(matches!( + synthesize_interface("test_rnodemulti", §ion), + Err(InterfaceFactoryError::InvalidValue { field, .. }) if field == "Invalid.vport" + )); + } + #[cfg(feature = "serial")] #[test] fn test_synthesize_rnode_multi_duplicate_vport() { diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index 6e46790..49cdd32 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -3519,8 +3519,21 @@ fn next_id(id_gen: &Arc) -> u64 { fn interface_kind_for_config(config: &interface_factory::InterfaceConfig) -> InterfaceKind { match config { - #[cfg(any(feature = "serial", feature = "rnode-tcp"))] - interface_factory::InterfaceConfig::RNode(_) => InterfaceKind::RNode, + #[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] + interface_factory::InterfaceConfig::RNode(_config) => { + #[cfg(target_os = "android")] + if _config.port.starts_with("androidusb://") { + return InterfaceKind::AndroidUsbRNode; + } + #[cfg(any(feature = "serial", feature = "rnode-tcp"))] + { + InterfaceKind::RNode + } + #[cfg(not(any(feature = "serial", feature = "rnode-tcp")))] + { + InterfaceKind::Standard + } + } #[cfg(feature = "serial")] interface_factory::InterfaceConfig::RNodeMulti(_) => InterfaceKind::RNodeMulti, #[cfg(feature = "ble")] @@ -3563,13 +3576,18 @@ impl PendingConfiguredRNodeRuntime { } } -#[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))] +#[cfg(any( + feature = "serial", + feature = "rnode-tcp", + feature = "ble", + target_os = "android" +))] fn pending_configured_rnode_runtime( config: &interface_factory::InterfaceConfig, handles: &[OwnedInterfaceHandle], ) -> Option { let configured_name = match config { - #[cfg(any(feature = "serial", feature = "rnode-tcp"))] + #[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] interface_factory::InterfaceConfig::RNode(config) => config.name.clone(), #[cfg(feature = "ble")] interface_factory::InterfaceConfig::BleRNode(config) => config.name.clone(), @@ -3590,7 +3608,12 @@ fn pending_configured_rnode_runtime( }) } -#[cfg(not(any(feature = "serial", feature = "rnode-tcp", feature = "ble")))] +#[cfg(not(any( + feature = "serial", + feature = "rnode-tcp", + feature = "ble", + target_os = "android" +)))] fn pending_configured_rnode_runtime( _config: &interface_factory::InterfaceConfig, _handles: &[OwnedInterfaceHandle], @@ -5103,7 +5126,7 @@ fn interface_config_name(iface_config: &interface_factory::InterfaceConfig) -> & #[cfg(feature = "serial")] interface_factory::InterfaceConfig::KissSerial(c) => &c.name, interface_factory::InterfaceConfig::Auto(c) => &c.name, - #[cfg(any(feature = "serial", feature = "rnode-tcp"))] + #[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] interface_factory::InterfaceConfig::RNode(c) => &c.name, interface_factory::InterfaceConfig::Local(c) => &c.name, interface_factory::InterfaceConfig::I2P(c) => &c.name, @@ -5138,7 +5161,7 @@ fn interface_config_mode_mut( #[cfg(feature = "serial")] interface_factory::InterfaceConfig::KissSerial(c) => &mut c.mode, interface_factory::InterfaceConfig::Auto(c) => &mut c.mode, - #[cfg(any(feature = "serial", feature = "rnode-tcp"))] + #[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] interface_factory::InterfaceConfig::RNode(c) => &mut c.mode, interface_factory::InterfaceConfig::Local(c) => &mut c.mode, interface_factory::InterfaceConfig::I2P(c) => &mut c.mode, @@ -5176,7 +5199,7 @@ fn apply_discovery_mode_autocorrect( let is_rnode = { #[allow(unused_mut)] let mut rnode = false; - #[cfg(any(feature = "serial", feature = "rnode-tcp"))] + #[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] { rnode |= matches!(iface_config, interface_factory::InterfaceConfig::RNode(_)); } @@ -5292,7 +5315,7 @@ fn discovery_config_for_interface( None, None, ), - #[cfg(any(feature = "serial", feature = "rnode-tcp"))] + #[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] interface_factory::InterfaceConfig::RNode(c) => ( "RNodeInterface", configured_reachable_on(section), @@ -7045,7 +7068,12 @@ async fn spawn_interface_with_rnode_startup_options( is_foreground: Arc, rnode_startup_options: rns_interface::rnode::RNodeStartupOptions, ) -> Result, String> { - #[cfg(not(any(feature = "serial", feature = "rnode-tcp", feature = "ble")))] + #[cfg(not(any( + feature = "serial", + feature = "rnode-tcp", + feature = "ble", + target_os = "android" + )))] let _ = rnode_startup_options; match iface_config { @@ -7125,20 +7153,64 @@ async fn spawn_interface_with_rnode_startup_options( .map(|h| vec![h.into()]) .map_err(|e| format!("Auto: {e}")) } - #[cfg(any(feature = "serial", feature = "rnode-tcp"))] + #[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] interface_factory::InterfaceConfig::RNode(c) => { - let rnode_config = c - .to_rnode_config() - .map_err(|error| format!("RNode: {error}"))?; - rns_interface::rnode::spawn_rnode_interface_with_driver_and_options( - rnode_config, - id, - transport_tx, - rnode_startup_options, - ) - .await - .map(|spawned| vec![spawned.into()]) - .map_err(|e| format!("RNode: {e}")) + #[cfg(target_os = "android")] + if let Some(device_name) = c.port.strip_prefix("androidusb://") { + if device_name.is_empty() { + return Err(format!( + "Android USB RNode '{}': empty USB device name", + c.name + )); + } + let tx_power = u8::try_from(c.tx_power) + .map_err(|_| format!("Android USB RNode '{}': invalid TX power", c.name))?; + let mut config = + rns_interface::android_usb::AndroidUsbConfig::new(&c.name, device_name); + config.baud_rate = c.baud_rate; + config.frequency = c.frequency; + config.bandwidth = c.bandwidth; + config.spreading_factor = c.spreading_factor; + config.coding_rate = c.coding_rate; + config.tx_power = tx_power; + config.mode = c.mode; + config.flow_control = c.flow_control; + config.st_alock = c.st_alock; + config.lt_alock = c.lt_alock; + return rns_interface::android_usb::spawn_android_usb_rnode_interface_with_driver_and_options( + config, + id, + transport_tx, + rnode_startup_options, + ) + .await + .map(|spawned| vec![spawned.into()]) + .map_err(|error| format!("Android USB RNode: {error}")); + } + + #[cfg(any(feature = "serial", feature = "rnode-tcp"))] + { + let rnode_config = c + .to_rnode_config() + .map_err(|error| format!("RNode: {error}"))?; + rns_interface::rnode::spawn_rnode_interface_with_driver_and_options( + rnode_config, + id, + transport_tx, + rnode_startup_options, + ) + .await + .map(|spawned| vec![spawned.into()]) + .map_err(|e| format!("RNode: {e}")) + } + + #[cfg(not(any(feature = "serial", feature = "rnode-tcp")))] + { + Err(format!( + "RNodeInterface '{}': non-Android port requires serial or rnode-tcp support", + c.name + )) + } } interface_factory::InterfaceConfig::Local(c) => { let local_config = rns_interface::local::LocalClientConfig {