- Project Overview
- Project Structure
- Architecture & Data Flow
- Core Components
- User Interface
- Configuration & Data
- Hardware Integration
- Build & Distribution
- Documentation
- Development Workflow
- Performance Considerations
- Security Considerations
- Troubleshooting
- Development Guidelines
- Extensibility Guide
- API Reference
- Testing Strategy
- Deployment Guide
- Migration Guide
X-Plane Dataref Bridge is a cross-platform application that serves as a bridge between X-Plane flight simulator and external hardware devices (Arduino, HID devices). The application enables cockpit builders to create physical controls that interact with X-Plane through datarefs and commands.
The project is built using Python with PyQt6 for the GUI, and supports communication with X-Plane via UDP and with Arduino/ESP32 devices via serial communication. It provides a comprehensive solution for creating custom hardware cockpits with authentic instruments, switches, and controls that interact with X-Plane in real-time.
- Hardware Support: Arduino devices with custom firmware, standard HID devices (joysticks, game controllers), and hybrid mode for ESP32-S2/S3 devices
- Profile-based Configuration: Save and load different configurations for various aircraft
- Real-time Communication: Bidirectional communication with X-Plane via UDP protocol
- Logic Engine: Create virtual variables with conditional logic
- Input Mapping: Map physical inputs to X-Plane actions with advanced options
- Output Management: Route X-Plane dataref updates to hardware outputs
- Array Handling: Support for array datarefs with element-specific operations
- Variable System: Unified variable system for custom values and logic
- Auto-discovery: Automatic detection of X-Plane and connected devices
XPDRB_branch1/
├── Arduino libraries/ # Arduino library files
├── config/ # Configuration files
│ ├── profiles/ # Saved profiles
│ ├── custom_datarefs.json # Custom dataref definitions
│ ├── input_mappings.json # Input mapping configurations
│ └── settings.json # Application settings
├── core/ # Core application logic
│ ├── arduino/ # Arduino communication modules
│ ├── bridge/ # Bridge communication logic
│ ├── hid/ # HID device management
│ ├── dataref_manager.py # Dataref management
│ ├── dataref_writer.py # Dataref writing utilities
│ ├── hid_manager.py # HID device manager
│ ├── input_mapper.py # Input mapping logic
│ ├── logic_engine.py # Logic engine for conditional operations
│ ├── logic_library.py # Logic operations library
│ ├── profile_manager.py # Profile management
│ ├── variable_store.py # Variable storage system
│ └── xplane_connection.py # X-Plane communication
├── docs/ # Documentation files
├── examples/ # Example configurations and Arduino sketches
│ └── arduino/ # Arduino example sketches
│ ├── Advanced_Hybrid/
│ ├── Basic_Template/
│ ├── Byte_Arrays_with_OUTPUT_IDs/
│ ├── Complete_Dataref_Reference/
│ ├── General_Encoder_With_Output/
│ ├── Handling_FloatOrInt_Arrays_w_OUTPUT_IDs/
│ ├── Handling_X-Plane_Dataref_Types_with_OUTPUT_IDs/
│ ├── Input_Examples/
│ └── Output_Examples/
├── gui/ # PyQt6 GUI components
│ ├── widgets/ # Custom GUI widgets
│ ├── arduino_panel.py # Arduino device panel
│ ├── axis_calibration_wizard.py # Calibration wizard
│ ├── custom_dataref_dialog.py # Custom dataref dialog
│ ├── dataref_editor_dialog.py # Dataref editor dialog
│ ├── dataref_panel.py # Dataref panel
│ ├── dataref_search_dialog.py # Dataref search dialog
│ ├── firmware_panel.py # Firmware panel
│ ├── hat_switch_widget.py # Hat switch widget
│ ├── help_panel.py # Help panel
│ ├── hid_panel.py # HID device panel
│ ├── input_mapping_dialog.py # Input mapping dialog
│ ├── input_panel.py # Input configuration panel
│ ├── logic_schematic_widget.py # Logic schematic widget
│ ├── main_window.py # Main application window
│ ├── monitor_panel.py # Monitor panel
│ ├── output_panel_array_edit.py # Output panel array editor
│ ├── output_panel.py # Output configuration panel
│ ├── settings_panel.py # Settings panel
│ └── variable_dialog.py # Variable dialog
├── resources/ # Icons and assets
├── scripts/ # Build and utility scripts
│ ├── Output/
│ ├── build_package.py # Package building script
│ ├── convert_datarefs.py # Dataref conversion script
│ ├── installer_setup.iss # Installer setup script
│ └── integrate_datarefs.py # Dataref integration script
├── tests/ # Unit tests
├── tools/ # Utility tools
├── utils/ # Utility functions
├── main.py # Application entry point
├── README.md # Project documentation
├── requirements.txt # Python dependencies
└── datarefcommands_database.json # X-Plane dataref and command database
The X-Plane Dataref Bridge follows a modular architecture with clear separation of concerns:
graph TD
XPlane[X-Plane Simulator] <-->|UDP| XPDRB[Dataref Bridge]
XPDRB <-->|Serial| Arduino[Arduino Devices]
XPDRB <-->|HID| HID[HID Devices]
XPDRB -->|GUI| User[User Interface]
XPDRB --> DM[Dataref Manager]
XPDRB --> AM[Arduino Manager]
XPDRB --> XC[X-Plane Connection]
XPDRB --> IM[Input Mapper]
XPDRB --> LE[Logic Engine]
XPDRB --> VS[Variable Store]
XPDRB --> PM[Profile Manager]
DM <--> XC
AM <--> XC
IM <--> DM
IM <--> AM
LE <--> IM
VS <--> LE
PM <--> All[All Components]
- Physical input occurs (button press, encoder rotation, etc.)
- Hardware device sends INPUT command via serial:
INPUT <KEY> <VALUE> - Arduino Manager receives and parses the message
- Arduino Manager emits input event to Input Mapper
- Input Mapper evaluates conditional logic and mappings
- Input Mapper sends appropriate dataref write or command execution to X-Plane Connection
- X-Plane Connection sends UDP packet to X-Plane
- X-Plane processes the input
- X-Plane sends dataref updates via UDP (RREF packets)
- X-Plane Connection receives and parses the data
- X-Plane Connection notifies Dataref Manager of updates
- Dataref Manager checks for universal mappings
- If universal mapping exists, Arduino Manager broadcasts to all connected devices
- Arduino Manager sends SET command to hardware:
SET <KEY> <VALUE> - Hardware receives and processes the command
- Array datarefs are parsed with
parse_array_type()method - Multidimensional arrays are flattened using row-major order
- Element indices are generated with
_generate_element_indices() - Individual elements can be accessed via
[index]notation - Array updates can be sent as comma-separated values for bulk operations
- X-Plane dataref updates typically occur at 10Hz (configurable)
- Arduino serial communication operates at 115200 baud
- Input events are processed immediately upon receipt
- Output updates are throttled to prevent spam with caching mechanism
- Logic engine processes at 100ms intervals (10Hz)
Purpose: Manages Arduino/ESP32 device connections and communication. Supports Universal Mapping (Dataref -> Key Broadcast).
Key Functions:
- Device discovery and connection management
- Serial communication handling with proper error handling for PyInstaller
- Protocol message parsing and routing
- Input/output routing with caching to avoid spam
- Universal mapping system for broadcasting data to all devices
- Handshake protocol implementation
- Device state management
Important Methods:
connect_to_device(): Establishes connection to Arduino devicesend_output(): Sends output commands to Arduino deviceprocess_input(): Processes incoming input from Arduino devicebroadcast_by_key(): Sends data to all devices registered for a specific keyset_universal_mapping(): Register a mapping from a source (dataref or variable) to a universal keyon_dataref_update(): Called when a dataref value changes, broadcasts to all devices if a universal mapping exists_device_loop(): Main communication loop for a device_perform_handshake(): Perform handshake with device_process_incoming(): Process incoming messages from device_handle_input(): Handle INPUT message from device_handle_dref(): Handle DREF message from device to set dataref value_handle_cmd(): Handle CMD message from device to send X-Plane command
Purpose: Represents a single Arduino device with state management.
Key Attributes:
- Device identification (name, type, firmware version)
- Connection status and state management
- Input/output capabilities
- Subscription tracking
- Last seen timestamp
Important Methods:
handshake(): Performs initial handshake with devicesend_command(): Sends commands to deviceparse_message(): Parses incoming messages from devicetransition(): Changes device state with validationset_input(): Updates input value for the device
Purpose: Manages UDP communication with X-Plane
Key Functions:
- Connection management (connect/disconnect)
- Dataref subscription and value updates
- Command execution
- Version detection
- Beacon listening for auto-discovery
- Array dataref handling
- String dataref writing
Important Methods:
connect(): Establishes connection to X-Planesubscribe_dataref(): Subscribes to dataref updates with frequency controlwrite_dataref(): Writes values to datarefssend_command(): Executes X-Plane commands_receive_loop(): Background loop for receiving data from X-Plane_parse_rref(): Parses dataref update packets_parse_data(): Parses standard X-Plane DATA packets_parse_dref(): Parses DREF response packetsstart_beacon_listener(): Starts thread to listen for X-Plane discovery beaconswrite_dataref_string(): Writes string values to byte[n] datarefsselect_data_output(): Sends DSEL packet to enable specific Data Output rowsset_data_output_target(): Sends ISE4 packet to configure X-Plane data output target
Purpose: Manages X-Plane dataref definitions and provides search functionality
Key Functions:
- Dataref database loading and searching
- Dataref information retrieval
- Custom dataref management
- Array type parsing and handling
- Category-based organization
- Expanded dataref views for arrays
Important Methods:
get_dataref_info(): Retrieves information about a specific datarefsearch_datarefs(): Searches datarefs by name or descriptionadd_custom_dataref(): Adds custom dataref definitionsget_all_datarefs(): Returns all available datarefsparse_array_type(): Parse array type string and return (flattened_size, dimensions_list)get_array_size_from_type(): Extract array size from type stringget_expanded_datarefs(): Return datarefs with arrays expanded into per-element entries_generate_element_indices(): Generate all possible index combinations for multidimensional arraysget_base_dataref_from_element(): Map a per-element name back to its base datarefupdate_array_element_value(): Update a specific element in an array datarefget_array_metadata(): Get array-specific metadata for a datarefget_array_elements(): Get all elements of an array datarefget_array_base_from_element(): Get the base name of an array from an element nameis_array_dataref(): Check if a dataref is an array
Purpose: Handles writing different dataref types to X-Plane
Key Functions:
- Scalar value writing (int, float, bool)
- Array value writing (byte, int, float arrays)
- String writing to byte[n] datarefs
- Command execution
- Type-specific validation and conversion
Important Methods:
write_by_output_id(): Writes value using OUTPUT ID mapping_write_scalar(): Writes scalar values to datarefs_write_byte_array(): Writes byte arrays to datarefs_write_int_array(): Writes integer arrays to datarefs_write_float_array(): Writes float arrays to datarefs_write_string(): Writes strings to byte[n] datarefs
Purpose: Maps physical inputs to X-Plane actions
Key Functions:
- Input action definition
- Input processing and routing
- Conditional execution
- Toggle state management
- Sequence execution
- Hardware-to-X-Plane synchronization
Important Methods:
map_input(): Creates input mapping configurationprocess_input(): Processes incoming input and executes mapped actionsget_mapping(): Retrieves mapping for a specific inputon_dataref_update(): Handles dataref updates for conditional logicsync_hardware_to_xplane(): Synchronize hardware switches to X-Plane stateupdate_current_value(): Update current value for a dataref in the input mapper
Purpose: Processes virtual variables and conditional logic
Key Functions:
- Virtual variable management
- Conditional logic evaluation
- Variable updates and notifications
- Logic gate operations
- Expression evaluation
- State machine operations
Important Methods:
add_variable(): Adds a virtual variableupdate_variable(): Updates variable valueevaluate_condition(): Evaluates conditional logicget_variable_value(): Retrieves current variable valueprocess_tick(): Process logic engine ticksync_initial_values(): Synchronize initial values for variablesadd_logic_block(): Add a logic block to the engineremove_logic_block(): Remove a logic block from the engine
Purpose: Manages loading and saving of application profiles
Key Functions:
- Profile persistence (save/load)
- Configuration management
- Device alias management
- Cross-component state preservation
Important Methods:
save_profile(): Saves current configuration to profileload_profile(): Loads configuration from profileexport_profile(): Exports profile to external fileimport_profile(): Imports profile from external fileset_device_alias(): Sets alias for deviceget_device_alias(): Retrieves device alias
Purpose: Stores virtual variables for logic operations
Key Functions:
- Variable type management
- Value storage and retrieval
- Update notifications
- Cross-component variable sharing
- Variable lifecycle management
Important Methods:
set_variable(): Sets variable valueget_variable(): Retrieves variable valueregister_callback(): Registers callback for variable updatesupdate_value(): Updates variable value with metadataget_names(): Gets all variable namesget_all_variables(): Gets all variables with their values
Purpose: Main application window that hosts all panels
Key Functions:
- Panel management and layout
- Menu and toolbar setup
- Status bar updates
- Profile management UI
- Component orchestration
- Donation popup management
- Aircraft auto-profile switching
Important Methods:
_setup_ui(): Initializes UI components_setup_menu(): Creates application menu_on_xplane_connection_changed(): Handles connection state changes_on_dataref_update(): Handles dataref value updates_handle_aircraft_icao_change(): Detects aircraft changes and loads profiles_toggle_xplane_connection(): Toggle X-Plane connection_on_arduino_input_received(): Handle Arduino input in main thread_handle_arduino_input(): Process Arduino input in main thread_process_arduino_input(): Process Arduino input asynchronously_on_arduino_dataref_write(): Handle dataref write request from Arduino_on_arduino_command_send(): Handle command send request from Arduino_update_status(): Periodic status updaterefresh_search_helpers(): Notify all UI components that searchable IDs have changed
Purpose: Panel for Arduino device management and configuration
Key Functions:
- Device connection management
- Input/output mapping
- Device status display
- Port scanning and selection
- Device configuration
Important Methods:
_connect_device(): Connects to selected Arduino device_disconnect_device(): Disconnects from Arduino device_configure_input(): Opens input configuration dialog_configure_output(): Opens output configuration dialog_update_device_list(): Updates the list of available devices_refresh_device_status(): Refreshes device status information
Purpose: Panel for browsing, searching, and subscribing to X-Plane datarefs
Key Functions:
- Dataref browsing and searching
- Subscription management
- Value display and editing
- Category filtering
- Real-time value updates
Important Methods:
_populate_list(): Populates list with available datarefs_on_search_changed(): Handles search input_subscribe_dataref(): Subscribes to selected datarefupdate_value(): Updates displayed value for dataref_on_dataref_selected(): Handles dataref selection_refresh_dataref_list(): Refreshes the dataref list
Purpose: Panel for configuring input mappings
Key Functions:
- Input mapping configuration
- Input visualization
- Mapping testing
- Learn mode for automatic mapping
- HID device integration
Important Methods:
_add_mapping(): Adds new input mapping_edit_mapping(): Edits existing mapping_delete_mapping(): Deletes mapping_test_mapping(): Tests mapping configurationhandle_input_signal(): Handle input signals for learn mode_start_learn_mode(): Start learn mode for mapping inputs_stop_learn_mode(): Stop learn mode
Purpose: Panel for configuring output mappings
Key Functions:
- Output mapping configuration
- Value display
- Output testing
- Array element editing
- Universal mapping management
Important Methods:
_add_output(): Adds new output mapping_edit_output(): Edits existing output_delete_output(): Deletes output_test_output(): Tests output configurationon_dataref_update(): Handles dataref updatesrefresh_from_manager(): Refreshes from dataref managerexecute_sequence_by_key(): Execute sequence by key
Purpose: Stores saved profile configurations
File Format: JSON
Key Elements:
- Output mappings (dataref to hardware key)
- Input mappings (hardware input to X-Plane action)
- Logic blocks (virtual variables)
- Calibration data
- Device aliases
- Custom dataref definitions
- HID device configurations
Schema Example:
{
"outputs": [
{
"dataref": "sim/cockpit2/switches/gear_handle_status",
"output_id": "GEAR_HANDLE",
"device_port": "COM3",
"frequency": 5
}
],
"inputs": [
{
"device": "COM3",
"input_id": "BUTTON_1",
"action": "sim/autopilot/heading_sync",
"conditions": [
{
"dataref": "sim/flightmodel/position/altitude",
"operator": ">",
"value": 1000
}
]
}
],
"variables": [
{
"name": "custom_altitude",
"type": "float",
"expression": "sim/cockpit2/gauges/indicators/altitude_ft_pilot * 0.3048"
}
]
}Purpose: Stores custom dataref definitions
File Format: JSON
Key Elements:
- Dataref name
- Dataref type
- Read/write permissions
- Description
- Category assignment
- Array dimensions (if applicable)
Purpose: Stores input mapping configurations
File Format: JSON
Key Elements:
- Input device identifier
- Input type (button, axis, encoder)
- X-Plane action mapping
- Conditional logic rules
- Sequence definitions
Purpose: Stores application settings
File Format: JSON
Key Elements:
- X-Plane connection settings (IP, ports)
- Auto-connect preferences
- UI preferences
- Logging settings
- Serial port settings
- Default profile selection
Schema Example:
{
"xplane": {
"ip": "127.0.0.1",
"send_port": 49000,
"recv_port": 49001
},
"ui": {
"theme": "dark",
"language": "en",
"window_position": [100, 100],
"window_size": [1200, 800]
},
"logging": {
"level": "INFO",
"file_path": "bridge_log.txt"
}
}Purpose: Comprehensive database of X-Plane datarefs and commands
File Format: JSON
Key Elements:
- Dataref names and paths
- Data types (int, float, bool, array)
- Read/write permissions
- Descriptions
- Categories
- Deprecated dataref mappings
- X-Plane version compatibility
Purpose: Documents communication protocol between PC and Arduino
Key Sections:
- Handshake protocol
- PC to Arduino commands
- Arduino to PC commands
- Message format specifications
- Array handling
- Command execution
- Error handling
- Arduino sends identification:
XPDR;fw=<version>;board=<type>;name=<name> - PC responds with configuration
- Arduino acknowledges:
ACK <KEY> <VALUE>
SET <KEY> <VALUE>: Set output valueHELLO: Handshake initiationREAD <DATAREF> <TYPE>: Request dataref valueWRITE <DATAREF> <TYPE> <VALUE>: Write to datarefCMD <COMMAND>: Execute commandREADARRAY <ARRAY_NAME> <TYPE>: Read array valuesWRITEARRAY <ARRAY_NAME> <TYPE> <CSV_VALUES>: Write array values
INPUT <KEY> <VALUE>: Input notificationCMD <COMMAND>: Command executionDREF <DATAREF> <VALUE>: Dataref writeACK <KEY> <VALUE>: AcknowledgmentVALUE <DATAREF> <VALUE>: Dataref value responseARRAYVALUE <ARRAY_NAME> <TYPE> <CSV_VALUES>: Array value responseELEMVALUE <ARRAY_NAME[INDEX]> <TYPE> <VALUE>: Array element value response
ERR_TIMEOUT: Communication timeout occurredERR_INVALID_FORMAT: Invalid message format receivedERR_DEVICE_BUSY: Device is busy processing another commandERR_DATAREF_NOT_FOUND: Requested dataref does not existERR_PERMISSION_DENIED: Insufficient permissions for operation
- Default timeout: 5 seconds for handshake
- Retry attempts: 3 for critical operations
- Backoff strategy: Exponential backoff (1s, 2s, 4s)
Purpose: Manages HID device connections
Key Functions:
- Device discovery
- Input monitoring
- Button and axis mapping
- Device state tracking
- Cross-platform HID support
Important Methods:
enumerate_devices(): Lists available HID devicesconnect_device(): Connects to HID deviceprocess_input(): Processes HID inputstart(): Start HID monitoringstop(): Stop HID monitoringget_device_info(): Get information about a HID device
Purpose: Represents a single HID device
Key Attributes:
- Device identification
- Input capabilities (buttons, axes)
- Connection status
- Input state tracking
- Vendor/product IDs
Important Methods:
get_button_state(): Returns current button stateget_axis_value(): Returns current axis valueset_mapping(): Sets input mappingupdate_state(): Updates device stateis_connected(): Checks if device is connected
Purpose: Configuration for building standalone executables with cx_Freeze
Key Sections:
- Build options for different platforms
- Included packages and modules
- Icon configuration
- Executable settings
- Dependency bundling
- Platform-specific optimizations
- Windows: GUI application without console, installer creation
- Linux/macOS: Console application with proper dependencies, app bundle creation
Purpose: Lists Python package dependencies
Key Dependencies:
- PyQt6: GUI framework
- qasync: Async/await support for PyQt
- pyserial: Arduino communication
- hidapi: HID device communication
- requests: HTTP requests
- aiohttp: Async HTTP client/server
- websockets: WebSocket communication
- lxml: XML parsing
- beautifulsoup4: HTML/XML parsing
Purpose: Comprehensive guide to system architecture and operation
Key Sections:
- System architecture overview
- Serial protocol documentation
- Example sketch usage
- Debugging procedures
- Best practices
Purpose: Marketing and announcement content for X-Plane forums
Key Sections:
- Project introduction
- Feature highlights
- Getting started guide
- Community engagement
Purpose: Application entry point and initialization
Key Functions:
- Logging configuration
- Exception handling
- Component initialization
- Application startup
- Serial backend import handling
- Async event loop setup
Key Features:
- Runtime serial backend import with fallbacks
- Global exception handling
- Async event loop integration
- Component dependency injection
- Application icon setup
Purpose: Converts DataRefs.txt file to JSON format
Usage: python scripts/convert_datarefs.py --input DataRefs.txt --output dataref_database.json
Purpose: Integrates new datarefs into existing database
Usage: python scripts/integrate_datarefs.py <datareftool_export.txt>
- Critical datarefs (airspeed, altitude, attitude): 10-20Hz
- Standard datarefs (fuel, electrical): 5Hz
- Slow-changing datarefs (flight plan, weather): 1Hz
- Static datarefs (aircraft configuration): On change only
- UDP communication: Minimal overhead (typically <1KB/s per dataref)
- Serial communication: 115200 baud limit (approximately 11KB/s)
- Recommended max datarefs per device: 50-100 depending on update frequency
- Dataref database: ~50-100MB RAM
- Active connections: ~10-20MB per device
- Cached values: ~1-2MB per 1000 active datarefs
- GUI components: ~20-50MB baseline
- Serial communication bottleneck: Use buffering and batching for high-frequency updates
- GUI update bottleneck: Implement virtual scrolling and lazy loading
- Dataref subscription bottleneck: Limit concurrent subscriptions to 200-300 per connection
- Logic engine bottleneck: Optimize conditional evaluations and caching
- Validate X-Plane IP addresses to prevent unauthorized connections
- Implement rate limiting for incoming UDP packets
- Use local loopback (127.0.0.1) by default for X-Plane communication
- Sanitize all incoming dataref names and values
- Validate numeric ranges for dataref values
- Prevent injection attacks through dataref names
- Implement proper error handling for malformed messages
- Validate JSON configuration files before loading
- Sanitize file paths to prevent directory traversal
- Validate Arduino sketch uploads
- Implement proper permissions for file operations
- Arduino not detected: Check USB cable, drivers, and COM port selection
- X-Plane connection fails: Verify X-Plane is running, IP/port settings, and firewall
- HID devices not working: Check driver installation and permissions
- Handshake fails: Verify Arduino sketch is uploaded correctly
- Too frequent updates: Reduce subscription frequency in output panel
- Delayed updates: Check network latency and X-Plane settings
- Missing updates: Verify dataref exists and has proper permissions
- Profile not found: Check file location and permissions
- Corrupted profile: Restore from backup or recreate
- Incompatible profile: Update profile format or downgrade application
- Classes: PascalCase (e.g.,
ArduinoManager) - Methods/Functions: snake_case (e.g.,
connect_device) - Variables: snake_case (e.g.,
device_port) - Constants: UPPER_CASE (e.g.,
DEFAULT_BAUD_RATE) - Private members: Leading underscore (e.g.,
_private_method)
- Use specific exception types when possible
- Log errors with appropriate severity levels
- Provide meaningful error messages to users
- Implement graceful degradation when possible
- Unit tests for core logic components
- Integration tests for communication protocols
- Mock objects for external dependencies
- Automated testing for critical paths
- Separate concerns into distinct modules
- Follow single responsibility principle
- Use dependency injection for testability
- Maintain consistent code style
- Create a new device class inheriting from the base device class
- Implement the required communication protocol
- Register the device type in the device manager
- Add UI support in the appropriate panels
- Extend the dataref manager to handle new types
- Implement serialization/deserialization methods
- Add validation logic for the new type
- Update the UI to support the new type
- Add the operation to the logic engine
- Implement the operation logic
- Add UI controls for configuring the operation
- Document the new operation
- Create new PyQt6 widgets as needed
- Follow the existing UI patterns and conventions
- Implement proper event handling
- Add internationalization support if needed
dataref_manager.get_dataref_info(name)- Get information about a datarefarduino_manager.connect(port, baudrate)- Connect to Arduino devicexplane_connection.write_dataref(name, value)- Write to X-Plane datarefinput_mapper.map_input(device, input_id, action)- Map input to actionlogic_engine.add_variable(name, expression)- Add logic variable
dataref_manager._parse_array_type(type_str)- Parse array type stringarduino_manager._handle_input(device, message)- Handle input messagexplane_connection._parse_rref(data)- Parse RREF packetinput_mapper._evaluate_conditions(mapping)- Evaluate input conditionslogic_engine._evaluate_expression(expr)- Evaluate logic expression
- Core logic components (dataref manager, input mapper, etc.)
- Mathematical operations and calculations
- Data parsing and validation
- Error handling scenarios
- Communication protocols (serial, UDP)
- End-to-end data flow
- Device connection and disconnection
- Profile save/load operations
- Core components: 90%+ coverage
- UI components: 70%+ coverage
- Communication protocols: 95%+ coverage
- Error handling: 80%+ coverage
- Install Python 3.8+ and required dependencies
- Run
pip install -r requirements.txt - Execute
python main.pyor build executable with cx_Freeze - Configure firewall to allow UDP communication
- Install Python 3.8+, PyQt6, and pyserial
- Install udev rules for serial device access
- Run
pip install -r requirements.txt - Execute
python main.py
- Install Python 3.8+ and dependencies
- Grant accessibility permissions for HID devices
- Run
pip install -r requirements.txt - Execute
python main.py
- v1.0: Initial release with basic Arduino support
- v1.2: Added HID device support
- v1.5: Introduced logic engine and variables
- v2.0: Major architecture overhaul with universal mapping
- v2.0: Profile format changed to support universal mapping
- v1.8: Arduino protocol updated to support array operations
- v1.5: Input mapping format extended with conditional logic
- Backup existing profiles before upgrading
- Review release notes for breaking changes
- Update Arduino sketches to match new protocol
- Test configuration after upgrade
- Report any issues to the development team
This comprehensive documentation provides a complete understanding of the X-Plane Dataref Bridge codebase, enabling AI assistants to provide accurate and contextual assistance for development, debugging, and feature implementation.
The X-Plane Dataref Bridge facilitates bidirectional communication between X-Plane flight simulator and Arduino/ESP32 microcontrollers via serial communication. This section outlines the complete protocol for all dataref operations.
- Bridge sends:
HELLO - Arduino responds:
XPDR;fw=<version>;board=<type>;name=<device_name>
All messages are terminated with \n (newline character).
- Arduino sends:
READ <dataref_name> <type> - Bridge responds:
VALUE <dataref_name> <value>
- Arduino sends:
READ <dataref_name> <type> <index> - Bridge responds:
VALUE <dataref_name> <index> <value>
- Arduino sends:
READ <dataref_name> <type> ALL - Bridge responds:
<dataref_name>: <value0>, <value1>, <value2>, ...
- Arduino sends:
MULTIREAD <dataref_name[start,end]> <type> - Bridge responds:
MULTIVALUE <dataref_name[start,end]> <type> <csv_values>
- Arduino sends:
DREF <dataref_name> <value> - Bridge responds: UDP packet to X-Plane (no direct response)
- Arduino sends:
CMD <command_name> - Bridge responds: UDP command packet to X-Plane (no direct response)
- Arduino sends:
WRITEELEM <dataref_name[index]> <type> <value> - Bridge responds:
OKorERROR
- Arduino sends:
READELEM <dataref_name[index]> <type> - Bridge responds:
ELEMVALUE <dataref_name[index]> <type> <value>
- Arduino sends:
WRITEARRAY <dataref_name> <type> <csv_values> - Bridge responds:
OKorERROR
- Arduino sends:
READARRAY <dataref_name> <type> - Bridge responds:
ARRAYVALUE <dataref_name> <type> <csv_values>
- Arduino sends:
STRING <dataref_name> <string_value> - Bridge processes: Converts string to character codes and sends DREF packet with 8 float values
- UDP Format: Character codes packed as float32 values (ASCII ordinals)
- Arduino sends:
DREF <dataref_name> <value>(value as float representing byte) - Bridge processes: Converts float to byte for X-Plane
- Arduino sends:
DREF <dataref_name> <csv_float_values>(for raw binary data) - Bridge processes: Each float represents a byte value
- Format:
INPUT <output_id> <value> - Purpose: Send values from Arduino to mapped X-Plane datarefs
- Bridge action: Maps
output_idto X-Plane dataref and sends DREF command
- Format:
SET <output_id> <value> - Purpose: Send X-Plane dataref values to Arduino
- Arduino action: Process value for local use
- Writing: Use
STRING <dataref> <text>command - Reading: Receive character codes as float values in array elements
- Decoding: Combine character codes until null terminator (0.0) is found
- int: 32-bit signed integer, transmitted as float32
- float: Single precision floating point
- double: Double precision (transmitted as float32 approximation)
- Format:
<type>[N]where N is array size - Storage: Sequential float32 values in UDP packets
- Access: Individual elements via
[index]notation
- Format:
string[N]where N is maximum string length - Encoding: ASCII character codes as float32 values
- Termination: Null-terminated (0.0 marks end of string)
- Maximum: 8 characters per UDP DREF packet (due to packet format limitations)
- Format:
data[N]orbyte[N] - Encoding: Raw binary data as float32 values
- Processing: Each float represents one byte value
- Malformed commands: Bridge responds with error message
- Invalid datarefs: Bridge logs error, no response to Arduino
- Communication timeouts: Automatic retry mechanisms in bridge application
- Always implement proper handshake before sending commands
- Use appropriate data types for each operation
- Handle array bounds checking in Arduino code
- Implement error checking for invalid responses
- Use descriptive output IDs for easier debugging
- No response: Check handshake completion and serial connection
- Wrong values: Verify dataref names and type specifications
- Array issues: Confirm index bounds and array size specifications
- String problems: Ensure proper null termination and character encoding