Files
I150/docs/ai-guide/README.md
2026-07-03 16:37:12 +07:00

24 KiB

AI Collaboration Guide / Hướng dẫn cho AI Agents

🤖 Welcome AI Agent! / Chào mừng AI Agent!

Tài liệu này được thiết kế đặc biệt để giúp các AI agents (như bạn) hiểu nhanh dự án RobotNet10 và làm việc hiệu quả.

QUAN TRỌNG: Đọc tài liệu này TRƯỚC KHI bắt đầu làm việc với dự án.

📋 Quick Context / Bối cảnh Nhanh

Project Summary / Tóm tắt Dự án

What: Mobile robot AMR fleet management system Goal: Manage multiple autonomous mobile robots following VDA 5050 standard Components:

  • RobotApp: Software runs on each robot (Ubuntu 22.04)
  • FleetManager: Central management system on factory server
  • Communication: MQTT broker with VDA 5050 protocol

Technology Stack:

  • .NET 10 (C#) - FleetManager và RobotApp
  • Blazor Web App (Web UI) - FleetManager dashboard
  • MQTT (MQTTnet library) - VDA 5050 communication
  • SQL Server - FleetManager database
  • SQLite - RobotApp local database
  • VDA 5050 (v2.1.0) - Standard protocol (backward compatible with v2.0.0)
  • VDMA LIF - Map data standard

Project Status / Trạng thái Dự án

Current Phase: 📝 Documentation & Architecture Design

What exists:

  • Project structure defined
  • Comprehensive documentation
  • Linux RT kernel prepared
  • Source code implementation (NOT started yet)

What doesn't exist yet:

  • RobotApp source code
  • FleetManager source code
  • Shared libraries
  • Tests
  • Database schemas

This means: When implementing, you'll be creating NEW code, not modifying existing code.

🎯 Key Design Decisions / Quyết định Thiết kế Quan trọng

1. Why VDA 5050?

  • Interoperability: Work with third-party systems
  • Standardization: Clear protocol specification
  • Industry adoption: Widely supported

2. Why .NET/Blazor?

  • Cross-platform: Runs on Linux (robots) and Windows/Linux (server)
  • Performance: High-performance runtime
  • Unified UI: Blazor for both RobotApp and FleetManager web interfaces
  • Strong typing: C# type safety reduces bugs
  • Ecosystem: Rich libraries (MQTTnet, EF Core, etc.)

3. Why MQTT?

  • Lightweight: Low overhead for IoT/robotics
  • Publish-Subscribe: Perfect for 1-to-many communication
  • QoS Levels: Reliable message delivery
  • VDA 5050 requirement: Standard specifies MQTT

4. Architecture Pattern

  • Clean Architecture: Separation of concerns
  • Dependency Injection: Testable, maintainable code
  • Async/Await: Non-blocking I/O operations
  • Repository Pattern: Data access abstraction

5. FleetManager Core Modules

FleetManager được tổ chức thành 7 core modules:

  1. Identity: Authentication & Authorization (ASP.NET Identity, RBAC)
  2. MapEditor: Map management theo VDMA LIF standard (shared library)
  3. RobotConnections: MQTT connection management, heartbeat monitoring
  4. RobotManager: Robot state, order, và action management
  5. TrafficControl: Route calculation (A*), conflict detection & resolution
  6. ScriptEngine: C# scripting engine cho custom behaviors (shared library)
  7. FleetManagerConfig: Dynamic configuration management (runtime updates)

Important: ScriptEngine và MapEditor là shared libraries được dùng bởi cả RobotApp và FleetManager.

📂 Code Organization Principles / Nguyên tắc Tổ chức Code

Project Structure

srcs/
├── RobotApp/              # Robot control application
│   ├── Services/          # Business logic
│   │   ├── Navigation/    # Navigation algorithms
│   │   ├── VDA5050/       # VDA 5050 protocol handling
│   │   └── Hardware/      # Hardware abstraction
│   ├── Models/            # Data models
│   ├── Controllers/       # API controllers (if needed)
│   ├── Components/        # Blazor UI components
│   └── Pages/             # Blazor pages
│
├── FleetManager/          # Fleet management system
│   ├── Modules/           # Core modules
│   │   ├── Identity/      # Authentication & Authorization
│   │   ├── MapEditor/     # Map management (VDMA LIF)
│   │   ├── RobotConnections/  # MQTT connection management
│   │   ├── RobotManager/  # Robot state, order, action management
│   │   ├── TrafficControl/ # Route calculation, conflict resolution
│   │   ├── ScriptEngine/  # Script management, mission/task execution
│   │   └── FleetManagerConfig/  # Dynamic configuration
│   ├── Models/            # Data models
│   ├── Data/              # EF Core DbContext (SQL Server)
│   ├── Controllers/       # API controllers
│   ├── Components/        # Blazor UI components
│   └── Pages/             # Blazor pages
│
└── Shared/                # Shared libraries
    ├── ScriptEngine/      # C# scripting engine (shared)
    ├── MapEditor/         # Map editor library (shared)
    ├── VDA5050/           # VDA 5050 models (shared)
    ├── MQTT/              # MQTT utilities
    └── Common/            # Common utilities

Important Notes:

  • ScriptEngineMapEditor là shared libraries được dùng bởi cả RobotApp và FleetManager
  • FleetManager sử dụng SQL Server cho database
  • RobotApp sử dụng SQLite cho local database
  • MQTT Broker chạy trên service riêng, không phải trong FleetManager

Naming Conventions

Interfaces:

public interface IFleetCoordinator { }
public interface IMissionPlanner { }
public interface IVda5050Handler { }

Services:

public class FleetCoordinator : IFleetCoordinator { }
public class MissionPlanner : IMissionPlanner { }

Models (VDA 5050 - match standard):

public class Order { }      // Exactly as in VDA 5050
public class State { }      // Exactly as in VDA 5050
public class Node { }       // Exactly as in VDA 5050

Models (Domain-specific):

public class Robot { }
public class Mission { }
public class Waypoint { }

🔍 Important Patterns / Các Pattern Quan trọng

1. Dependency Injection

Always use constructor injection:

public class FleetCoordinator : IFleetCoordinator
{
    private readonly ILogger<FleetCoordinator> _logger;
    private readonly IMqttClient _mqttClient;
    private readonly IRepository<Robot> _robotRepository;

    // ✅ Correct: Constructor injection
    public FleetCoordinator(
        ILogger<FleetCoordinator> logger,
        IMqttClient mqttClient,
        IRepository<Robot> robotRepository)
    {
        _logger = logger;
        _mqttClient = mqttClient;
        _robotRepository = robotRepository;
    }
}

// ❌ Wrong: Don't use service locator pattern
public class BadExample
{
    public void DoSomething()
    {
        var service = ServiceLocator.Get<ISomeService>(); // Don't do this
    }
}

2. Async/Await

All I/O operations must be async:

// ✅ Correct
public async Task PublishStateAsync(RobotState state)
{
    var message = CreateMqttMessage(state);
    await _mqttClient.PublishAsync(message);
}

// ❌ Wrong: Blocking synchronous call
public void PublishState(RobotState state)
{
    var message = CreateMqttMessage(state);
    _mqttClient.PublishAsync(message).Wait(); // Don't do this
}

3. Repository Pattern

Abstract data access:

public interface IRepository<T> where T : class
{
    Task<T> GetByIdAsync(Guid id);
    Task<IEnumerable<T>> GetAllAsync();
    Task<T> AddAsync(T entity);
    Task UpdateAsync(T entity);
    Task DeleteAsync(Guid id);
}

public class Repository<T> : IRepository<T> where T : class
{
    private readonly DbContext _context;
    private readonly DbSet<T> _dbSet;

    public Repository(DbContext context)
    {
        _context = context;
        _dbSet = context.Set<T>();
    }

    public async Task<T> GetByIdAsync(Guid id)
    {
        return await _dbSet.FindAsync(id);
    }
    // ... other implementations
}

4. VDA 5050 Message Handling

Always validate VDA 5050 messages:

public class OrderProcessor
{
    private readonly IVda5050Validator _validator;

    public async Task<bool> ProcessOrderAsync(Order order)
    {
        // 1. Validate against VDA 5050 spec
        var validationResult = _validator.ValidateOrder(order);
        if (!validationResult.IsValid)
        {
            _logger.LogError("Invalid order: {Errors}", validationResult.Errors);
            return false;
        }

        // 2. Check business logic
        if (!IsOrderFeasible(order))
        {
            _logger.LogWarning("Order not feasible: {OrderId}", order.OrderId);
            return false;
        }

        // 3. Process order
        await ExecuteOrderAsync(order);
        return true;
    }
}

🚨 Critical Implementation Guidelines / Hướng dẫn Triển khai Quan trọng

1. VDA 5050 Compliance / Tuân thủ VDA 5050

DO:

  • Use exact field names from VDA 5050 specification
  • Follow sequence ID ordering (nodes: even, edges: odd)
  • Validate all messages against VDA 5050 schema
  • Handle all mandatory fields
  • Implement all required message types

DON'T:

  • Change VDA 5050 field names (e.g., don't rename orderId to OrderId)
  • Skip message validation
  • Ignore optional fields that might be used by third-party systems

Example - Correct VDA 5050 Model:

// ✅ Correct: Matches VDA 5050 exactly
public class Order
{
    [JsonPropertyName("headerId")]
    public long HeaderId { get; set; }

    [JsonPropertyName("timestamp")]
    public DateTime Timestamp { get; set; }

    [JsonPropertyName("version")]
    public string Version { get; set; }

    [JsonPropertyName("manufacturer")]
    public string Manufacturer { get; set; }

    [JsonPropertyName("serialNumber")]
    public string SerialNumber { get; set; }

    [JsonPropertyName("orderId")]
    public string OrderId { get; set; }

    [JsonPropertyName("orderUpdateId")]
    public long OrderUpdateId { get; set; }

    [JsonPropertyName("nodes")]
    public List<Node> Nodes { get; set; }

    [JsonPropertyName("edges")]
    public List<Edge> Edges { get; set; }
}

// ❌ Wrong: Field names don't match VDA 5050
public class BadOrder
{
    public long Id { get; set; }           // Should be "headerId"
    public string OrderNumber { get; set; } // Should be "orderId"
}

2. MQTT Connection Management / Quản lý Kết nối MQTT

Implement reconnection logic:

public class MqttService
{
    private readonly IMqttClient _mqttClient;
    private bool _isReconnecting;

    public async Task ConnectAsync()
    {
        var options = new MqttClientOptionsBuilder()
            .WithTcpServer(_config.BrokerAddress, _config.Port)
            .WithClientId(_config.ClientId)
            .WithCleanSession(false)
            .WithKeepAlivePeriod(TimeSpan.FromSeconds(60))
            .Build();

        _mqttClient.DisconnectedAsync += async e =>
        {
            if (_isReconnecting) return;

            _isReconnecting = true;
            _logger.LogWarning("MQTT disconnected. Reconnecting...");

            await Task.Delay(TimeSpan.FromSeconds(5));

            try
            {
                await _mqttClient.ConnectAsync(options);
                _logger.LogInformation("MQTT reconnected successfully");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "MQTT reconnection failed");
            }
            finally
            {
                _isReconnecting = false;
            }
        };

        await _mqttClient.ConnectAsync(options);
    }
}

3. Error Handling / Xử lý Lỗi

Use structured error handling:

public async Task<Result<Mission>> CreateMissionAsync(MissionRequest request)
{
    try
    {
        // Validate input
        if (request == null)
            return Result<Mission>.Failure("Request cannot be null");

        // Business logic
        var mission = await _missionPlanner.CreateMissionAsync(request);

        if (mission == null)
            return Result<Mission>.Failure("Failed to create mission");

        // Persist
        await _repository.AddAsync(mission);

        _logger.LogInformation("Mission created: {MissionId}", mission.Id);
        return Result<Mission>.Success(mission);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Error creating mission");
        return Result<Mission>.Failure($"Error: {ex.Message}");
    }
}

// Result class for clean error handling
public class Result<T>
{
    public bool IsSuccess { get; set; }
    public T Data { get; set; }
    public string ErrorMessage { get; set; }

    public static Result<T> Success(T data) =>
        new Result<T> { IsSuccess = true, Data = data };

    public static Result<T> Failure(string errorMessage) =>
        new Result<T> { IsSuccess = false, ErrorMessage = errorMessage };
}

4. Logging Best Practices / Thực hành Log tốt

public class OrderProcessor
{
    private readonly ILogger<OrderProcessor> _logger;

    public async Task ProcessOrderAsync(Order order)
    {
        // ✅ Use structured logging with parameters
        _logger.LogInformation(
            "Processing order: OrderId={OrderId}, UpdateId={UpdateId}, Nodes={NodeCount}",
            order.OrderId,
            order.OrderUpdateId,
            order.Nodes.Count
        );

        // ❌ Don't use string interpolation in logs
        // _logger.LogInformation($"Processing order: {order.OrderId}");

        try
        {
            await ExecuteOrderAsync(order);
            _logger.LogInformation("Order completed: {OrderId}", order.OrderId);
        }
        catch (Exception ex)
        {
            // ✅ Include exception and context
            _logger.LogError(ex,
                "Failed to process order: OrderId={OrderId}",
                order.OrderId
            );
        }
    }
}

📝 Common Tasks & Workflows / Nhiệm vụ & Quy trình Thường gặp

Task 1: Implement a VDA 5050 Message Handler

Steps:

  1. Review VDA 5050 specification for the message type
  2. Create/verify model in Shared/VDA5050/Models/
  3. Create handler in appropriate project
  4. Add validation logic
  5. Implement business logic
  6. Add unit tests
  7. Add integration tests

Example:

// 1. Model (in Shared project)
public class Order
{
    [JsonPropertyName("orderId")]
    public string OrderId { get; set; }
    // ... other fields
}

// 2. Handler (in RobotApp project)
public interface IOrderHandler
{
    Task<bool> HandleOrderAsync(Order order);
}

public class OrderHandler : IOrderHandler
{
    private readonly ILogger<OrderHandler> _logger;
    private readonly IVda5050Validator _validator;
    private readonly INavigationController _navigation;

    public OrderHandler(
        ILogger<OrderHandler> logger,
        IVda5050Validator validator,
        INavigationController navigation)
    {
        _logger = logger;
        _validator = validator;
        _navigation = navigation;
    }

    public async Task<bool> HandleOrderAsync(Order order)
    {
        // Validate
        var validationResult = _validator.ValidateOrder(order);
        if (!validationResult.IsValid)
        {
            _logger.LogError("Invalid order: {Errors}", validationResult.Errors);
            return false;
        }

        // Process
        _logger.LogInformation("Handling order: {OrderId}", order.OrderId);
        await _navigation.ExecuteOrderAsync(order);
        return true;
    }
}

// 3. Register in Program.cs
builder.Services.AddScoped<IOrderHandler, OrderHandler>();

Task 2: Add New Service

Steps:

  1. Define interface in appropriate namespace
  2. Implement service class
  3. Add dependencies via constructor injection
  4. Add unit tests
  5. Register in DI container (Program.cs)
  6. Use in other services/controllers

Example:

// 1. Interface
public interface IMissionPlanner
{
    Task<Mission> CreateMissionAsync(MissionRequest request);
    Task<bool> ValidateMissionAsync(Mission mission);
}

// 2. Implementation
public class MissionPlanner : IMissionPlanner
{
    private readonly ILogger<MissionPlanner> _logger;
    private readonly IRouteOptimizer _routeOptimizer;

    public MissionPlanner(
        ILogger<MissionPlanner> logger,
        IRouteOptimizer routeOptimizer)
    {
        _logger = logger;
        _routeOptimizer = routeOptimizer;
    }

    public async Task<Mission> CreateMissionAsync(MissionRequest request)
    {
        // Implementation
    }

    public async Task<bool> ValidateMissionAsync(Mission mission)
    {
        // Implementation
    }
}

// 3. Register
builder.Services.AddScoped<IMissionPlanner, MissionPlanner>();

Task 3: Add Database Entity

Steps:

  1. Create model class in Models/
  2. Add DbSet to DbContext
  3. Create migration
  4. Apply migration
  5. Create repository (if needed)
  6. Add seed data (if needed)

Example:

// 1. Model
public class Robot
{
    public Guid Id { get; set; }
    public string SerialNumber { get; set; }
    public string Manufacturer { get; set; }
    public RobotStatus Status { get; set; }
    public double? CurrentX { get; set; }
    public double? CurrentY { get; set; }
    public double? BatteryLevel { get; set; }
    public DateTime Created { get; set; }
    public DateTime Modified { get; set; }
}

// 2. DbContext
public class FleetDbContext : DbContext
{
    public DbSet<Robot> Robots { get; set; }
    public DbSet<Mission> Missions { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Robot>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.HasIndex(e => e.SerialNumber).IsUnique();
            entity.Property(e => e.SerialNumber).IsRequired().HasMaxLength(50);
        });
    }
}

