LFS-Ayats

LFS-Ayats: Live for Speed InSim Telemetry System

Python 3.8+ License: MIT Code style: black Tests Code Quality codecov

A professional, modular telemetry collection system for Live for Speed racing simulator.

A modular and complete system for collecting, processing, and visualizing telemetry data from the Live for Speed racing simulator using the InSim protocol.

πŸ“‹ Description

This repository provides a professional implementation of the Live for Speed InSim protocol, enabling:

πŸ—οΈ Repository Structure

LFS-Ayats/
β”œβ”€β”€ src/                          # Main source code
β”‚   β”œβ”€β”€ api/                      # REST API (FastAPI)
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ main.py              # FastAPI application
β”‚   β”‚   β”œβ”€β”€ models.py            # Pydantic models
β”‚   β”‚   β”œβ”€β”€ dependencies.py      # Dependency injection
β”‚   β”‚   β”œβ”€β”€ middleware.py        # CORS and logging
β”‚   β”‚   β”œβ”€β”€ exceptions.py        # Custom exceptions
β”‚   β”‚   └── routers/             # API endpoints
β”‚   β”œβ”€β”€ connection/               # InSim connection module
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ insim_client.py      # InSim TCP/UDP client
β”‚   β”‚   └── packet_handler.py    # InSim packet handling
β”‚   β”œβ”€β”€ telemetry/               # Telemetry module
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ collector.py         # Telemetry data collection
β”‚   β”‚   └── processor.py         # Data processing and validation
β”‚   β”œβ”€β”€ database/                # Database module
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ models.py            # SQLAlchemy models
β”‚   β”‚   └── repository.py        # Data access layer
β”‚   β”œβ”€β”€ visualization/           # Visualization module
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ dashboard.py         # Real-time web dashboard (Dash)
β”‚   β”‚   β”œβ”€β”€ plots.py             # Analysis plots
β”‚   β”‚   β”œβ”€β”€ map_view.py          # Circuit map visualization
β”‚   β”‚   β”œβ”€β”€ comparator.py        # Lap comparison
β”‚   β”‚   └── components/          # Reusable components
β”‚   β”œβ”€β”€ export/                  # Export module
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ csv_exporter.py     # CSV export
β”‚   β”‚   β”œβ”€β”€ json_exporter.py    # JSON export
β”‚   β”‚   └── db_exporter.py      # Database export
β”‚   β”œβ”€β”€ config/                  # Configuration management
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   └── settings.py         # Application configuration
β”‚   └── utils/                   # Common utilities
β”‚       β”œβ”€β”€ __init__.py
β”‚       └── logger.py           # Logging system
β”œβ”€β”€ tests/                       # Automated tests
β”‚   β”œβ”€β”€ unit/                   # Unit tests
β”‚   β”œβ”€β”€ integration/            # Integration tests
β”‚   └── fixtures/               # Test data
β”œβ”€β”€ examples/                    # Usage examples
β”‚   β”œβ”€β”€ basic_connection.py     # Basic connection
β”‚   β”œβ”€β”€ telemetry_monitor.py   # Telemetry monitor
β”‚   β”œβ”€β”€ data_logger.py         # Data logger
β”‚   └── api_client_example.py  # REST API client
β”œβ”€β”€ docs/                       # Documentation
β”‚   β”œβ”€β”€ insim_protocol.md      # InSim protocol documentation
β”‚   β”œβ”€β”€ packet_reference.md    # Packet reference
β”‚   β”œβ”€β”€ api_reference.md       # API reference
β”‚   β”œβ”€β”€ api_documentation.md   # REST API documentation
β”‚   └── development.md         # Development guide
β”œβ”€β”€ scripts/                    # Utility scripts
β”‚   └── delete-branches.sh     # Branch management
β”œβ”€β”€ .gitignore                 # Git ignored files
β”œβ”€β”€ requirements.txt           # Python dependencies
β”œβ”€β”€ setup.py                   # Package installation
β”œβ”€β”€ pytest.ini                 # pytest configuration
└── README.md                  # This file

πŸš€ Installation

Prerequisites

Quick Installation

# Clone the repository
git clone https://github.com/lfsplayer97/LFS-Ayats.git
cd LFS-Ayats

# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate  # Linux/Mac
# or
venv\Scripts\activate  # Windows

# Install dependencies
pip install -r requirements.txt

# ⚠️ IMPORTANT: Install package in development mode
pip install -e .

πŸ’‘ Why pip install -e . is required:

The -e flag installs the package in editable/development mode, which:

Without this step, you’ll encounter ModuleNotFoundError: No module named 'src' when running examples or tests.

βœ… Verify installation: pip show lfs-ayats should display the package info

