pyirsdk Documentation

repository·master·Indexed 18 days ago

https://github.com/kutu/pyirsdk

A Python 3 implementation of the iRacing SDK that allows developers to extract session data, live telemetry, and broadcast commands to the iRacing simulator. It provides a Python interface for programmatic interaction with the sim state, supporting the retrieval of static session information, real-time driving metrics, and the execution of camera, replay, chat, and pit commands.

Tokens
2.6K
Snippets
9
Records
13
Agent score
62%

What's inside pyirsdk

  1. Overview of pyirsdk

    master
    pyirsdk is a Python wrapper for the iRacing SDK, allowing developers to access real-time telemetry data from the iRacing simulator. It enables programmatic interaction with the sim state for applications like dashboards, telemetry loggers, or AI assistants.
  2. Capabilities of pyirsdk

    master

    The pyirsdk library provides three primary capabilities for interacting with iRacing:

    1. Session Data: Retrieve static or semi-static session information such as WeekendInfo and SessionInfo.
    2. Live Telemetry: Access real-time driving data including Speed, FuelLevel, and other telemetry metrics.
    3. Command Broadcasting: Send commands to the simulator, including camera, replay, chat, pit, and telemetry commands.
  3. Ensure data consistency with freeze_var_buffer_latest()

    master

    When retrieving multiple telemetry variables that belong to the same logical group (for example, multiple CarIdxXXX variables), call ir.freeze_var_buffer_latest() at the beginning of your processing loop.

    Without this, iRacing might update its internal tick while your code is mid-execution, causing you to retrieve some variables from one tick and subsequent variables from the next tick. This results in inconsistent data snapshots. Freezing the buffer ensures all variable reads within that loop iteration correspond to the same iRacing internal tick.

    # Call this at the start of your loop to snapshot telemetry
    ir.freeze_var_buffer_latest()
    
    # Now all subsequent reads are consistent for this tick
    t = ir['SessionTime']
    # ...
  4. Quickstart: Accessing iRacing telemetry data

    master

    To start reading data from a running iRacing session, initialize the IRSDK object and call .startup(). Once started, you can access telemetry variables using dictionary-style access.

    Note: Always check if a variable exists before accessing it to avoid errors, especially when dealing with nested data structures.

    import irsdk
    
    # Initialize and start the SDK
    ir = irsdk.IRSDK()
    ir.startup()
    
    # Access a simple variable
    speed = ir['Speed']
    
    # Safely access nested data
    if ir['WeekendInfo']:
        grid_info = ir['WeekendInfo']['WeekendOptions']['StartingGrid']
        print(grid_info)
  5. Configure iRacing for SDK access

    master

    To ensure the SDK can communicate with iRacing, you may need to disable fullscreen mode. Open your iRacing configuration file located at C:\Users\...\Documents\iRacing\app.ini and ensure the fullScreen setting under the [Graphics] section is set to 0.

    [Graphics]
    ...
    fullScreen=0
  6. Install pyirsdk

    master

    To use the Python iRacing SDK, ensure you have Python 3.7+ installed and add your Python Scripts directory (e.g., X:\Python37\Scripts) to your system's PATH environment variable. You must also install PyYaml (version 5.3 or higher). Finally, install the package using pip.

    pip install pyirsdk
  7. Basic usage of pyirsdk

    master

    To interact with iRacing, import the irsdk module, instantiate the IRSDK class, and call .startup() to establish the connection. Once started, you can access telemetry data using dictionary-style access with the data key names (e.g., 'Speed').

    #!python3
    import irsdk
    ir = irsdk.IRSDK()
    ir.startup()
    print(ir['Speed'])
  8. Create a base iRacing application loop

    master

    To build an iRacing application using pyirsdk, you should implement a main loop that manages the connection state and retrieves telemetry data.

    Key lifecycle steps include:

    1. Initialize: Create an instance of irsdk.IRSDK().
    2. Connection Management: Periodically check ir.is_initialized and ir.is_connected. Use ir.startup() to connect and ir.shutdown() to clean up internal variables when disconnecting.
    3. Data Consistency: Call ir.freeze_var_buffer_latest() at the start of every loop iteration. This ensures that if you are reading multiple related variables (like CarIdxXXX series), you get a consistent snapshot from the same iRacing internal tick, preventing data from changing mid-loop.
    4. Data Retrieval: Access telemetry via dictionary-style indexing (e.g., ir['SessionTime']). Always verify that a data block exists before accessing its sub-keys to avoid errors.
    5. Change Detection: Use ir.get_session_info_update_by_key(key) to get a tick count for specific data blocks (like CarSetup). Compare this against your stored last_update_tick to detect when a user has actually changed and applied settings in the iRacing garage.
    6. Command Execution: Use methods like ir.cam_switch_pos(index, mode) to send commands back to iRacing.
    import irsdk
    import time
    
    # 1. Initialize
    ir = irsdk.IRSDK()
    
    # State management
    class State:
        ir_connected = False
        last_car_setup_tick = -1
    state = State()
    
    def check_iracing():
        # 2. Connection Management
        if state.ir_connected and not (ir.is_initialized and ir.is_connected):
            state.ir_connected = False
            state.last_car_setup_tick = -1
            ir.shutdown()
        elif not state.ir_connected and ir.startup() and ir.is_initialized and ir.is_connected:
            state.ir_connected = True
    
    def loop():
        # 3. Data Consistency
        ir.freeze_var_buffer_latest()
    
        # 4. Data Retrieval
        t = ir['SessionTime']
        
        # 5. Change Detection
        car_setup = ir['CarSetup']
        if car_setup:
            car_setup_tick = ir.get_session_info_update_by_key('CarSetup')
            if car_setup_tick != state.last_car_setup_tick:
                state.last_car_setup_tick = car_setup_tick
                print('car setup updated')
    
        # 6. Command Execution
        ir.cam_switch_pos(0, 1)
    
    if __name__ == '__main__':
        try:
            while True:
                check_iracing()
                if state.ir_connected:
                    loop()
                time.sleep(1)
        except KeyboardInterrupt:
            pass
  9. Test pyirsdk scripts using a binary data file

    master

    Instead of keeping the iRacing simulator running during development, you can pass a previously dumped binary file (e.g., data.bin) to the ir.startup() method. This allows you to simulate the SDK environment using static data.

    Note: The file provided can also be an IBT Telemetry file. If you are working with IBT Telemetry samples, you should use the irsdk.IBT class instead of the standard IRSDK class.

    #!python3
    import irsdk
    ir = irsdk.IRSDK()
    # Use a binary file for testing instead of a live simulator connection
    ir.startup(test_file='data.bin')
    print(ir['Speed'])
  10. Detect updates to session data using get_session_info_update_by_key()

    master

    To avoid processing the same data repeatedly, use ir.get_session_info_update_by_key(key) to monitor when a specific data block (like CarSetup or WeekendInfo) has been updated by iRacing.

    Workflow:

    1. Retrieve the data block (e.g., car_setup = ir['CarSetup']).
    2. Call ir.get_session_info_update_by_key('CarSetup') to get the current update tick.
    3. Compare this tick to a locally stored last_update_tick from your previous loop.
    4. If they differ, the data has changed (e.g., a user applied new settings in the garage).
    # Example: Detecting CarSetup changes
    car_setup = ir['CarSetup']
    if car_setup:
        current_tick = ir.get_session_info_update_by_key('CarSetup')
        if current_tick != state.last_car_setup_tick:
            state.last_car_setup_tick = current_tick
            # Process the update...