Custom Interfaces

This guide shows you how to build your own industrial communication interfaces in realvirtual using the FastInterface framework. FastInterface provides thread-safe, high-performance communication with automatic signal management and connection handling.

Overview

realvirtual's FastInterface framework makes it easy to connect your simulation to external systems like PLCs, robots, IoT devices, or any system with a network API. You implement just three core methods, and FastInterface handles threading, reconnection, signal management, and UI integration automatically.

What you'll learn:

  • Setting up the FastInterface class structure

  • Implementing connection and communication logic

  • Handling signal exchange with thread safety

  • Using metadata for protocol mapping

  • Debugging and troubleshooting your interface

FastInterface Architecture

FastInterface Architecture Overview

This diagram illustrates the streamlined FastInterface development approach:

FastInterface Foundation

The FastInterfaceBase class provides six core services automatically:

  • Thread Management: Handles background thread lifecycle

  • Auto Reconnection: Automatic connection recovery on failure

  • Signal Discovery: Finds and manages all child signal components

  • Error Handling: Comprehensive error recovery and logging

  • State Management: Connection status tracking and monitoring

  • Unity Integration: Seamless Inspector UI and Unity compatibility

Simple 3-Method Implementation

You only need to implement 3 methods to create a complete interface:

  1. EstablishConnection() - Set up your protocol connection (TCP, serial, etc.)

  2. CommunicationLoop() - Exchange data continuously with external system

  3. CloseConnection() - Clean up resources and close connections

Data Flow Architecture

The bottom section shows the thread-safe data flow:

  • Unity Thread: Manages GameObjects and signal components

  • Background Thread: Runs your protocol implementation safely

  • External System: Your target device (PLC, Robot, IoT, Server)

Signal exchange uses built-in methods:

  • Reading Signals: GetInputsForPLC() - Unity → External System

  • Writing Signals: SetOutputsFromPLC(data) - External System → Unity

Core Components:

  1. FastInterfaceBase Class - The foundation that provides thread management, reconnection logic, and signal management infrastructure

  2. Background Thread - All protocol communication runs on a dedicated background thread, keeping Unity's main thread responsive

  3. Connection State Management - Automatic connection monitoring with visual status indicators and error reporting

  4. Signal Manager - Handles automatic discovery of child signal objects and manages thread-safe signal data exchange

  5. Thread-Safe Communication - Built-in mechanisms for safely passing data between Unity's main thread and the background communication thread

  6. Precise Timing Control - Automatic integration with realvirtual's PrePost FixedUpdate system for deterministic signal processing (Available in realvirtual 6.0.5+)

Standard Workflow:

The architecture ensures a consistent pattern across all FastInterface implementations:

  • Initialize → Copy Inspector properties to thread-safe variables

  • Connect → Establish connection on background thread with automatic retry logic

  • Communicate → Continuous loop reading Unity signals, sending to external system, receiving responses, and updating Unity signals

  • Monitor → Real-time connection state tracking with performance metrics

  • Cleanup → Proper resource cleanup with graceful shutdown

Key Benefits:

  • Consistency - All custom interfaces follow the same proven architecture pattern

  • Reliability - Built-in connection recovery and error handling

  • Performance - Non-blocking communication with optimized signal change detection

  • Visibility - Inspector integration shows connection status, cycle counts, and timing metrics

  • Safety - Thread-safe design prevents Unity threading issues

This standardized approach means you can focus on implementing your specific protocol logic while FastInterface handles all the complex threading, connection management, and Unity integration automatically.

Precise Timing Control (realvirtual 6.0.5+)

FastInterface automatically integrates with realvirtual's PrePost FixedUpdate system to provide deterministic timing for industrial automation applications. This system ensures that all FastInterface components process signals at precisely the same moments relative to Unity's physics calculations.

Timing Architecture

Signal Processing Flow:

  1. PreFixedUpdate Phase: All FastInterface instances synchronously process PLC outputs (data FROM PLC TO Unity objects)

  2. FixedUpdate Phase: Unity runs physics calculations, component logic, and movement updates

  3. PostFixedUpdate Phase: All FastInterface instances synchronously process PLC inputs (data FROM Unity objects TO PLC)

No Configuration Required: FastInterface automatically participates in the timing system - no additional setup or configuration needed.

FastInterface Inspector

FastInterface Inspector Panel

