### Initialize and Manage YourControls GUI and Session Source: https://context7.com/sequal32/yourcontrols/llms.txt Initializes the YourControls application with an embedded webview, populates the aircraft selection list, sends configuration to the UI, and enters a main loop to process UI messages and check for application exit. It handles various application messages like starting a server, connecting, transferring control, and setting observer status. ```Rust use yourcontrols::app::{App, AppMessage, ConnectionMethod}; use crossbeam_channel::TryRecvError; use std::net::IpAddr; // Initialize application with embedded webview let app = App::setup("YourControls v2.8.5".to_string()); // Populate aircraft selection list let aircraft_configs = vec![ "Asobo Studio - Cessna 172SP Skyhawk.yaml", "Asobo Studio - Cessna 152.yaml", "Asobo Studio - Cirrus SR22T G6 GTS.yaml", ]; for config in aircraft_configs { app.add_aircraft(config); } // Send configuration to UI let config_json = r#"{"port":25071,"name":"Pilot1","ui_dark_theme":true}"#; app.send_config(config_json); // Process messages from UI in main loop loop { match app.get_next_message() { Ok(msg) => { match msg { AppMessage::StartServer { username, port, is_ipv6, method, use_upnp } => { println!("Starting server: {} on port {}", username, port); app.attempt(); // Show "Attempting connection..." status // ... start server logic ... app.server_started(); // Update UI to show server running app.set_session_code("ABC123"); // Display session code } AppMessage::Connect { username, session_id, isipv6, ip, hostname, port, method } => { println!("Connecting as {}", username); app.attempt(); // ... connect logic ... app.connected(); // Update UI to show connected status } AppMessage::TransferControl { target } => { println!("Transferring control to {}", target); // ... transfer control logic ... } AppMessage::SetObserver { target, is_observer } => { app.set_observing(&target, is_observer); } AppMessage::LoadAircraft { config_file_name } => { println!("Selected aircraft: {}", config_file_name); } AppMessage::Disconnect => { println!("User requested disconnect"); // ... disconnect logic ... app.client_fail("Disconnected by user"); } _ => {} } } Err(TryRecvError::Empty) => { // No messages, continue } Err(TryRecvError::Disconnected) => break, } // Check if user closed the window if app.exited() { println!("Application closed"); break; } std::thread::sleep(std::time::Duration::from_millis(10)); } // Display notifications to user app.error("Could not connect to SimConnect!"); app.gain_control(); // Show "You have control" notification app.lose_control(); // Show control transferred away app.new_connection("Pilot2"); // Show new pilot joined app.lost_connection("Pilot2"); // Show pilot disconnected ``` -------------------------------- ### Configuration Management - User Settings and Persistence (Rust) Source: https://context7.com/sequal32/yourcontrols/llms.txt Shows how to manage application configuration using the `yourcontrols::simconfig::Config` struct. This includes reading configuration from a JSON file, creating default configurations, writing configurations to a file, and obtaining a JSON string representation. Supports runtime updates to configuration values. ```rust use yourcontrols::simconfig::Config; // Load configuration from file let config = match Config::read_from_file("config.json") { Ok(cfg) => { println!("Loaded configuration:"); println!(" Username: {}", cfg.name); println!(" Port: {}", cfg.port); println!(" Dark theme: {}", cfg.ui_dark_theme); cfg } Err(e) => { println!("Could not load config ({}), using defaults", e); Config::default() } }; // Create custom configuration let mut custom_config = Config { conn_timeout: 10, // Connection timeout in seconds check_for_betas: false, // Check for beta updates port: 25071, // Default listening port ip: "192.168.1.100".to_string(), name: "Pilot1".to_string(), // Username ui_dark_theme: true, // UI theme preference streamer_mode: false, // Hide IPs in UI instructor_mode: false, // Force new clients as observers sound_muted: false, // Audio notifications }; // Save configuration to file match custom_config.write_to_file("config.json") { Ok(_) => println!("Configuration saved"), Err(e) => eprintln!("Failed to save config: {}", e), } // Get JSON string representation for web UI let json_string = custom_config.get_json_string(); println!("Config as JSON: {}", json_string); // Update configuration at runtime custom_config.port = 25072; custom_config.name = "UpdatedPilot".to_string(); custom_config.sound_muted = true; custom_config.write_to_file("config.json").unwrap(); ``` -------------------------------- ### SimConnect Integration - Read/Write Simulator Variables (Rust) Source: https://context7.com/sequal32/yourcontrols/llms.txt Demonstrates how to connect to SimConnect, read and write aircraft variables, and trigger simulator events using the `simconnect` and `yourcontrols` crates. Handles SimConnect messages for data, events, and exceptions. Requires a running instance of Microsoft Flight Simulator. ```rust use simconnect::{SimConnector, DispatchResult}; use yourcontrols::definitions::Definitions; use yourcontrols::sync::transfer::{AircraftVars, LVarSyncer, Events}; // Initialize SimConnect connection let mut conn = SimConnector::new(); if !conn.connect("YourControls") { eprintln!("Failed to connect to SimConnect - is the sim running?"); return; } println!("Connected to SimConnect"); // Initialize variable syncer for local variables (LVars) let mut lvar_syncer = LVarSyncer::new(); lvar_syncer.add_var("L:XMLVAR_LTS_Test".to_string(), None); lvar_syncer.add_var("L:ASCRJ_FCP_BARO_STD_PILOT".to_string(), Some("Bool")); lvar_syncer.on_connected(&conn); // Set local variable value lvar_syncer.set(&conn, "L:XMLVAR_LTS_Test", "1"); // Send raw calculator code lvar_syncer.send_raw(&conn, "(>K:2:HEADING_BUG_SET)"); // Initialize event mapper for triggering SimConnect events let mut events = Events::new(1); // group_id = 1 let event_id = events.get_or_map_event_id("AP_MASTER", true); events.on_connected(&conn); // Trigger event with parameter events.trigger_event(&conn, "AP_MASTER", 1) .expect("Failed to trigger event"); // Process SimConnect messages in main loop loop { match conn.get_next_message() { Ok(message) => { match message { DispatchResult::SimObjectData(data) => { // Process aircraft variable data println!("Received sim object data"); } DispatchResult::ClientData(data) => { // Process local variable data let results = lvar_syncer.process_client_data(&data); for result in results { println!("{} = {}", result.var_name, result.value); } } DispatchResult::Event(data) => { // Process event callbacks if let Some(event_name) = events.match_event_id(data.uEventID) { println!("Event triggered: {}", event_name); } } DispatchResult::Exception(data) => { eprintln!("SimConnect exception: {}", unsafe { std::ptr::addr_of!(data.dwException).read_unaligned() }); } DispatchResult::Quit(_) => { println!("Sim closed"); break; } _ => {} } } Err(_) => break, } } conn.close(); ``` -------------------------------- ### SimConnect Integration with Aircraft Definitions (Rust) Source: https://context7.com/sequal32/yourcontrols/llms.txt This Rust code demonstrates loading aircraft definitions, connecting to SimConnect, and processing received data. It uses the `yourcontrols` and `simconnect` crates. The code initializes definitions, establishes a connection, retrieves initial state, and handles incoming data with specified synchronization permissions. ```rust use yourcontrols::definitions::Definitions; use simconnect::SimConnector; // Load aircraft definition from file let mut definitions = Definitions::new(); match definitions.load_config("definitions/aircraft/Cessna172.yaml".to_string()) { Ok(_) => { println!( "Loaded {} aircraft vars, {} local vars, {} events", definitions.get_number_avars(), definitions.get_number_lvars(), definitions.get_number_events() ); // Connect definitions to SimConnect let conn = SimConnector::new(); definitions.on_connected(&conn).expect("Failed to connect definitions"); // Get all current aircraft state for initial sync let current_state = definitions.get_all_current(); // Process received data from network let received_data = /* ... from network ... */; let permission = yourcontrols::definitions::SyncPermission { is_server: false, is_master: false, is_init: true, }; definitions.on_receive_data(&conn, received_data, 0.0, &permission) .expect("Failed to process received data"); } Err(e) => eprintln!("Failed to load definition: {}", e), } ``` -------------------------------- ### Rust Network Server - Host Multiplayer Sessions Source: https://context7.com/sequal32/yourcontrols/llms.txt This Rust code demonstrates how to create and manage a server instance for hosting shared cockpit sessions. It supports direct connections, hole-punching, and cloud relay functionalities. The server can be configured with connection details, send aircraft definitions, manage control transfers, and set clients as observers. Error handling for server startup and message retrieval is included. ```rust use yourcontrols_net::{Server, TransferClient}; use std::net::IpAddr; // Create server with username, version string, and connection timeout (seconds) let mut server = Server::new( "Pilot1".to_string(), "2.8.5".to_string(), 5 // timeout in seconds ); // Start server on IPv4 with specific port and UPnP port forwarding match server.start(false, 25071, true) { Ok(_) => { println!("Server started on port 25071"); // Get session ID for cloud-based connections if let Some(session_id) = server.get_session_id() { println!("Session code: {}", session_id); } // Send aircraft definition to newly connected client let aircraft_bytes = std::fs::read("definitions/aircraft/Cessna172.yaml") .expect("Failed to read aircraft definition"); server.send_definitions(aircraft_bytes.into_boxed_slice(), "Pilot2".to_string()); // Transfer control to another pilot server.transfer_control("Pilot2".to_string()); // Set a client as observer (receive only, no control) server.set_observer("Pilot3".to_string(), true); } Err(e) => eprintln!("Server start failed: {}", e), } // Alternative: Start with cloud hole-punching for NAT traversal match server.start_with_hole_punching(false) { Ok(_) => println!("Server started with hole-punching"), Err(e) => eprintln!("Hole-punch start failed: {}", e), } // Check server status and retrieve messages loop { match server.get_next_message() { Ok(msg) => { // Handle incoming messages (player joined, control transfer, etc.) println!("Message received: {:?}", msg); } Err(_) => break, } } ``` -------------------------------- ### Rust: Connect to Remote Aircraft Network Client Source: https://context7.com/sequal32/yourcontrols/llms.txt Establishes a client connection to a remote aircraft session using direct IP, hostname, or a cloud session code. It handles sending control requests, processing incoming aircraft state updates, and managing connection events. Requires the 'yourcontrols_net' crate. ```rust use yourcontrols_net::{Client, TransferClient, ReceiveMessage, Event, Payloads}; use std::net::{IpAddr, Ipv4Addr}; // Create client with username, version, and timeout let mut client = Client::new( "Pilot2".to_string(), "2.8.5".to_string(), 5 ); // Connect directly to server IP and port let server_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)); let session_id = Some("SESSION123".to_string()); match client.start(server_ip, 25071, session_id) { Ok(_) => { println!("Connected to server at {}:25071", server_ip); // Send ready signal after receiving aircraft definitions client.send_ready(); // Request control from current pilot client.take_control("Pilot1".to_string()); // Process incoming network events while let Ok(message) = client.get_next_message() { match message { ReceiveMessage::Event(Event::ConnectionEstablished) => { println!("Connection established"); } ReceiveMessage::Event(Event::ConnectionLost(reason)) => { eprintln!("Connection lost: {}", reason); break; } ReceiveMessage::Payload(payload) => { match payload { Payloads::TransferControl { from, to } => { println!("Control transferred from {} to {}", from, to); } Payloads::Update { data, from, is_unreliable, time } => { // Process aircraft state update println!("Update from {}: {:?}", from, data); } _ => {} } } } } } Err(e) => eprintln!("Connection failed: {}", e), } // Alternative: Connect via cloud server with hole-punching let session_code = "ABC123".to_string(); match client.start_with_hole_punch(session_code, false) { Ok(_) => println!("Connected via cloud server"), Err(e) => eprintln!("Cloud connection failed: {}", e), } // Stop client connection client.stop("User disconnected".to_string()); ``` -------------------------------- ### YAML: Define Aircraft Synchronization Variables Source: https://context7.com/sequal32/yourcontrols/llms.txt Configures which aircraft variables and events are synchronized between the client and server. This is done using YAML definition files, allowing for flexible customization of data transfer. ```yaml # Cessna 172 Electrical System Definition ``` -------------------------------- ### Cessna 172 Electrical System Configuration (YAML) Source: https://context7.com/sequal32/yourcontrols/llms.txt This YAML file defines the electrical system components for the Cessna 172, including toggle switches, numeric settings, read-only variables, and events. It utilizes include directives for shared module definitions. Conditional synchronization is supported based on master battery state. ```yaml include: - definitions/modules/general.yaml - definitions/modules/engines.yaml - definitions/modules/controls.yaml shared: # Toggle switch - synchronize boolean switch states - type: ToggleSwitch var_name: A:ELECTRICAL MASTER BATTERY:1 var_units: Bool var_type: bool event_name: TOGGLE_MASTER_BATTERY event_param: 1 # Numeric value - synchronize numeric settings - type: NumSet var_name: A:GENERAL ENG MASTER ALTERNATOR:1 var_units: Bool var_type: i32 event_name: ALTERNATOR_SET # Variable only - read-only synchronization without events - type: var var_name: A:ELECTRICAL BATTERY VOLTAGE:1 var_units: Volts var_type: f64 update_every: 0.5 # seconds # Event only - trigger simulator events - type: event event_name: SET_STARTER1_HELD # Conditional synchronization - only sync when condition met - type: NumSet var_name: A:LIGHT LANDING:1 var_units: Bool var_type: i32 event_name: LANDING_LIGHTS_SET event_param: 1 condition: var: var_name: A:ELECTRICAL MASTER BATTERY:1 var_units: Bool var_type: bool equals: 1 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.