Verify Installation

Run the verification script to check your setup:

python scripts/verify_setup.py

This will check:

Troubleshooting Installation

If you see ModuleNotFoundError: No module named 'src':

  1. Make sure you activated the virtual environment
  2. Run pip install -e . from the project root directory
  3. Verify with pip show lfs-ayats
  4. Run python scripts/verify_setup.py to diagnose issues

For more help, see the Troubleshooting Guide.

πŸ“š Complete Documentation

LFS-Ayats has extensive documentation for all user levels:

πŸš€ Getting Started

πŸŽ“ Interactive Tutorials

Tutorial Description Time Level
01 - First Session Collect and export basic telemetry 30 min Beginner
02 - Lap Analysis Compare laps and find improvements 45 min Intermediate
03 - Real-time Dashboard Create interactive web dashboard 30 min Intermediate
04 - Advanced Analysis Machine learning and predictions 60 min Advanced
05 - Database Store historical data 45 min Advanced

πŸ’‘ Use Cases

πŸ—οΈ Technical Documentation

πŸ‘¨β€πŸ’» For Developers

πŸ“– Complete Documentation Index

πŸ“– Basic Usage

Connecting to LFS

from src.connection import InSimClient
from src.telemetry import TelemetryCollector

# Create InSim client
client = InSimClient(
    host='127.0.0.1',
    port=29999,
    admin_password='',
    app_name='LFS-Ayats'
)

# Connect
client.connect()

# Create telemetry collector
collector = TelemetryCollector(client)

# Start data collection
collector.start()

Data Export

from src.export import CSVExporter, JSONExporter

# Export to CSV
csv_exporter = CSVExporter('telemetry_data.csv')
csv_exporter.export(telemetry_data)

# Export to JSON
json_exporter = JSONExporter('telemetry_data.json')
json_exporter.export(telemetry_data)

REST API

The system includes a complete REST API built with FastAPI for programmatic access:

Configuration

The API supports environment-based configuration for different deployment scenarios:

Database Configuration:

# Copy the example environment file
cp .env.example .env

# Edit .env to configure your database
# For development (default):
DATABASE_URL=sqlite:///telemetry.db

# For production with PostgreSQL:
DATABASE_URL=postgresql://username:password@localhost:5432/lfs_telemetry

# For production with MySQL:
DATABASE_URL=mysql://username:password@localhost:3306/lfs_telemetry

Security Notes:

Starting the API

# Start the API server
uvicorn src.api.main:app --reload --host 0.0.0.0 --port 8000

Automatic Documentation:

Client usage example:

import requests

# List sessions
response = requests.get("http://localhost:8000/api/v1/sessions")
sessions = response.json()

# Get lap telemetry
response = requests.get("http://localhost:8000/api/v1/1/telemetry")
telemetry = response.json()

# WebSocket for real-time telemetry
import websockets
import asyncio

async def receive_telemetry():
    uri = "ws://localhost:8000/api/v1/telemetry/live"
    async with websockets.connect(uri) as websocket:
        while True:
            data = await websocket.recv()
            print(f"Telemetry: {data}")

asyncio.run(receive_telemetry())

Available endpoints:

See docs/api_documentation.md for complete API documentation.

πŸ”Œ External Integrations

LFS-Ayats offers integrations with external services for notifications, streaming, and automatic backup.

Discord

Send automatic notifications to Discord channels:

from src.integrations import DiscordIntegration

discord = DiscordIntegration(webhook_url="https://discord.com/api/webhooks/...")

# Notify personal best
await discord.notify_personal_best({
    'circuit': 'Blackwood GP',
    'time': 98.456,
    'vehicle': 'XF GTI',
    'improvement': 0.234
})

Telegram

Send messages and images via a Telegram bot:

from src.integrations import TelegramIntegration

telegram = TelegramIntegration(bot_token="YOUR_TOKEN", chat_id="YOUR_CHAT_ID")
await telegram.send_message("<b>System online!</b>")

Streaming Overlay (OBS)

Display real-time telemetry in OBS Studio:

from src.integrations import StreamingOverlay

overlay = StreamingOverlay(port=5000)
overlay.start()  # Access at http://localhost:5000

# Update telemetry data
overlay.update_telemetry({
    'speed': 120.5,
    'rpm': 6500,
    'gear': 4,
    'lap_time': 98.456
})

Cloud Storage (Google Drive / Dropbox)

Automatic backup to Google Drive or Dropbox:

from src.integrations import GoogleDriveIntegration

gdrive = GoogleDriveIntegration('./credentials.json')
gdrive.auto_backup('./data/', folder_id='optional_folder_id')

Configuration:

Add to config.yaml:

integrations:
  discord:
    enabled: true
    webhook_url: "${DISCORD_WEBHOOK_URL}"
    notifications:
      personal_best: true
      session_summary: true
      anomalies: true
  
  telegram:
    enabled: false
    bot_token: "${TELEGRAM_BOT_TOKEN}"
    chat_id: "${TELEGRAM_CHAT_ID}"
  
  streaming:
    enabled: false
    overlay_port: 5000
    update_rate: 10  # Hz
  
  cloud_backup:
    enabled: false
    provider: google_drive
    auto_backup: true
    backup_interval: 3600  # seconds
    credentials_path: ./credentials.json

Complete examples:

See docs/integrations.md for complete integration documentation.

Real-time Visualization

from src.visualization import TelemetryDashboard

# Create real-time web dashboard
dashboard = TelemetryDashboard(
    host='127.0.0.1',
    port=29999,
    update_interval=100  # update every 100ms
)

# Run the dashboard server
dashboard.run(debug=True, port=8050)
# Open browser at http://localhost:8050

Lap Analysis and Comparison

from src.visualization import (
    LapComparator,
    create_speed_vs_distance_plot,
    create_track_map,
    create_heatmap_plot
)

# Compare laps
comparator = LapComparator()
comparator.add_lap("Lap 1", lap1_telemetry)
comparator.add_lap("Lap 2", lap2_telemetry)

# Create comparison plots
fig = comparator.create_comparison_plot()
fig.write_html("lap_comparison.html")

# Create track map with speeds
track_fig = create_track_map(telemetry, show_speed_colors=True)
track_fig.write_html("track_map.html")

# Create heatmap
heatmap_fig = create_heatmap_plot(telemetry)
heatmap_fig.write_html("speed_heatmap.html")

For more information on visualization, see docs/visualization.md

πŸ§ͺ Automated Tests

The project includes comprehensive automated tests to ensure code quality:

# Run all tests
pytest

# Run tests with coverage
pytest --cov=src --cov-report=html

# Run specific tests
pytest tests/unit/connection/
pytest tests/integration/

πŸ“š InSim Protocol

InSim (Internet Simulator) is Live for Speed’s communication protocol that allows external applications to interact with the simulator.

Main InSim Packets

Packet Description Usage
IS_ISI InSim Init Initialize InSim connection
IS_VER Version InSim protocol version
IS_TINY Tiny Small control packets
IS_SMALL Small Small data packets
IS_MCI Multi Car Info Multiple car information
IS_NLP Node and Lap Node and lap information
IS_MSO Message Out Server messages
IS_III InSim Info Server information
IS_STA State Server state
IS_NCN New Connection New player connection
IS_CNL Connection Leave Player disconnect
IS_CPR Connection Player Rename Player name change
IS_NPL New Player New player on track
IS_PLP Player Leave Player leaves track
IS_PIT Pit Stop Pit stop
IS_PSF Pit Stop Finish Pit stop finish
IS_LAP Lap Time Lap time
IS_SPX Split Time Sector time
IS_PEN Penalty Penalty
IS_TOC Take Over Car Car control change
IS_FLG Flag Flag
IS_RES Result Results
IS_REO Reorder Car reordering
IS_BTN Button Interface buttons
IS_BFN Button Function Button functions
IS_AXI Autocross Info Autocross information
IS_RIP Replay Info Replay information

Available Telemetry

Telemetry that can be collected includes:

πŸ“– References

Official Documentation

Additional Resources

🀝 Contributing

Contributions are welcome! If you want to contribute:

  1. Fork the repository
  2. Create a branch for your feature (git checkout -b feature/new-feature)
  3. Commit your changes (git commit -m 'Add new feature')
  4. Push to the branch (git push origin feature/new-feature)
  5. Open a Pull Request

Developer Guides

To start contributing, see:

Best Practices

πŸ”„ Continuous Integration

This project uses GitHub Actions for automated testing and quality checks:

Workflows

Pre-commit Hooks

Install pre-commit hooks for local development:

pip install pre-commit
pre-commit install

This will automatically check your code before each commit.

πŸ“„ License

This project is licensed under the MIT License. See the LICENSE file for more details.

✨ Authors

πŸ™ Acknowledgments

πŸ“ž Contact

If you have questions, suggestions, or ideas to improve the project, feel free to contact me!

Email: lfsplayer97@gmail.com

πŸš€ Help Us Make It Better!

LFS-Ayats is an open-source project and your collaboration is very important. If you have ideas, find bugs, or want to contribute with new features:

Every contribution, no matter how small, helps grow and improve this project for the entire Live for Speed community! 🏎️

Note: This project is under active development. Check the documentation and examples for more information on usage and available features.