The FastInterface Inspector provides comprehensive monitoring and configuration for your custom interfaces. Understanding these fields is essential for effective interface development and troubleshooting:

State Section

  • State: Shows the current connection status with visual indicators:

    • 🟢 Connected (green) - Interface is connected and communicating successfully

    • 🔴 Disconnected (red) - Interface is not connected

    • 🟡 Connecting (yellow) - Interface is attempting to establish connection

    • 🟠 Error (orange) - Interface encountered an error and will attempt reconnection

  • Input Signals: Number of input signals (Unity → External System) discovered automatically

  • Output Signals: Number of output signals (External System → Unity) discovered automatically

  • Comm Cycle Ms: Actual communication cycle time in milliseconds (performance indicator)

  • Cycle Count: Total number of communication cycles completed since connection

Configuration Section

  • Update Cycle Ms: Target cycle time in milliseconds for communication loop

  • Only Transmit Changed Inputs: ✅ Performance optimization - only sends changed input values

  • Auto Reconnect: ✅ Automatically attempts reconnection on connection loss

  • Reconnect Interval Seconds: Wait time between reconnection attempts

  • Max Reconnect Attempts: Maximum number of consecutive reconnection attempts (-1 = infinite)

  • Debug Mode: ✅ Enables detailed logging for troubleshooting

Key Benefits of the Inspector:

  1. Real-time Monitoring - Watch connection state and performance metrics live during runtime

  2. Performance Optimization - "Only Transmit Changed Inputs" reduces network traffic significantly

  3. Automatic Recovery - Built-in reconnection logic handles temporary connection losses

  4. Development Support - Debug mode provides detailed logging for troubleshooting

  5. Signal Discovery - Automatically counts and manages all child signal objects

Why use FastInterface:

  • Thread-safe background communication without blocking Unity

  • Automatic reconnection with customizable retry logic

  • Zero-configuration signal discovery - automatically finds all child signals

  • High performance with optimized signal exchange and change detection

  • Built-in debugging with comprehensive logging and state visualization

New Standard: FastInterface is the new standard for all realvirtual interface development. All new interfaces should use FastInterface for optimal performance, reliability, and maintainability.

Reference Implementations: For production-quality examples, examine these FastInterface implementations in the realvirtual codebase:

  • KEBA Interface - Industrial robot controller communication

  • KUKA Interface - KUKA robot integration

  • MQTT Interface - IoT messaging protocol

Legacy Note: Some older interfaces in realvirtual still use the deprecated InterfaceBaseClass/InterfaceThreadedBaseClass approach and will be migrated to FastInterface in future releases.

Migrating from Legacy Interfaces? If you have existing interfaces built with the deprecated InterfaceBaseClass or InterfaceThreadedBaseClass, see Legacy Interfaces (Deprecated) for migration guidance and reference documentation.

Quick Start with Template

The fastest way to create a custom interface is using the blueprint template. Copy one of these working templates from the realvirtual codebase:

  • BlueprintFastInterfaceSimple.cs - Minimal template for basic protocols

  • BlueprintFastInterface.cs - Full template with advanced features

Copy /Assets/realvirtual/Interfaces/Common/Fast/BlueprintFastInterfaceSimple.cs and replace the TODO sections with your protocol logic:

Step-by-Step Implementation

Step 1: Create Your Interface Class

Start by creating a new C# script that inherits from FastInterfaceBase:

Key points:

  • Always inherit from FastInterfaceBase

  • Add Inspector properties for connection settings

  • Declare connection objects as private fields

  • Use [Header] attributes to organize Inspector settings

Step 2: Implement Connection Logic

The EstablishConnection method runs once on the background thread when starting communication:

Important:

  • Use ThreadSafeLogger instead of Debug.Log in background threads

  • Throw exceptions on connection failure - FastInterface handles reconnection automatically

  • Copy Inspector properties to thread-safe fields using CopyPropertiesToThreadSafe()

  • Use CancellationToken for responsive shutdown during connection attempts

Step 3: Build the Communication Loop

The CommunicationLoop method runs repeatedly on the background thread after connection is established:

Key concepts:

  • GetInputsForPLC(): Returns all input signal values as Dictionary<string, object>

  • SetOutputsFromPLC(): Updates output signals with received data

  • Signal metadata: Use TryGetSignalMetadataSafe<T>() to access signal configuration safely from background thread

  • Error handling: Use try/catch and ThreadSafeLogger for robust error reporting

