Initial commit

This commit is contained in:
2026-07-03 16:37:12 +07:00
commit 63b8c1ea8b
1931 changed files with 640587 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,961 @@
# RobotMonitor Architecture - Design Document
_Last Updated: 2024-12-XX_
## 📋 Overview
Tài liệu này mô tả cấu trúc và thiết kế cho **RobotMonitor** - trang giám sát robot trên layout map. RobotMonitor cho phép người dùng xem vị trí và trạng thái của các robot trong thời gian thực trên layout map với background image.
**Framework:** MudBlazor
**Note:** Tài liệu này tập trung vào cấu trúc và thiết kế, chưa triển khai code.
---
## 🎯 Requirements Summary
### **1. Layout Base (từ LayoutEditor)**
- Sử dụng cơ chế zoom, pan tương tự LayoutEditor
- Hiển thị background image (SLAM Map)
- Hiển thị grid (tùy chọn)
- Hiển thị nodes và edges của layout
- **KHÔNG** có các event click hay scanner như LayoutEditor
### **2. Robot Display**
- Mỗi robot được hiển thị như một image (từ robot model)
- Image được lấy từ model của robot đó
- Robot được đặt tại vị trí từ StateMsg (x, y, theta)
### **3. SignalR Integration**
- Thông tin robot được lấy bằng SignalR
- **Subscribe đến HubServer và hiển thị theo broadcast từ phía Server**
- Chỉ hiển thị những robot có dữ liệu từ bản tin
- Thêm robot nếu bản tin có robot chưa được hiển thị
- Xóa robot nếu bản tin không còn thông tin về robot đó
### **4. Robot Selection**
- Có cơ chế click vào robot để hiển thị thông tin của robot đó (Selected robot)
- Hiển thị thông tin robot selected ở panel bên phải
### **5. Layout Structure**
Layout gồm 3 phần:
- **Bên trái:**
- **Bên trên:** Thanh công cụ (Toolbar)
- **Bên dưới:** Layout monitor (SVG Canvas)
- **Bên phải:** Thông tin về robot đang được selected (Robot Info Panel)
### **6. Toolbar Components**
- **Buttons:**
- ZoomIn
- ZoomOut
- FitScale (fit to screen)
- Focus (tìm kiếm robot đang được selected, đưa view về giữa robot selected)
- **Expand/Collapse RobotInfoPanel** (cạnh phía InfoPanel)
- **Checkboxes:**
- FollowRobot(Selected) - Tự động follow robot selected khi di chuyển
- Show Path - Hiển thị path của robot (nếu có)
- Show Name - Hiển thị tên robot
- Show Grid - Hiển thị grid
- **SelectBox:**
- Chọn Layout
- Chọn Version
- Chọn Level
- Chọn Robot (Selected Robot)
### **7. Robot Information Display**
Thông tin về robot selected sẽ hiển thị:
- **BatteryState** - Trạng thái pin (charge, voltage, health, charging)
- **Visualization** - Thông tin visualization từ VisualizationMsg
- **Errors** - Danh sách lỗi từ StateMsg.Errors
- **Informations** - Danh sách thông tin từ StateMsg.Information
---
## 🏗️ Architecture Overview
### **Component Hierarchy**
```
RobotMonitor (Page)
→ RobotMonitorComponent
├── MonitorToolbar (top left)
├── SvgMonitorCanvas (left, below toolbar)
└── RobotInfoPanel (right)
└── SelectedRobotInfo
├── BatteryStateCard
├── VisualizationCard
├── ErrorsCard
└── InformationCard
```
### **Component Structure**
```
RobotNet10.FleetManager.Client/
└─ Components/
└─ RobotMonitor/
├─ RobotMonitorComponent.razor ← Main container (MudBlazor)
├─ RobotMonitorComponent.razor.css
├─ MonitorToolbar.razor ← Toolbar with controls (MudBlazor)
├─ MonitorToolbar.razor.css
├─ SvgMonitorCanvas.razor ← Main SVG canvas
├─ SvgMonitorCanvas.razor.css
└─ RobotInfoPanel/
├─ RobotInfoPanel.razor ← Container for robot info (MudBlazor)
└─ SelectedRobotInfo.razor ← Selected robot details
├─ BatteryStateCard.razor ← Battery state display
├─ VisualizationCard.razor ← Visualization display
├─ ErrorsCard.razor ← Errors display
└─ InformationCard.razor ← Information display
```
### **Services Structure**
```
RobotNet10.FleetManager.Client/
└─ Services/
└─ State/
└─ RobotMonitorState.cs ← Centralized state
```
---
## 📐 Design Specifications
### **1. Coordinate System**
| Item | Value |
|------|-------|
| Web Origin | Top-Left (0,0) |
| Layout Origin | Bottom-Left (0,0) |
| Transform | `WebY = ImageHeight - LayoutY` |
| Robot Position | Từ StateMsg (x, y, theta) trong world coordinates |
### **2. SVG Layers (Bottom → Top)**
1. Background Image (SLAM Map)
2. Grid (optional)
3. Edges (layout edges)
4. Nodes (layout nodes)
5. Robot Paths (optional, nếu Show Path = true)
6. Robots (robot images với position và rotation)
7. Robot Names (optional, nếu Show Name = true)
8. Selection Highlight (ring around selected robot)
### **3. Robot Display**
| Property | Source | Type |
|----------|--------|------|
| RobotId | StateMsg.SerialNumber | string |
| Position (X, Y) | StateMsg.Pose.X, StateMsg.Pose.Y | double (meters) |
| Orientation (Theta) | StateMsg.Pose.Theta | double (radians) |
| Image | RobotModel.Image (từ RobotModelId) | base64 string |
| Model Info | RobotDto.ModelId → RobotModelDto | DTO |
| BatteryState | StateMsg.BatteryState | BatteryState |
| Visualization | VisualizationMsg | VisualizationMsg |
| Errors | StateMsg.Errors | Error[] |
| Informations | StateMsg.Information | Information[] |
### **4. Viewport Controls**
| Control | Behavior |
|--------|----------|
| Pan | Middle mouse drag |
| Zoom | Mouse wheel (zoom at cursor position) |
| ZoomIn | Toolbar button (zoom at center) |
| ZoomOut | Toolbar button (zoom at center) |
| FitScale | Fit to image bounds |
| Focus | Center view on selected robot |
### **5. Display Settings**
| Setting | Default | Persist |
|---------|---------|---------|
| Show Grid | ✅ | Session |
| Show Background | ✅ | Session |
| Show Path | ❌ | Session |
| Show Name | ✅ | Session |
| FollowRobot | ❌ | Session |
| RobotInfoPanelExpanded | ✅ | Session |
| Selected Layout | - | Session |
| Selected Version | - | Session |
| Selected Level | - | Session |
| Selected Robot | - | Session |
---
## 🔄 Data Flow
### **1. Initialization Flow**
```
User navigates to /robot-monitor
→ RobotMonitorComponent loads
→ RobotMonitorState.InitializeAsync()
├── Load Layouts (from API)
├── Load Versions (from selected Layout)
├── Load Levels (from selected Version)
├── Load Layout Data (Nodes, Edges, Background Image)
├── Load Robots (from API)
├── Load Robot Models (from API, for images)
└── Connect SignalR
└── Subscribe to all robots
→ Viewport initialized to fit image bounds
```
### **2. SignalR Update Flow (Broadcast từ Server)**
```
Server broadcasts StateMsg và VisualizationMsg (1Hz)
→ RobotStateHubClient.OnStateUpdate event
→ RobotStateHubClient.OnVisualizationUpdate event
→ RobotMonitorState.HandleStateUpdate(StateMsg)
→ RobotMonitorState.HandleVisualizationUpdate(VisualizationMsg)
├── Update robot position/state
├── Update robot visualization
├── Add robot if not exists
└── Remove robot if timeout (no update for X seconds)
→ NotifyStateChanged()
→ UI updates (robot position, info panel)
```
### **3. Robot Selection Flow**
```
User clicks robot on canvas
→ SvgMonitorCanvas.HandleRobotClick(robotId)
→ RobotMonitorState.SelectRobot(robotId)
→ NotifyStateChanged()
→ RobotInfoPanel displays robot info
├── BatteryStateCard.Update(state)
├── VisualizationCard.Update(visualization)
├── ErrorsCard.Update(state)
└── InformationCard.Update(state)
→ If FollowRobot = true → Focus on selected robot
```
### **4. Toolbar Actions Flow**
```
User clicks toolbar button
→ MonitorToolbar.HandleAction(action)
→ RobotMonitorState.Action(action)
├── ZoomIn/Out → Viewport.Zoom()
├── FitScale → Viewport.FitToScreen()
├── Focus → Viewport.FocusOnRobot(selectedRobotId)
├── ToggleExpandPanel → Toggle RobotInfoPanel visibility
└── Toggle settings → Update display options
→ NotifyStateChanged()
→ UI updates
```
---
## 📊 State Management
### **RobotMonitorState Class Structure**
```csharp
public class RobotMonitorState
{
// ===== DATA =====
public Guid? SelectedLayoutId { get; set; }
public Guid? SelectedVersionId { get; set; }
public Guid? SelectedLevelId { get; set; }
public LayoutLevelDto? Level { get; private set; }
public List<NodeDto> Nodes { get; private set; } = new();
public List<EdgeDto> Edges { get; private set; } = new();
public byte[]? BackgroundImage { get; private set; }
// ===== ROBOTS =====
public Dictionary<string, RobotMonitorData> Robots { get; private set; } = new();
public string? SelectedRobotId { get; set; }
// ===== DISPLAY OPTIONS =====
public bool ShowGrid { get; set; } = true;
public bool ShowBackgroundImage { get; set; } = true;
public bool ShowPath { get; set; } = false;
public bool ShowName { get; set; } = true;
public bool FollowRobot { get; set; } = false;
public bool RobotInfoPanelExpanded { get; set; } = true;
// ===== VIEWPORT =====
public ViewportState Viewport { get; } = new();
// ===== SIGNALR =====
private RobotStateHubClient? _hubClient;
// ===== EVENTS =====
public event Action? OnStateChanged;
// ===== METHODS =====
public async Task InitializeAsync();
public void HandleStateUpdate(StateMsg state);
public void HandleVisualizationUpdate(VisualizationMsg visualization);
public void SelectRobot(string? robotId);
public void ZoomIn();
public void ZoomOut();
public void FitToScreen();
public void FocusOnRobot(string robotId);
public void ToggleFollowRobot();
public void ToggleRobotInfoPanel();
// ... other methods
}
```
### **RobotMonitorData Class**
```csharp
public class RobotMonitorData
{
public string RobotId { get; set; } = string.Empty;
public Guid? ModelId { get; set; }
public string? ModelImageBase64 { get; set; }
public double X { get; set; }
public double Y { get; set; }
public double Theta { get; set; } // radians
public StateMsg? LastState { get; set; }
public VisualizationMsg? LastVisualization { get; set; }
public DateTime LastUpdateTime { get; set; }
public List<(double X, double Y)>? Path { get; set; } // For path visualization
}
```
---
## 🎨 Component Details (MudBlazor)
### **1. RobotMonitorComponent.razor**
**Purpose:** Main container component using MudBlazor
**Structure:**
```razor
<MudContainer MaxWidth="MaxWidth.False" Class="robot-monitor-container">
<MudGrid Spacing="0">
<!-- Left: Toolbar + Canvas -->
<MudItem xs="12" md="@(State.RobotInfoPanelExpanded ? 8 : 12)">
<MudStack Spacing="0">
<!-- Toolbar -->
<MonitorToolbar State="@State" />
<!-- Canvas -->
<SvgMonitorCanvas State="@State" />
</MudStack>
</MudItem>
<!-- Right: Robot Info Panel -->
@if (State.RobotInfoPanelExpanded)
{
<MudItem xs="12" md="4">
<RobotInfoPanel State="@State" />
</MudItem>
}
</MudGrid>
</MudContainer>
```
**Responsibilities:**
- Initialize state
- Setup SignalR connection
- Handle component lifecycle
- Subscribe/unsubscribe to SignalR events
---
### **2. MonitorToolbar.razor**
**Purpose:** Toolbar with all controls using MudBlazor
**Components:**
- **Buttons:** ZoomIn, ZoomOut, FitScale, Focus, Expand/Collapse Panel
- **Checkboxes:** FollowRobot, Show Path, Show Name, Show Grid
- **SelectBoxes:** Layout, Version, Level, Robot
**Layout:**
```razor
<MudPaper Class="pa-2" Elevation="2">
<MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
<!-- Viewport Controls -->
<MudButtonGroup>
<MudIconButton Icon="@Icons.Material.Filled.ZoomIn"
OnClick="HandleZoomIn" />
<MudIconButton Icon="@Icons.Material.Filled.ZoomOut"
OnClick="HandleZoomOut" />
<MudIconButton Icon="@Icons.Material.Filled.FitScreen"
OnClick="HandleFitScale" />
<MudIconButton Icon="@Icons.Material.Filled.CenterFocusStrong"
OnClick="HandleFocus" />
</MudButtonGroup>
<MudDivider Vertical="true" />
<!-- Display Options -->
<MudCheckBox @bind-Checked="State.FollowRobot"
Label="Follow Robot" />
<MudCheckBox @bind-Checked="State.ShowPath"
Label="Show Path" />
<MudCheckBox @bind-Checked="State.ShowName"
Label="Show Name" />
<MudCheckBox @bind-Checked="State.ShowGrid"
Label="Show Grid" />
<MudDivider Vertical="true" />
<!-- SelectBoxes -->
<MudSelect @bind-Value="State.SelectedLayoutId"
Label="Layout"
T="Guid?" />
<MudSelect @bind-Value="State.SelectedVersionId"
Label="Version"
T="Guid?" />
<MudSelect @bind-Value="State.SelectedLevelId"
Label="Level"
T="Guid?" />
<MudSelect @bind-Value="State.SelectedRobotId"
Label="Robot"
T="string?" />
<!-- Expand/Collapse Panel Button (cạnh phía InfoPanel) -->
<MudSpacer />
<MudIconButton Icon="@(State.RobotInfoPanelExpanded ? Icons.Material.Filled.ChevronRight : Icons.Material.Filled.ChevronLeft)"
OnClick="HandleTogglePanel" />
</MudStack>
</MudPaper>
```
**Responsibilities:**
- Handle toolbar button clicks
- Handle checkbox toggles
- Handle selectbox changes
- Update state accordingly
---
### **3. SvgMonitorCanvas.razor**
**Purpose:** SVG canvas for rendering layout and robots
**Rendering Layers:**
1. Background Image
2. Grid (if ShowGrid = true)
3. Edges
4. Nodes
5. Robot Paths (if ShowPath = true)
6. Robots (images with rotation)
7. Robot Names (if ShowName = true)
8. Selection Highlight
**Event Handling:**
- **Mouse Wheel:** Zoom
- **Middle Mouse Drag:** Pan
- **Robot Click:** Select robot
- **No other interactions** (unlike LayoutEditor)
**Robot Rendering:**
- Robot image positioned at (X, Y) from StateMsg
- Rotated by Theta (radians)
- Image from RobotModel (cached in state)
- Scale based on robot model dimensions and zoom level
**Responsibilities:**
- Render layout (background, grid, nodes, edges)
- Render robots with correct position and rotation
- Handle viewport interactions (zoom, pan)
- Handle robot selection
---
### **4. RobotInfoPanel.razor**
**Purpose:** Display information about selected robot using MudBlazor
**Structure:**
```razor
<MudPaper Class="pa-4" Elevation="2" Style="height: calc(100vh - 100px); overflow-y: auto;">
<MudText Typo="Typo.h6" Class="mb-4">Robot Information</MudText>
@if (State.SelectedRobotId != null && State.Robots.TryGetValue(State.SelectedRobotId, out var robot))
{
<SelectedRobotInfo RobotData="robot" State="State" />
}
else
{
<MudAlert Severity="Severity.Info">
No robot selected. Click on a robot to view its information.
</MudAlert>
}
</MudPaper>
```
**Responsibilities:**
- Display selected robot information
- Update when selection changes
- Show robot state details
---
### **5. SelectedRobotInfo.razor**
**Purpose:** Display detailed robot information using MudBlazor Expansion Panels
**Structure:**
```razor
<MudExpansionPanels Dense="true" Elevation="0">
<!-- Battery State Panel -->
<MudExpansionPanel Text="Battery State" Icon="@Icons.Material.Filled.BatteryChargingFull" Expanded="true">
<BatteryStateCard State="@robotData.LastState" />
</MudExpansionPanel>
<!-- Visualization Panel -->
<MudExpansionPanel Text="Visualization" Icon="@Icons.Material.Filled.Visibility" Expanded="false">
<VisualizationCard Visualization="@robotData.LastVisualization" />
</MudExpansionPanel>
<!-- Errors Panel -->
<MudExpansionPanel Text="Errors" Icon="@Icons.Material.Filled.Error" Expanded="false">
<ErrorsCard State="@robotData.LastState" />
</MudExpansionPanel>
<!-- Information Panel -->
<MudExpansionPanel Text="Information" Icon="@Icons.Material.Filled.Info" Expanded="false">
<InformationCard State="@robotData.LastState" />
</MudExpansionPanel>
</MudExpansionPanels>
```
**Information Displayed:**
- **BatteryState:** Charge, Voltage, Health, Charging status (từ StateMsg.BatteryState)
- **Visualization:** Visualization data (từ VisualizationMsg)
- **Errors:** Error list (từ StateMsg.Errors)
- **Informations:** Information list (từ StateMsg.Information)
**Responsibilities:**
- Format and display robot data in tabs
- Update in real-time when state changes
- Reuse existing card components (BatteryCard, ErrorsCard, InformationCard)
---
### **6. BatteryStateCard.razor**
**Purpose:** Display battery state information
**Reuse:** Similar to `RobotDetail/BatteryCard.razor`
**Display:**
- Battery Charge (progress bar + percentage)
- Battery Voltage
- Battery Health
- Charging status (chip)
---
### **7. VisualizationCard.razor**
**Purpose:** Display visualization information from VisualizationMsg
**Display:**
- Visualization data from VisualizationMsg
- Format similar to other cards
---
### **8. ErrorsCard.razor**
**Purpose:** Display errors list
**Reuse:** Similar to `RobotDetail/ErrorsCard.razor`
**Display:**
- MudTable với columns: Error Type, Level, Description, Hint, References
- Color coding by ErrorLevel (NONE=Success, WARNING=Warning, FATAL=Error)
---
### **9. InformationCard.razor**
**Purpose:** Display information list
**Reuse:** Similar to `RobotDetail/InformationCard.razor`
**Display:**
- MudTable với columns: Info Type, Level, Description, References
- Color coding by InfoLevel (INFO=Info, DEBUG=Default)
---
## 🔌 SignalR Integration
### **Subscription Strategy**
**Subscribe to All Robots (Broadcast từ Server)**
- Get list of all robots from API
- Subscribe to each robot individually
- Handle add/remove robots dynamically
- **Server broadcasts StateMsg và VisualizationMsg đến tất cả subscribed clients**
**Implementation:**
```csharp
private async Task SubscribeToAllRobots()
{
// Get all robots from API
var robots = await RobotApiService.GetAllAsync();
foreach (var robot in robots)
{
await _hubClient.SubscribeToRobotAsync(robot.RobotId);
}
}
```
### **Update Handling (Broadcast từ Server)**
```csharp
private void HandleStateUpdate(StateMsg state)
{
var robotId = state.SerialNumber;
// Get or create robot data
if (!Robots.TryGetValue(robotId, out var robotData))
{
// Load robot model image
robotData = new RobotMonitorData
{
RobotId = robotId,
ModelId = GetRobotModelId(robotId), // From RobotDto
ModelImageBase64 = await LoadRobotModelImage(robotId)
};
Robots[robotId] = robotData;
}
// Update position and state
robotData.X = state.Pose?.X ?? 0;
robotData.Y = state.Pose?.Y ?? 0;
robotData.Theta = state.Pose?.Theta ?? 0;
robotData.LastState = state;
robotData.LastUpdateTime = DateTime.UtcNow;
// Update path if ShowPath = true
if (ShowPath)
{
UpdateRobotPath(robotData);
}
// If FollowRobot and this is selected robot, update viewport
if (FollowRobot && SelectedRobotId == robotId)
{
FocusOnRobot(robotId);
}
NotifyStateChanged();
}
private void HandleVisualizationUpdate(VisualizationMsg visualization)
{
var robotId = visualization.SerialNumber;
if (Robots.TryGetValue(robotId, out var robotData))
{
robotData.LastVisualization = visualization;
robotData.LastUpdateTime = DateTime.UtcNow;
NotifyStateChanged();
}
}
```
### **Robot Timeout (Remove Inactive Robots)**
```csharp
private void RemoveInactiveRobots()
{
var timeout = TimeSpan.FromSeconds(10); // 10 seconds timeout
var now = DateTime.UtcNow;
var inactiveRobots = Robots
.Where(kvp => now - kvp.Value.LastUpdateTime > timeout)
.Select(kvp => kvp.Key)
.ToList();
foreach (var robotId in inactiveRobots)
{
Robots.Remove(robotId);
if (SelectedRobotId == robotId)
{
SelectedRobotId = null;
}
}
if (inactiveRobots.Count > 0)
{
NotifyStateChanged();
}
}
```
---
## 🎯 Viewport Operations
### **Zoom**
- Similar to LayoutEditor
- Zoom at cursor position (mouse wheel)
- Zoom at center (toolbar buttons)
- Limit zoom level (0.1x to 10x)
### **Pan**
- Middle mouse drag
- Incremental delta (like LayoutEditor fix)
### **FitToScreen**
- Fit viewport to image bounds
- Similar to LayoutEditor
### **FocusOnRobot**
- Center viewport on selected robot position
- Optional: Zoom to fit robot (or keep current zoom)
```csharp
public void FocusOnRobot(string robotId)
{
if (!Robots.TryGetValue(robotId, out var robot))
return;
// Center viewport on robot
var (physicalWidth, physicalHeight) = GetPhysicalDimensions();
var svgX = WorldToSvg(robot.X, robot.Y).X;
var svgY = WorldToSvg(robot.X, robot.Y).Y;
Viewport.ViewBoxX = svgX - Viewport.ViewBoxWidth / 2;
Viewport.ViewBoxY = svgY - Viewport.ViewBoxHeight / 2;
NotifyStateChanged();
}
```
---
## 🖼️ Robot Image Rendering
### **Image Loading**
- Load robot model image when robot is first added
- Cache images in state (Dictionary<Guid, string> for base64)
- Load from API: `RobotModelApiService.GetImageAsync(modelId)`
### **Image Positioning**
- Position at (X, Y) from StateMsg
- Convert world coordinates to SVG coordinates
- Apply rotation by Theta (radians)
### **Image Scaling**
- Scale based on robot model dimensions (Length, Width)
- Adjust for zoom level
- Maintain aspect ratio
### **SVG Implementation**
```xml
<g transform="translate(@svgX, @svgY) rotate(@degrees)">
<image href="data:image/png;base64,@robotData.ModelImageBase64"
x="@(-robotModel.Length/2)"
y="@(-robotModel.Width/2)"
width="@robotModel.Length"
height="@robotModel.Width"
preserveAspectRatio="xMidYMid" />
</g>
```
---
## 📝 Key Design Decisions
### **1. Robot Data Management**
- **Decision:** Store robot data in Dictionary<string, RobotMonitorData>
- **Rationale:** Fast lookup by robotId, easy add/remove
### **2. SignalR Subscription**
- **Decision:** Subscribe to all robots individually, receive broadcast từ Server
- **Rationale:** More control, can unsubscribe specific robots, Server broadcasts to all subscribed clients
### **3. Robot Timeout**
- **Decision:** Remove robots after 10 seconds of no updates
- **Rationale:** Clean up inactive robots, avoid stale data
### **4. Follow Robot**
- **Decision:** Auto-update viewport when selected robot moves (if enabled)
- **Rationale:** Better UX for tracking specific robot
### **5. Path Visualization**
- **Decision:** Store path as list of (X, Y) points
- **Rationale:** Simple, can draw as polyline
### **6. MudBlazor Components**
- **Decision:** Use MudBlazor for all UI components
- **Rationale:** Consistent with existing codebase, faster development
### **7. Panel Expand/Collapse**
- **Decision:** Button on toolbar to toggle RobotInfoPanel visibility
- **Rationale:** More screen space for canvas when needed
---
## 🔄 API Integration
### **APIs Used**
1. **Layout APIs:**
- `GET /api/layouts` - Get all layouts
- `GET /api/layouts/{layoutId}/versions` - Get versions
- `GET /api/layouts/{layoutId}/versions/{versionId}/levels` - Get levels
- `GET /api/layouts/{layoutId}/levels/{levelId}` - Get level info
- `GET /api/layouts/{layoutId}/levels/{levelId}/data` - Get layout data
- `GET /api/layouts/{layoutId}/levels/{levelId}/background-image` - Get background image
2. **Robot APIs:**
- `GET /api/robots` - Get all robots
- `GET /api/robots/{id}` - Get robot by ID
3. **Robot Model APIs:**
- `GET /api/robot-models/{id}` - Get robot model
- `GET /api/robot-models/{id}/image` - Get robot model image
---
## 📊 Implementation Phases
### **Phase 1: Foundation (Core Structure)**
**Status:** ❌ Not Started
**Deliverables:**
- [ ] `RobotMonitorState.cs` - Centralized state management
- [ ] `RobotMonitorComponent.razor` - Main container với MudBlazor layout
- [ ] Basic layout structure (left: toolbar+canvas, right: info panel)
- [ ] Host page: `RobotMonitor.razor` với route `/robot-monitor`
- [ ] CSS files for styling
**Key Features:**
- State management structure
- MudBlazor container và grid layout
- Basic component hierarchy
---
### **Phase 2: Toolbar**
**Status:** ❌ Not Started
**Deliverables:**
- [ ] `MonitorToolbar.razor` - Full toolbar với MudBlazor components
- [ ] Layout/Version/Level/Robot selectboxes (MudSelect)
- [ ] Zoom/Pan/FitScale/Focus buttons (MudIconButton)
- [ ] Display options checkboxes (MudCheckBox)
- [ ] Expand/Collapse Panel button
**Key Features:**
- All toolbar controls
- Event handlers
- State updates
---
### **Phase 3: SVG Canvas (Basic Layout)**
**Status:** ❌ Not Started
**Deliverables:**
- [ ] `SvgMonitorCanvas.razor` - SVG rendering component
- [ ] Background image rendering
- [ ] Grid rendering (togglable)
- [ ] Nodes and edges rendering
- [ ] Viewport controls (zoom, pan) - reuse logic from LayoutEditor
**Key Features:**
- Layout rendering
- Viewport interactions
- Coordinate transformations
---
### **Phase 4: Robot Display**
**Status:** ❌ Not Started
**Deliverables:**
- [ ] Robot image loading and caching
- [ ] Robot rendering with position and rotation
- [ ] Robot selection (click to select)
- [ ] Selection highlight
**Key Features:**
- Robot image display
- Position và rotation
- Click selection
---
### **Phase 5: SignalR Integration**
**Status:** ❌ Not Started
**Deliverables:**
- [ ] SignalR connection setup
- [ ] Subscribe to all robots
- [ ] Handle StateMsg updates (broadcast từ Server)
- [ ] Handle VisualizationMsg updates (broadcast từ Server)
- [ ] Add/remove robots dynamically
- [ ] Robot timeout handling
**Key Features:**
- Real-time updates
- Broadcast handling
- Dynamic robot management
---
### **Phase 6: Robot Info Panel - Basic**
**Status:** ❌ Not Started
**Deliverables:**
- [ ] `RobotInfoPanel.razor` - Container với MudBlazor
- [ ] `SelectedRobotInfo.razor` - Main info component với MudTabs
- [ ] Basic structure for tabs
**Key Features:**
- Panel layout
- Tab structure
---
### **Phase 7: Robot Info Panel - Content**
**Status:** ❌ Not Started
**Deliverables:**
- [ ] `BatteryStateCard.razor` - Battery state display (reuse từ RobotDetail)
- [ ] `VisualizationCard.razor` - Visualization display
- [ ] `ErrorsCard.razor` - Errors display (reuse từ RobotDetail)
- [ ] `InformationCard.razor` - Information display (reuse từ RobotDetail)
- [ ] Real-time updates khi state changes
**Key Features:**
- All information cards
- Real-time updates
- MudBlazor components
---
### **Phase 8: Advanced Features**
**Status:** ❌ Not Started
**Deliverables:**
- [ ] Follow Robot mode
- [ ] Path visualization
- [ ] Robot name display
- [ ] Focus on robot
- [ ] Panel expand/collapse animation
**Key Features:**
- Advanced viewport features
- Path tracking
- UX improvements
---
### **Phase 9: Polish**
**Status:** ❌ Not Started
**Deliverables:**
- [ ] Error handling
- [ ] Loading states
- [ ] Performance optimization
- [ ] UI/UX improvements
- [ ] Responsive design
**Key Features:**
- Production-ready features
- Performance tuning
- User experience
---
## 🎯 Next Steps
1. **Review and approve architecture**
2. **Start Phase 1: Foundation**
3. **Iterate through phases**
---
**Last Updated:** 2024-12-XX
**Status:** Design Phase - Awaiting Approval
**Framework:** MudBlazor

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,625 @@
# VDA5050 Robot Management Architecture
## 📋 Tổng quan / Overview
Tài liệu này mô tả kiến trúc hệ thống quản lý nhiều robot theo tiêu chuẩn VDA5050 trong FleetManager. Hệ thống được thiết kế để quản lý tối đa 203 robots với single FleetManager instance.
## 🎯 Mục tiêu / Goals
- Quản lý kết nối MQTT với nhiều robots theo VDA5050
- Quản lý state, order, action của từng robot (in-memory, latest only)
- Cung cấp high-level APIs để điều khiển robot
- Real-time updates qua SignalR
- Auto-discovery robots qua connection/state messages
## 🏗️ Kiến trúc Tổng thể / System Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ FleetManager Instance │
│ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ RobotConnections Service │ │
│ │ - MQTT Client (single instance) │ │
│ │ - Subscribe topics (wildcard) │ │
│ │ - Publish orders/instantActions │ │
│ │ - Message routing by SerialNumber │ │
│ └──────────────────┬───────────────────────────────────┘ │
│ │ │
│ │ Event Bus │
│ │ │
│ ┌──────────────────▼───────────────────────────────────┐ │
│ │ RobotManager Service │ │
│ │ - Quản lý RobotController instances │ │
│ │ - Subscribe events từ RobotConnections │ │
│ │ - Update RobotData vào RobotController │ │
│ │ - Timeout monitoring (30s) │ │
│ │ - Auto-create RobotController khi discover robot │ │
│ └──────────────────┬───────────────────────────────────┘ │
│ │ │
│ ┌──────────────────▼───────────────────────────────────┐ │
│ │ RobotController (Instance per Robot) │ │
│ │ - Chứa RobotData của robot │ │
│ │ - Methods: MoveToNode(), SendInstantAction(), etc. │ │
│ │ - Thread-safe với lock │ │
│ └──────────────────┬───────────────────────────────────┘ │
│ │ │
│ ┌──────────────────▼───────────────────────────────────┐ │
│ │ SignalR Hub (RobotStateHub) │ │
│ │ - Broadcast state changes │ │
│ │ - Per-robot subscriptions │ │
│ └──────────────────────────────────────────────────────┘ │
└──────────────────────────┬───────────────────────────────────┘
│ MQTT
┌──────────────────┴──────────────────┐
│ │
┌───────▼────────┐ ┌─────────▼────────┐
│ MQTT Broker │ │ Robot Fleet │
│ │ │ (203 robots) │
└────────────────┘ └─────────────────┘
```
## 📦 Module Structure
### 1. RobotConnections Service
**Trách nhiệm:**
- Quản lý MQTT client connection (single instance)
- Subscribe topics với wildcard pattern
- Deserialize và route messages dựa trên SerialNumber
- Publish orders và instantActions đến robots
- Validate SerialNumber tồn tại trong database trước khi xử lý
**MQTT Topics:**
**Subscribe (wildcard):**
- `uagv/v2/{Manufacturer}/+/state` (QoS 0, Retain: true)
- `uagv/v2/{Manufacturer}/+/connection` (QoS 1, Retain: true)
- `uagv/v2/{Manufacturer}/+/visualization` (QoS 0, Retain: false)
- `uagv/v2/{Manufacturer}/+/factsheet` (QoS 0, Retain: true)
**Publish:**
- `uagv/v2/{Manufacturer}/{SerialNumber}/order` (QoS 1, Retain: false)
- `uagv/v2/{Manufacturer}/{SerialNumber}/instantActions` (QoS 1, Retain: false)
**Configuration (appsettings.json):**
```json
{
"VDA5050": {
"MqttBroker": {
"Host": "localhost",
"Port": 1883,
"Username": "",
"Password": "",
"EnablePassword": false,
"EnableTls": false,
"CaCertificatesPath": "",
"ClientCertificatePath": "",
"ClientKeyPath": ""
},
"Protocol": {
"Manufacturer": "RobotNet",
"Version": "2.1.0",
"TopicPrefix": "uagv/v2"
}
}
}
```
**Interfaces:**
```csharp
public interface IRobotConnectionsService
{
Task StartAsync(CancellationToken cancellationToken = default);
Task StopAsync(CancellationToken cancellationToken = default);
bool IsConnected();
Task<bool> PublishOrderAsync(string robotId, OrderMsg order, CancellationToken cancellationToken = default);
Task<bool> PublishInstantActionsAsync(string robotId, InstantActionsMsg instantActions, CancellationToken cancellationToken = default);
}
```
### 2. RobotManager Service
**Trách nhiệm:**
- Quản lý `RobotController` instances (mỗi robot có 1 instance)
- Subscribe events từ RobotConnectionsService qua Event Bus
- Route events đến đúng RobotController instance và update RobotData
- Auto-create RobotController khi nhận Connection/State message đầu tiên (sau khi validate có trong DB)
- Timeout monitoring: Check mỗi 15s, nếu 30s không có State hoặc Visualization → set ConnectionState = OFFLINE
- Remove RobotController khi robotId bị xóa khỏi DB
**Data Structures (In-Memory):**
```csharp
// RobotController instances per robot
ConcurrentDictionary<string, IRobotController> // Key: RobotId (SerialNumber)
```
**Timeout Monitoring:**
- Sử dụng `WatchTimerAsync` từ RobotNet10.Common
- Check interval: 15 giây
- Timeout threshold: 30 giây không có State hoặc Visualization message
- Reset timeout riêng biệt cho State và Visualization
- Khi timeout: Set `ConnectionState = OFFLINE` trong RobotController.RobotData
- Không cần retry/reconnect/event notification
**RobotController Lifecycle:**
- **Creation**: Tạo khi nhận Connection/State message đầu tiên và SerialNumber tồn tại trong DB
- **Deletion**: Xóa khi robotId bị xóa khỏi DB (service xóa robot sẽ inject RobotManagerService và gọi `RemoveRobotController(robotId)`)
- **Dispose**: RobotController implement IDisposable để cleanup resources
**Interfaces:**
```csharp
public interface IRobotManagerService
{
// RobotController Management
IRobotController? GetRobotController(string robotId);
IReadOnlyDictionary<string, IRobotController> GetAllRobotControllers();
void RemoveRobotController(string robotId);
// Backward compatibility (delegate to RobotController)
RobotData? GetRobotData(string robotId);
IReadOnlyDictionary<string, RobotData> GetAllRobotData();
IReadOnlyList<string> GetAvailableRobots(); // Robots với IsOnline == true
}
```
### 3. RobotController (Instance per Robot)
**Trách nhiệm:**
- Mô hình hóa thông tin của 1 robot, định danh bằng RobotId (SerialNumber)
- Không phải service, mà là instance với mỗi robot
- Chứa thông tin robot gửi lên (RobotData)
- Chứa các functions để xử lý và publish xuống robot
- Thread-safe với lock cho các methods gửi order/instantAction
**Properties:**
```csharp
public interface IRobotController : IDisposable
{
string RobotId { get; } // SerialNumber
RobotData RobotData { get; } // Tất cả thông tin robot
bool IsOnline { get; } // Derived từ ConnectionState
}
```
**Methods (Thread-safe với lock):**
```csharp
public interface IRobotController
{
// Robot Control
Task<bool> MoveToNodeAsync(string nodeName, CancellationToken cancellationToken = default);
Task<bool> SendInstantActionAsync(Action action, CancellationToken cancellationToken = default);
Task<bool> SendOrderAsync(OrderMsg order, CancellationToken cancellationToken = default);
Task<bool> SendInstantActionsAsync(InstantActionsMsg instantActions, CancellationToken cancellationToken = default);
Task<bool> RequestFactsheetAsync(CancellationToken cancellationToken = default);
Task<bool> RequestStateAsync(CancellationToken cancellationToken = default);
Task<bool> CancelOrderAsync(CancellationToken cancellationToken = default);
}
```
**Dependencies (Injected):**
- `IRobotConnectionsService` - Để publish messages
- `IConfigManager` - Để lấy VDA5050 config (Manufacturer, Version)
- `Logger<RobotController>` - Để logging
- `IRobotManagerService` - (Optional) Để tự xóa khi cần
**MoveToNode Implementation:**
- Implement cơ bản: Tạo OrderMsg đơn giản với 1 node (target node)
- Có thể inject `ITrafficControlService` sau để tính route phức tạp hơn
- Sẽ được implement trong cuộc hội thoại khác
**Thread-Safety:**
- Lock các methods có thể gửi order hoặc instantAction xuống robot
- Không cần lock RobotData (read-only access từ bên ngoài)
- RobotManagerService update RobotData trực tiếp (thread-safe dictionary)
### 4. Event Bus System
**Trách nhiệm:**
- In-memory event system để communication giữa modules
- Decouple RobotConnections và RobotManager
- Sử dụng C# event pattern
**Events:**
```csharp
public interface IRobotEventBus
{
event EventHandler<StateMessageReceivedEvent>? StateMessageReceived;
event EventHandler<ConnectionStateChangedEvent>? ConnectionStateChanged;
event EventHandler<VisualizationMessageReceivedEvent>? VisualizationMessageReceived;
event EventHandler<FactsheetMessageReceivedEvent>? FactsheetMessageReceived;
void PublishStateMessageReceived(string robotId, StateMsg stateMsg);
void PublishConnectionStateChanged(string robotId, ConnectionState connectionState);
void PublishVisualizationMessageReceived(string robotId, Visualizationmsg visualizationMsg);
void PublishFactsheetMessageReceived(string robotId, FactSheetMsg factsheetMsg);
}
```
**Event Classes:**
- `StateMessageReceivedEvent` - Khi nhận state message từ robot
- `ConnectionStateChangedEvent` - Khi connection state thay đổi
- `VisualizationMessageReceivedEvent` - Khi nhận visualization message
- `FactsheetMessageReceivedEvent` - Khi nhận factsheet message
### 5. SignalR Hub
**Trách nhiệm:**
- Broadcast real-time updates đến WebUI clients
- Support per-robot subscriptions
- Broadcast tất cả state changes
**Hub Methods:**
- `SubscribeToRobot(string robotId)` - Subscribe updates cho 1 robot
- `UnsubscribeFromRobot(string robotId)` - Unsubscribe
**Broadcast:**
- Broadcast tất cả state changes đến tất cả clients
- Group: `robot:{robotId}` cho subscription per robot
## 🔄 Data Flow
### State Message Flow
```
Robot → MQTT Broker → RobotConnectionsService
→ Deserialize & Validate SerialNumber exists in DB
→ Publish StateMessageReceivedEvent via Event Bus
→ RobotManagerService receives event
→ Tìm RobotController instance theo RobotId
→ Update RobotData.State vào RobotController
→ Determine OrderStatus từ State message
→ Broadcast via SignalR Hub
→ WebUI Clients receive update
```
### Order Flow
```
ScriptEngine/WebUI → RobotManagerService.GetRobotController(robotId)
→ robotController.MoveToNode("NodeA")
→ RobotController tính toán route (cơ bản)
→ Tạo OrderMsg
→ RobotConnectionsService.PublishOrderAsync()
→ MQTT Broker → Robot
→ Robot processes order
→ Robot sends State message with orderId/orderUpdateId
→ RobotManagerService updates RobotData vào RobotController
→ Determine OrderStatus (Accepted, Completed, etc.)
```
### Connection State Flow
```
Robot → MQTT Broker (connection message)
→ RobotConnectionsService
→ Publish ConnectionStateChangedEvent
→ RobotManagerService receives event
→ Tìm hoặc tạo RobotController instance
→ Update RobotData.ConnectionState vào RobotController
→ SignalR broadcasts update
```
### RobotController Creation Flow
```
Robot → MQTT Broker (connection/state message)
→ RobotConnectionsService
→ Validate SerialNumber exists in DB
→ Publish event via Event Bus
→ RobotManagerService receives event
→ Check if RobotController exists
→ If not exists: Create new RobotController instance
→ Inject dependencies (IRobotConnectionsService, IConfigManager, Logger)
→ Add to ConcurrentDictionary<string, IRobotController>
→ Update RobotData vào RobotController
```
## 📊 Data Models
### RobotData
```csharp
public class RobotData
{
public string RobotId { get; set; } // SerialNumber
public StateMsg? State { get; set; } // Latest State message
public ConnectionState ConnectionState { get; set; }
public OrderMsg? Order { get; set; } // Latest Order message
public OrderStatus OrderStatus { get; set; } // Order status tracking
public FactSheetMsg? Factsheet { get; set; } // Latest Factsheet
public VisualizationMsg? Visualization { get; set; } // Latest Visualization
public DateTime LastUpdated { get; set; } // Last update timestamp
}
```
### OrderStatus
```csharp
public enum OrderStatus
{
Pending, // Order đã tạo nhưng chưa gửi
Sent, // Order đã gửi qua MQTT
Accepted, // Robot đã accept order (orderId và orderUpdateId khớp)
Rejected, // Robot reject order (error với errorReferences)
Completed, // Order hoàn thành (nodeStates và edgeStates empty)
Failed // Order failed (FATAL error liên quan đến order)
}
```
**Order Status Determination Logic:**
- **Accepted**: `orderId``orderUpdateId` trong state khớp với order đã gửi
- **Rejected (Error)**: Có error với `errorReferences` chứa `orderId` hoặc `orderUpdateId` → Log và hủy order (không retry)
- **Completed**: `nodeStates``edgeStates` empty, `orderId` khác rỗng
- **Failed**: Có error FATAL liên quan đến order
## 🔍 Robot Discovery
**Auto-Discovery:**
- Khi nhận connection/state message với SerialNumber
- Kiểm tra SerialNumber có trong database không (qua IRobotService)
- Nếu không có → Bỏ qua message (không tự động tạo robot)
- Nếu có → Xử lý message và update state
**Mapping:**
- `SerialNumber` (từ VDA5050) = `RobotId` (trong database)
## ⚙️ Configuration
### MQTT Configuration
- Lưu trong `appsettings.json` section `VDA5050`
- Bao gồm: Host, Port, Username, Password, TLS settings, Manufacturer, Version, TopicPrefix
### Service Registration
- `IRobotConnectionsService` → Singleton
- `IRobotManagerService` → Singleton
- `IRobotEventBus` → Singleton
- `RobotController` instances → Managed by RobotManagerService (không register trong DI)
## 🔄 Retry Logic
**Order Rejection Handling:**
- **Reject do Error**: Log và hủy order (không retry)
- **Reject do Connection/Timeout**: Retry với exponential backoff
- Retry cho đến khi có hành động hủy bỏ
## 📡 Factsheet Handling
- Subscribe factsheet topic với wildcard
- Lưu factsheet per robot khi nhận được
- Có thể request factsheet bằng instant action `factsheetRequest`
- Factsheet được retain trên MQTT broker
## 🎯 Performance Considerations
**Với 203 robots:**
- State messages: ~1,015 messages/second (5 Hz per robot)
- Visualization: ~406 messages/second (2 Hz per robot)
- Total inbound: ~1,500 messages/second
- Estimated CPU: ~2.25 cores for message processing
- Memory: ~1-2 GB (in-memory state + overhead)
**Optimization:**
- In-memory storage (no database writes for state)
- Single MQTT client (no connection pool needed)
- Event-driven architecture (async processing)
## 🔐 Security Considerations
- MQTT TLS support (optional)
- Certificate-based authentication (optional)
- SerialNumber validation (must exist in database)
- No auto-creation of robots from messages
## 📝 Notes
- **Single Instance**: FleetManager chạy single instance (không cần HA)
- **In-Memory Queue**: Sử dụng Channel<T> cho async processing nếu cần
- **No History**: Chỉ lưu state/order/action mới nhất (không lưu history)
- **RobotController**: Instance per robot, không phải service
- **MoveToNode**: Implement cơ bản (tạo order đơn giản), có thể enhance với TrafficControl sau
- **Timeout Monitoring**: 30s không có State hoặc Visualization → OFFLINE
## 🔗 Dependencies
- `RobotNet.VDA5050` - VDA5050 message models (qua RobotNet10.Common)
- `RobotNet10.Common` - Common utilities (WatchTimerAsync, MQTTClient, etc.)
- `Microsoft.AspNetCore.SignalR` - SignalR for real-time updates
- `IRobotService` - Existing service for robot database operations
## 🚀 Implementation Phases
Công việc được chia thành các phase nhỏ để thực hiện lần lượt:
### Phase 1: Foundation - Configuration & Event Bus
**Mục tiêu:** Thiết lập nền tảng cơ bản
**Tasks:**
- [ ] Tạo MQTT configuration models (`MqttConfig`, `VDA5050ProtocolConfig`, `VDA5050Config`)
- [ ] Thêm VDA5050 section vào `appsettings.json`
- [ ] Tạo Event Bus interface và implementation (`IRobotEventBus`, `RobotEventBus`)
- [ ] Tạo Event classes (`StateMessageReceivedEvent`, `ConnectionStateChangedEvent`, `VisualizationMessageReceivedEvent`, `FactsheetMessageReceivedEvent`)
- [ ] Register Event Bus trong DI container (Singleton)
**Deliverables:**
- Configuration models
- Event Bus system hoàn chỉnh
- Service registration trong Program.cs
---
### Phase 2: RobotConnections Service - Core MQTT
**Mục tiêu:** Implement MQTT client connection và subscription
**Tasks:**
- [ ] Tạo `IRobotConnectionsService` interface
- [ ] Implement `RobotConnectionsService` với MQTT client
- [ ] Load configuration từ appsettings.json
- [ ] Implement `StartAsync()` - Connect to MQTT broker
- [ ] Implement `StopAsync()` - Disconnect from broker
- [ ] Implement `IsConnected()` - Check connection status
- [ ] Subscribe to topics với wildcard pattern:
- `uagv/v2/{Manufacturer}/+/state`
- `uagv/v2/{Manufacturer}/+/connection`
- `uagv/v2/{Manufacturer}/+/visualization`
- `uagv/v2/{Manufacturer}/+/factsheet`
- [ ] Message handler để deserialize messages
- [ ] Validate SerialNumber exists in database (qua IRobotService)
- [ ] Route messages to Event Bus based on message type
- [ ] Register service trong DI container (Singleton)
**Deliverables:**
- RobotConnectionsService hoàn chỉnh
- MQTT connection và subscription working
- Message routing to Event Bus
---
### Phase 3: RobotManager Service - Core Management
**Mục tiêu:** Quản lý RobotController instances và event routing
**Tasks:**
- [ ] Refactor RobotManagerService: Xóa `_robotData` dictionary
- [ ] Thêm `ConcurrentDictionary<string, IRobotController> _robotControllers`
- [ ] Subscribe to Event Bus events
- [ ] Implement event handlers:
- `OnStateMessageReceived` → Tìm RobotController, update RobotData.State, determine OrderStatus
- `OnConnectionStateChanged` → Tìm hoặc tạo RobotController, update ConnectionState
- `OnVisualizationMessageReceived` → Tìm RobotController, update Visualization
- `OnFactsheetMessageReceived` → Tìm RobotController, update Factsheet
- [ ] Implement `GetRobotController(robotId)` - Trả về instance
- [ ] Implement `GetAllRobotControllers()` - Trả về tất cả instances
- [ ] Implement `RemoveRobotController(robotId)` - Xóa instance và dispose
- [ ] Backward compatibility: `GetRobotData()` → delegate to `GetRobotController().RobotData`
- [ ] Register service trong DI container (Singleton)
**Deliverables:**
- RobotManagerService quản lý RobotController instances
- Event routing working
- RobotController creation on first message
---
### Phase 4: RobotController Implementation
**Mục tiêu:** Implement RobotController class (instance per robot)
**Tasks:**
- [ ] Tạo `IRobotController` interface
- [ ] Implement `RobotController` class với IDisposable
- [ ] Properties: `RobotId`, `RobotData`, `IsOnline`
- [ ] Inject dependencies: `IRobotConnectionsService`, `IConfigManager`, `Logger<RobotController>`
- [ ] Implement methods với thread-safe lock:
- `MoveToNodeAsync()` - Tạo OrderMsg đơn giản với 1 node
- `SendInstantActionAsync()` - Gửi instant action
- `SendOrderAsync()` - Gửi order
- `SendInstantActionsAsync()` - Gửi instant actions
- `RequestFactsheetAsync()` - Gửi factsheetRequest action
- `RequestStateAsync()` - Gửi RequestState action
- `CancelOrderAsync()` - Gửi cancelOrder action
- [ ] Implement `Dispose()` để cleanup resources
- [ ] Helper methods: `FillVDA5050Header()`, `GetNextHeaderId()`
**Deliverables:**
- RobotController class hoàn chỉnh
- Thread-safe methods
- All control methods working
---
### Phase 5: Timeout Monitoring
**Mục tiêu:** Monitor robot timeout và set OFFLINE khi cần
**Tasks:**
- [ ] Implement timeout monitoring trong RobotManagerService
- [ ] Sử dụng `WatchTimerAsync` từ RobotNet10.Common
- [ ] Check interval: 15 giây
- [ ] Timeout threshold: 30 giây không có State hoặc Visualization
- [ ] Track last update time riêng biệt cho State và Visualization
- [ ] Reset timeout khi nhận State hoặc Visualization mới
- [ ] Set `ConnectionState = OFFLINE` khi timeout
- [ ] Start timer khi RobotManagerService start
**Deliverables:**
- Timeout monitoring working
- Auto-set OFFLINE khi timeout
---
### Phase 7: SignalR Integration
**Mục tiêu:** Real-time updates đến WebUI
**Tasks:**
- [ ] Update `RobotStateHub` để integrate với RobotManagerService
- [ ] Implement broadcast state changes khi state updated
- [ ] Implement per-robot subscriptions (groups)
- [ ] Broadcast connection state changes
- [ ] Broadcast order status changes
- [ ] Broadcast action status changes
- [ ] Test SignalR connections từ WebUI
**Deliverables:**
- SignalR integration hoàn chỉnh
- Real-time updates working
- WebUI có thể subscribe và nhận updates
---
### Phase 8: Testing & Integration
**Mục tiêu:** Test toàn bộ hệ thống
**Tasks:**
- [ ] Unit tests cho từng service
- [ ] Integration tests cho message flow
- [ ] Test với real MQTT broker
- [ ] Test với multiple robots (simulated)
- [ ] Performance testing (203 robots)
- [ ] Error handling testing
- [ ] Retry logic testing
- [ ] Documentation updates
**Deliverables:**
- Test suite hoàn chỉnh
- System tested và validated
- Documentation updated
---
## 📋 Implementation Checklist
### Phase 1: Foundation ✅
- [ ] Configuration models
- [ ] Event Bus system
- [ ] Service registration
### Phase 2: RobotConnections Core ⏳
- [ ] MQTT client connection
- [ ] Topic subscription
- [ ] Message routing
### Phase 3: RobotManager Core ⏳
- [ ] RobotController instance management
- [ ] Event routing to RobotController
- [ ] Auto-create RobotController
- [ ] Remove RobotController
### Phase 4: RobotController Implementation ⏳
- [ ] IRobotController interface
- [ ] RobotController class
- [ ] Thread-safe methods
- [ ] All control methods
### Phase 5: Timeout Monitoring ⏳
- [ ] WatchTimerAsync integration
- [ ] Timeout check logic
- [ ] Auto-set OFFLINE
### Phase 7: SignalR ⏳
- [ ] Hub integration
- [ ] Broadcast updates
### Phase 8: Testing ⏳
- [ ] Unit tests
- [ ] Integration tests
- [ ] Performance tests
## 📚 Related Documents
- VDA5050_EN.md - VDA5050 protocol specification
- RobotConnections.md - RobotConnections module documentation
- RobotManager.md - RobotManager module documentation

View File

@@ -0,0 +1,64 @@
# FleetManagerConfig Module / Module Cấu hình
## 📋 Overview / Tổng quan
FleetManagerConfig Module quản lý cấu hình động cho hệ thống, cho phép thay đổi cấu hình runtime mà không cần restart.
## 🎯 Mục đích / Purpose
Quản lý các tham số cấu hình cho hệ thống, cho phép thay đổi runtime và lưu trữ trong database.
## 🔧 Chức năng chính / Main Features
- Quản lý cấu hình động cho các services
- Thay đổi cấu hình runtime (không cần restart)
- Lưu trữ cấu hình trong database (thay vì chỉ dùng appsettings.json)
- UI để config các tham số hệ thống
## ⚙️ Cấu hình bao gồm / Configuration Includes
- MQTT broker connection settings
- Database connection strings
- System parameters (timeouts, intervals, etc.)
- Map settings
- ScriptEngine settings
- TrafficControl parameters
- RobotManager settings
## 🔄 Cấu hình Runtime / Runtime Configuration
```mermaid
flowchart TD
User[User changes config<br/>via UI] --> Validate[Validate config values]
Validate -->|Valid| SaveDB[Save to Database]
Validate -->|Invalid| Error[Show error message]
SaveDB --> Notify[Notify affected services]
Notify --> Update[Services update config<br/>without restart]
style SaveDB fill:#e6ffe6
style Update fill:#e6f3ff
```
## 💾 Config Storage / Lưu trữ Cấu hình
- Primary: Database (SQL Server)
- Fallback: appsettings.json (cho initial setup)
- Services đọc config từ database thay vì appsettings.json
## 🖥️ UI Features / Tính năng Giao diện
- Web UI để config các tham số
- Validation khi thay đổi config
- Real-time update cho các services
- Config history (optional)
## 🔗 Related Documents / Tài liệu Liên quan
- [FleetManager Overview](README.md) - Tổng quan FleetManager
- [Identity Module](Identity.md) - Quản lý permissions cho config access
---
**Last Updated**: 2025-11-13

View File

@@ -0,0 +1,69 @@
# Identity Module / Module Xác thực
## 📋 Overview / Tổng quan
Identity Module quản lý authentication và authorization cho FleetManager, đảm bảo người dùng có quyền truy cập phù hợp với vai trò của họ.
## 🎯 Mục đích / Purpose
- User authentication (Individual Account - ASP.NET Identity)
- Role-based access control (RBAC)
- Permission management
- User management
## 👥 Roles được định nghĩa / Defined Roles
```mermaid
graph TB
subgraph "Development Team Roles"
SystemAdmin[SystemAdmin<br/>Quản trị hệ thống<br/>Full access]
Developer[Developer<br/>Nhà phát triển<br/>Script editing, Debug]
end
subgraph "Operations Team Roles"
FleetOperator[FleetOperator<br/>Vận hành đội xe<br/>Mission control, Robot control]
MapEditor[MapEditor<br/>Biên tập bản đồ<br/>Map management]
Viewer[Viewer<br/>Người xem<br/>Read-only access]
end
subgraph "Special Roles"
ScriptEditor[ScriptEditor<br/>Biên tập Script<br/>Script editing only]
Analyst[Analyst<br/>Phân tích<br/>Analytics & Reports]
end
style SystemAdmin fill:#ffe6e6
style Developer fill:#fff0e6
style FleetOperator fill:#e6ffe6
style MapEditor fill:#e6f3ff
style Viewer fill:#f0e6ff
style ScriptEditor fill:#fff9e6
style Analyst fill:#e6e6ff
```
## 🔐 Permissions Matrix / Ma trận Quyền
| Feature | SystemAdmin | Developer | FleetOperator | MapEditor | ScriptEditor | Analyst | Viewer |
|---------|-------------|-----------|---------------|-----------|--------------|---------|--------|
| System Config | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| User Management | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| Script Editing | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ |
| Mission Control | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ |
| Robot Control | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ |
| Map Editing | ✅ | ✅ | ❌ | ✅ | ❌ | ❌ | ❌ |
| Analytics | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ |
| View Dashboard | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
## 🏭 Multi-tenant Support / Hỗ trợ Đa Tenant
- Mỗi nhà máy có FleetManager instance riêng trên server local
- Nhiều khu vực trong nhà máy có thể dùng chung FleetManager nếu robot di chuyển qua lại giữa các khu vực
## 🔗 Related Documents / Tài liệu Liên quan
- [FleetManager Overview](README.md) - Tổng quan FleetManager
- [Architecture Overview](../architecture/README.md) - Kiến trúc hệ thống
---
**Last Updated**: 2025-11-13

View File

@@ -0,0 +1,74 @@
# MapEditor Module / Module Quản lý Bản đồ
## 📋 Overview / Tổng quan
MapEditor Module quản lý bản đồ nhà máy theo tiêu chuẩn VDMA LIF, cho phép tạo, chỉnh sửa và quản lý maps cho robot navigation.
## 🎯 Mục đích / Purpose
Quản lý bản đồ nhà máy theo tiêu chuẩn VDMA LIF để hỗ trợ robot navigation và route planning.
## 🏗️ Kiến trúc / Architecture
- **Shared Library**: MapEditor là shared library cho FleetManager và RobotApp
- **Components**:
- C# Library: Xử lý logic (map data, pathfinding, validation)
- Blazor Library: UI components (shared cho FleetManager và RobotApp)
## 🔧 Chức năng chính / Main Features
- Tạo và chỉnh sửa maps
- Import/Export VDMA LIF JSON
- Visual editing với SVG canvas
- PathFinding giữa các stations (A* algorithm)
- Validate map data theo VDMA LIF standard
- Quản lý stations, nodes, edges
## 📊 Map States / Trạng thái Bản đồ
```mermaid
stateDiagram-v2
[*] --> Draft: Create map
Draft --> Active: Activate map
Active --> Draft: Deactivate
Active --> [*]: Delete map
note right of Draft
Map có thể chỉnh sửa
Không thể tạo order
end note
note right of Active
Map không thể chỉnh sửa
Có thể tạo order cho robot
end note
```
## 📋 Map Activation Rules / Quy tắc Kích hoạt Bản đồ
- Map ở trạng thái **Draft**: Có thể chỉnh sửa, không thể tạo order
- Map ở trạng thái **Active**: Không thể chỉnh sửa, có thể tạo order cho robot
- **FleetManager**: Có thể active nhiều maps cùng lúc
- **RobotApp**: Chỉ active 1 map tại một thời điểm
## 💾 Data Storage / Lưu trữ Dữ liệu
- Map data lưu trong SQL Server database (FleetManager)
- MapEditor sử dụng dữ liệu từ database để tính toán routes
## ✅ VDMA LIF Compliance / Tuân thủ VDMA LIF
- Import/Export VDMA LIF JSON format
- Validate map structure theo VDMA LIF standard
- Cấu trúc dữ liệu có thể thể hiện được theo tiêu chuẩn VDMA LIF
## 🔗 Related Documents / Tài liệu Liên quan
- [FleetManager Overview](README.md) - Tổng quan FleetManager
- [TrafficControl Module](TrafficControl.md) - Sử dụng map data để tính toán routes
- [MapEditor Documentation](../MapEditor/README.md) - Chi tiết về MapEditor shared library
---
**Last Updated**: 2025-11-13

701
docs/fleetmanager/README.md Normal file
View File

@@ -0,0 +1,701 @@
# FleetManager Documentation / Tài liệu FleetManager
## 📋 Overview / Tổng quan
FleetManager là hệ thống quản lý và điều phối đội xe robot AMR, chạy trên server tại nhà máy. Ứng dụng này giám sát, điều phối nhiều robot AMR, gán nhiệm vụ, tối ưu hóa lộ trình và cung cấp giao diện web cho người vận hành.
## 🎯 Bối cảnh & Mục tiêu / Context & Goals
### Vấn đề Cần Giải quyết
Trong môi trường sản xuất hiện đại:
- **Quản lý nhiều robot**: Điều phối hàng chục đến hàng trăm robot làm việc đồng thời
- **Tối ưu hóa hiệu quả**: Giảm thời gian chờ, tối ưu lộ trình, cân bằng tải
- **Giải quyết xung đột**: Tránh deadlock, collision giữa các robot
- **Giám sát real-time**: Theo dõi trạng thái và hiệu suất của từng robot
- **Tích hợp hệ thống**: Kết nối với WMS, ERP, MES và các hệ thống khác
### Giải pháp FleetManager
FleetManager cung cấp:
1. **Fleet Coordination** - Điều phối tập trung toàn bộ đội xe
2. **Mission Planning** - Lập kế hoạch và quản lý nhiệm vụ thông minh
3. **Route Optimization** - Tối ưu hóa lộ trình dựa trên nhiều tiêu chí
4. **Conflict Resolution** - Tự động giải quyết xung đột giữa robot
5. **Real-time Monitoring** - Giám sát và phân tích hiệu suất
6. **Web Dashboard** - Giao diện trực quan cho operators
## 🏗️ Kiến trúc Tổng thể / System Architecture
### High-Level Architecture
```mermaid
graph TB
subgraph "FleetManager Server"
subgraph "Presentation Layer"
WebUI[Blazor Web UI<br/>Dashboard, Mission Control<br/>Fleet Map, Analytics]
SignalR[SignalR Hub<br/>Real-time Updates]
end
subgraph "Application Layer - Core Modules"
Identity[Identity Module<br/>Authentication & Authorization<br/>RBAC]
MapEditor[MapEditor Module<br/>Map Management<br/>VDMA LIF]
RobotConn[RobotConnections Module<br/>MQTT Management<br/>VDA 5050 Protocol]
RobotMgr[RobotManager Module<br/>State, Order, Action<br/>VDA 5050 Handler]
TrafficCtrl[TrafficControl Module<br/>Route Calculation<br/>Conflict Resolution]
ScriptEngine[ScriptEngine Module<br/>Script Management<br/>Mission & Task Execution]
Config[FleetManagerConfig Module<br/>Dynamic Configuration<br/>Runtime Updates]
end
subgraph "Data Layer"
DB[(SQL Server Database<br/>Robots, Missions<br/>Analytics, Maps<br/>MapEditor Data)]
end
subgraph "Communication Layer"
MQTT[MQTT Client<br/>Multi-robot Connection<br/>Topic Management]
end
end
subgraph "External Systems"
MQTTBroker[MQTT Broker<br/>Eclipse Mosquitto]
Robots[Robot Fleet<br/>RobotApp instances]
External[External Systems<br/>WMS, ERP, MES]
end
WebUI --> SignalR
SignalR --> Identity
SignalR --> RobotMgr
SignalR --> ScriptEngine
Identity --> WebUI
MapEditor --> DB
RobotConn --> MQTT
RobotMgr --> RobotConn
RobotMgr --> TrafficCtrl
TrafficCtrl --> MapEditor
TrafficCtrl --> RobotMgr
ScriptEngine --> RobotMgr
ScriptEngine --> TrafficCtrl
Config --> RobotConn
Config --> RobotMgr
Config --> TrafficCtrl
Config --> ScriptEngine
MQTT --> MQTTBroker
MQTTBroker <--> Robots
RobotMgr --> DB
MapEditor --> DB
ScriptEngine --> DB
Config --> DB
External --> WebUI
External --> ScriptEngine
style WebUI fill:#e6f3ff
style Identity fill:#ffe6e6
style MapEditor fill:#fff0e6
style RobotConn fill:#e6ffe6
style RobotMgr fill:#e6f3ff
style TrafficCtrl fill:#fff0e6
style ScriptEngine fill:#e6ffe6
style Config fill:#f0e6ff
style DB fill:#ffe6f0
style MQTT fill:#f0e6ff
```
### Component Interaction Flow
```mermaid
sequenceDiagram
participant Operator
participant WebUI
participant MissionSvc as Mission Service
participant RouteSvc as Route Optimizer
participant ConflictSvc as Conflict Resolver
participant VDAHandler as VDA 5050 Handler
participant MQTT
participant Robot
Operator->>WebUI: Create Mission
WebUI->>MissionSvc: Mission Request
MissionSvc->>RouteSvc: Optimize Route
RouteSvc->>ConflictSvc: Check Conflicts
ConflictSvc-->>RouteSvc: Route Approved
RouteSvc-->>MissionSvc: Optimized Route
MissionSvc->>VDAHandler: Generate Order
VDAHandler->>MQTT: Publish Order
MQTT->>Robot: VDA 5050 Order
Robot->>MQTT: State Update
MQTT->>VDAHandler: Process State
VDAHandler->>MissionSvc: Update Progress
MissionSvc->>WebUI: Real-time Update
WebUI->>Operator: Show Status
```
## 📚 Cấu trúc Tài liệu / Documentation Structure
Tài liệu FleetManager được tổ chức thành các module riêng biệt để dễ dàng tra cứu và bảo trì:
```
docs/fleetmanager/
├── README.md # File này - Tổng quan FleetManager
├── Identity.md # Module Xác thực và Phân quyền
├── MapEditor.md # Module Quản lý Bản đồ
├── RobotConnections.md # Module Kết nối Robot
├── RobotManager.md # Module Quản lý Robot
├── TrafficControl.md # Module Điều khiển Giao thông
├── ScriptEngine.md # Module Script Engine
└── FleetManagerConfig.md # Module Cấu hình
```
## 🔧 Core Modules / Các Module Chính
FleetManager được tổ chức thành 7 module chính, mỗi module có trách nhiệm cụ thể:
### 1. [Identity Module](Identity.md) - Module Xác thực và Phân quyền
Quản lý authentication và authorization cho FleetManager với 7 roles (SystemAdmin, Developer, FleetOperator, MapEditor, Viewer, ScriptEditor, Analyst).
📖 **[Xem chi tiết →](Identity.md)**
### 2. [MapEditor Module](MapEditor.md) - Module Quản lý Bản đồ
Quản lý bản đồ nhà máy theo tiêu chuẩn VDMA LIF. Shared library cho FleetManager và RobotApp với visual editing và pathfinding.
📖 **[Xem chi tiết →](MapEditor.md)**
### 3. [RobotConnections Module](RobotConnections.md) - Module Kết nối Robot
Quản lý kết nối MQTT của các robot theo VDA 5050. MQTT Broker chạy trên service ngoài FleetManager.
📖 **[Xem chi tiết →](RobotConnections.md)**
### 4. [RobotManager Module](RobotManager.md) - Module Quản lý Robot
Quản lý state, order, và action của robots. Cung cấp APIs cho ScriptEngine và xử lý VDA 5050 protocol.
📖 **[Xem chi tiết →](RobotManager.md)**
### 5. [TrafficControl Module](TrafficControl.md) - Module Điều khiển Giao thông
Tính toán route cho order, phát hiện conflict và giải quyết xung đột. Quản lý base và horizon của VDA 5050 orders.
📖 **[Xem chi tiết →](TrafficControl.md)**
### 6. [ScriptEngine Module](ScriptEngine.md) - Module Script Engine
Quản lý script do người dùng thiết kế, chạy Task và Mission. Shared library với IntelliSense support và FleetManager APIs.
📖 **[Xem chi tiết →](ScriptEngine.md)**
### 7. [FleetManagerConfig Module](FleetManagerConfig.md) - Module Cấu hình
Quản lý cấu hình động cho hệ thống, cho phép thay đổi runtime mà không cần restart. Lưu trữ trong database.
📖 **[Xem chi tiết →](FleetManagerConfig.md)**
## 📡 VDA 5050 Protocol Handler
**Mục đích**: Xử lý giao tiếp VDA 5050 với các robot (không phải module riêng, mà là phần của RobotManager và RobotConnections).
**Chức năng**:
- **Order Generation**: Tạo VDA 5050 orders từ TrafficControl
- **Order Updates**: Tạo OrderUpdate (cùng orderId, orderUpdateId tăng) khi TrafficControl yêu cầu
- **State Processing**: Xử lý state messages từ robots (chỉ quản lý state hiện tại, không lưu history)
- **Action Generation**: Tạo instant actions (stopPause, cancelOrder, etc.)
- **Message Validation**: Validate VDA 5050 messages
**Lưu ý**: VDA 5050 Protocol Handler không phải là module riêng, mà là chức năng được tích hợp trong RobotManager và RobotConnections modules.
### 6. Analytics & Reporting
**Mục đích**: Thu thập, phân tích và báo cáo dữ liệu vận hành.
**Metrics theo dõi**:
```mermaid
graph TB
subgraph "Fleet Metrics"
CompletionRate[Mission Completion Rate<br/>% missions completed]
AvgDuration[Average Mission Duration<br/>Time per mission]
Utilization[Robot Utilization Rate<br/>% time active]
Distance[Total Distance Traveled<br/>km per day/week]
end
subgraph "Robot Metrics"
Battery[Battery Consumption<br/>Charging patterns]
Errors[Error Frequency<br/>Error types and rates]
IdleTime[Idle Time<br/>Waiting time]
Performance[Performance Comparison<br/>Robot vs Robot]
end
subgraph "Reports"
Daily[Daily Summary<br/>24-hour overview]
Weekly[Weekly Report<br/>Trends and patterns]
Monthly[Monthly Analysis<br/>Long-term trends]
Predictive[Predictive Alerts<br/>Maintenance warnings]
end
CompletionRate --> Daily
AvgDuration --> Daily
Utilization --> Weekly
Distance --> Weekly
Battery --> Monthly
Errors --> Predictive
IdleTime --> Monthly
Performance --> Weekly
style CompletionRate fill:#e6f3ff
style Daily fill:#e6ffe6
```
### 7. Web Dashboard (Blazor)
**Mục đích**: Giao diện web cho operators.
**Technology Stack**:
- **Blazor Web App**: .NET 10
- **Authentication**: Individual Account (ASP.NET Identity)
- **Real-time**: SignalR for live updates
- **Script Editor**: Monaco Editor với ScriptEngine integration
**Các trang chính**:
```mermaid
graph TB
subgraph "Dashboard Pages"
Dashboard[Dashboard<br/>Fleet overview<br/>Key metrics<br/>Active missions]
FleetMap[Fleet Map<br/>Real-time positions<br/>Route visualization<br/>Zone management]
MissionCtrl[Mission Control<br/>Create missions<br/>Edit missions<br/>Queue management]
RobotMgr[Robot Management<br/>Robot list<br/>Individual details<br/>Manual control]
Analytics[Analytics<br/>Performance metrics<br/>Charts and graphs<br/>Reports]
Config[Configuration<br/>Map management<br/>System settings<br/>User management]
ScriptEditor[Script Editor<br/>C# Code Editing<br/>Monaco Editor<br/>ScriptEngine Integration]
end
Dashboard --> SignalR[SignalR Real-time]
FleetMap --> SignalR
MissionCtrl --> SignalR
RobotMgr --> SignalR
Analytics --> DB[(Database)]
Config --> DB
ScriptEditor --> ScriptEngine[ScriptEngine<br/>SignalR Locking]
style Dashboard fill:#e6f3ff
style SignalR fill:#fff0e6
style ScriptEditor fill:#e6ffe6
```
**Script Editor Features**:
- Monaco Editor với C# IntelliSense
- SignalR-based file locking: Khi user đang edit, các session khác không được sửa file
- Save action: Không có realtime update file content, chỉ khi user gọi action Save mới gửi lên server
- ScriptEngine quản lý trạng thái cho phép chỉnh sửa hay không
## 📡 Communication Architecture / Kiến trúc Giao tiếp
### MQTT Topic Structure
```mermaid
graph TB
subgraph "Published Topics<br/>FleetManager → Robots"
OrderTopic[uagv/v2/{manufacturer}/{serialNumber}/order<br/>QoS: 1, Retain: false]
InstantTopic[uagv/v2/{manufacturer}/{serialNumber}/instantActions<br/>QoS: 1, Retain: false]
end
subgraph "Subscribed Topics<br/>Robots → FleetManager"
StateTopic[uagv/v2/{manufacturer}/+/state<br/>QoS: 0, Retain: true]
VizTopic[uagv/v2/{manufacturer}/+/visualization<br/>QoS: 0, Retain: false]
ConnTopic[uagv/v2/{manufacturer}/+/connection<br/>QoS: 1, Retain: true]
end
FleetMgr[FleetManager] --> OrderTopic
FleetMgr --> InstantTopic
StateTopic --> FleetMgr
VizTopic --> FleetMgr
ConnTopic --> FleetMgr
style FleetMgr fill:#e6f3ff
style OrderTopic fill:#fff0e6
style StateTopic fill:#e6ffe6
```
### Message Flow Patterns
**Order Assignment Flow**:
```mermaid
sequenceDiagram
participant Operator
participant FleetMgr as FleetManager
participant MQTT as MQTT Broker
participant Robot
Operator->>FleetMgr: Create Mission
FleetMgr->>FleetMgr: Plan Route
FleetMgr->>FleetMgr: Check Conflicts
FleetMgr->>FleetMgr: Generate VDA 5050 Order
FleetMgr->>MQTT: Publish Order (QoS 1)
MQTT->>Robot: Forward Order
Robot->>MQTT: Publish State (QoS 0)
MQTT->>FleetMgr: Forward State
FleetMgr->>Operator: Update Dashboard
Note over Robot: Execute Order
Robot->>MQTT: State Updates (1-10 Hz)
MQTT->>FleetMgr: Forward States
FleetMgr->>Operator: Real-time Updates
```
**Emergency Stop Flow**:
```mermaid
sequenceDiagram
participant Operator
participant FleetMgr as FleetManager
participant MQTT as MQTT Broker
participant Robot
Operator->>FleetMgr: Emergency Stop
FleetMgr->>FleetMgr: Generate InstantAction<br/>(stopPause)
FleetMgr->>MQTT: Publish InstantAction (QoS 1)
Note over FleetMgr,MQTT: < 50ms latency required
MQTT->>Robot: Forward InstantAction
Robot->>Robot: Stop Motors Immediately
Robot->>Robot: Set paused=true
Robot->>MQTT: Publish State (paused=true)
MQTT->>FleetMgr: Forward State
FleetMgr->>Operator: Show PAUSED Status
```
## 💾 Data Architecture / Kiến trúc Dữ liệu
### Core Entities
```mermaid
erDiagram
Robots ||--o{ MissionInstances : assigned
Robots ||--o{ Orders : has
MissionInstances ||--o{ Orders : generates
Maps ||--o{ Stations : contains
Maps ||--o{ Edges : contains
Maps ||--o{ Nodes : contains
Robots {
uuid id PK
string serialNumber UK
string manufacturer
int status
float currentX
float currentY
float batteryLevel
datetime lastSeen
string currentOrderId
int currentOrderUpdateId
}
MissionInstances {
uuid id PK
string missionName
string parameters
int status
uuid assignedRobotId FK
datetime startedAt
datetime completedAt
}
Orders {
uuid id PK
uuid robotId FK
string orderId UK
int orderUpdateId
string orderData
datetime createdAt
datetime completedAt
}
Maps {
uuid id PK
string mapId UK
string name
float resolution
}
Stations {
uuid id PK
uuid mapId FK
string stationId UK
string stationType
float positionX
float positionY
}
Edges {
uuid id PK
uuid mapId FK
string edgeId UK
string startNodeId
string endNodeId
}
Nodes {
uuid id PK
uuid mapId FK
string nodeId UK
float positionX
float positionY
}
```
**Lưu ý về State Management**:
- FleetManager chỉ quản lý state hiện tại của robot, không lưu state history
- State được cập nhật real-time từ VDA 5050 state messages
- Khi robot mất kết nối, FleetManager dựa vào thời gian state cuối cùng để quyết định timeout cho order
### Data Flow
```mermaid
graph LR
subgraph "Input Sources"
Operator[Operator Input]
Robots[Robot States]
External[External Systems]
end
subgraph "Processing"
FleetSvc[Fleet Service]
MissionSvc[Mission Service]
AnalyticsSvc[Analytics Service]
end
subgraph "Storage"
DB[(SQL Server<br/>Robots, Missions<br/>Maps, Analytics)]
end
subgraph "Output"
Dashboard[Web Dashboard]
Reports[Analytics Reports]
Orders[VDA 5050 Orders]
end
Operator --> FleetSvc
Operator --> MissionSvc
Robots --> FleetSvc
External --> MissionSvc
FleetSvc --> DB
MissionSvc --> DB
AnalyticsSvc --> DB
DB --> Dashboard
DB --> Reports
FleetSvc --> Orders
style DB fill:#ffe6f0
style Dashboard fill:#e6f3ff
```
## 🎯 Design Principles / Nguyên tắc Thiết kế
### 1. Scalability / Khả năng Mở rộng
**Mục tiêu**: Hỗ trợ 100+ robot đồng thời
**Thiết kế**:
- Stateless service design (không lưu state trong memory)
- Asynchronous processing (async/await)
- Efficient database queries (indexes, pagination)
- MQTT broker clustering support (nếu cần)
### 2. Reliability / Độ Tin cậy
**Mục tiêu**: Hệ thống không được gián đoạn
**Thiết kế**:
- MQTT QoS levels phù hợp (QoS 1 cho orders)
- Auto-reconnection logic
- Graceful degradation (degraded mode khi có lỗi)
- Comprehensive error handling
- Safety monitoring (emergency stop < 50ms)
### 3. Real-time Performance / Hiệu năng Real-time
**Yêu cầu**:
- State processing: < 50ms per robot state
- Order generation: < 100ms
- Conflict detection: < 500ms
- Dashboard update: < 100ms (via SignalR)
**Thiết kế**:
- SignalR for real-time updates
- Efficient state processing pipeline
- Background workers for heavy tasks
- Caching frequently accessed data
### 4. Interoperability / Khả năng Tương tác
**Mục tiêu**: Tương thích với hệ thống bên thứ 3
**Thiết kế**:
- Tuân thủ nghiêm ngặt VDA 5050 v2.1.0 (tương thích ngược với v2.0.0)
- Standard MQTT protocol
- REST API for external integration (planned)
- JSON message format (camelCase)
## 🔐 Security Architecture / Kiến trúc Bảo mật
```mermaid
graph TB
subgraph "Network Security"
TLS[MQTT over TLS/SSL]
Cert[Certificate-based Authentication]
Firewall[Network Segmentation]
end
subgraph "Application Security"
Auth[User Authentication<br/>ASP.NET Identity]
RBAC[Role-based Access Control<br/>Admin/Operator/Viewer]
Encrypt[Encrypted Credentials]
Audit[Audit Logging]
end
subgraph "Data Security"
DBEncrypt[Database Encryption]
Backup[Backup & Recovery]
Access[Access Control]
end
TLS --> Auth
Cert --> Auth
Auth --> RBAC
RBAC --> Access
Access --> DBEncrypt
DBEncrypt --> Backup
style TLS fill:#ffe6e6
style Auth fill:#e6ffe6
style DBEncrypt fill:#e6f3ff
```
## 📈 Performance Requirements / Yêu cầu Hiệu năng
| Chỉ số | Mục tiêu | Ghi chú |
|--------|----------|---------|
| **Max Robots** | 100+ | Per FleetManager instance |
| **State Processing** | < 50ms | Per robot state message |
| **Order Generation** | < 100ms | From mission to VDA 5050 order |
| **Conflict Detection** | < 500ms | Multi-robot conflict check |
| **Route Optimization** | < 2 seconds | A* pathfinding |
| **Dashboard Update** | < 100ms | Via SignalR real-time |
| **Database Query** | < 200ms | Average response time |
## 🔌 ScriptEngine Integration / Tích hợp ScriptEngine
**Mục đích**: Cho phép tùy chỉnh logic mission planning và tích hợp hệ thống bên ngoài.
**FleetManager Script APIs**:
ScriptEngine trong FleetManager expose các APIs thông qua `FleetScriptGlobals`:
```csharp
// Robot Management
Robot GetRobotById(string robotId);
Robot GetRobotBySerial(string serialNumber);
List<Robot> GetAvailableRobots();
// Order Creation (tự động tìm route và tạo order)
Task MoveToNode(string robotSerial, string nodeId);
Task MoveToStation(string robotSerial, string stationId);
// Robot State
RobotState GetRobotState(string robotSerial);
// External System Integration
// Có thể khai báo kết nối với:
// - HTTP APIs
// - Modbus TCP
// - OPC UA
// - CcLink
// - ProfileNet
// - MQTT (external)
```
**Mission và Task trong FleetManager**:
- **Mission**: Methods có `[Mission]` attribute trong script, được ScriptEngine extract và tạo thành MissionInstance
- **Task**: Methods có `[Task]` attribute, chạy lặp lại theo interval
- Mission và Task có thể tương tác qua common APIs:
- `EnableTask(string taskName)` / `DisableTask(string taskName)`
- `CreateMission(string missionName, params)` / `CancelMission(Guid missionId)`
**Luồng Mission Execution**:
```mermaid
sequenceDiagram
participant Script as C# Script
participant ScriptEngine
participant MissionInstance
participant FleetAPI as FleetManager APIs
participant RouteSvc as Route Service
participant VDAHandler as VDA Handler
participant Robot
Script->>ScriptEngine: [Mission] method defined
ScriptEngine->>ScriptEngine: Extract & compile
ScriptEngine->>MissionInstance: Create MissionInstance
MissionInstance->>FleetAPI: MoveToNode("ROBOT001", "NodeA")
FleetAPI->>RouteSvc: Find route to NodeA
RouteSvc->>VDAHandler: Generate VDA 5050 Order
VDAHandler->>Robot: Send Order
Robot->>FleetAPI: State updates
FleetAPI->>MissionInstance: Continue execution
```
## 🚀 Deployment Architecture / Kiến trúc Triển khai
**Deployment Model**:
- **Single Instance**: FleetManager chạy một instance duy nhất, có thể điều phối nhiều robot (100+)
- **Không hỗ trợ multiple instances**: FleetManager không chạy multiple instances để share workload
**Infrastructure**:
```mermaid
graph TB
subgraph "FleetManager Server"
App[FleetManager App<br/>Blazor Web App<br/>.NET 10]
end
subgraph "Infrastructure"
Server[Server<br/>Linux/Windows]
MQTTBroker[MQTT Broker<br/>Eclipse Mosquitto]
Database[SQL Server<br/>Database]
ReverseProxy[Reverse Proxy<br/>Nginx/IIS]
end
App --> MQTTBroker
App --> Database
ReverseProxy --> App
style App fill:#e6f3ff
style Database fill:#fff0e6
```
## 📚 Related Documents / Tài liệu Liên quan
- [Architecture Overview](../architecture/README.md) - System architecture overview
- [RobotApp Documentation](../robotapp/README.md) - Robot-side application
- [VDA 5050 Implementation](../vda5050/README.md) - Protocol details
- [MapEditor Documentation](../MapEditor/README.md) - Map management
- [ScriptEngine Documentation](../ScriptEngine/README.md) - Custom scripting
- [Development Guide](../development/README.md) - Implementation details
---
**Status**: Architecture & Design Document
**Focus**: System Architecture, Design Concepts, Component Interactions
**Last Updated**: 2025-11-13
**Version**: 2.2 (Updated with 7 core modules structure)

View File

@@ -0,0 +1,68 @@
# RobotConnections Module / Module Kết nối Robot
## 📋 Overview / Tổng quan
RobotConnections Module quản lý kết nối MQTT của các robot theo VDA 5050, đảm bảo giao tiếp ổn định giữa FleetManager và RobotApp.
## 🎯 Mục đích / Purpose
Quản lý kết nối MQTT của các robot theo VDA 5050 để đảm bảo giao tiếp ổn định và real-time.
## ⚠️ Lưu ý / Important Note
**MQTT Broker chạy trên service ngoài FleetManager** (không phải trong FleetManager).
## 🔧 Chức năng chính / Main Features
- Quản lý MQTT connection status của từng robot
- Subscribe/unsubscribe MQTT topics theo VDA 5050
- Connection timeout và reconnection logic
- Heartbeat mechanism (qua VDA 5050 connection messages)
- Thông báo cho RobotManager khi robot disconnect/reconnect
## 📡 MQTT Topics Management / Quản lý MQTT Topics
```mermaid
graph TB
subgraph "Subscribed Topics<br/>Robot → FleetManager"
StateTopic[uagv/v2/{manufacturer}/+/state<br/>QoS: 0, Retain: true]
VizTopic[uagv/v2/{manufacturer}/+/visualization<br/>QoS: 0, Retain: false]
ConnTopic[uagv/v2/{manufacturer}/+/connection<br/>QoS: 1, Retain: true]
end
subgraph "Published Topics<br/>FleetManager → Robot"
OrderTopic[uagv/v2/{manufacturer}/{serialNumber}/order<br/>QoS: 1, Retain: false]
InstantTopic[uagv/v2/{manufacturer}/{serialNumber}/instantActions<br/>QoS: 1, Retain: false]
end
RobotConnections[RobotConnections Module] --> StateTopic
RobotConnections --> VizTopic
RobotConnections --> ConnTopic
RobotConnections --> OrderTopic
RobotConnections --> InstantTopic
style RobotConnections fill:#e6f3ff
```
## 🔌 Connection States / Trạng thái Kết nối
- **ONLINE**: Robot connected và operational
- **OFFLINE**: Robot disconnected
- **CONNECTIONBROKEN**: Connection lost unexpectedly
## ✨ Features / Tính năng
- Không lưu connection history (chỉ quản lý state hiện tại)
- Auto-reconnection logic khi connection lost
- Notify RobotManager về connection status changes
## 🔗 Related Documents / Tài liệu Liên quan
- [FleetManager Overview](README.md) - Tổng quan FleetManager
- [RobotManager Module](RobotManager.md) - Nhận thông báo từ RobotConnections
- [VDA 5050 Integration](../vda5050/README.md) - Chi tiết về VDA 5050 protocol
---
**Last Updated**: 2025-11-13

View File

@@ -0,0 +1,87 @@
# RobotManager Module / Module Quản lý Robot
## 📋 Overview / Tổng quan
RobotManager Module quản lý state, order, và action của robots, cung cấp APIs cho các module khác và ScriptEngine.
## 🎯 Mục đích / Purpose
Quản lý toàn bộ thông tin về robots bao gồm state hiện tại, orders đang thực hiện, và actions.
## 🔧 Chức năng chính / Main Features
### 1. State Management / Quản lý Trạng thái
- Quản lý state mới nhất mà robot gửi lên (không lưu history)
- Cập nhật state real-time từ VDA 5050 state messages
- Expose state cho các module khác (TrafficControl, ScriptEngine)
### 2. Order Management / Quản lý Order
- Quản lý orders đã yêu cầu xuống robot
- Quản lý orders đang thực hiện
- Order timeout handling → order failed
- Quản lý order theo từng robot
### 3. Action Management / Quản lý Action
- Quản lý instant actions đã gửi
- Quản lý actions đang thực hiện
- Track action status
## ⏱️ Order Timeout Handling / Xử lý Timeout Order
```mermaid
flowchart TD
Start[Robot has active order] --> CheckConnection{Robot<br/>connected?}
CheckConnection -->|Yes| UpdateState[Update state from<br/>VDA 5050 messages]
CheckConnection -->|No| CheckTimeout{Last state<br/>timeout?}
UpdateState --> HasOrder{Order still<br/>active?}
HasOrder -->|Yes| Continue[Continue monitoring]
HasOrder -->|No| Completed[Order completed]
CheckTimeout -->|Yes| OrderFailed[Order failed<br/>Notify modules]
CheckTimeout -->|No| Wait[Wait for reconnect]
style OrderFailed fill:#ffe6e6
style Completed fill:#e6ffe6
```
## 🔌 APIs cho ScriptEngine
RobotManager expose các APIs cho ScriptEngine thông qua `FleetScriptGlobals`:
- `GetRobotById(string robotId)`: Lấy thông tin robot
- `GetRobotBySerial(string serialNumber)`: Lấy robot theo serial number
- `GetAvailableRobots()`: Lấy danh sách robot available
- `GetRobotState(string robotSerial)`: Lấy state hiện tại của robot
- `MoveToNode(string robotSerial, string nodeId)`: Tạo order di chuyển đến node
- `MoveToStation(string robotSerial, string stationId)`: Tạo order di chuyển đến station
## 🔗 Integration với RobotConnections
- Nhận thông báo từ RobotConnections về connection status
- Xử lý order timeout dựa trên connection status và last state timestamp
## 📡 VDA 5050 Protocol Handler
RobotManager cũng xử lý VDA 5050 protocol:
- Order Generation: Tạo VDA 5050 orders từ TrafficControl
- Order Updates: Tạo OrderUpdate khi TrafficControl yêu cầu
- State Processing: Xử lý state messages từ robots
- Action Generation: Tạo instant actions
## 🔗 Related Documents / Tài liệu Liên quan
- [FleetManager Overview](README.md) - Tổng quan FleetManager
- [RobotConnections Module](RobotConnections.md) - Cung cấp connection status
- [TrafficControl Module](TrafficControl.md) - Sử dụng RobotManager để check robot state
- [ScriptEngine Module](ScriptEngine.md) - Sử dụng RobotManager APIs
- [VDA 5050 Integration](../vda5050/README.md) - Chi tiết về VDA 5050 protocol
---
**Last Updated**: 2025-11-13

View File

@@ -0,0 +1,118 @@
# ScriptEngine Module / Module Script Engine
## 📋 Overview / Tổng quan
ScriptEngine Module quản lý script do người dùng thiết kế, chạy Task và Mission để tùy chỉnh logic của FleetManager.
## 🎯 Mục đích / Purpose
Cho phép người dùng viết C# scripts để tùy chỉnh mission planning, tích hợp hệ thống bên ngoài, và tự động hóa các tác vụ.
## 🏗️ Kiến trúc / Architecture
- **Shared Library**: ScriptEngine là shared library cho FleetManager và RobotApp
- **Implementation**: FleetManager và RobotApp implement `IScriptResource` để cung cấp Type mô tả và object cho API mở rộng
- **Components**:
- C# Library: Script compilation, execution, state machine
- Blazor Library: Monaco Editor component với IntelliSense
## 🔧 Chức năng chính / Main Features
### 1. Script File Management / Quản lý File Script
- Quản lý script files bằng file system
- Backup và restore scripts (ZIP format)
- File locking qua SignalR (khi user đang edit, các session khác không được sửa)
### 2. Script Compilation / Biên dịch Script
- Compile C# scripts với Roslyn
- Extract Mission methods (có `[Mission]` attribute)
- Extract Task methods (có `[Task]` attribute)
- Extract Variables (có `[Variable]` attribute)
### 3. Mission và Task Execution / Thực thi Mission và Task
- MissionInstance execution: Chạy Mission methods với progress tracking
- Task execution: Chạy Task methods theo interval (periodic)
- State machine: Idle → Building → Ready → Running
### 4. IntelliSense Support / Hỗ trợ IntelliSense
- Sử dụng AdhocWorkspace trên WebAssembly
- IntelliSense, Hover information, Diagnostics
- Real-time code analysis
## 🔌 FleetManager Script APIs
FleetManager implement `IScriptResource` để expose APIs cho scripts:
```csharp
public class FleetScriptGlobals
{
// Robot Management
Robot GetRobotById(string robotId);
Robot GetRobotBySerial(string serialNumber);
List<Robot> GetAvailableRobots();
// Order Creation (tự động tìm route và tạo order)
Task MoveToNode(string robotSerial, string nodeId);
Task MoveToStation(string robotSerial, string stationId);
// Robot State
RobotState GetRobotState(string robotSerial);
// External System Integration
// Có thể khai báo kết nối với:
// - HTTP APIs
// - Modbus TCP
// - OPC UA
// - CcLink
// - ProfileNet
// - MQTT (external)
}
```
## 📝 Mission và Task trong ScriptEngine
- **Mission**: Methods có `[Mission]` attribute, được extract và tạo thành MissionInstance
- **Task**: Methods có `[Task]` attribute, chạy lặp lại theo interval
- Mission và Task có thể tương tác qua common APIs:
- `EnableTask(string taskName)` / `DisableTask(string taskName)`
- `CreateMission(string missionName, params)` / `CancelMission(Guid missionId)`
## 🔄 Luồng Mission Execution / Mission Execution Flow
```mermaid
sequenceDiagram
participant Script as C# Script
participant ScriptEngine
participant MissionInstance
participant FleetAPI as FleetManager APIs<br/>(RobotManager)
participant TrafficControl
participant VDAHandler as VDA 5050 Handler
participant Robot
Script->>ScriptEngine: [Mission] method defined
ScriptEngine->>ScriptEngine: Extract & compile
ScriptEngine->>MissionInstance: Create MissionInstance
MissionInstance->>FleetAPI: MoveToNode("ROBOT001", "NodeA")
FleetAPI->>TrafficControl: Calculate route to NodeA
TrafficControl->>TrafficControl: Find path using A*
TrafficControl->>VDAHandler: Generate VDA 5050 Order
VDAHandler->>Robot: Send Order
Robot->>FleetAPI: State updates
FleetAPI->>MissionInstance: Continue execution
```
## 🔗 Related Documents / Tài liệu Liên quan
- [FleetManager Overview](README.md) - Tổng quan FleetManager
- [RobotManager Module](RobotManager.md) - Cung cấp APIs cho ScriptEngine
- [TrafficControl Module](TrafficControl.md) - Được gọi từ ScriptEngine để tính toán routes
- [ScriptEngine Documentation](../ScriptEngine/README.md) - Chi tiết về ScriptEngine shared library
---
**Last Updated**: 2025-11-13

View File

@@ -0,0 +1,99 @@
# TrafficControl Module / Module Điều khiển Giao thông
## 📋 Overview / Tổng quan
TrafficControl Module tính toán route cho order, phát hiện conflict và đưa tuyến đường mới để giải quyết xung đột giữa các robot.
## 🎯 Mục đích / Purpose
- Tính toán route tối ưu cho robot orders
- Phát hiện và giải quyết conflicts giữa các robot
- Quản lý base và horizon của VDA 5050 orders
## 🔧 Chức năng chính / Main Features
### 1. Route Calculation / Tính toán Tuyến đường
- Tính toán route giữa hai nodes/stations
- Sử dụng A* algorithm trên map data từ MapEditor
- Đọc map data từ SQL Server database
- Tạo VDA 5050 order structure với nodes và edges
### 2. Base và Horizon Management
- **Base**: Phần order đã được release và robot đang thực hiện
- **Horizon**: Phần order chưa được release, đang chờ điều kiện
- Monitor traffic trên map
- Quyết định khi nào release thêm nodes/edges vào order
- Update `orderUpdateId` khi release thêm phần horizon
### 3. Conflict Detection / Phát hiện Xung đột
- Dựa trên **planned routes** của các robot
- Phát hiện head-on collisions
- Phát hiện deadlock situations
- Phát hiện resource conflicts
### 4. Conflict Resolution / Giải quyết Xung đột
- Sử dụng OrderUpdate để tạo tuyến đường mới cho một robot
- Deadlock resolution: Một robot đợi robot khác đi qua
- Robot nào hoàn thành phần base trước sẽ được đăng ký thêm phần base tiếp theo
## 🔄 Conflict Resolution Flow / Luồng Giải quyết Xung đột
```mermaid
flowchart TD
Detect[TrafficControl<br/>Detects Conflict<br/>based on planned routes] --> Analyze{Conflict Type}
Analyze -->|Head-on Collision| CheckBase{Which robot<br/>finished base first?}
Analyze -->|Deadlock| UpdateOrder[Send OrderUpdate<br/>to one robot]
CheckBase -->|Robot A| UpdateA[Update Order for Robot A<br/>Add new base section<br/>via OrderUpdate]
CheckBase -->|Robot B| UpdateB[Update Order for Robot B<br/>Add new base section<br/>via OrderUpdate]
UpdateOrder --> Wait[Other robot waits<br/>via OrderUpdate]
UpdateA --> Resolved[Conflict Resolved]
UpdateB --> Resolved
Wait --> Resolved
style Detect fill:#ffe6e6
style Resolved fill:#e6ffe6
```
## 📡 OrderUpdate Flow / Luồng OrderUpdate
```mermaid
sequenceDiagram
participant TrafficControl
participant MapEditor as Map Data
participant RobotManager
participant VDAHandler as VDA 5050 Handler
participant MQTT
participant Robot
Note over TrafficControl: Detects conflict or<br/>traffic allows extension
TrafficControl->>MapEditor: Get route extension
MapEditor->>TrafficControl: New route section
TrafficControl->>RobotManager: Check robot state
RobotManager->>TrafficControl: Current order info
TrafficControl->>VDAHandler: Generate OrderUpdate<br/>(same orderId, orderUpdateId++)
VDAHandler->>MQTT: Publish OrderUpdate (QoS 1)
MQTT->>Robot: Forward OrderUpdate
Robot->>Robot: Continue with extended route
Robot->>MQTT: State Update (new orderUpdateId)
MQTT->>RobotManager: Forward State
```
## 🔗 Related Documents / Tài liệu Liên quan
- [FleetManager Overview](README.md) - Tổng quan FleetManager
- [MapEditor Module](MapEditor.md) - Cung cấp map data cho route calculation
- [RobotManager Module](RobotManager.md) - Cung cấp robot state để check conflicts
- [VDA 5050 Integration](../vda5050/README.md) - Chi tiết về OrderUpdate mechanism
---
**Last Updated**: 2025-11-13