diff --git a/crates/muninn-daemon/src/main.rs b/crates/muninn-daemon/src/main.rs index b2d21ca..5e7f8f2 100644 --- a/crates/muninn-daemon/src/main.rs +++ b/crates/muninn-daemon/src/main.rs @@ -34,7 +34,7 @@ use muninn_contracts::{ }; #[cfg(feature = "psmoveapi-tracker")] use muninn_contracts::MuninnMoveTrackerHealthRecord; -use odin_core::{EveProviderAdvertisementRecord, EveSurfaceStateRecord, OdinDocuments}; +use odin_core::{EveProviderAdvertisementRecord, OdinDocuments}; use serde::{Deserialize, Serialize}; use serde_json::json; use std::collections::{HashMap, HashSet}; @@ -72,7 +72,6 @@ use windows_sys::Win32::UI::Input::XboxController::{XINPUT_GAMEPAD, XINPUT_STATE const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0"; const MUNINN_MEDIA_RUDP_CONNECTION_ID: u32 = 0x6d75_0001; const MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID: u32 = 0x6d75_0005; -const MUNINN_COMMAND_RUDP_CONNECTION_ID: u32 = 0x61e0_0001; const MUNINN_RUDP_MEDIA_PROFILE_ID: &str = "muninn.rudp.low_latency_h264_lan.v1"; const MUNINN_RUDP_MEDIA_VIDEO_BITRATE_KBPS: u32 = 12_000; const MUNINN_RUDP_MEDIA_VBV_FRAME_BUDGETS: u32 = 1; @@ -217,7 +216,6 @@ struct Options { hid_controller_rudp_target: Option, hid_controller_rudp_bind: Option, hid_controller_rudp_advertise: Option, - command_rudp_bind: Option, command_rudp_advertise: Option, hid_controller_receipt_retention_seconds: u64, } @@ -433,7 +431,6 @@ fn serve(options: Options) -> Result<()> { ); } start_move_hue_program_sync_worker(&options, Arc::clone(&move_hue_program)); - start_provider_command_ingress(&options, Arc::clone(&move_hue_program))?; start_odin_provider_lease_worker(&options); let mut answered_requests: HashMap = HashMap::new(); @@ -607,10 +604,6 @@ fn move_hue_program_key(host_id: &str) -> String { format!("muninn:{host_id}:move-hue-program") } -fn move_hue_surface_key(host_id: &str) -> String { - format!("surface:muninn.telemetry.{host_id}.move-hue") -} - fn load_or_initialize_move_hue_program( options: &Options, ) -> Result>> { @@ -720,135 +713,6 @@ fn start_move_hue_program_sync_worker( }); } -fn start_provider_command_ingress( - options: &Options, - runtime_program: Arc>, -) -> Result<()> { - let Some(bind) = options.command_rudp_bind else { - return Ok(()); - }; - let socket = UdpSocket::bind(bind) - .with_context(|| format!("binding Muninn provider command route at {bind}"))?; - socket.set_read_timeout(Some(Duration::from_millis(5)))?; - let options = options.clone(); - thread::spawn(move || { - if let Err(error) = run_provider_command_ingress(socket, options, runtime_program) { - eprintln!("Muninn provider command ingress stopped: {error:#}"); - } - }); - Ok(()) -} - -fn run_provider_command_ingress( - socket: UdpSocket, - options: Options, - runtime_program: Arc>, -) -> Result<()> { - let mut transport = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { - media_delivery: None, - runtime_id: format!("muninn-{}-command-ingress", options.host_id), - socket, - mode: cultnet_rs::CultNetRudpSocketMode::Server, - remote_addr: None, - connection_id: MUNINN_COMMAND_RUDP_CONNECTION_ID, - initial_sequence: 1, - resend_delay_ms: 15, - transport_id: Some("muninn-provider-command-rudp".to_string()), - max_payload_bytes: None, - max_fragment_bytes: Some(1200), - max_pending_reliable_packets: Some(64), - media_reliable_expire_after_ms: None, - reconnect_policy: None, - })?; - loop { - if let Some(frame) = transport.receive_once()? - && frame.channel_id == "schema" - { - let message = decode_cultnet_message_from_slice( - &frame.payload, - CultNetWireContract::CultNetSchemaV0, - )?; - if let CultNetMessage::DocumentPutRaw { document, .. } = message { - apply_provider_command_document(&options, &runtime_program, document)?; - } - } - transport.poll_resends()?; - } -} - -fn apply_provider_command_document( - options: &Options, - runtime_program: &Arc>, - document: CultNetRawDocumentRecord, -) -> Result<()> { - if document.schema_id != "gamecult.eve.command.v1" { - return Ok(()); - } - let value: serde_json::Value = match document.payload_encoding { - CultNetRawPayloadEncoding::Messagepack => rmp_serde::from_slice(&document.payload)?, - }; - let command_type = value - .get("command") - .or_else(|| value.get("type")) - .and_then(serde_json::Value::as_str) - .unwrap_or_default(); - if command_type != "muninn.set-move-hue-program" { - return Ok(()); - } - let payload = value - .get("payload") - .filter(|payload| payload.is_object()) - .unwrap_or(&value); - let provider_id = value - .get("providerId") - .and_then(serde_json::Value::as_str) - .unwrap_or_default(); - if provider_id != muninn_provider_id(options) { - return Err(anyhow!( - "Move hue command targets provider {provider_id}, not {}", - muninn_provider_id(options) - )); - } - let mut program = runtime_program - .lock() - .map_err(|_| anyhow!("Move hue runtime program lock is poisoned"))? - .clone(); - if let Some(mode) = payload.get("mode").and_then(serde_json::Value::as_str) { - program.mode = mode.to_string(); - if mode == "hold" { - program.hold_at_ns = timestamp_ns()?; - } - } - if let Some(order) = payload.get("orderMode").and_then(serde_json::Value::as_str) { - program.order_mode = order.to_string(); - } - if let Some(cycle_ms) = payload.get("cycleMs").and_then(serde_json::Value::as_u64) { - program.cycle_ms = cycle_ms; - } - if let Some(value) = payload - .get("transitionPercent") - .and_then(serde_json::Value::as_u64) - { - program.transition_percent = u8::try_from(value) - .map_err(|_| anyhow!("Move hue transitionPercent must be at most 100"))?; - program.transition_percent_explicit = true; - } - program.requested_by = value - .get("publishedBy") - .and_then(serde_json::Value::as_str) - .unwrap_or("eve-command") - .to_string(); - program.updated_at = timestamp()?; - validate_move_hue_program(&program)?; - let key = move_hue_program_key(&options.host_id); - open_node(options, "muninn-provider-command")?.put(&key, &program)?; - *runtime_program - .lock() - .map_err(|_| anyhow!("Move hue runtime program lock is poisoned"))? = program; - Ok(()) -} - const MUNINN_VIDEO_CODECS: [&str; 1] = ["h264"]; const MUNINN_AUDIO_CODECS: [&str; 1] = ["pcm-f32le-interleaved"]; @@ -2630,155 +2494,6 @@ fn publish_surface( }; node.put("latest", &record)?; node.put(&record.surface_id, &record)?; - publish_move_hue_eve_surface(node, options)?; - Ok(()) -} - -fn publish_move_hue_eve_surface( - node: &mut cultmesh_rs::CultMeshNode, - options: &Options, -) -> Result<()> { - let program_key = move_hue_program_key(&options.host_id); - let program = node - .get::(&program_key)? - .unwrap_or_else(|| bootstrap_move_hue_program(options)); - let provider_id = muninn_provider_id(options); - let surface_key = move_hue_surface_key(&options.host_id); - let action = |id: &str, - label: &str, - mode: Option<&str>, - order_mode: Option<&str>, - cycle_ms: Option, - transition_percent: Option| { - json!({ - "id": format!("{provider_id}.move-hue.{id}"), - "kind": "card", - "props": { - "title": label, - "commandId": "muninn.set-move-hue-program", - "action": { - "type": "muninn.set-move-hue-program", - "providerId": provider_id, - "programId": program_key, - "schema": MUNINN_MOVE_HUE_PROGRAM_SCHEMA, - "mode": mode, - "orderMode": order_mode, - "cycleMs": cycle_ms, - "transitionPercent": transition_percent - } - }, - "children": [] - }) - }; - let surface = EveSurfaceStateRecord { - provider_id: provider_id.clone(), - title: format!("Muninn {} Move Hue Program", options.host_id), - version: SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_millis() as i64, - updated_at: timestamp()?, - surface: json!({ - "schema": "gamecult.eve.surface.v1", - "id": format!("{provider_id}.move-hue.surface"), - "title": "Move Hue Program", - "root": { - "id": format!("{provider_id}.move-hue.root"), - "kind": "dashboard", - "props": { - "title": "Move Hue Program", - "summary": format!("{} / {} / {} ms / {}% transition", program.mode, program.order_mode, program.cycle_ms, effective_transition_percent(&program)) - }, - "children": [ - { - "id": format!("{provider_id}.move-hue.state"), - "kind": "pane", - "props": { "title": "State" }, - "children": [ - { "id": format!("{provider_id}.move-hue.state.mode"), "kind": "text", "props": { "text": format!("mode: {}", program.mode) } }, - { "id": format!("{provider_id}.move-hue.state.order"), "kind": "text", "props": { "text": format!("order: {}", program.order_mode) } }, - { "id": format!("{provider_id}.move-hue.state.rate"), "kind": "text", "props": { "text": format!("cycle: {} ms", program.cycle_ms) } }, - { "id": format!("{provider_id}.move-hue.state.transition"), "kind": "text", "props": { "text": format!("transition: {}%", effective_transition_percent(&program)) } } - ] - }, - { - "id": format!("{provider_id}.move-hue.mode"), - "kind": "pane", - "props": { "title": "Mode" }, - "children": [ - action("mode-animated", "Animate", Some("animated"), None, None, None), - action("mode-hold", "Hold Current Colors", Some("hold"), None, None, None), - action("mode-static", "Static Palette", Some("static"), None, None, None) - ] - }, - { - "id": format!("{provider_id}.move-hue.order"), - "kind": "pane", - "props": { "title": "Update Order" }, - "children": [ - action("order-descending", "Descending", None, Some("descending"), None, None), - action("order-ascending", "Ascending", None, Some("ascending"), None, None), - action("order-bounce", "Bounce", None, Some("bounce"), None, None), - action("order-rotating", "Rotating Lead", None, Some("rotating-lead"), None, None), - action("order-golden", "Golden Permutation", None, Some("golden-permutation"), None, None) - ] - }, - { - "id": format!("{provider_id}.move-hue.rate"), - "kind": "pane", - "props": { "title": "Cycle Rate" }, - "children": [ - action("rate-500", "2 Hz", None, None, Some(500), None), - action("rate-1000", "1 Hz", None, None, Some(1000), None), - action("rate-2000", "0.5 Hz", None, None, Some(2000), None) - ] - }, - { - "id": format!("{provider_id}.move-hue.transition"), - "kind": "pane", - "props": { "title": "Transition Duration" }, - "children": [ - action("transition-0", "Off", None, None, None, Some(0)), - action("transition-10", "10%", None, None, None, Some(10)), - action("transition-25", "25%", None, None, None, Some(25)), - action("transition-50", "50%", None, None, None, Some(50)), - action("transition-75", "75%", None, None, None, Some(75)), - action("transition-100", "100%", None, None, None, Some(100)) - ] - } - ] - } - }), - }; - node.put(&surface_key, &surface)?; - if let Some(target) = resolve_odin_cultmesh_uri(options) { - let _ = node.publish_document_to_rudp_catalog( - &program_key, - &program, - CultMeshRudpDocumentPublishOptions { - target, - runtime_id: muninn_daemon_id(options), - source_role: Some("muninn.move-hue-program-state".to_string()), - tags: vec!["muninn".to_string(), "move-hue-program".to_string()], - flush_timeout: Duration::from_millis(300), - resend_delay_ms: 15, - ..CultMeshRudpDocumentPublishOptions::default() - }, - ); - let _ = node.publish_document_to_rudp_catalog( - &surface_key, - &surface, - CultMeshRudpDocumentPublishOptions { - target, - runtime_id: muninn_daemon_id(options), - source_role: Some("muninn.move-hue-eve-surface".to_string()), - tags: vec!["muninn".to_string(), "eve-surface".to_string()], - flush_timeout: Duration::from_millis(300), - resend_delay_ms: 15, - ..CultMeshRudpDocumentPublishOptions::default() - }, - ); - } Ok(()) } @@ -2829,27 +2544,10 @@ fn publish_runtime_boundary_records( .clone() .unwrap_or_else(|| bind.to_string()) }); - let mut provider_routes = vec![json!({ + let provider_routes = vec![json!({ "transport": "cultcache-store", "address": options.store_path.display().to_string() })]; - if let Some(bind) = options.command_rudp_bind { - let address = options - .command_rudp_advertise - .clone() - .unwrap_or_else(|| bind.to_string()); - provider_routes.push(json!({ - "id": "muninn.provider.command", - "role": "muninn provider command ingress", - "uri": format!("cultmesh://{address}/muninn/{}/commands", options.host_id), - "transport": CULTNET_RUDP_PROTOCOL_ID, - "address": address, - "connectionId": MUNINN_COMMAND_RUDP_CONNECTION_ID, - "channel": "schema", - "schema": "gamecult.eve.command.v1", - "tags": ["muninn", "command", "provider-owned"] - })); - } let hid_controller_devices_snake = live_move_sources .iter() .map(|source| { @@ -3070,12 +2768,6 @@ fn publish_runtime_boundary_records( "endpoints": provider_endpoints, "inputStreams": provider_input_streams, "routes": provider_routes, - "surfaces": [{ - "surfaceId": format!("{provider_id}.move-hue.surface"), - "surfaceKind": "gamecult.eve.surface_state.v1", - "recordRef": move_hue_surface_key(&options.host_id), - "title": "Move Hue Program" - }], "commandSurface": { "commandBoundaryId": command_boundary_key, "transportProfileId": transport_profile_key @@ -9664,7 +9356,6 @@ impl Options { hid_controller_rudp_target: None, hid_controller_rudp_bind: None, hid_controller_rudp_advertise: None, - command_rudp_bind: None, command_rudp_advertise: None, hid_controller_receipt_retention_seconds: 3_600, }; @@ -9934,11 +9625,10 @@ impl Options { Some(take_value(&mut args, "--hid-controller-rudp-advertise")?) } "--command-rudp-bind" => { - options.command_rudp_bind = Some( - take_value(&mut args, "--command-rudp-bind")? - .parse() - .context("--command-rudp-bind must be a socket address")?, - ) + let _ = take_value(&mut args, "--command-rudp-bind")?; + return Err(anyhow!( + "--command-rudp-bind has been removed; the Eve command ingress was quarantined (tag parked/Muninn-eve-surface)" + )); } "--command-rudp-advertise" => { options.command_rudp_advertise = @@ -11560,42 +11250,6 @@ mod tests { ); } - #[test] - fn muninn_eve_surface_exposes_live_move_hue_program_controls() { - let store_path = std::env::temp_dir().join(format!( - "muninn-move-hue-eve-{}.cc", - timestamp_ns().unwrap() - )); - let options = Options::parse( - [ - "serve", - "--store", - store_path.to_str().unwrap(), - "--host", - "nightwing", - "--odin-cultmesh-uri", - "none", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - let _ = load_or_initialize_move_hue_program(&options).unwrap(); - let mut node = open_node(&options, "muninn-move-hue-eve-test").unwrap(); - publish_surface(&mut node, &options, "idle", &[]).unwrap(); - let surface = node - .get_required::(&move_hue_surface_key("nightwing")) - .unwrap(); - let encoded = surface.surface.to_string(); - assert!(encoded.contains("Hold Current Colors")); - assert!(encoded.contains("golden-permutation")); - assert!(encoded.contains("Transition Duration")); - assert!(encoded.contains("transitionPercent")); - assert!(encoded.contains(MUNINN_MOVE_HUE_PROGRAM_SCHEMA)); - drop(node); - let _ = fs::remove_file(store_path); - } - #[test] fn move_hue_program_command_updates_typed_live_state() { let store_path = std::env::temp_dir().join(format!( @@ -11635,115 +11289,6 @@ mod tests { let _ = fs::remove_file(store_path); } - #[test] - fn provider_command_rudp_ingress_applies_move_hue_command() { - let store_path = std::env::temp_dir().join(format!( - "muninn-provider-command-{}.cc", - timestamp_ns().unwrap() - )); - let options = Options::parse( - [ - "serve", - "--store", - store_path.to_str().unwrap(), - "--host", - "nightwing", - "--odin-cultmesh-uri", - "none", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - let runtime_program = load_or_initialize_move_hue_program(&options).unwrap(); - let server_socket = UdpSocket::bind("127.0.0.1:0").unwrap(); - server_socket - .set_read_timeout(Some(Duration::from_millis(5))) - .unwrap(); - let server_address = server_socket.local_addr().unwrap(); - let server_options = options.clone(); - let server_program = Arc::clone(&runtime_program); - thread::spawn(move || { - run_provider_command_ingress(server_socket, server_options, server_program).unwrap() - }); - - let client_socket = UdpSocket::bind("127.0.0.1:0").unwrap(); - client_socket - .set_read_timeout(Some(Duration::from_millis(5))) - .unwrap(); - let mut client = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { - media_delivery: None, - runtime_id: "muninn-provider-command-test-client".to_string(), - socket: client_socket, - mode: cultnet_rs::CultNetRudpSocketMode::Client, - remote_addr: Some(server_address), - connection_id: MUNINN_COMMAND_RUDP_CONNECTION_ID, - initial_sequence: 1, - resend_delay_ms: 15, - transport_id: Some("muninn-provider-command-test".to_string()), - max_payload_bytes: None, - max_fragment_bytes: Some(1200), - max_pending_reliable_packets: Some(64), - media_reliable_expire_after_ms: None, - reconnect_policy: None, - }) - .unwrap(); - client.connect(Vec::new()).unwrap(); - let deadline = Instant::now() + Duration::from_secs(2); - while !client.connected() && Instant::now() < deadline { - let _ = client.receive_once().unwrap(); - client.poll_resends().unwrap(); - thread::sleep(Duration::from_millis(1)); - } - assert!(client.connected(), "provider command RUDP handshake"); - let command = json!({ - "type": "surface-command", - "schema": "gamecult.eve.command.v1", - "providerId": "muninn.telemetry.nightwing", - "command": "muninn.set-move-hue-program", - "payload": { - "type": "muninn.set-move-hue-program", - "mode": "hold", - "orderMode": "bounce", - "cycleMs": 1500, - "transitionPercent": 25 - }, - "publishedBy": "provider-command-test" - }); - let message = CultNetMessage::DocumentPutRaw { - message_id: "provider-command-test".to_string(), - document: CultNetRawDocumentRecord { - schema_id: "gamecult.eve.command.v1".to_string(), - record_key: "provider-command-test".to_string(), - stored_at: timestamp().unwrap(), - payload_encoding: CultNetRawPayloadEncoding::Messagepack, - payload: rmp_serde::to_vec_named(&command).unwrap(), - source_runtime_id: Some("provider-command-test".to_string()), - source_agent_id: None, - source_role: Some("test".to_string()), - tags: None, - }, - }; - client - .send( - "schema", - encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0) - .unwrap(), - ) - .unwrap(); - let apply_deadline = Instant::now() + Duration::from_secs(2); - while runtime_program.lock().unwrap().mode != "hold" && Instant::now() < apply_deadline { - client.poll_resends().unwrap(); - thread::sleep(Duration::from_millis(2)); - } - assert_eq!(runtime_program.lock().unwrap().mode, "hold"); - assert_eq!(runtime_program.lock().unwrap().order_mode, "bounce"); - assert_eq!(runtime_program.lock().unwrap().cycle_ms, 1500); - assert_eq!(runtime_program.lock().unwrap().transition_percent, 25); - let _ = fs::remove_file(store_path); - } - #[test] fn move_light_command_writes_ps_move_led_report() { let command = pending_move_light_command(); @@ -12930,8 +12475,6 @@ Device 00:07:04:A8:00:D0 (public) "0.0.0.0:17888", "--hid-controller-rudp-advertise", "198.51.100.66:17888", - "--command-rudp-bind", - "0.0.0.0:17889", "--command-rudp-advertise", "198.51.100.66:17889", ] @@ -12950,21 +12493,6 @@ Device 00:07:04:A8:00:D0 (public) let provider = node .get_required::("muninn.telemetry.starfire") .unwrap(); - let command_route = provider - .value - .get("routes") - .and_then(|value| value.as_array()) - .and_then(|routes| { - routes.iter().find(|route| { - route.get("role").and_then(|value| value.as_str()) - == Some("muninn provider command ingress") - }) - }) - .expect("provider-owned command route"); - assert_eq!( - command_route.get("uri").and_then(|value| value.as_str()), - Some("cultmesh://198.51.100.66:17889/muninn/starfire/commands") - ); let streams = provider .value .get("inputStreams") diff --git a/crates/sleipnir-daemon/src/main.rs b/crates/sleipnir-daemon/src/main.rs index cccedfd..32c9692 100644 --- a/crates/sleipnir-daemon/src/main.rs +++ b/crates/sleipnir-daemon/src/main.rs @@ -9,7 +9,7 @@ use cultnet_rs::{ }; use muninn_contracts::{MUNINN_HID_CONTROLLER_STATE_SCHEMA, MuninnHidControllerStateRecord}; use odin_core::{ - EVE_PROVIDER_ADVERTISEMENT_SCHEMA, EveProviderAdvertisementRecord, EveSurfaceStateRecord, + EVE_PROVIDER_ADVERTISEMENT_SCHEMA, EveProviderAdvertisementRecord, IdunnDaemonHealthRecord, OdinDocuments, OdinEndpointQuery, SleipnirInputMappingRecord, discover_provider_endpoints, }; @@ -341,7 +341,7 @@ fn main() -> Result<()> { None, ) }; - publish_sleipnir_runtime_surface(&mut node, &options, &initial_state, true)?; + publish_sleipnir_provider(&mut node, &options, &initial_state, true)?; let mut last_idunn_health_attempt_at = Instant::now() - Duration::from_secs(60); publish_idunn_health_if_configured(&options, &initial_state, &mut last_idunn_health_attempt_at); @@ -562,7 +562,7 @@ fn main() -> Result<()> { recent_input_latency.as_ref(), ) }; - publish_sleipnir_runtime_surface(&mut node, &options, &runtime_state, true)?; + publish_sleipnir_provider(&mut node, &options, &runtime_state, true)?; publish_idunn_health_if_configured( &options, &runtime_state, @@ -597,7 +597,7 @@ fn main() -> Result<()> { recent_input_latency.as_ref(), ) }; - publish_sleipnir_runtime_surface( + publish_sleipnir_provider( &mut node, &options, &runtime_state, @@ -689,7 +689,7 @@ impl SleipnirRuntimeState { } } -fn publish_sleipnir_runtime_surface( +fn publish_sleipnir_provider( node: &mut cultmesh_rs::CultMeshNode, options: &Options, state: &SleipnirRuntimeState, @@ -744,15 +744,7 @@ fn publish_sleipnir_runtime_surface( "channel": "schema" })); } - let surface = EveSurfaceStateRecord { - provider_id: state.provider_id.clone(), - title: sleipnir_provider_title(options), - version: unix_millis_i64(), - updated_at: state.updated_at.clone(), - surface: sleipnir_surface_document(state), - }; node.put(&state.provider_id, &advertisement)?; - node.put(&state.provider_id, &surface)?; if publish_remote && let Some(target) = resolve_odin_cultmesh_uri(options) { if let Err(error) = node.publish_document_to_rudp_catalog( &state.provider_id, @@ -769,23 +761,6 @@ fn publish_sleipnir_runtime_surface( eprintln!("Sleipnir could not publish provider advertisement to Odin: {error:#}"); } } - if let Err(error) = node.publish_document_to_rudp_catalog( - &state.provider_id, - &surface, - CultMeshRudpDocumentPublishOptions { - target, - runtime_id: sleipnir_daemon_id(options), - source_role: Some("sleipnir.input-mirror-surface".to_string()), - tags: vec!["sleipnir".to_string(), "eve-surface".to_string()], - flush_timeout: Duration::from_millis(300), - resend_delay_ms: 15, - ..CultMeshRudpDocumentPublishOptions::default() - }, - ) { - if options.trace { - eprintln!("Sleipnir could not publish surface state to Odin: {error:#}"); - } - } } Ok(()) } @@ -1019,411 +994,6 @@ fn hid_state_host_id_from_value(value: &serde_json::Value) -> Option { string_field(payload, &["host_id", "hostId"]) } -fn sleipnir_surface_document(state: &SleipnirRuntimeState) -> serde_json::Value { - let preset_cards = remap_preset_cards(state); - let binding_map = xbox_binding_map(state); - let device_cards = state - .available_devices - .iter() - .map(|device| { - let selected = state.selected_device_filter.as_deref() == Some(device.device_id.as_str()) - || state.selected_device_filter.as_deref() == Some(device.device_kind.as_str()) - || state.selected_device_filter.as_deref() == Some(device.stream_id.as_str()); - serde_json::json!({ - "id": format!("{}.device.{}", state.provider_id, stable_id(&device.device_id)), - "kind": "card", - "props": { - "title": format!("{} {}", if selected { "selected" } else { "available" }, device.device_id), - "commandId": "sleipnir.map-hid-device", - "action": { - "type": "sleipnir.map-hid-device", - "providerId": state.provider_id, - "deviceFilter": device.device_id, - "streamId": device.stream_id - } - }, - "children": [ - text_element(format!("{}.device.{}.kind", state.provider_id, stable_id(&device.device_id)), format!("kind: {}", device.device_kind)), - text_element(format!("{}.device.{}.host", state.provider_id, stable_id(&device.device_id)), format!("host: {}", device.host_id)), - text_element(format!("{}.device.{}.endpoint", state.provider_id, stable_id(&device.device_id)), format!("endpoint: {}", device.endpoint)), - text_element(format!("{}.device.{}.path", state.provider_id, stable_id(&device.device_id)), format!("source: {}", device.source_path)) - ] - }) - }) - .collect::>(); - let mut runtime_children = vec![ - serde_json::json!({ - "id": format!("{}.disable", state.provider_id), - "kind": "card", - "props": { - "title": "Stop consuming input", - "commandId": "sleipnir.disable-input", - "action": { - "type": "sleipnir.disable-input", - "providerId": state.provider_id - } - }, - "children": [] - }), - text_element( - format!("{}.state", state.provider_id), - format!("state: {}", state.stream_state), - ), - text_element( - format!("{}.backend", state.provider_id), - format!("virtual backend: {}", state.virtual_backend), - ), - text_element( - format!("{}.presentation", state.provider_id), - format!("presentation: {}", state.presentation), - ), - text_element( - format!("{}.muninn", state.provider_id), - format!( - "muninn endpoint: {}", - state - .selected_muninn_endpoint - .as_deref() - .unwrap_or("discovering") - ), - ), - text_element( - format!("{}.filter", state.provider_id), - format!( - "device filter: {}", - state.selected_device_filter.as_deref().unwrap_or("any") - ), - ), - text_element( - format!("{}.updated", state.provider_id), - format!("updated: {}", state.updated_at), - ), - ]; - runtime_children.push(serde_json::json!({ - "id": format!("{}.devices-inline", state.provider_id), - "kind": "pane", - "props": { "title": "Available HID Devices", "density": "compact" }, - "children": if device_cards.is_empty() { - vec![text_element( - format!("{}.devices.empty", state.provider_id), - "no Muninn HID devices discovered".to_string(), - )] - } else { - device_cards - } - })); - serde_json::json!({ - "schema": "gamecult.eve.surface.v1", - "id": format!("{}.surface", state.provider_id), - "title": "Sleipnir Input Mirror", - "root": { - "id": format!("{}.root", state.provider_id), - "kind": "dashboard", - "props": { - "title": "Sleipnir Input Mirror", - "summary": format!("{} via {}", state.stream_state, state.virtual_backend) - }, - "children": [ - { - "id": format!("{}.runtime", state.provider_id), - "kind": "pane", - "props": { "title": "Runtime" }, - "children": runtime_children - }, - { - "id": format!("{}.input", state.provider_id), - "kind": "pane", - "props": { "title": "Input" }, - "children": [ - text_element(format!("{}.device", state.provider_id), format!("device: {}", state.last_device_id.as_deref().unwrap_or("none"))), - text_element(format!("{}.kind", state.provider_id), format!("kind: {}", state.last_device_kind.as_deref().unwrap_or("unknown"))), - text_element(format!("{}.sequence", state.provider_id), format!("sequence: {}", state.last_sequence.map(|value| value.to_string()).unwrap_or_else(|| "none".to_string()))), - text_element(format!("{}.age", state.provider_id), format!("last frame age ms: {}", state.last_frame_age_ms.map(|value| value.to_string()).unwrap_or_else(|| "none".to_string()))), - text_element(format!("{}.ignored", state.provider_id), format!("ignored stream frames: {}", state.ignored_stream_frames)) - ] - }, - { - "id": format!("{}.latency", state.provider_id), - "kind": "pane", - "props": { "title": "Input Latency" }, - "children": input_latency_elements(state) - }, - { - "id": format!("{}.axis", state.provider_id), - "kind": "pane", - "props": { "title": "Axis Classification" }, - "children": [ - text_element(format!("{}.axis.summary", state.provider_id), format!("mapped axes: {}", state.last_input_latency.as_ref().map(|trace| trace.axis_summary.join(", ")).filter(|text| !text.is_empty()).unwrap_or_else(|| "none".to_string()))) - ] - }, - { - "id": format!("{}.remap", state.provider_id), - "kind": "pane", - "props": { "title": "Remapping Presets" }, - "children": preset_cards - }, - { - "id": format!("{}.binding-map-pane", state.provider_id), - "kind": "pane", - "props": { "title": "Xbox Controller Mapping", "span": "wide" }, - "children": [binding_map] - } - ] - }, - "assets": [] - }) -} - -fn input_latency_elements(state: &SleipnirRuntimeState) -> Vec { - let Some(trace) = state.last_input_latency.as_ref() else { - return vec![text_element( - format!("{}.latency.empty", state.provider_id), - "no emitted input trace yet".to_string(), - )]; - }; - vec![ - text_element( - format!("{}.latency.identity", state.provider_id), - format!( - "device: {} seq={} emitted={}", - trace.device_id, trace.sequence, trace.emitted - ), - ), - text_element( - format!("{}.latency.source-arrival", state.provider_id), - format!( - "signal arrival: {}", - trace - .source_to_arrival_ms - .map(|value| format!("source to arrival {} ms", value)) - .unwrap_or_else(|| "source timestamp unavailable".to_string()) - ), - ), - text_element( - format!("{}.latency.buffer", state.provider_id), - format!("arrival to buffer: {} ms", trace.arrival_to_buffer_ms), - ), - text_element( - format!("{}.latency.axis", state.provider_id), - format!( - "buffer to axis classification: {} ms", - trace.buffer_to_axis_ms - ), - ), - text_element( - format!("{}.latency.hid", state.provider_id), - format!("axis to HID emission: {} ms", trace.axis_to_hid_ms), - ), - text_element( - format!("{}.latency.total", state.provider_id), - format!( - "observed mirror total: {} ms{}", - trace.total_observed_ms, - trace - .source_to_hid_ms - .map(|value| format!(" / source to HID {} ms", value)) - .unwrap_or_default() - ), - ), - ] -} - -fn remap_preset_cards(state: &SleipnirRuntimeState) -> Vec { - vec![ - remap_preset_card( - state, - "nav-to-xbox", - "Nav to Xbox", - "xbox360", - serde_json::json!({ - "leftX": {"source": 0}, - "leftY": {"source": 1, "invert": true}, - "leftTrigger": {"source": 2}, - "rightTrigger": {"source": 5} - }), - serde_json::json!({ - "cross": "a", - "circle": "b", - "square": "x", - "triangle": "y", - "select": "back", - "ps": "guide" - }), - ), - remap_preset_card( - state, - "invert-y", - "Invert Y", - "xbox360", - serde_json::json!({ - "leftX": {"source": 0}, - "leftY": {"source": 1, "invert": true}, - "leftTrigger": {"source": 2}, - "rightTrigger": {"source": 5} - }), - serde_json::json!({}), - ), - ] -} - -fn remap_preset_card( - state: &SleipnirRuntimeState, - preset_id: &str, - title: &str, - presentation: &str, - axis_map: serde_json::Value, - button_map: serde_json::Value, -) -> serde_json::Value { - serde_json::json!({ - "id": format!("{}.remap.{}", state.provider_id, preset_id), - "kind": "card", - "props": { - "title": title, - "commandId": "sleipnir.apply-remap-preset", - "action": { - "type": "sleipnir.apply-remap-preset", - "providerId": state.provider_id, - "deviceFilter": state.selected_device_filter, - "presentation": presentation, - "axisMap": axis_map, - "buttonMap": button_map - } - }, - "children": [ - text_element(format!("{}.remap.{}.detail", state.provider_id, preset_id), format!("presentation: {presentation}")) - ] - }) -} - -fn xbox_binding_map(state: &SleipnirRuntimeState) -> serde_json::Value { - let targets = [ - ( - "leftX", "axis", "Left X", "axis 0", "16%", "34%", "265", "224", - ), - ( - "leftY", "axis", "Left Y", "axis 1", "16%", "49%", "265", "224", - ), - ( - "leftTrigger", - "axis", - "LT", - "axis 2", - "20%", - "12%", - "253", - "68", - ), - ( - "rightTrigger", - "axis", - "RT", - "axis 5", - "80%", - "12%", - "527", - "68", - ), - ("a", "button", "A", "unmapped", "88%", "72%", "568", "244"), - ("b", "button", "B", "unmapped", "92%", "58%", "608", "204"), - ("x", "button", "X", "unmapped", "80%", "58%", "528", "204"), - ("y", "button", "Y", "unmapped", "84%", "44%", "568", "164"), - ("lb", "button", "LB", "unmapped", "22%", "22%", "253", "108"), - ("rb", "button", "RB", "unmapped", "78%", "22%", "527", "108"), - ( - "back", "button", "Back", "unmapped", "40%", "43%", "363", "197", - ), - ( - "start", "button", "Start", "unmapped", "60%", "43%", "419", "197", - ), - ( - "guide", "button", "Guide", "unmapped", "50%", "36%", "391", "224", - ), - ("l3", "button", "L3", "unmapped", "30%", "76%", "265", "224"), - ("r3", "button", "R3", "unmapped", "70%", "76%", "474", "256"), - ( - "up", "button", "D-Up", "unmapped", "12%", "64%", "245", "224", - ), - ( - "down", "button", "D-Down", "unmapped", "12%", "78%", "245", "306", - ), - ( - "left", "button", "D-Left", "unmapped", "12%", "71%", "204", "267", - ), - ( - "right", "button", "D-Right", "unmapped", "26%", "71%", "286", "267", - ), - ]; - let children = targets - .into_iter() - .map( - |(target, kind, label, fallback, x, y, anchor_x, anchor_y)| { - binding_target( - state, - target, - kind, - label, - binding_summary(state, target, kind, fallback), - x, - y, - anchor_x, - anchor_y, - ) - }, - ) - .collect::>(); - serde_json::json!({ - "id": format!("{}.binding-map", state.provider_id), - "kind": "input.binding-map", - "props": { - "label": "Xbox controller remapping" - }, - "children": children - }) -} - -fn binding_target( - state: &SleipnirRuntimeState, - target: &str, - binding_kind: &str, - label: &str, - current: String, - x: &str, - y: &str, - anchor_x: &str, - anchor_y: &str, -) -> serde_json::Value { - let listening = state - .pending_learn - .as_ref() - .is_some_and(|learn| learn.target == target && learn.binding_kind == binding_kind); - serde_json::json!({ - "id": format!("{}.binding.{}", state.provider_id, stable_id(target)), - "kind": "binding.target", - "props": { - "target": target, - "bindingKind": binding_kind, - "label": label, - "current": if listening { "listening..." } else { current.as_str() }, - "x": x, - "y": y, - "anchorX": anchor_x, - "anchorY": anchor_y, - "documentId": format!("cultmesh://sleipnir/{}/binding/{target}", state.provider_id), - "slotId": format!("sleipnir.binding.{target}"), - "schemaId": "gamecult.eve.surface.v1", - "presentationKind": "modal.binding", - "deviceFilter": state.selected_device_filter, - "presentation": "xbox360" - }, - "embeddedDocuments": [{ - "slotId": format!("sleipnir.binding.{target}"), - "documentId": format!("cultmesh://sleipnir/{}/binding/{target}", state.provider_id), - "schemaId": "gamecult.eve.surface.v1", - "presentationKind": "modal.binding" - }] - }) -} - fn binding_summary( state: &SleipnirRuntimeState, target: &str, @@ -1445,23 +1015,6 @@ fn binding_summary( } } -fn axis_binding_label(binding: Option<&AxisBinding>) -> String { - match binding { - Some(binding) if binding.invert => format!("axis {} inverted", binding.source), - Some(binding) => format!("axis {}", binding.source), - None => "unmapped".to_string(), - } -} - -fn text_element(id: String, text: String) -> serde_json::Value { - serde_json::json!({ - "id": id, - "kind": "text", - "props": { "text": text }, - "children": [] - }) -} - fn read_desired_mapping( node: &mut cultmesh_rs::CultMeshNode, options: &Options, @@ -3120,49 +2673,6 @@ mod tests { let _ = fs::remove_file(store_path); } - #[test] - fn surface_exposes_input_latency_and_axis_classification() { - let mapping = default_mapping(); - let state = SleipnirRuntimeState { - provider_id: "sleipnir.input-mirror.test".to_string(), - selected_muninn_endpoint: Some("127.0.0.1:17888".to_string()), - selected_device_filter: Some("nav".to_string()), - presentation: "xbox360".to_string(), - virtual_backend: "logging.dry-run".to_string(), - stream_state: "connected".to_string(), - last_device_id: Some("nav".to_string()), - last_device_kind: Some("ps3-navigation".to_string()), - last_sequence: Some(42), - last_frame_age_ms: Some(3), - last_input_latency: Some(SleipnirInputLatencySnapshot { - device_id: "nav".to_string(), - sequence: 42, - source_to_arrival_ms: Some(2), - arrival_to_buffer_ms: 3, - buffer_to_axis_ms: 1, - axis_to_hid_ms: 1, - source_to_hid_ms: Some(7), - total_observed_ms: 5, - axis_summary: vec!["leftX<-axis0 value=0.500".to_string()], - emitted: true, - }), - ignored_stream_frames: 0, - available_devices: Vec::new(), - axis_map: mapping.axis_map, - button_map: mapping.button_map, - pending_learn: None, - updated_at: "unix-1".to_string(), - }; - - let surface = serde_json::to_string(&sleipnir_surface_document(&state)).unwrap(); - - assert!(surface.contains("Input Latency")); - assert!(surface.contains("arrival to buffer: 3 ms")); - assert!(surface.contains("buffer to axis classification: 1 ms")); - assert!(surface.contains("axis to HID emission: 1 ms")); - assert!(surface.contains("mapped axes: leftX<-axis0 value=0.500")); - } - #[test] fn available_hid_devices_ignore_move_evidence_streams() { let provider = json!({ @@ -3385,44 +2895,6 @@ mod tests { ); } - #[test] - fn endpoint_discovery_does_not_borrow_other_hosts_from_surfaces() { - let (mut node, store_path) = test_node("hid-no-surface-leak"); - node.put( - "sleipnir.input-mirror.raven", - &EveSurfaceStateRecord { - provider_id: "sleipnir.input-mirror.raven".to_string(), - title: "Sleipnir Raven".to_string(), - version: 1, - updated_at: "unix:0".to_string(), - surface: json!({ - "id": "sleipnir.input-mirror.raven.surface", - "root": { - "kind": "dashboard", - "children": [{ - "kind": "text", - "props": { - "text": "raven sees nightwing endpoint 198.51.100.75:17888" - } - }] - } - }), - }, - ) - .unwrap(); - - assert_eq!( - discover_muninn_hid_endpoint( - &node, - Some("xbox-raven"), - Some("raven:xbox-raven:hid-controller-state"), - false, - ), - None - ); - let _ = fs::remove_file(store_path); - } - #[test] fn stream_id_host_hint_filters_provider_routes() { let (mut node, store_path) = test_node("hid-host-hint"); diff --git a/scripts/restart-nightwing-muninn.ps1 b/scripts/restart-nightwing-muninn.ps1 index 5c7392c..58fa1b1 100644 --- a/scripts/restart-nightwing-muninn.ps1 +++ b/scripts/restart-nightwing-muninn.ps1 @@ -21,7 +21,6 @@ param( [string] $OdinCultMeshRudpEndpoint = $(if ($env:CULTMESH_URI_ODIN_RUDP) { $env:CULTMESH_URI_ODIN_RUDP } else { "10.77.0.2:17871" }), [string] $HidControllerRudpBind = "0.0.0.0:17888", [string] $HidControllerRudpAdvertise = $(if ($env:MUNINN_HID_CONTROLLER_RUDP_ADVERTISE) { $env:MUNINN_HID_CONTROLLER_RUDP_ADVERTISE } else { "10.77.0.3:17888" }), - [string] $CommandRudpBind = "0.0.0.0:17889", [string] $CommandRudpAdvertise = "10.77.0.3:17889" ) @@ -126,7 +125,7 @@ if (-not [string]::IsNullOrWhiteSpace($HidControllerRudpAdvertise)) { $hidControllerRudpSetLines += "set -- ""`$@"" --hid-controller-rudp-advertise $(Quote-ShSingle $HidControllerRudpAdvertise)" } $hidControllerRudpSetBlock = ($hidControllerRudpSetLines -join "`n") -$commandRudpSetBlock = "set -- ""`$@"" --command-rudp-bind $(Quote-ShSingle $CommandRudpBind) --command-rudp-advertise $(Quote-ShSingle $CommandRudpAdvertise)" +$commandRudpSetBlock = "set -- ""`$@"" --command-rudp-advertise $(Quote-ShSingle $CommandRudpAdvertise)" $remoteScript = @" set -eu mkdir -p '$LogRoot'