Step 4: Handle Signal Exchange

FastInterface provides two main methods for signal data exchange:

Performance optimization:

  • Use OnlyTransmitChangedInputs = true in Inspector to only send changed input signals

  • Access this setting thread-safely with threadSafeOnlyTransmitChangedInputs

  • Use appropriate data types - FastInterface handles conversion automatically

Step 5: Implement Connection Cleanup

The CloseConnection method runs on the background thread when stopping communication:

Advanced Features

Using Signal Metadata for Protocol Mapping

Signal metadata allows you to store protocol-specific configuration with each signal:

Dynamic Signal Import

You can create and update signals dynamically using the signal management API:

Thread-Safe Property Access

For Inspector properties that need background thread access, copy them to thread-safe fields:

Real Interface Examples: For complete production implementations, examine the FastInterface-based interfaces in Assets/realvirtual/Interfaces/:

FastInterface Standard (Recommended):

  • KEBA Interface - Modern industrial robot controller with comprehensive error handling

  • KUKA Interface - Advanced robotic integration with real-time communication

  • MQTT Interface - IoT protocol implementation with automatic topic management

Legacy Implementations (being migrated):

  • S7, OPC-UA, and Modbus interfaces still use the older approach but demonstrate advanced features like bulk operations and protocol-specific optimizations.

Best Practices

Performance Optimization

  1. Use change detection for input signals:

  2. Cache signal metadata for better performance:

  3. Batch operations when possible:

Thread Safety Guidelines

  1. Never access Unity GameObjects from background thread methods (EstablishConnection, CommunicationLoop, CloseConnection)

  2. Use ThreadSafeLogger instead of Debug.Log in background threads:

  3. Copy Inspector properties to thread-safe fields:

  4. Use thread-safe signal metadata access:

Error Handling and Debugging

  1. Comprehensive error handling:

  2. Enable debug mode for detailed logging:

  3. Monitor connection state in Inspector:

    • State: Shows current connection status with visual indicators

    • CycleCount: Number of communication cycles completed

    • CommCycleMs: Actual communication timing

    • ErrorMessage: Last error message if connection failed

Testing Your Interface

  1. Start with the blueprint - copy BlueprintFastInterface.cs for a working foundation

  2. Test connection logic first:

  3. Add simulation mode for testing without external hardware:

Troubleshooting

Common Issues

Interface doesn't connect:

  • Check network connectivity and firewall settings

  • Verify IP address and port configuration

  • Look for error messages in Unity Console and Interface Inspector

  • Test with external tools (telnet, protocol-specific clients)

Signals not updating:

  • Verify signals are child objects of the interface GameObject

  • Check signal directions (Input vs Output)

  • Enable Debug Mode for detailed signal logging

  • Ensure metadata mapping is correct

Performance issues:

  • Enable OnlyTransmitChangedInputs to reduce network traffic

  • Increase UpdateCycleMs if communication is too frequent

  • Use batch operations instead of individual signal writes

  • Check for blocking operations in CommunicationLoop

Threading errors:

  • Never access Unity GameObjects from background thread methods

  • Use ThreadSafeLogger instead of Debug.Log in background threads

  • Copy Inspector properties to thread-safe fields

  • Use thread-safe metadata access methods

Debug Tools

  1. Inspector debugging:

    • Enable Debug Mode for detailed logging

    • Monitor State field for connection status

    • Check ErrorMessage for failure details

    • Watch CycleCount and CommCycleMs for performance

  2. Console logging:

  3. Signal state monitoring:

FastInterface API Reference

FastInterface provides several high-performance helper methods for signal operations in your custom implementations. These methods are available through extension methods and provide thread-safe, optimized signal access.

Signal Value Operations

Batch Signal Operations

Signal Discovery and Management

Thread-Safe Metadata Access

Dynamic Signal Creation

Signal Manager Utilities

Common Usage Patterns

Pattern 1: Metadata-Based Protocol Mapping

Pattern 2: Dynamic Signal Import

Pattern 3: High-Performance Communication

Performance Tips:

  • Use batch operations (GetInputsForPLC(), SetOutputsFromPLC()) instead of individual signal access for better performance

  • Call RefreshSignalManager() after creating or modifying signals to enable high-performance lookups

  • Use metadata for protocol-specific configuration to avoid hardcoding addresses or parameters

  • Always use ThreadSafeLogger in background thread methods instead of Debug.Log

Last updated