// 3. Create migration
// dotnet ef migrations add AddRobotEntity

// 4. Apply migration
// dotnet ef database update

🔍 When to Ask for Human Help / Khi nào Cần Hỏi Con người

Ask for clarification when:

  • Requirements are ambiguous or conflicting
  • Multiple valid approaches exist (e.g., architectural decisions)
  • Security-sensitive decisions
  • Performance trade-offs
  • Budget constraints (e.g., cloud services)

You can decide independently:

  • Naming conventions (follow established patterns)
  • Code organization (follow project structure)
  • Implementation details (algorithms, data structures)
  • Refactoring for code quality
  • Adding logging/error handling
  • Writing tests

🎓 Learning Resources for AI / Tài liệu Học cho AI

📚 Documentation Structure Note: Tài liệu đã được tổ chức thành cấu trúc modular:

  • Mỗi module có file README.md tổng quan và các file chi tiết riêng
  • FleetManager: 7 module files trong docs/fleetmanager/
  • ScriptEngine: 9 module files trong docs/ScriptEngine/
  • MapEditor: 7 module files trong docs/MapEditor/
  • Luôn bắt đầu từ README.md của module để có overview, sau đó đọc các file chi tiết khi cần

Priority Reading Order:

  1. This document (you're here!) - Start here
  2. Architecture Overview - Understand system design
  3. FleetManager Documentation - Core modules overview
  4. ScriptEngine Documentation - Shared scripting library
  5. MapEditor Documentation - Shared map editor library
  6. VDA 5050 Integration - Critical protocol details
  7. RobotApp Documentation - Robot-side implementation
  8. Development Guide - Technical setup

When implementing:

Pre-Implementation Checklist / Checklist Trước Khi Code

Before starting a task, verify:

  • I understand the requirement clearly
  • I've read relevant documentation
  • I know which project the code belongs to (RobotApp/FleetManager/Shared)
  • I understand the dependencies needed
  • I know the design patterns to follow
  • I understand VDA 5050 requirements (if applicable)
  • I know how to test the feature

🚀 Getting Started / Bắt đầu

First steps for a new AI agent joining the project:

  1. Read this document completely
  2. Scan architecture docs for system understanding
  3. Review VDA 5050 docs if working on protocol
  4. Check current project status (see git commits, issues)
  5. Ask clarifying questions if needed
  6. Start coding following patterns above

💡 Pro Tips for AI Agents / Mẹo cho AI Agents

  1. Always validate VDA 5050 compliance - This is critical for interoperability
  2. Use structured logging - Makes debugging easier for humans
  3. Write async code - All I/O should be non-blocking
  4. Follow naming conventions - Consistency matters
  5. Add XML documentation - Helps other AI and human developers
  6. Think about error cases - Don't just code the happy path
  7. Consider scalability - System will manage 100+ robots
  8. Security first - Validate inputs, encrypt sensitive data
  9. Test your code - Write unit tests
  10. Keep it simple - Don't over-engineer

🤝 Collaboration with Humans / Cộng tác với Con người

Communication style:

  • Be concise but complete
  • Explain technical decisions
  • Highlight trade-offs
  • Ask questions when uncertain
  • Provide examples

Code review expectations:

  • Humans will review your code
  • Be open to feedback
  • Explain your reasoning
  • Learn from review comments

📞 Summary / Tóm tắt

Remember:

  • 🎯 Goal: Build VDA 5050-compliant AMR fleet management system
  • 🏗️ Tech: .NET 10, Blazor Web App, MQTT, SQL Server (FleetManager), SQLite (RobotApp)
  • 📏 Standards: VDA 5050 v2.1.0 (critical!, backward compatible with v2.0.0), VDMA LIF, Clean Architecture, Async/Await
  • 📂 Structure:
    • RobotApp (on robot, SQLite)
    • FleetManager (on server, SQL Server) với 7 core modules
    • Shared libraries: ScriptEngine, MapEditor
  • Quality: Tests, logging, error handling, validation
  • 🔑 Key Modules: Identity, MapEditor, RobotConnections, RobotManager, TrafficControl, ScriptEngine, FleetManagerConfig

Your mission: Write clean, maintainable, VDA 5050-compliant code that enables robots and fleet managers to communicate effectively.


Welcome to the team! Happy coding! 🤖

Last Updated: 2025-11-13 Status: Essential Reading for AI Agents Version: 2.0 (Updated with modular documentation structure and correct tech stack)