initial commit
This commit is contained in:
8
.claude/settings.local.json
Normal file
8
.claude/settings.local.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(dotnet publish:*)",
|
||||
"mcp__grapuco__list_repositories"
|
||||
]
|
||||
}
|
||||
}
|
||||
22
.dockerignore
Normal file
22
.dockerignore
Normal file
@@ -0,0 +1,22 @@
|
||||
.git
|
||||
.github
|
||||
.vs
|
||||
.vscode
|
||||
.claude
|
||||
|
||||
**/bin/
|
||||
**/obj/
|
||||
**/out/
|
||||
**/node_modules/
|
||||
|
||||
**/*.user
|
||||
**/*.rsuser
|
||||
**/*.suo
|
||||
**/*.pfx
|
||||
|
||||
Lab505/certs/
|
||||
Lab505/keys/
|
||||
Lab505/auth.db
|
||||
Lab505/auth.db-shm
|
||||
Lab505/auth.db-wal
|
||||
docker-data/
|
||||
35
.vscode/launch.json
vendored
Normal file
35
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
// Use IntelliSense to find out which attributes exist for C# debugging
|
||||
// Use hover for the description of the existing attributes
|
||||
// For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md.
|
||||
"name": ".NET Core Launch (web)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build",
|
||||
// If you have changed target frameworks, make sure to update the program path.
|
||||
"program": "${workspaceFolder}/Lab505/bin/Debug/net10.0/Lab505.dll",
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}/Lab505",
|
||||
"stopAtEntry": false,
|
||||
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
|
||||
"serverReadyAction": {
|
||||
"action": "openExternally",
|
||||
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
|
||||
},
|
||||
"env": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"sourceFileMap": {
|
||||
"/Views": "${workspaceFolder}/Views"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": ".NET Core Attach",
|
||||
"type": "coreclr",
|
||||
"request": "attach"
|
||||
}
|
||||
]
|
||||
}
|
||||
41
.vscode/tasks.json
vendored
Normal file
41
.vscode/tasks.json
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "build",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"build",
|
||||
"${workspaceFolder}/Lab505.sln",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary;ForceNoAlign"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "publish",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"publish",
|
||||
"${workspaceFolder}/Lab505.sln",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary;ForceNoAlign"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "watch",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"watch",
|
||||
"run",
|
||||
"--project",
|
||||
"${workspaceFolder}/Lab505.sln"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
}
|
||||
]
|
||||
}
|
||||
3
BlazorApp1.slnx
Normal file
3
BlazorApp1.slnx
Normal file
@@ -0,0 +1,3 @@
|
||||
<Solution>
|
||||
<Project Path="../BlazorApp1/BlazorApp1.csproj" />
|
||||
</Solution>
|
||||
31
Dockerfile
Normal file
31
Dockerfile
Normal file
@@ -0,0 +1,31 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
|
||||
COPY ["Lab505/Lab505.csproj", "Lab505/"]
|
||||
COPY ["Lab505.Client/Lab505.Client.csproj", "Lab505.Client/"]
|
||||
COPY ["Lab505.Shared/Lab505.Shared.csproj", "Lab505.Shared/"]
|
||||
COPY ["Lab505.Script/Lab505.Script.csproj", "Lab505.Script/"]
|
||||
COPY ["Lab505.Sim/Lab505.Sim.csproj", "Lab505.Sim/"]
|
||||
|
||||
RUN dotnet restore "Lab505/Lab505.csproj"
|
||||
|
||||
COPY . .
|
||||
WORKDIR /src/Lab505
|
||||
RUN dotnet publish "Lab505.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
|
||||
WORKDIR /app
|
||||
|
||||
RUN mkdir -p /data /app/certs
|
||||
|
||||
COPY --from=build /app/publish .
|
||||
|
||||
ENV ASPNETCORE_ENVIRONMENT=Production
|
||||
|
||||
EXPOSE 7000
|
||||
EXPOSE 7222
|
||||
|
||||
ENTRYPOINT ["dotnet", "Lab505.dll"]
|
||||
974
HUONG_DAN_VAN_HANH.md
Normal file
974
HUONG_DAN_VAN_HANH.md
Normal file
@@ -0,0 +1,974 @@
|
||||
# Hướng Dẫn Vận Hành Hệ Thống Lab 505
|
||||
|
||||
> Tài liệu này dành cho **người vận hành** (operator) — không cần biết lập trình.
|
||||
> Đọc từ đầu đến cuối một lần để nắm toàn bộ luồng làm việc.
|
||||
|
||||
---
|
||||
|
||||
## Mục lục
|
||||
|
||||
6.1. [Tổng quan giao diện](#61-tổng-quan-giao-diện)
|
||||
6.2. [Đăng nhập và chế độ SIM / REAL](#62-đăng-nhập-và-chế-độ-sim--real)
|
||||
6.3. [STATUS — Xem trạng thái hệ thống](#63-status--xem-trạng-thái-hệ-thống)
|
||||
6.4. [CONTROL ACCESS — Lấy quyền điều khiển](#64-control-access--lấy-quyền-điều-khiển)
|
||||
6.5. [OPERATIONS — Chạy từng bước workflow](#65-operations--chạy-từng-bước-workflow)
|
||||
6.6. [CONTROL — Lệnh workflow tắt gọn](#66-control--lệnh-workflow-tắt-gọn)
|
||||
6.7. [IMR — Điều khiển robot nội địa](#67-imr--điều-khiển-robot-nội-địa)
|
||||
6.8. [AMR — Điều khiển robot vận chuyển](#68-amr--điều-khiển-robot-vận-chuyển)
|
||||
6.9. [DOBOT — Điều khiển cánh tay robot](#69-dobot--điều-khiển-cánh-tay-robot)
|
||||
6.10. [ASRS — Điều khiển kho tự động](#610-asrs--điều-khiển-kho-tự-động)
|
||||
6.11. [SCRIPT — Viết kịch bản tự động](#611-script--viết-kịch-bản-tự-động)
|
||||
- 6.11.1 Giao diện Script
|
||||
- 6.11.2 Biến có sẵn trong script
|
||||
- 6.11.3 Bảng lệnh đầy đủ
|
||||
- 6.11.4 State — Điều kiện (Assert / WaitUntil / Require)
|
||||
- 6.11.5 Chạy song song (Task.WhenAll)
|
||||
- 6.11.6 Ví dụ flow hoàn chỉnh
|
||||
- 6.11.7 Quy tắc viết script
|
||||
- 6.11.8 Xem output log
|
||||
6.12. [Xử lý sự cố thường gặp](#612-xử-lý-sự-cố-thường-gặp)
|
||||
|
||||
---
|
||||
|
||||
## 6.1. Tổng quan giao diện
|
||||
|
||||
*(Xem hình)*
|
||||
|
||||
---
|
||||
|
||||
## 6.2. Đăng nhập và chế độ SIM / REAL
|
||||
|
||||
### 6.2.1 Đăng nhập
|
||||
|
||||
Truy cập địa chỉ web hệ thống → nhập **Username** và **Password** → **Login**.
|
||||
|
||||
### 6.2.2 Chế độ SIM và REAL
|
||||
|
||||
| Chip hiển thị | Ý nghĩa |
|
||||
|---|---|
|
||||
| **SIM** (màu xanh dương) | Đang dùng robot mô phỏng, KHÔNG ảnh hưởng phần cứng thật |
|
||||
| **REAL** (màu vàng cam) | Đang điều khiển robot thật — thao tác có tác dụng ngay |
|
||||
|
||||
> **Lưu ý:** Chip SIM/REAL chỉ hiện với tài khoản có quyền dùng real.
|
||||
> Nếu không thấy chip, tài khoản bạn chỉ dùng được SIM.
|
||||
|
||||
Để **chuyển chế độ**: nhấn vào chip SIM hoặc REAL → hệ thống tự chuyển và kết nối lại.
|
||||
|
||||
---
|
||||
|
||||
## 6.3. STATUS — Xem trạng thái hệ thống
|
||||
|
||||
Panel **STATUS** ở đầu cột phải. Đây là nơi **quan sát**, không điều khiển.
|
||||
|
||||
### 6.3.1 Dòng tiêu đề
|
||||
|
||||
```
|
||||
STATUS [IDLE / RUNNING / Step name] [m:ss] [số chu kỳ ×]
|
||||
```
|
||||
|
||||
| Nhãn | Ý nghĩa |
|
||||
|---|---|
|
||||
| `IDLE` | Không có gì đang chạy |
|
||||
| `RUNNING` | Đang thực thi workflow |
|
||||
| Tên bước (vd `C2 AMR`) | Đang chạy bước cụ thể đó |
|
||||
| `m:ss` | Thời gian đã chạy |
|
||||
| `5 ×` | Đã hoàn thành 5 chu kỳ |
|
||||
| `ERROR` đỏ | Có lỗi — xem chi tiết ngay bên dưới |
|
||||
|
||||
### 6.3.2 Bảng ASRS (lưới 4×3)
|
||||
|
||||
Hiển thị tình trạng ô lưu trữ trong kho ASRS:
|
||||
|
||||
```
|
||||
41 42 43 ← tầng 4 (S34)
|
||||
31 32 33 ← tầng 3 (S34)
|
||||
21 22 23 ← tầng 2 (S12)
|
||||
11 12 13 ← tầng 1 (S12)
|
||||
```
|
||||
|
||||
- **Ô sáng xanh** = có hàng trong ô đó
|
||||
- **Ô tối / viền** = ô trống
|
||||
|
||||
### 6.3.3 Nút điều hướng nhanh
|
||||
|
||||
`CTRL` `OPS` `IMR` `AMR` `Dobot` `ASRS` — nhấn để cuộn ngay đến panel tương ứng.
|
||||
|
||||
---
|
||||
|
||||
## 6.4. CONTROL ACCESS — Lấy quyền điều khiển
|
||||
|
||||
> Đây là bước **bắt buộc** trước khi dùng bất kỳ nút nào trong OPERATIONS, CONTROL, hay Script.
|
||||
> Nếu bỏ qua, tất cả nút sẽ bị khóa với cảnh báo màu cam.
|
||||
|
||||
### Hai chế độ quyền
|
||||
|
||||
| Chế độ | Dành cho | Phạm vi |
|
||||
|---|---|---|
|
||||
| **Workflow Mode (OPS)** | Người có quyền WF | Nắm toàn bộ hệ thống — chạy workflow đầy đủ |
|
||||
| **Manual Mode (Group lock)** | Người có quyền Manual | Nắm 1 nhóm thiết bị — điều khiển thủ công từng robot |
|
||||
|
||||
Hai chế độ **xung đột nhau**: khi Workflow đang bật, Manual bị tắt và ngược lại.
|
||||
|
||||
---
|
||||
|
||||
### 6.4.1 Lấy quyền Workflow (OPS)
|
||||
|
||||
**Dành cho:** tài khoản có quyền Workflow.
|
||||
|
||||
**Các bước:**
|
||||
|
||||
1. Nhìn vào dòng **OPS** trong CONTROL ACCESS
|
||||
2. Nếu hiện `Free` → nhấn **ACQUIRE**
|
||||
3. Chip chuyển sang màu xanh lá **"Bạn giữ"** — bạn đã có quyền
|
||||
4. Bắt đầu thao tác trong OPERATIONS hoặc CONTROL
|
||||
|
||||
**Khi người khác đang giữ:**
|
||||
- Hiện tên người đang giữ (chip đỏ)
|
||||
- Nếu bạn có quyền WF → nhấn **JOIN** để vào hàng chờ
|
||||
- Khi người kia **RELEASE**, bạn tự động lên đầu hàng và nhấn ACQUIRE
|
||||
|
||||
**Khi xong việc:**
|
||||
- Nhấn **RELEASE** để nhả quyền cho người khác
|
||||
- Nhấn **↻** (Refresh) để gia hạn thêm 30 phút nếu cần
|
||||
|
||||
---
|
||||
|
||||
### 6.4.2 Lấy quyền Manual (Group lock)
|
||||
|
||||
**Dành cho:** tài khoản có quyền Manual — điều khiển riêng từng nhóm.
|
||||
|
||||
Ba nhóm thiết bị:
|
||||
|
||||
| Nhóm | Thiết bị |
|
||||
|---|---|
|
||||
| **IMR·Dobot** | Robot IMR + cánh tay Dobot |
|
||||
| **AMR·C1** | Robot AMR + băng tải C1 |
|
||||
| **C2·ASRS** | Băng tải C2 + kho ASRS |
|
||||
|
||||
**Các bước:**
|
||||
|
||||
1. Tìm nhóm bạn cần dùng (vd `IMR·Dobot`)
|
||||
2. Nếu hiện `Free` → nhấn **LOCK**
|
||||
3. Chip chuyển xanh lá **"Bạn"** — bạn đã giữ nhóm đó
|
||||
4. Thao tác trên panel IMR / Dobot
|
||||
5. Xong việc → nhấn **UNLOCK**
|
||||
|
||||
**Quyền Manager / Admin:**
|
||||
- Nút **Preempt** (OPS): thu hồi workflow lock của người khác
|
||||
- Nút **Unassign** (Group): thu hồi group lock của người khác
|
||||
- Icon **👤+**: phân nhóm cho user cụ thể từ danh sách
|
||||
|
||||
---
|
||||
|
||||
## 6.5. OPERATIONS — Chạy từng bước workflow
|
||||
|
||||
> Cần **giữ quyền Workflow (OPS)** trước. Xem mục 4.1.
|
||||
|
||||
Panel **OPERATIONS** liệt kê 8 bước của một chu kỳ sản xuất:
|
||||
|
||||
| Nút | Tên | Mô tả |
|
||||
|---|---|---|
|
||||
| **Home All** | Về vị trí gốc | Đưa tất cả robot về vị trí bắt đầu làm việc |
|
||||
| **1 · Init** | Khởi tạo | Đưa IMR về C1, AMR về Cap2 — chuẩn bị chu kỳ |
|
||||
| **2 · C2 AMR** | AMR lấy từ C2 | AMR load khay từ băng tải C2 |
|
||||
| **3 · → Cap1** | AMR đến Cap1 | AMR chạy từ Cap2 sang trạm Cap1 |
|
||||
| **4 · C:AMR→IMR** | Chuyển AMR→IMR | Chuyển khay từ AMR sang IMR tại C1 |
|
||||
| **5 · →ABB:PICKUP** | Xử lý tại ABB | IMR chạy đến ABB, Dobot thực hiện pick-up |
|
||||
| **6 · C:IMR→AMR** | Chuyển IMR→AMR | Chuyển khay từ IMR sang AMR |
|
||||
| **7 · → Cap2** | AMR đến Cap2 | AMR chạy từ Cap1 về Cap2 |
|
||||
| **8 · AMR C2** | AMR trả về C2 | AMR unload khay lên băng tải C2 |
|
||||
|
||||
### 6.5.1 Thông số trước khi chạy
|
||||
|
||||
| Trường | Ý nghĩa | Để trống |
|
||||
|---|---|---|
|
||||
| **OK** | Số sản phẩm OK | Mặc định = 1 |
|
||||
| **NG** | Số sản phẩm NG | Mặc định = 0 |
|
||||
|
||||
### 6.5.2 Các cách chạy
|
||||
|
||||
**Chạy toàn bộ chu kỳ:**
|
||||
1. Điền OK/NG (hoặc để trống)
|
||||
2. Nhấn nút **▶** (màu xanh lá) — chạy tất cả 8 bước liên tiếp
|
||||
|
||||
**Chạy các bước chọn lọc:**
|
||||
1. Nhấn vào từng bước muốn chạy — nút sáng lên, hiện số thứ tự `1`, `2`, ...
|
||||
2. Có thể chọn nhiều bước (chạy theo thứ tự bạn chọn)
|
||||
3. Nhấn **[n]** (nút vuông, hiện số bước đã chọn) để chạy
|
||||
|
||||
**Chạy một bước đơn lẻ:**
|
||||
- Nhấn thẳng vào nút bước đó (vd `Step 3`) khi đang không chạy gì
|
||||
|
||||
**Dừng khẩn cấp:**
|
||||
- Nhấn **Cancel** (màu đỏ) ở đầu panel — dừng ngay + gửi lệnh emergency stop
|
||||
|
||||
### 6.5.3 Cảnh báo vị trí
|
||||
|
||||
Nếu bạn cố chạy một bước mà robot chưa ở đúng vị trí, hệ thống sẽ in **cảnh báo vàng** ra output log (không block nhưng cần chú ý):
|
||||
|
||||
```
|
||||
[WARN] AMR chưa ở Cap2 → chạy Step 1 Init trước
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6.6. CONTROL — Lệnh workflow tắt gọn
|
||||
|
||||
> Cần **giữ quyền Workflow (OPS)** trước. Xem mục 4.1.
|
||||
|
||||
Panel **CONTROL** cung cấp các lệnh workflow đóng gói sẵn (chạy xong cả chu kỳ chỉ 1 nút).
|
||||
|
||||
### 6.6.1 Thông số
|
||||
|
||||
| Trường | Ý nghĩa |
|
||||
|---|---|
|
||||
| **OK** | Số sản phẩm OK trong lần chạy |
|
||||
| **NG** | Số sản phẩm NG |
|
||||
|
||||
### 6.6.2 Nhóm X_A (màu vàng cam) — lấy từ kệ S34/S4x
|
||||
|
||||
| Nút | Điều kiện bật | Ý nghĩa |
|
||||
|---|---|---|
|
||||
| **X1A** | Ô 31 hoặc 41 có hàng | Lấy từ cột 1 kệ S34 |
|
||||
| **X2A** | Ô 32 hoặc 42 có hàng | Lấy từ cột 2 kệ S34 |
|
||||
| **X3A** | Ô 33 hoặc 43 có hàng | Lấy từ cột 3 kệ S34 |
|
||||
|
||||
### 6.6.3 Nhóm X_B (màu xanh dương) — lấy từ kệ S12/S1x/S2x
|
||||
|
||||
| Nút | Điều kiện bật | Ý nghĩa |
|
||||
|---|---|---|
|
||||
| **X1B** | Ô 11 hoặc 21 có hàng | Lấy từ cột 1 kệ S12 |
|
||||
| **X2B** | Ô 12 hoặc 22 có hàng | Lấy từ cột 2 kệ S12 |
|
||||
| **X3B** | Ô 13 hoặc 23 có hàng | Lấy từ cột 3 kệ S12 |
|
||||
|
||||
> Nút tự động **disabled** (xám) nếu ô kho tương ứng trống, hoặc đang có workflow khác chạy.
|
||||
|
||||
**Nút Cancel** (đầu panel, màu đỏ): dừng workflow đang chạy.
|
||||
|
||||
---
|
||||
|
||||
## 6.7. IMR — Điều khiển robot nội địa
|
||||
|
||||
> Cần giữ quyền **Manual Group IMR·Dobot** hoặc **Workflow**.
|
||||
|
||||
### Trạng thái
|
||||
|
||||
| Màu chấm | Trạng thái | Ý nghĩa |
|
||||
|---|---|---|
|
||||
| 🟢 Xanh lá | `OK` | Sẵn sàng |
|
||||
| 🔵 Xanh dương | `MOVING` | Đang di chuyển |
|
||||
| 🔴 Đỏ | `ERROR` | Có lỗi, xem dòng Errors |
|
||||
| ⚫ Tối | `OFF` | Mất kết nối |
|
||||
|
||||
### 6.7.1 Move — Di chuyển đến vị trí
|
||||
|
||||
| Nút | Vị trí |
|
||||
|---|---|
|
||||
| **C1** | Trạm C1 (băng tải 1) |
|
||||
| **ABB** | Trạm ABB (cánh tay Dobot) |
|
||||
|
||||
> **Cảnh báo:** Nếu IMR đang docked (đã kết nối trạm), nhấn C1/ABB sẽ có popup cảnh báo "IMR đang docked — lùi trước khi di chuyển!". Phải **Undock** trước.
|
||||
|
||||
### 6.7.2 Action — Hành động
|
||||
|
||||
| Nút | Ý nghĩa |
|
||||
|---|---|
|
||||
| **Load** | Nhận khay lên robot (qua conveyor/dock) |
|
||||
| **Unload** | Trả khay xuống |
|
||||
| **MS Xm** (ví dụ MS0.5m) | Undock — lùi ra khỏi trạm một khoảng cố định |
|
||||
|
||||
### 6.7.3 NAV — Điều khiển navigation
|
||||
|
||||
| Nút | Ý nghĩa |
|
||||
|---|---|
|
||||
| **Resume** | Tiếp tục di chuyển sau khi tạm dừng |
|
||||
| **Pause** | Tạm dừng |
|
||||
| **Reset** | Reset lỗi navigation |
|
||||
| **Cancel** | Hủy lệnh đang thực thi |
|
||||
|
||||
### 6.7.4 InitPose — Đặt lại vị trí ban đầu
|
||||
|
||||
Dùng khi bản đồ SLAM bị lệch (robot "nghĩ" nó ở sai chỗ).
|
||||
|
||||
1. Nhập tọa độ **X**, **Y**, **Yaw** (góc) theo bản đồ thực tế
|
||||
2. Nhấn **InitPose** — robot cập nhật lại vị trí trong hệ thống SLAM
|
||||
3. Chờ confirm xanh lá hoặc cảnh báo vàng
|
||||
|
||||
---
|
||||
|
||||
## 6.8. AMR — Điều khiển robot vận chuyển
|
||||
|
||||
> Cần giữ quyền **Manual Group AMR·C1** hoặc **Workflow**.
|
||||
|
||||
### Trạng thái
|
||||
|
||||
Tương tự IMR: OK / MOVING / ERROR / OFF.
|
||||
|
||||
### 6.8.1 Move — Di chuyển đến vị trí
|
||||
|
||||
| Nút | Vị trí |
|
||||
|---|---|
|
||||
| **Cap1** | Trạm Cap1 (kết nối với IMR) |
|
||||
| **Cap2** | Trạm Cap2 (kết nối băng tải C2) |
|
||||
| **Home** | Vị trí đỗ nghỉ |
|
||||
|
||||
> **Cảnh báo:** Tương tự IMR — không di chuyển khi đang docked, phải **Undock** trước.
|
||||
|
||||
### 6.8.2 Action — Hành động
|
||||
|
||||
| Nút | Ý nghĩa |
|
||||
|---|---|
|
||||
| **Load** | Nhận khay lên AMR tại trạm hiện tại |
|
||||
| **Unload** | Trả khay xuống trạm |
|
||||
| **Undock** | Tách ra khỏi trạm đang kết nối |
|
||||
| **Cancel** | Hủy lệnh đang thực thi |
|
||||
|
||||
---
|
||||
|
||||
## 6.9. DOBOT — Điều khiển cánh tay robot
|
||||
|
||||
> Cần giữ quyền **Manual Group IMR·Dobot** hoặc **Workflow**.
|
||||
|
||||
### Trạng thái
|
||||
|
||||
| Màu chấm | Trạng thái |
|
||||
|---|---|
|
||||
| 🟢 Xanh lá | OK / Idle |
|
||||
| 🔵 Xanh dương | MOVING (đang thực hiện lệnh) |
|
||||
| 🟡 Vàng | CANCELED |
|
||||
| 🔴 Đỏ | ERROR |
|
||||
| ⚫ Tối | OFF (code = 9999) |
|
||||
|
||||
Dòng dưới trạng thái hiện: `DobotStatus | Code: X` — tra theo tài liệu Dobot nếu code ≠ 0.
|
||||
|
||||
### 6.9.1 Control
|
||||
|
||||
| Nút | Ý nghĩa |
|
||||
|---|---|
|
||||
| **Home** | Đưa cánh tay về vị trí gốc (GoHome) |
|
||||
| **Continue** | Tiếp tục task đang bị pause |
|
||||
| **PowerOn** | Bật nguồn cánh tay |
|
||||
| **Cancel** | Dừng task hiện tại |
|
||||
|
||||
### 6.9.2 Pick — Thực hiện gắp hàng
|
||||
|
||||
1. Nhập số **OK** và **NG** (sản phẩm trong khay)
|
||||
2. Nhấn **Pick Up** — Dobot thực hiện sequence gắp
|
||||
|
||||
---
|
||||
|
||||
## 6.10. ASRS — Điều khiển kho tự động
|
||||
|
||||
> Cần giữ quyền **Manual Group C2·ASRS** hoặc **Workflow**.
|
||||
|
||||
### 6.10.1 Cấu trúc kho
|
||||
|
||||
ASRS có 4 tầng × 3 cột = 12 ô:
|
||||
|
||||
```
|
||||
Cột: 1 2 3
|
||||
T4: [41] [42] [43] ← S34 (tầng 3-4)
|
||||
T3: [31] [32] [33] ↗
|
||||
T2: [21] [22] [23] ← S12 (tầng 1-2)
|
||||
T1: [11] [12] [13] ↗
|
||||
```
|
||||
|
||||
### 6.10.2 Tên lệnh
|
||||
|
||||
Lệnh ASRS theo cấu trúc: `[X/R][1/2/3]_[S12/S34]`
|
||||
|
||||
- **X** = lấy ra (eXtract / Pick empty box)
|
||||
- **R** = trả vào (Return tray)
|
||||
- **1/2/3** = cột
|
||||
- **S12** = kệ tầng 1-2 | **S34** = kệ tầng 3-4
|
||||
|
||||
| Nút | Hành động |
|
||||
|---|---|
|
||||
| **X1_S34** | Lấy khay trống từ cột 1, kệ S34 |
|
||||
| **X2_S34** | Lấy khay trống từ cột 2, kệ S34 |
|
||||
| **X3_S34** | Lấy khay trống từ cột 3, kệ S34 |
|
||||
| **X1_S12** | Lấy khay trống từ cột 1, kệ S12 |
|
||||
| ... | ... |
|
||||
| **X1_R43** | Trả khay vào cột 1, kệ S34 |
|
||||
| **X1_R12** | Trả khay vào cột 1, kệ S12 |
|
||||
| **Homing** | Đưa ASRS về vị trí gốc (chạy khi khởi động) |
|
||||
|
||||
> Nút tự động **disabled** nếu:
|
||||
> - ASRS đang bận (`IsBusy`)
|
||||
> - Ô không có hàng (lệnh X) / ô đã đầy (lệnh R)
|
||||
> - SAFETY_MODE = OFF (cảm biến an toàn không OK)
|
||||
|
||||
---
|
||||
|
||||
## 6.11. SCRIPT — Viết kịch bản tự động
|
||||
|
||||
> Cần giữ quyền **Workflow (OPS)** hoặc **Manual** trước khi nhấn Run. Xem mục 6.4.
|
||||
|
||||
> Script dùng ngôn ngữ C# — **không cần biết lập trình sâu**. Chỉ cần copy ví dụ bên dưới và sửa lại tên bước, số OK/NG theo nhu cầu.
|
||||
|
||||
Panel Script ở **cột trái** giao diện. Đây là nơi bạn viết chương trình tự động hóa.
|
||||
|
||||
### 6.11.1 Giao diện Script
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ SCRIPT [Run] [Cancel] [Workflow/Manual badge] │
|
||||
│ [Connected ✓] [Lưu] [VI/EN] │
|
||||
├──────────┬──────────────────────────────────────────┤
|
||||
│ FILES │ │
|
||||
│ │ EDITOR (Monaco) │
|
||||
│ script1 │ │
|
||||
│ script2* │ │
|
||||
│ │ │
|
||||
│ ├──────────────────────────────────────────┤
|
||||
│ [+] │ Output / History │
|
||||
│ │ [INFO] [DONE] [WARN] [ERR] [DEV] │
|
||||
│ │ search log... │
|
||||
└──────────┴──────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 6.11.1.1 Các nút toolbar
|
||||
|
||||
| Nút | Ý nghĩa |
|
||||
|---|---|
|
||||
| **Run** | Chạy script đang có trong editor |
|
||||
| **Cancel** | Dừng script đang chạy |
|
||||
| Badge **Workflow** | Script đang chạy ở chế độ Workflow |
|
||||
| Badge **Manual** | Script đang chạy ở chế độ Manual |
|
||||
| **Connected ✓** | Kết nối SignalR tốt |
|
||||
| **Disconnect** (đỏ) | Mất kết nối — nhấn để kết nối lại |
|
||||
| **Lưu** | Lưu script với tên |
|
||||
| **VI / EN** | Chuyển ngôn ngữ giao diện |
|
||||
|
||||
### 6.11.1.2 Quản lý file script
|
||||
|
||||
- Nhấn **+** trong sidebar để tạo script mới
|
||||
- Nhấn vào tên script để mở
|
||||
- Nhấn **×** trên tên để xóa
|
||||
- Kéo thanh bên để mở rộng/thu hẹp sidebar
|
||||
|
||||
---
|
||||
|
||||
### 6.11.2 Biến có sẵn trong script
|
||||
|
||||
Khi script chạy, bạn có sẵn các đối tượng sau:
|
||||
|
||||
| Biến | Loại | Dùng để |
|
||||
|---|---|---|
|
||||
| `IMR` | `IImrFacade` | Điều khiển robot IMR |
|
||||
| `AMR` | `IAmrFacade` | Điều khiển robot AMR |
|
||||
| `Dobot` | `IDobotFacade` | Điều khiển cánh tay Dobot |
|
||||
| `ASRS` | `IAsrsFacade` | Điều khiển kho ASRS |
|
||||
| `Conveyor` | `IConveyorFacade` | Điều khiển băng tải |
|
||||
| `State` | `ICondition` | Kiểm tra điều kiện / chờ sự kiện |
|
||||
| `Log` | `TextWriter` | Ghi ra output panel |
|
||||
| `Token` | `CancellationToken` | Nhận tín hiệu Cancel từ nút Stop |
|
||||
|
||||
### 6.11.2.1 Template khởi đầu
|
||||
|
||||
Copy đoạn sau vào editor rồi bắt đầu sửa:
|
||||
|
||||
```csharp
|
||||
// ── Bắt đầu script ─────────────────────────────────
|
||||
await Log.WriteLineAsync("[INFO] Bắt đầu...");
|
||||
|
||||
// Viết lệnh của bạn ở đây, ví dụ:
|
||||
await IMR.GoTo("C1", Token);
|
||||
await AMR.GoTo("Cap2", Token);
|
||||
|
||||
await Log.WriteLineAsync("[DONE] Hoàn thành.");
|
||||
```
|
||||
|
||||
> **Lưu ý:** Luôn thêm `Token` vào cuối mỗi lệnh `await` để nút **Cancel** dừng được ngay.
|
||||
|
||||
---
|
||||
|
||||
### 6.11.3 Bảng lệnh đầy đủ
|
||||
|
||||
#### IMR
|
||||
|
||||
```csharp
|
||||
await IMR.GoTo("C1"); // Di chuyển đến C1
|
||||
await IMR.GoTo("ABB"); // Di chuyển đến ABB
|
||||
await IMR.Undock("C1"); // Undock từ trạm C1
|
||||
await IMR.Undock("ABB"); // Undock từ trạm ABB
|
||||
await IMR.Load(); // Nhận khay
|
||||
await IMR.Unload(); // Trả khay
|
||||
await IMR.PickUp(ok: 3, ng: 1);// Gắp hàng (3 OK, 1 NG)
|
||||
await IMR.Cancel(); // Hủy lệnh
|
||||
bool atC1 = IMR.IsAt("C1"); // Kiểm tra vị trí
|
||||
```
|
||||
|
||||
#### AMR
|
||||
|
||||
```csharp
|
||||
await AMR.GoTo("Cap1"); // Di chuyển đến Cap1
|
||||
await AMR.GoTo("Cap2"); // Di chuyển đến Cap2
|
||||
await AMR.GoTo("Home"); // Về Home
|
||||
await AMR.Undock(); // Tách khỏi trạm
|
||||
await AMR.Load(); // Nhận khay
|
||||
await AMR.Unload(); // Trả khay
|
||||
await AMR.Cancel(); // Hủy lệnh
|
||||
bool atCap1 = AMR.IsAt("Cap1");// Kiểm tra vị trí
|
||||
```
|
||||
|
||||
#### Dobot
|
||||
|
||||
```csharp
|
||||
await Dobot.PowerOn(); // Bật nguồn
|
||||
await Dobot.GoHome(); // Về vị trí gốc
|
||||
await Dobot.Continue(); // Tiếp tục task
|
||||
await Dobot.Cancel(); // Dừng
|
||||
await Dobot.Pickup(ok: 2, ng: 0); // Gắp hàng
|
||||
```
|
||||
|
||||
#### ASRS
|
||||
|
||||
```csharp
|
||||
// ── Lấy khay ra (X = eXtract) ──────────────────────
|
||||
await ASRS.X1_S34(Token); // Lấy từ cột 1, kệ S34 (tầng 3-4)
|
||||
await ASRS.X2_S34(Token); // Lấy từ cột 2, kệ S34
|
||||
await ASRS.X3_S34(Token); // Lấy từ cột 3, kệ S34
|
||||
await ASRS.X1_S12(Token); // Lấy từ cột 1, kệ S12 (tầng 1-2)
|
||||
await ASRS.X2_S12(Token); // Lấy từ cột 2, kệ S12
|
||||
await ASRS.X3_S12(Token); // Lấy từ cột 3, kệ S12
|
||||
|
||||
// ── Trả khay vào (R = Return) ───────────────────────
|
||||
await ASRS.X1_R43(Token); // Trả vào cột 1, kệ S34 (tầng 3-4)
|
||||
await ASRS.X2_R43(Token); // Trả vào cột 2, kệ S34
|
||||
await ASRS.X3_R43(Token); // Trả vào cột 3, kệ S34
|
||||
await ASRS.X1_R12(Token); // Trả vào cột 1, kệ S12 (tầng 1-2)
|
||||
await ASRS.X2_R12(Token); // Trả vào cột 2, kệ S12
|
||||
await ASRS.X3_R12(Token); // Trả vào cột 3, kệ S12
|
||||
|
||||
// ── Về gốc ──────────────────────────────────────────
|
||||
await ASRS.SYSTEM_HOMING(Token); // Homing về gốc (chạy khi khởi động)
|
||||
|
||||
// ⚠ Để chờ băng tải có hàng sau khi ASRS chạy, dùng State.WaitUntil (xem mục 6.11.4)
|
||||
```
|
||||
|
||||
#### Conveyor (băng tải)
|
||||
|
||||
```csharp
|
||||
Conveyor.C1In(true); // Bật băng tải C1 chiều vào
|
||||
Conveyor.C1In(false); // Tắt
|
||||
Conveyor.C1Out(true); // Bật băng tải C1 chiều ra
|
||||
Conveyor.C1IMRin(true); // Bật C1 chiều từ IMR vào băng tải
|
||||
Conveyor.C1IMRout(true); // Bật C1 chiều từ băng tải ra IMR
|
||||
Conveyor.C2In(true); // Bật C2 chiều vào
|
||||
Conveyor.C2Out(true); // Bật C2 chiều ra
|
||||
Conveyor.C1Ready(true); // Tín hiệu C1 sẵn sàng
|
||||
Conveyor.C2Ready(true); // Tín hiệu C2 sẵn sàng
|
||||
Conveyor.StopAll(); // Dừng tất cả
|
||||
```
|
||||
|
||||
#### Log — Ghi ra output
|
||||
|
||||
```csharp
|
||||
await Log.WriteLineAsync("Bắt đầu chu kỳ");
|
||||
await Log.WriteLineAsync($"IMR ở C1: {IMR.IsAt("C1")}");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6.11.4 State — Kiểm tra điều kiện hệ thống
|
||||
|
||||
Biến `State` trong script cho phép bạn **đọc trạng thái thực tế** của robot/băng tải và **chờ điều kiện** trước khi ra lệnh.
|
||||
|
||||
#### Các property kiểm tra ngay (instant)
|
||||
|
||||
| Property | Kiểu | Ý nghĩa |
|
||||
|---|---|---|
|
||||
| `State.ImrOnline` | bool | IMR đang kết nối |
|
||||
| `State.ImrReady` | bool | IMR online + không đang di chuyển |
|
||||
| `State.ImrBusy` | bool | IMR đang thực thi lệnh |
|
||||
| `State.ImrAtC1` | bool | IMR đang đứng tại vị trí C1 |
|
||||
| `State.ImrAtABB` | bool | IMR đang đứng tại ABB |
|
||||
| `State.ImrReadyAtC1` | bool | IMR ready VÀ đang tại C1 (để giao khay) |
|
||||
| `State.ImrReadyAtABB` | bool | IMR ready VÀ đang tại ABB |
|
||||
| `State.AmrOnline` | bool | AMR đang kết nối |
|
||||
| `State.AmrReady` | bool | AMR online + không đang di chuyển |
|
||||
| `State.AmrBusy` | bool | AMR đang thực thi lệnh |
|
||||
| `State.AmrAtCap1` | bool | AMR đang tại Cap1 |
|
||||
| `State.AmrAtCap2` | bool | AMR đang tại Cap2 |
|
||||
| `State.AmrReadyAtCap1` | bool | AMR ready VÀ tại Cap1 |
|
||||
| `State.AmrReadyAtCap2` | bool | AMR ready VÀ tại Cap2 |
|
||||
| `State.DobotOnline` | bool | OPC UA (Dobot) đang kết nối |
|
||||
| `State.C1Online` | bool | Modbus C1 đang kết nối |
|
||||
| `State.C1HasGoods` | bool | Băng tải C1 đang có hàng |
|
||||
| `State.C1NotGoods` | bool | Băng tải C1 không có hàng |
|
||||
| `State.C1Idle` | bool | C1 đang đứng yên (không có coil nào bật) |
|
||||
| `State.C1Ready` | bool | C1 báo sẵn sàng |
|
||||
| `State.C1InOn` | bool | Coil C1In đang bật |
|
||||
| `State.C1OutOn` | bool | Coil C1Out đang bật |
|
||||
| `State.C1IMRinOn` | bool | Coil C1IMRin đang bật |
|
||||
| `State.C1IMRoutOn` | bool | Coil C1IMRout đang bật |
|
||||
| `State.C2Online` | bool | Modbus C2 đang kết nối |
|
||||
| `State.C2HasGoods` | bool | Băng tải C2 đang có hàng |
|
||||
| `State.C2Ready` | bool | C2 báo sẵn sàng |
|
||||
| `State.C2Idle` | bool | C2 đang đứng yên |
|
||||
| `State.C2InOn` | bool | Coil C2In đang bật |
|
||||
| `State.C2OutOn` | bool | Coil C2Out đang bật |
|
||||
|
||||
#### Ba phương thức kiểm tra điều kiện
|
||||
|
||||
---
|
||||
|
||||
**`State.Assert(...)` — Kiểm tra ngay, ném lỗi nếu sai**
|
||||
|
||||
Dùng trước khi ra lệnh khi bạn **không muốn chờ**, chỉ muốn xác nhận điều kiện đúng rồi mới tiếp.
|
||||
|
||||
```csharp
|
||||
// Ném InvalidOperationException ngay nếu IMR không ở C1
|
||||
State.Assert(s => s.ImrReadyAtC1, "IMR phải ở C1 trước khi chuyển khay");
|
||||
|
||||
// Sau đó ra lệnh an toàn
|
||||
await IMR.Load(Token);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**`await State.WaitUntil(...)` — Chờ điều kiện (trả về bool)**
|
||||
|
||||
Dừng script tại chỗ cho đến khi điều kiện đúng hoặc hết timeout. Trả về `true` nếu điều kiện đạt, `false` nếu timeout.
|
||||
|
||||
```csharp
|
||||
// Chờ tối đa 30 giây cho IMR về C1
|
||||
bool ok = await State.WaitUntil(s => s.ImrReadyAtC1, timeoutMs: 30_000, ct: Token);
|
||||
if (!ok)
|
||||
{
|
||||
await Log.WriteLineAsync("[ERR] Timeout — IMR không về C1 sau 30s");
|
||||
return;
|
||||
}
|
||||
await Log.WriteLineAsync("[DONE] IMR đã sẵn sàng tại C1");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**`await State.Require(...)` — Chờ điều kiện, tự ném lỗi nếu timeout**
|
||||
|
||||
Như `WaitUntil` nhưng tự ném `TimeoutException` nếu không đạt — script dừng hẳn, không cần `if (!ok)`.
|
||||
|
||||
```csharp
|
||||
// Bắt buộc C1 phải có hàng trong 20 giây, nếu không → throw
|
||||
await State.Require(
|
||||
s => s.C1HasGoods,
|
||||
"C1 không có hàng sau 20 giây",
|
||||
timeoutMs: 20_000,
|
||||
ct: Token
|
||||
);
|
||||
|
||||
// Nếu không throw, chắc chắn C1 đã có hàng
|
||||
await IMR.Load(Token);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Khi nào dùng cái nào?
|
||||
|
||||
| Tình huống | Dùng |
|
||||
|---|---|
|
||||
| Cần kiểm tra ngay — không chờ | `State.Assert(...)` |
|
||||
| Chờ và tự xử lý nếu timeout | `await State.WaitUntil(...)` |
|
||||
| Chờ và để hệ thống tự báo lỗi | `await State.Require(...)` |
|
||||
|
||||
---
|
||||
|
||||
### 6.11.5 Chạy song song (Parallel)
|
||||
|
||||
Mặc định các lệnh `await` chạy **tuần tự** — lệnh sau chờ lệnh trước xong.
|
||||
Khi muốn **hai robot cùng di chuyển một lúc**, dùng `Task.WhenAll(...)`.
|
||||
|
||||
#### Cú pháp
|
||||
|
||||
```csharp
|
||||
// Tuần tự (chậm hơn)
|
||||
await IMR.GoTo("C1", Token); // chờ IMR đến C1 xong
|
||||
await AMR.GoTo("Cap1", Token); // mới bắt đầu AMR
|
||||
|
||||
// Song song (nhanh hơn)
|
||||
await Task.WhenAll(
|
||||
IMR.GoTo("C1", Token), // IMR và AMR chạy cùng lúc
|
||||
AMR.GoTo("Cap1", Token)
|
||||
);
|
||||
// Đến đây: cả 2 đã đến đích
|
||||
```
|
||||
|
||||
#### Ví dụ thực tế — Init song song
|
||||
|
||||
```csharp
|
||||
// ── Init: đưa IMR về C1 và AMR về Cap2 cùng lúc ──
|
||||
await Log.WriteLineAsync("[INFO] Init song song: IMR → C1, AMR → Cap2");
|
||||
await Task.WhenAll(
|
||||
IMR.GoTo("C1", Token),
|
||||
AMR.GoTo("Cap2", Token)
|
||||
);
|
||||
await Log.WriteLineAsync("[DONE] Cả 2 robot đã về vị trí init");
|
||||
```
|
||||
|
||||
#### Ví dụ — Chờ cả 2 điều kiện trước khi tiếp
|
||||
|
||||
```csharp
|
||||
// Chờ cả IMR lẫn AMR đồng thời sẵn sàng (mỗi cái chờ độc lập)
|
||||
await Task.WhenAll(
|
||||
State.WaitUntil(s => s.ImrReadyAtC1, timeoutMs: 60_000, ct: Token),
|
||||
State.WaitUntil(s => s.AmrReadyAtCap1, timeoutMs: 60_000, ct: Token)
|
||||
);
|
||||
await Log.WriteLineAsync("[DONE] Cả IMR và AMR đã ở vị trí trao khay");
|
||||
```
|
||||
|
||||
#### Lưu ý khi chạy song song
|
||||
|
||||
| Quy tắc | Lý do |
|
||||
|---|---|
|
||||
| Chỉ song song khi 2 lệnh **độc lập nhau** | Nếu lệnh B cần kết quả của lệnh A → phải tuần tự |
|
||||
| Không song song IMR và Dobot cùng Pick | Pick đi qua IMR queue — tự khóa lẫn nhau |
|
||||
| Không song song 2 lệnh trên cùng 1 robot | Robot chỉ nhận 1 lệnh tại một thời điểm |
|
||||
| Luôn truyền cùng `Token` | Khi Cancel, cả 2 task đều dừng ngay |
|
||||
|
||||
---
|
||||
|
||||
### 6.11.6 Ví dụ flow hoàn chỉnh
|
||||
|
||||
Một **flow** là chuỗi lệnh `await` chạy tuần tự, mỗi lệnh chờ lệnh trước xong mới chạy tiếp.
|
||||
|
||||
#### Ví dụ A — Flow đơn giản: đưa IMR từ C1 sang ABB
|
||||
|
||||
```csharp
|
||||
// Kiểm tra IMR đang ở C1 chưa
|
||||
if (!IMR.IsAt("C1"))
|
||||
{
|
||||
await Log.WriteLineAsync("[WARN] IMR chưa ở C1, đang di chuyển...");
|
||||
await IMR.GoTo("C1", Token);
|
||||
}
|
||||
|
||||
// Undock khỏi C1
|
||||
await Log.WriteLineAsync("[INFO] Undock khỏi C1...");
|
||||
await IMR.Undock("C1", Token);
|
||||
|
||||
// Di chuyển sang ABB
|
||||
await Log.WriteLineAsync("[INFO] Di chuyển sang ABB...");
|
||||
await IMR.GoTo("ABB", Token);
|
||||
|
||||
await Log.WriteLineAsync("[DONE] IMR đã đến ABB.");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Ví dụ B — Flow 1 chu kỳ sản xuất đầy đủ (có State check + song song)
|
||||
|
||||
```csharp
|
||||
// ─── BƯỚC 1: Init song song ────────────────────────
|
||||
await Log.WriteLineAsync("[INFO] Step 1: Init — IMR → C1 và AMR → Cap2 cùng lúc");
|
||||
await Task.WhenAll(
|
||||
IMR.GoTo("C1", Token),
|
||||
AMR.GoTo("Cap2", Token)
|
||||
);
|
||||
|
||||
// ─── BƯỚC 2: AMR lấy khay từ C2 ───────────────────
|
||||
await Log.WriteLineAsync("[INFO] Step 2: AMR load từ C2");
|
||||
// Chắc chắn AMR đã sẵn sàng tại Cap2 (throw nếu không đạt trong 30s)
|
||||
await State.Require(s => s.AmrReadyAtCap2, "AMR phải ở Cap2", 30_000, Token);
|
||||
Conveyor.C2In(true);
|
||||
await AMR.Load(Token);
|
||||
Conveyor.C2In(false);
|
||||
|
||||
// ─── BƯỚC 3: AMR chạy đến Cap1 ────────────────────
|
||||
await Log.WriteLineAsync("[INFO] Step 3: AMR → Cap1");
|
||||
await AMR.Undock(Token);
|
||||
await AMR.GoTo("Cap1", Token);
|
||||
|
||||
// ─── BƯỚC 4: Chuyển khay AMR → IMR ────────────────
|
||||
await Log.WriteLineAsync("[INFO] Step 4: Chuyển khay AMR → IMR");
|
||||
// Đảm bảo cả 2 robot đã ở đúng vị trí trao khay
|
||||
await State.Require(s => s.ImrReadyAtC1, "IMR phải sẵn sàng tại C1", 30_000, Token);
|
||||
await State.Require(s => s.AmrReadyAtCap1, "AMR phải sẵn sàng tại Cap1", 30_000, Token);
|
||||
Conveyor.C1In(true);
|
||||
await AMR.Unload(Token);
|
||||
await State.Require(s => s.C1HasGoods, "C1 phải có hàng sau khi AMR unload", 15_000, Token);
|
||||
await IMR.Load(Token);
|
||||
Conveyor.C1In(false);
|
||||
|
||||
// ─── BƯỚC 5: IMR đến ABB, Dobot pick-up ───────────
|
||||
await Log.WriteLineAsync("[INFO] Step 5: IMR → ABB + Dobot PickUp");
|
||||
await IMR.Undock("C1", Token);
|
||||
await IMR.GoTo("ABB", Token);
|
||||
await State.Require(s => s.ImrReadyAtABB, "IMR phải ở ABB", 60_000, Token);
|
||||
await IMR.PickUp(ok: 3, ng: 0, ct: Token);
|
||||
|
||||
// ─── BƯỚC 6: Chuyển khay IMR → AMR ────────────────
|
||||
await Log.WriteLineAsync("[INFO] Step 6: Chuyển khay IMR → AMR");
|
||||
Conveyor.C1IMRout(true);
|
||||
await IMR.Unload(Token);
|
||||
await State.Require(s => s.C1HasGoods, "C1 phải có hàng từ IMR", 15_000, Token);
|
||||
await AMR.Load(Token);
|
||||
Conveyor.C1IMRout(false);
|
||||
|
||||
// ─── BƯỚC 7: AMR chạy đến Cap2 ────────────────────
|
||||
await Log.WriteLineAsync("[INFO] Step 7: AMR → Cap2");
|
||||
await AMR.Undock(Token);
|
||||
await AMR.GoTo("Cap2", Token);
|
||||
|
||||
// ─── BƯỚC 8: AMR trả khay lên C2 ──────────────────
|
||||
await Log.WriteLineAsync("[INFO] Step 8: AMR unload lên C2");
|
||||
await State.Require(s => s.AmrReadyAtCap2, "AMR phải ở Cap2", 30_000, Token);
|
||||
Conveyor.C2Out(true);
|
||||
await AMR.Unload(Token);
|
||||
Conveyor.C2Out(false);
|
||||
|
||||
await Log.WriteLineAsync("[DONE] Hoàn thành 1 chu kỳ.");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Ví dụ C — Vòng lặp nhiều chu kỳ với Cancel
|
||||
|
||||
```csharp
|
||||
int cycles = 5; // Số chu kỳ muốn chạy
|
||||
|
||||
for (int i = 1; i <= cycles; i++)
|
||||
{
|
||||
// Kiểm tra Cancel trước mỗi chu kỳ
|
||||
if (Token.IsCancellationRequested)
|
||||
{
|
||||
await Log.WriteLineAsync($"[WARN] Hủy tại chu kỳ {i}");
|
||||
break;
|
||||
}
|
||||
|
||||
await Log.WriteLineAsync($"[INFO] ── Chu kỳ {i}/{cycles} ──");
|
||||
|
||||
// ... các bước 1-8 ở đây (copy từ ví dụ 2) ...
|
||||
await IMR.GoTo("C1", Token);
|
||||
// ...
|
||||
|
||||
await Log.WriteLineAsync($"[DONE] Xong chu kỳ {i}");
|
||||
}
|
||||
|
||||
await Log.WriteLineAsync("[DONE] Hoàn thành tất cả chu kỳ.");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Ví dụ D — Dùng ASRS trong flow (chờ bằng State.WaitUntil)
|
||||
|
||||
```csharp
|
||||
// Lấy khay trống từ ASRS cột 1, kệ S34
|
||||
await Log.WriteLineAsync("[INFO] ASRS lấy khay từ X1_S34");
|
||||
await ASRS.X1_S34(Token);
|
||||
|
||||
// Chờ băng tải C2 có hàng (timeout 15 giây)
|
||||
// Dùng State.WaitUntil — KHÔNG dùng ASRS.WaitCoil với State.* (type không khớp)
|
||||
bool hasGoods = await State.WaitUntil(s => s.C2HasGoods, timeoutMs: 15_000, ct: Token);
|
||||
if (!hasGoods)
|
||||
{
|
||||
await Log.WriteLineAsync("[ERR] Timeout — C2 không có hàng sau 15s");
|
||||
return;
|
||||
}
|
||||
|
||||
await Log.WriteLineAsync("[DONE] C2 đã có hàng, tiếp tục...");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6.11.7 Quy tắc viết script
|
||||
|
||||
| Quy tắc | Lý do |
|
||||
|---|---|
|
||||
| Luôn truyền `Token` vào mọi lệnh `await` | Để nút **Cancel** dừng được ngay lập tức |
|
||||
| Luôn `await` mỗi lệnh | Lệnh robot là async — không await sẽ chạy song song, gây va chạm |
|
||||
| Ghi `Log.WriteLine` ở đầu mỗi bước | Dễ debug khi xem output |
|
||||
| Kiểm tra `IMR.IsAt()` / `AMR.IsAt()` trước khi di chuyển | Tránh lệnh di chuyển không cần thiết |
|
||||
| Dùng `if (Token.IsCancellationRequested) break;` trong vòng lặp | Script dừng sạch khi nhấn Cancel |
|
||||
|
||||
---
|
||||
|
||||
### 6.11.8 Xem output log
|
||||
|
||||
Sau khi chạy script, kết quả hiện trong panel **Output** bên dưới editor:
|
||||
|
||||
| Badge | Màu | Ý nghĩa |
|
||||
|---|---|---|
|
||||
| `INFO` | Xanh dương | Thông tin thông thường |
|
||||
| `DONE` | Xanh lá | Bước hoàn thành thành công |
|
||||
| `WARN` | Cam | Cảnh báo, cần chú ý |
|
||||
| `ERR` | Đỏ | Lỗi |
|
||||
| `DEV` | Tím | Debug nội bộ |
|
||||
|
||||
Nhấn vào badge để **lọc** chỉ hiện loại đó. Ô **search log** để tìm kiếm text.
|
||||
|
||||
**Tab History** (Manager/Admin): xem lịch sử tất cả lần chạy script — ai chạy, khi nào, kết quả gì.
|
||||
|
||||
---
|
||||
|
||||
## 6.12. Xử lý sự cố thường gặp
|
||||
|
||||
### Tất cả nút bị xám / disabled
|
||||
|
||||
**Nguyên nhân:** Chưa lấy quyền điều khiển.
|
||||
**Xử lý:** Vào **CONTROL ACCESS** → ACQUIRE (Workflow) hoặc LOCK nhóm (Manual).
|
||||
|
||||
---
|
||||
|
||||
### Cảnh báo cam "Bạn chưa giữ quyền điều khiển"
|
||||
|
||||
**Nguyên nhân:** Đang dùng REAL mà chưa acquire lock.
|
||||
**Xử lý:** Vào CONTROL ACCESS → ACQUIRE.
|
||||
|
||||
---
|
||||
|
||||
### Robot không phản hồi, trạng thái `OFF`
|
||||
|
||||
**Nguyên nhân:** Mất kết nối mạng với robot.
|
||||
**Xử lý:**
|
||||
1. Kiểm tra robot có bật nguồn không
|
||||
2. Kiểm tra cáp mạng / WiFi
|
||||
3. Liên hệ kỹ thuật
|
||||
|
||||
---
|
||||
|
||||
### IMR báo lỗi khi di chuyển: "IMR đang docked"
|
||||
|
||||
**Nguyên nhân:** IMR đang kết nối trạm, cần lùi ra trước.
|
||||
**Xử lý:** Nhấn **MS Xm** (Undock) trước khi nhấn C1/ABB.
|
||||
|
||||
---
|
||||
|
||||
### Script chạy xong không có gì xảy ra
|
||||
|
||||
**Nguyên nhân phổ biến:**
|
||||
1. Đang ở chế độ **SIM** — chạy trên robot giả, không ảnh hưởng thật
|
||||
2. Thiếu `await` trước lệnh
|
||||
3. Chạy lệnh song song (gửi nhưng không chờ) — thêm `await`
|
||||
|
||||
---
|
||||
|
||||
### Nút "Disconnect" đỏ ở toolbar Script
|
||||
|
||||
**Nguyên nhân:** Mất kết nối SignalR realtime.
|
||||
**Xử lý:** Nhấn vào nút **Disconnect** để thử kết nối lại. Nếu không được, reload trang.
|
||||
|
||||
---
|
||||
|
||||
### ASRS không nhận lệnh (nút xám)
|
||||
|
||||
**Nguyên nhân có thể:**
|
||||
- `SAFETY_MODE = OFF` — cảm biến an toàn chưa OK
|
||||
- Ô kho không có hàng (lệnh X) hoặc đã đầy (lệnh R)
|
||||
- ASRS đang bận (`IsBusy`)
|
||||
|
||||
**Xử lý:** Kiểm tra bảng ASRS trong STATUS — ô sáng = có hàng, ô tối = trống.
|
||||
|
||||
---
|
||||
|
||||
### Workflow bị người khác giữ
|
||||
|
||||
**Nguyên nhân:** Đồng nghiệp đang dùng quyền WF.
|
||||
**Xử lý:**
|
||||
1. Nhìn chip đỏ trong **OPS** → tên người đang giữ
|
||||
2. Nhấn **JOIN** để vào hàng chờ
|
||||
3. Chờ họ RELEASE → bạn lên đầu hàng → nhấn ACQUIRE
|
||||
4. Nếu khẩn cấp: nhờ Manager/Admin nhấn **Preempt**
|
||||
|
||||
---
|
||||
|
||||
*Tài liệu cập nhật: 2026-04-02 | Hệ thống: Lab 505*
|
||||
30
Lab505.Client/Lab505.Client.csproj
Normal file
30
Lab505.Client/Lab505.Client.csproj
Normal file
@@ -0,0 +1,30 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<HotReloadEnabled>false</HotReloadEnabled>
|
||||
<!-- Thêm 2 dòng này -->
|
||||
<BlazorWebAssemblyEnableLinking>true</BlazorWebAssemblyEnableLinking>
|
||||
<PublishTrimmed>true</PublishTrimmed>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Loại bỏ HotReload package khỏi publish -->
|
||||
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="10.0.6" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.6" />
|
||||
<PackageReference Include="MudBlazor" Version="9.3.0" />
|
||||
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Thêm block này để exclude HotReload -->
|
||||
<ItemGroup>
|
||||
<BlazorWebAssemblyLazyLoad Remove="Microsoft.DotNet.HotReload.WebAssembly.Browser.dll" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Lab505.Shared\Lab505.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
211
Lab505.Client/Pages/AmrPanel.razor
Normal file
211
Lab505.Client/Pages/AmrPanel.razor
Normal file
@@ -0,0 +1,211 @@
|
||||
@implements IAsyncDisposable
|
||||
|
||||
<MudPaper Elevation="0" Class="pa-3" Style="background:transparent;">
|
||||
|
||||
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
|
||||
Style="cursor:pointer" @onclick="ToggleAMR">
|
||||
<MudText Typo="Typo.subtitle1">AMR</MudText>
|
||||
<MudIcon Icon="@(IsAmrExpanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
|
||||
</MudStack>
|
||||
|
||||
<div class="status-row mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Circle" Size="Size.Small" Color="@AmrMudColor" />
|
||||
<div>
|
||||
<MudText Typo="Typo.caption">@AmrStatus.ToUpper()</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color:#9a9a9a;">
|
||||
Errors: @(State.Amr.Errors is { Count: > 0 } errs ? string.Join(", ", errs) : "none")
|
||||
</MudText>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-1 mb-1">
|
||||
<MudButton FullWidth="true" Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small" OnClick="Cancel_Vda" Disabled="@(!State.CanControl)">Cancel</MudButton>
|
||||
</div>
|
||||
|
||||
@if (IsAmrExpanded)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Move</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="MovetoCap1" Disabled="@AmrLocked("MoveTo Cap1")">Cap1</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="MovetoCap2" Disabled="@AmrLocked("MoveTo Cap2")">Cap2</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="MovetoHome" Disabled="@AmrLocked("MoveTo Home")">Home</MudButton>
|
||||
</div>
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Action</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="AMR_Load" Disabled="@AmrLocked("Load")">Load</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="AMR_Unload" Disabled="@AmrLocked("Unload")">Unload</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="UndockFromStation" Disabled="@UndockBlocked()">Undock</MudButton>
|
||||
</div>
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">NAV</MudText>
|
||||
<div class="op-grid-2">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Resume" Disabled="@(!State.CanControl)">Resume</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Pause" Disabled="@(!State.CanControl)">Pause</MudButton>
|
||||
</div>
|
||||
<div class="op-grid-4 mt-2">
|
||||
<MudNumericField T="double?" @bind-Value="_poseX" Placeholder="X" Variant="Variant.Outlined"
|
||||
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
|
||||
HideSpinButtons="true" Class="pnl-num" />
|
||||
<MudNumericField T="double?" @bind-Value="_poseY" Placeholder="Y" Variant="Variant.Outlined"
|
||||
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
|
||||
HideSpinButtons="true" Class="pnl-num" />
|
||||
<MudNumericField T="double?" @bind-Value="_poseTheta" Placeholder="θ" Variant="Variant.Outlined"
|
||||
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
|
||||
HideSpinButtons="true" Class="pnl-num" />
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Color="Color.Warning"
|
||||
StartIcon="@(_settingPose ? Icons.Material.Filled.HourglassBottom : null)"
|
||||
OnClick="RunInitPosition" Disabled="@(_settingPose || !State.CanControl)">
|
||||
@(_settingPose ? "..." : "InitPos")
|
||||
</MudButton>
|
||||
</div>
|
||||
}
|
||||
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Inject] StateService State { get; set; } = default!;
|
||||
[Inject] CommandService Cmd { get; set; } = default!;
|
||||
[Inject] ISnackbar Snackbar { get; set; } = default!;
|
||||
[Inject] LangService Lang { get; set; } = default!;
|
||||
|
||||
bool IsAmrExpanded = true;
|
||||
void ToggleAMR() => IsAmrExpanded = !IsAmrExpanded;
|
||||
|
||||
private double? _poseX;
|
||||
private double? _poseY;
|
||||
private double? _poseTheta;
|
||||
private bool _settingPose;
|
||||
private CancellationTokenSource? _initPoseCts;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.AmrChanged += Refresh;
|
||||
State.WorkflowChanged += Refresh;
|
||||
Lang.LangChanged += Refresh;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.AmrChanged -= Refresh;
|
||||
State.WorkflowChanged -= Refresh;
|
||||
Lang.LangChanged -= Refresh;
|
||||
try { _initPoseCts?.Cancel(); } catch { }
|
||||
_initPoseCts?.Dispose();
|
||||
_initPoseCts = null;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void Refresh() => InvokeAsync(StateHasChanged);
|
||||
|
||||
private string AmrStatus
|
||||
{
|
||||
get
|
||||
{
|
||||
var s = State.Amr;
|
||||
if (!s.IsOnline) return "off";
|
||||
if (s.Errors.Count > 0) return "error";
|
||||
if (s.NewBaseRequest == false) return "moving";
|
||||
return "ok";
|
||||
}
|
||||
}
|
||||
|
||||
private Color AmrMudColor => AmrStatus switch
|
||||
{
|
||||
"ok" => Color.Success,
|
||||
"moving" => Color.Info,
|
||||
"error" => Color.Error,
|
||||
_ => Color.Default
|
||||
};
|
||||
|
||||
private Task Cancel_Vda() => Cmd.AmrCancelAsync();
|
||||
|
||||
// Nút bị khóa nếu là lệnh đang chạy HOẶC lệnh đang chờ trong hàng đợi, hoặc không có quyền điều khiển
|
||||
private bool AmrLocked(string label)
|
||||
=> !State.CanControl || State.Workflow.AmrBusyLabel == label || State.Workflow.AmrNextLabel == label;
|
||||
|
||||
// Undock bị khóa khi không ở trạm dock hoặc đang bận
|
||||
private bool UndockBlocked() => AmrLocked("Undock") || !AmrAtDock();
|
||||
|
||||
// Cảnh báo khi robot online+idle tại Home (không phải trạm dock)
|
||||
private bool AmrIdleAtHome()
|
||||
{
|
||||
var s = State.Amr;
|
||||
return s.IsOnline && s.NewBaseRequest == true
|
||||
&& Near(s.X, s.Y, RobotPositions.AMR_HOME_X, RobotPositions.AMR_HOME_Y);
|
||||
}
|
||||
|
||||
private static bool Near(double x, double y, double tx, double ty)
|
||||
=> Math.Abs(x - tx) < RobotPositions.POS_TOL && Math.Abs(y - ty) < RobotPositions.POS_TOL;
|
||||
|
||||
private bool AmrAtDock()
|
||||
{
|
||||
var s = State.Amr;
|
||||
return Near(s.X, s.Y, RobotPositions.AMR_CAP1_X, RobotPositions.AMR_CAP1_Y)
|
||||
|| Near(s.X, s.Y, RobotPositions.AMR_CAP2_X, RobotPositions.AMR_CAP2_Y);
|
||||
}
|
||||
|
||||
private Task MovetoCap1()
|
||||
{
|
||||
if (AmrAtDock() && State.Workflow.AmrCmd != "undocking")
|
||||
{ Snackbar.Add(Lang.T("AMR đang docked — lùi trước khi di chuyển!", "AMR is docked — undock before moving!"), Severity.Warning); return Task.CompletedTask; }
|
||||
return Cmd.AmrMoveToAsync("Cap1");
|
||||
}
|
||||
|
||||
private Task MovetoCap2()
|
||||
{
|
||||
if (AmrAtDock() && State.Workflow.AmrCmd != "undocking")
|
||||
{ Snackbar.Add(Lang.T("AMR đang docked — lùi trước khi di chuyển!", "AMR is docked — undock before moving!"), Severity.Warning); return Task.CompletedTask; }
|
||||
return Cmd.AmrMoveToAsync("Cap2");
|
||||
}
|
||||
private Task MovetoHome() => Cmd.AmrMoveToAsync("Home");
|
||||
private Task AMR_Load() => Cmd.AmrLoadAsync();
|
||||
private Task AMR_Unload() => Cmd.AmrUnloadAsync();
|
||||
private Task UndockFromStation()=> Cmd.AmrUndockAsync();
|
||||
|
||||
private Task Pause() => Cmd.AmrPauseAsync();
|
||||
private Task Resume() => Cmd.AmrResumeAsync();
|
||||
|
||||
private async Task RunInitPosition()
|
||||
{
|
||||
_initPoseCts?.Dispose();
|
||||
_initPoseCts = new CancellationTokenSource();
|
||||
var ct = _initPoseCts.Token;
|
||||
|
||||
_settingPose = true;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
|
||||
try
|
||||
{
|
||||
var x = _poseX ?? 0;
|
||||
var y = _poseY ?? 0;
|
||||
var theta = _poseTheta ?? 0;
|
||||
|
||||
// VDA initPosition instant action
|
||||
await Cmd.AmrInitPositionAsync(x, y, theta, ct);
|
||||
Snackbar.Add(
|
||||
Lang.T(
|
||||
$"Đã gửi InitPosition ({x:F2}, {y:F2}, {theta:F2})",
|
||||
$"InitPosition sent ({x:F2}, {y:F2}, {theta:F2})"),
|
||||
Severity.Success);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Snackbar.Add(Lang.T("InitPosition đã huỷ", "InitPosition cancelled"), Severity.Info);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_settingPose = false;
|
||||
_initPoseCts?.Dispose();
|
||||
_initPoseCts = null;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
<style>
|
||||
.status-row { display:flex; align-items:center; gap:8px; margin-bottom:4px; }
|
||||
.sec-title { display:block; color:#9CA3AF; margin-bottom:4px; }
|
||||
.op-grid { display:grid; grid-template-columns:repeat(3, 1fr); gap:5px; }
|
||||
.op-grid-2 { display:grid; grid-template-columns:1fr 1fr; gap:5px; }
|
||||
.op-grid-4 { display:grid; grid-template-columns:repeat(4, 1fr); gap:5px; }
|
||||
</style>
|
||||
87
Lab505.Client/Pages/AsrsPanel.razor
Normal file
87
Lab505.Client/Pages/AsrsPanel.razor
Normal file
@@ -0,0 +1,87 @@
|
||||
@implements IAsyncDisposable
|
||||
|
||||
<MudPaper Elevation="0" Class="pa-2" Style="background:transparent;">
|
||||
|
||||
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
|
||||
Style="cursor:pointer" @onclick="ToggleASRS">
|
||||
<MudText Typo="Typo.subtitle1">ASRS</MudText>
|
||||
<MudIcon Icon="@(IsAsrsExpanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
|
||||
</MudStack>
|
||||
|
||||
|
||||
<MudCollapse Expanded="@IsAsrsExpanded">
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Pick Empty Box (S34)</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X1_S34", CanRun_S34(1)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X1_S34")'>X1_S34</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X2_S34", CanRun_S34(2)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X2_S34")'>X2_S34</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X3_S34", CanRun_S34(3)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X3_S34")'>X3_S34</MudButton>
|
||||
</div>
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Pick Empty Box (S12)</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X1_S12", CanRun_S12(1)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X1_S12")'>X1_S12</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X2_S12", CanRun_S12(2)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X2_S12")'>X2_S12</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X3_S12", CanRun_S12(3)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X3_S12")'>X3_S12</MudButton>
|
||||
</div>
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Return Tray (R43)</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X1_R43", CanRun_R43(1)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X1_R43")'>X1_R43</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X2_R43", CanRun_R43(2)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X2_R43")'>X2_R43</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X3_R43", CanRun_R43(3)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X3_R43")'>X3_R43</MudButton>
|
||||
</div>
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Return Tray (R12)</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X1_R12", CanRun_R12(1)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X1_R12")'>X1_R12</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X2_R12", CanRun_R12(2)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X2_R12")'>X2_R12</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X3_R12", CanRun_R12(3)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X3_R12")'>X3_R12</MudButton>
|
||||
</div>
|
||||
|
||||
<div class="mt-2">
|
||||
<MudButton FullWidth="true" Variant="Variant.Outlined" Color="Color.Primary" Size="Size.Small"
|
||||
Disabled="@(State.Asrs.IsBusy || !State.CanControl)" OnClick="Homing">Homing</MudButton>
|
||||
</div>
|
||||
|
||||
</MudCollapse>
|
||||
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Inject] StateService State { get; set; } = default!;
|
||||
[Inject] CommandService Cmd { get; set; } = default!;
|
||||
|
||||
bool IsAsrsExpanded = true;
|
||||
void ToggleASRS() => IsAsrsExpanded = !IsAsrsExpanded;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.AsrsChanged += Refresh;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.AsrsChanged -= Refresh;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void Refresh() => InvokeAsync(StateHasChanged);
|
||||
|
||||
private Task Homing() => Cmd.AsrsHomingAsync();
|
||||
|
||||
private bool CanOp(string label, bool canRun)
|
||||
=> State.CanControl && !State.Asrs.IsBusy && !State.AsrsIsLocked(label)
|
||||
&& State.Asrs.SAFETY_MODE == true && canRun;
|
||||
|
||||
private bool CanRun_S12(int col) => col switch { 1 => State.Asrs.X11 == true, 2 => State.Asrs.X12 == true, 3 => State.Asrs.X13 == true, _ => false };
|
||||
private bool CanRun_R12(int col) => col switch { 1 => State.Asrs.X11 == false, 2 => State.Asrs.X12 == false, 3 => State.Asrs.X13 == false, _ => false };
|
||||
private bool CanRun_S34(int col) => col switch { 1 => State.Asrs.X31 == true, 2 => State.Asrs.X32 == true, 3 => State.Asrs.X33 == true, _ => false };
|
||||
private bool CanRun_R43(int col) => col switch { 1 => State.Asrs.X31 == false, 2 => State.Asrs.X32 == false, 3 => State.Asrs.X33 == false, _ => false };
|
||||
}
|
||||
|
||||
<style>
|
||||
.sec-title { display:block; color:#9CA3AF; margin-bottom:4px; }
|
||||
.op-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px; }
|
||||
</style>
|
||||
208
Lab505.Client/Pages/ControlPanel.razor
Normal file
208
Lab505.Client/Pages/ControlPanel.razor
Normal file
@@ -0,0 +1,208 @@
|
||||
@implements IAsyncDisposable
|
||||
@inject HttpClient Http
|
||||
|
||||
<MudPaper Elevation="0" Class="pa-2" Style="background:transparent;">
|
||||
|
||||
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
|
||||
Style="cursor:pointer" @onclick="ToggleExpand">
|
||||
<MudText Typo="Typo.subtitle1">CONTROL</MudText>
|
||||
<MudIcon Icon="@(_expanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
|
||||
</MudStack>
|
||||
|
||||
@if (IsLockBlocked)
|
||||
{
|
||||
<div style="background:rgba(255,100,0,0.08);border:1px solid rgba(255,100,0,0.25);border-radius:5px;padding:4px 8px;margin-bottom:4px;">
|
||||
<MudText Typo="Typo.caption" Style="color:#f90;">@Lang.T("Bạn chưa giữ quyền điều khiển. Vào CONTROL ACCESS → TAKE CONTROL.", "You don't hold control. Go to CONTROL ACCESS → TAKE CONTROL.")</MudText>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="always-row">
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small" FullWidth="true"
|
||||
OnClick="Cancel" Disabled="@(!IsAnyRunning)">
|
||||
Cancel
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
@if (_expanded)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Params</MudText>
|
||||
<div class="op-grid-2">
|
||||
<MudNumericField T="int?" @bind-Value="_times" Placeholder="OK" Variant="Variant.Outlined" Class="pnl-num" Min="1" Max="99" />
|
||||
<MudNumericField T="int?" @bind-Value="_ng" Placeholder="NG" Variant="Variant.Outlined" Class="pnl-num" Min="0" Max="99" />
|
||||
</div>
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Test</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Tertiary" Size="Size.Small"
|
||||
Disabled="@(IsAnyRunning || IsLockBlocked)"
|
||||
OnClick='()=>RunOp("Test", ct => Cmd.WorkflowRunCycleAsync(_times ?? 1, _ng ?? 0, ct))'>No ASRS</MudButton>
|
||||
</div>
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">X_A</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Warning" Size="Size.Small" Disabled="@(!CanA(1))"
|
||||
OnClick='()=>RunOp("X1A", ct => Cmd.WorkflowX1AAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS34(1))'>X1A</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Warning" Size="Size.Small" Disabled="@(!CanA(2))"
|
||||
OnClick='()=>RunOp("X2A", ct => Cmd.WorkflowX2AAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS34(2))'>X2A</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Warning" Size="Size.Small" Disabled="@(!CanA(3))"
|
||||
OnClick='()=>RunOp("X3A", ct => Cmd.WorkflowX3AAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS34(3))'>X3A</MudButton>
|
||||
</div>
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">X_B</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" Size="Size.Small" Disabled="@(!CanB(1))"
|
||||
OnClick='()=>RunOp("X1B", ct => Cmd.WorkflowX1BAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS12(1))'>X1B</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" Size="Size.Small" Disabled="@(!CanB(2))"
|
||||
OnClick='()=>RunOp("X2B", ct => Cmd.WorkflowX2BAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS12(2))'>X2B</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" Size="Size.Small" Disabled="@(!CanB(3))"
|
||||
OnClick='()=>RunOp("X3B", ct => Cmd.WorkflowX3BAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS12(3))'>X3B</MudButton>
|
||||
</div>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Inject] StateService State { get; set; } = default!;
|
||||
[Inject] CommandService Cmd { get; set; } = default!;
|
||||
[Inject] LangService Lang { get; set; } = default!;
|
||||
|
||||
private bool _expanded = true;
|
||||
void ToggleExpand() => _expanded = !_expanded;
|
||||
|
||||
private int? _times;
|
||||
private int? _ng;
|
||||
private string _myUserId = "";
|
||||
|
||||
private bool IsLockBlocked =>
|
||||
!State.System.IsSimulation
|
||||
&& State.LockState is not null
|
||||
&& (State.LockState.Workflow is null || State.LockState.Workflow.UserId != _myUserId);
|
||||
|
||||
private readonly HashSet<string> _runningOps = new();
|
||||
private readonly Dictionary<string, CancellationTokenSource> _opCts = new();
|
||||
private Func<bool>? _goodsTaken;
|
||||
|
||||
|
||||
private bool IsAnyRunning => _runningOps.Count > 0 || State.Workflow.IsRunning;
|
||||
|
||||
private bool CanA(int col) => !IsAnyRunning && State.CanControl && !IsLockBlocked && col switch
|
||||
{
|
||||
1 => State.Asrs.X31 == true || State.Asrs.X41 == true,
|
||||
2 => State.Asrs.X32 == true || State.Asrs.X42 == true,
|
||||
3 => State.Asrs.X33 == true || State.Asrs.X43 == true,
|
||||
_ => false
|
||||
};
|
||||
|
||||
private bool CanB(int col) => !IsAnyRunning && State.CanControl && !IsLockBlocked && col switch
|
||||
{
|
||||
1 => State.Asrs.X11 == true || State.Asrs.X21 == true,
|
||||
2 => State.Asrs.X12 == true || State.Asrs.X22 == true,
|
||||
3 => State.Asrs.X13 == true || State.Asrs.X23 == true,
|
||||
_ => false
|
||||
};
|
||||
|
||||
// "Goods taken" lambdas for SAFETY_MODE check — read from cached SignalR state
|
||||
private Func<bool> GoodsGoneS34(int col) => col switch
|
||||
{
|
||||
1 => () => State.Asrs.X31 != true && State.Asrs.X41 != true,
|
||||
2 => () => State.Asrs.X32 != true && State.Asrs.X42 != true,
|
||||
_ => () => State.Asrs.X33 != true && State.Asrs.X43 != true,
|
||||
};
|
||||
|
||||
private Func<bool> GoodsGoneS12(int col) => col switch
|
||||
{
|
||||
1 => () => State.Asrs.X11 != true && State.Asrs.X21 != true,
|
||||
2 => () => State.Asrs.X12 != true && State.Asrs.X22 != true,
|
||||
_ => () => State.Asrs.X13 != true && State.Asrs.X23 != true,
|
||||
};
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.WorkflowChanged += OnWorkflowChanged;
|
||||
State.AsrsChanged += OnAsrsChanged;
|
||||
State.LockStateChanged += OnLockChanged;
|
||||
Lang.LangChanged += OnLockChanged;
|
||||
|
||||
try
|
||||
{
|
||||
var me = await Http.GetFromJsonAsync<MeCtrlDto>("/api/auth/me");
|
||||
_myUserId = me?.UserId ?? "";
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.WorkflowChanged -= OnWorkflowChanged;
|
||||
State.AsrsChanged -= OnAsrsChanged;
|
||||
State.LockStateChanged -= OnLockChanged;
|
||||
Lang.LangChanged -= OnLockChanged;
|
||||
CancelAll();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void OnWorkflowChanged() => InvokeAsync(StateHasChanged);
|
||||
private void OnLockChanged() => InvokeAsync(StateHasChanged);
|
||||
|
||||
private void OnAsrsChanged()
|
||||
{
|
||||
// SAFETY_MODE went off during an active operation → cancel unless goods already taken
|
||||
if (State.Asrs.SAFETY_MODE == false && IsAnyRunning)
|
||||
{
|
||||
bool goodsDone = _goodsTaken != null && _goodsTaken();
|
||||
if (!goodsDone)
|
||||
InvokeAsync(CancelAll);
|
||||
}
|
||||
InvokeAsync(StateHasChanged);
|
||||
}
|
||||
|
||||
private void Cancel() => CancelAll();
|
||||
|
||||
record MeCtrlDto(string? UserId);
|
||||
|
||||
private void CancelAll()
|
||||
{
|
||||
foreach (var cts in _opCts.Values) cts.Cancel();
|
||||
_ = Cmd.WorkflowEmergencyStopAsync();
|
||||
}
|
||||
|
||||
private void RunOp(string name, Func<CancellationToken, Task> action, Func<bool>? goodsTaken = null)
|
||||
{
|
||||
if (_runningOps.Contains(name)) return;
|
||||
_goodsTaken = goodsTaken;
|
||||
var cts = new CancellationTokenSource();
|
||||
_opCts[name] = cts;
|
||||
_ = ExecOpAsync(name, action, cts.Token);
|
||||
}
|
||||
|
||||
private async Task ExecOpAsync(string name, Func<CancellationToken, Task> action, CancellationToken token)
|
||||
{
|
||||
await InvokeAsync(() => { _runningOps.Add(name); StateHasChanged(); });
|
||||
try
|
||||
{
|
||||
await action(token);
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception)
|
||||
{
|
||||
_ = Cmd.WorkflowEmergencyStopAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
await InvokeAsync(() =>
|
||||
{
|
||||
_goodsTaken = null;
|
||||
_runningOps.Remove(name);
|
||||
if (_opCts.TryGetValue(name, out var c)) { c.Dispose(); _opCts.Remove(name); }
|
||||
StateHasChanged();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
<style>
|
||||
.sec-title { display:block; color:#9CA3AF; margin-bottom:4px; }
|
||||
.op-grid { display:grid; grid-template-columns:repeat(3, 1fr); gap:5px; }
|
||||
.op-grid-2 { display:grid; grid-template-columns:1fr 1fr; gap:5px; }
|
||||
</style>
|
||||
78
Lab505.Client/Pages/ConveyorPanel.razor
Normal file
78
Lab505.Client/Pages/ConveyorPanel.razor
Normal file
@@ -0,0 +1,78 @@
|
||||
@implements IAsyncDisposable
|
||||
|
||||
<div>
|
||||
@if (State.Conveyor.WriteError != null)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Dense="true" Class="mt-1" Style="font-size:0.7rem;">
|
||||
@State.Conveyor.WriteError
|
||||
</MudAlert>
|
||||
}
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Conveyor 1</MudText>
|
||||
<div class="op-grid-3">
|
||||
@CoilBtn("Ready", () => State.Conveyor.C1Ready, (v) => SetCoil("c1", "ready", v))
|
||||
@CoilBtn("In", () => State.Conveyor.C1In, (v) => SetCoil("c1", "in", v))
|
||||
@CoilBtn("Out", () => State.Conveyor.C1Out, (v) => SetCoil("c1", "out", v))
|
||||
@CoilBtn("IMRin", () => State.Conveyor.C1IMRin, (v) => SetCoil("c1", "imr-in", v))
|
||||
@CoilBtn("IMRout", () => State.Conveyor.C1IMRout, (v) => SetCoil("c1", "imr-out", v))
|
||||
@CoilBtn("Goods", () => State.Conveyor.C1HasGoods, (v) => SetCoil("c1", "has-goods", v))
|
||||
@CoilBtn("Empty", () => State.Conveyor.C1NotGoods, (v) => SetCoil("c1", "not-goods", v))
|
||||
</div>
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Conveyor 2</MudText>
|
||||
<div class="op-grid-3">
|
||||
@CoilBtn("Ready", () => State.Conveyor.C2Ready, (v) => SetCoil("c2", "ready", v))
|
||||
@CoilBtn("In", () => State.Conveyor.C2In, (v) => SetCoil("c2", "in", v))
|
||||
@CoilBtn("Out", () => State.Conveyor.C2Out, (v) => SetCoil("c2", "out", v))
|
||||
@CoilBtn("Goods", () => State.Conveyor.C2HasGoods, (v) => SetCoil("c2", "has-goods", v))
|
||||
@CoilBtn("Empty", () => State.Conveyor.C2NotGoods, (v) => SetCoil("c2", "not-goods", v))
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter] public bool? ReadOnly { get; set; }
|
||||
|
||||
[Inject] StateService State { get; set; } = default!;
|
||||
[Inject] CommandService Cmd { get; set; } = default!;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.ConveyorChanged += Refresh;
|
||||
State.WorkflowChanged += Refresh;
|
||||
State.SystemChanged += Refresh;
|
||||
State.LockStateChanged += Refresh;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.ConveyorChanged -= Refresh;
|
||||
State.WorkflowChanged -= Refresh;
|
||||
State.SystemChanged -= Refresh;
|
||||
State.LockStateChanged -= Refresh;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void Refresh() => InvokeAsync(StateHasChanged);
|
||||
|
||||
private bool IsDisabled => ReadOnly ?? (State.Workflow.IsRunning || !State.CanControl);
|
||||
|
||||
private Task SetCoil(string c, string coil, bool v) => Cmd.ConveyorSetCoilAsync(c, coil, v);
|
||||
|
||||
private RenderFragment CoilBtn(string label, Func<bool?> getter, Action<bool> setter) => __builder =>
|
||||
{
|
||||
bool on = getter() == true;
|
||||
<MudButton Size="Size.Small"
|
||||
Variant="@(on ? Variant.Filled : Variant.Outlined)"
|
||||
Color="@(on ? Color.Success : Color.Default)"
|
||||
Disabled="@IsDisabled"
|
||||
OnClick="@(() => setter(!on))">
|
||||
@label
|
||||
</MudButton>
|
||||
};
|
||||
}
|
||||
|
||||
<style>
|
||||
.sec-title { display:block; color:#9CA3AF; margin-bottom:4px; }
|
||||
.op-grid-3 { display:grid; grid-template-columns:repeat(3, 1fr); gap:5px; }
|
||||
</style>
|
||||
96
Lab505.Client/Pages/ConveyorSectionPanel.razor
Normal file
96
Lab505.Client/Pages/ConveyorSectionPanel.razor
Normal file
@@ -0,0 +1,96 @@
|
||||
@implements IAsyncDisposable
|
||||
|
||||
<MudPaper Elevation="0" Class="pa-3" Style="background:transparent;">
|
||||
|
||||
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
|
||||
Style="cursor:pointer" @onclick="ToggleExpand">
|
||||
<MudText Typo="Typo.subtitle1">CONVEYOR</MudText>
|
||||
<MudIcon Icon="@(_expanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
|
||||
</MudStack>
|
||||
|
||||
<div class="status-row mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Circle" Size="Size.Small" Color="@StatusColor" />
|
||||
<div>
|
||||
<MudText Typo="Typo.caption">@StatusText.ToUpper()</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color:#9a9a9a;">@DetailText</MudText>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (_expanded)
|
||||
{
|
||||
<ConveyorPanel />
|
||||
}
|
||||
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Inject] StateService State { get; set; } = default!;
|
||||
|
||||
private bool _expanded = true;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.ConveyorChanged += Refresh;
|
||||
State.WorkflowChanged += Refresh;
|
||||
State.SystemChanged += Refresh;
|
||||
State.LockStateChanged += Refresh;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.ConveyorChanged -= Refresh;
|
||||
State.WorkflowChanged -= Refresh;
|
||||
State.SystemChanged -= Refresh;
|
||||
State.LockStateChanged -= Refresh;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void ToggleExpand() => _expanded = !_expanded;
|
||||
|
||||
private void Refresh() => InvokeAsync(StateHasChanged);
|
||||
|
||||
private bool C1Online => State.Conveyor.C1Out != null;
|
||||
private bool C2Online => State.Conveyor.C2Out != null;
|
||||
|
||||
private bool AnyRunning =>
|
||||
State.Conveyor.C1In == true ||
|
||||
State.Conveyor.C1Out == true ||
|
||||
State.Conveyor.C1IMRin == true ||
|
||||
State.Conveyor.C1IMRout == true ||
|
||||
State.Conveyor.C2In == true ||
|
||||
State.Conveyor.C2Out == true;
|
||||
|
||||
private string StatusText
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(State.Conveyor.WriteError)) return "error";
|
||||
if (AnyRunning) return "running";
|
||||
if (C1Online || C2Online) return "ok";
|
||||
return "off";
|
||||
}
|
||||
}
|
||||
|
||||
private Color StatusColor => StatusText switch
|
||||
{
|
||||
"ok" => Color.Success,
|
||||
"running" => Color.Info,
|
||||
"error" => Color.Error,
|
||||
_ => Color.Default
|
||||
};
|
||||
|
||||
private string DetailText =>
|
||||
$"C1: {LineState(C1Online, State.Conveyor.C1In, State.Conveyor.C1Out, State.Conveyor.C1IMRin, State.Conveyor.C1IMRout)} | " +
|
||||
$"C2: {LineState(C2Online, State.Conveyor.C2In, State.Conveyor.C2Out)}";
|
||||
|
||||
private static string LineState(bool online, params bool?[] states)
|
||||
{
|
||||
if (!online) return "off";
|
||||
return states.Any(v => v == true) ? "running" : "ready";
|
||||
}
|
||||
}
|
||||
|
||||
<style>
|
||||
.status-row { display:flex; align-items:center; gap:8px; margin-bottom:4px; }
|
||||
</style>
|
||||
137
Lab505.Client/Pages/DobotPanel.razor
Normal file
137
Lab505.Client/Pages/DobotPanel.razor
Normal file
@@ -0,0 +1,137 @@
|
||||
@implements IAsyncDisposable
|
||||
|
||||
<MudPaper Elevation="0" Class="pa-3" Style="background:transparent;">
|
||||
|
||||
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
|
||||
Style="cursor:pointer" @onclick="ToggleDOBOT">
|
||||
<MudText Typo="Typo.subtitle1">DOBOT</MudText>
|
||||
<MudIcon Icon="@(IsDobotExpanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
|
||||
</MudStack>
|
||||
|
||||
<div class="status-row mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Circle" Size="Size.Small" Color="@DobotMudColor" />
|
||||
<div>
|
||||
<MudText Typo="Typo.caption">@DobotStatus.ToUpper()</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color:#9a9a9a;">
|
||||
Code: @State.Imr.CodeDobotStatus_Opc | @DobotStatusCodeText
|
||||
</MudText>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-1 mb-1">
|
||||
<MudButton FullWidth="true" Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small" OnClick="Dobot_Cancel" Disabled="@(!State.CanControl)">Cancel</MudButton>
|
||||
</div>
|
||||
|
||||
@if (IsDobotExpanded)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Control</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Dobot_Home" Disabled="@DobotLocked("GoHome")">Home</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Dobot_Continue" Disabled="@DobotLocked("Continue")">Continue</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Dobot_PowerOn" Disabled="@DobotLocked("PowerOn")">PowerOn</MudButton>
|
||||
</div>
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Pick</MudText>
|
||||
<div class="op-grid">
|
||||
<MudNumericField T="int?" @bind-Value="okCount" Placeholder="OK" Variant="Variant.Outlined" Class="pnl-num" Min="0" Max="99" />
|
||||
<MudNumericField T="int?" @bind-Value="ngCount" Placeholder="NG" Variant="Variant.Outlined" Class="pnl-num" Min="0" Max="99" />
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="PickUp_Vda" Disabled="@ImrLocked("PickUp")">Pick Up</MudButton>
|
||||
</div>
|
||||
}
|
||||
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Inject] StateService State { get; set; } = default!;
|
||||
[Inject] CommandService Cmd { get; set; } = default!;
|
||||
|
||||
bool IsDobotExpanded = true;
|
||||
void ToggleDOBOT() => IsDobotExpanded = !IsDobotExpanded;
|
||||
|
||||
int? okCount;
|
||||
int? ngCount;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.ImrChanged += Refresh; // DobotStatus comes from IMR state
|
||||
State.WorkflowChanged += Refresh;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.ImrChanged -= Refresh;
|
||||
State.WorkflowChanged -= Refresh;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void Refresh() => InvokeAsync(StateHasChanged);
|
||||
|
||||
private string DobotStatus
|
||||
{
|
||||
get
|
||||
{
|
||||
var s = State.Imr.DobotStatus_Opc?.ToLower() ?? "";
|
||||
var e = State.Imr.CodeDobotStatus_Opc;
|
||||
if (e == 9999) return "off";
|
||||
if (e != 0) return "error";
|
||||
if (s.Contains("error") || s.Contains("fault")) return "error";
|
||||
if (s.Contains("controlling") || s.Contains("move")) return "moving";
|
||||
if (s.Contains("canceled")) return "canceled";
|
||||
if (s.Contains("finished") || s.Contains("idle")) return "ok";
|
||||
return "ok";
|
||||
}
|
||||
}
|
||||
|
||||
private Color DobotMudColor => DobotStatus switch
|
||||
{
|
||||
"ok" => Color.Success,
|
||||
"idle" => Color.Success,
|
||||
"moving" => Color.Info,
|
||||
"canceled" => Color.Warning,
|
||||
"error" => Color.Error,
|
||||
_ => Color.Default
|
||||
};
|
||||
|
||||
private string DobotStatusCodeText => State.Imr.CodeDobotStatus_Opc switch
|
||||
{
|
||||
0 => "Dobot Waiting",
|
||||
98 => "Dobot Waiting for Connection",
|
||||
99 => "Dobot Reconnecting",
|
||||
100 => "Dobot Running",
|
||||
101 => "Dobot Disconnected",
|
||||
102 => "Dobot No Data Received",
|
||||
103 => "Dobot Data Not Updated",
|
||||
104 => "Dobot Target Coordinates Out of Range",
|
||||
105 => "Dobot Returning Home",
|
||||
106 => "Dobot Checking Emergency Stop Button",
|
||||
107 => "Dobot in Alarm State",
|
||||
108 => "Dobot Powering On, Waiting",
|
||||
109 => "Dobot Powered On",
|
||||
110 => "Dobot in Drag Mode",
|
||||
111 => "Dobot Waiting: Select Continue or Return Home",
|
||||
112 => "Dobot OK Count Limit Reached",
|
||||
113 => "Dobot NG Count Limit Reached",
|
||||
999 => "Dobot Error",
|
||||
_ => "Unknown"
|
||||
};
|
||||
|
||||
// Dobot queue locking
|
||||
private bool DobotLocked(string label)
|
||||
=> !State.CanControl || State.Workflow.DobotBusyLabel == label || State.Workflow.DobotNextLabel == label;
|
||||
|
||||
// PickUp goes through the IMR queue
|
||||
private bool ImrLocked(string label)
|
||||
=> !State.CanControl || State.Workflow.ImrBusyLabel == label || State.Workflow.ImrNextLabel == label;
|
||||
|
||||
private Task Dobot_Cancel() => Cmd.DobotCancelAsync();
|
||||
private Task Dobot_Home() => Cmd.DobotGoHomeAsync();
|
||||
private Task Dobot_Continue() => Cmd.DobotContinueAsync();
|
||||
private Task Dobot_PowerOn() => Cmd.DobotPowerOnAsync();
|
||||
private Task PickUp_Vda() => Cmd.ImrPickupAsync(okCount ?? 0, ngCount ?? 0);
|
||||
}
|
||||
|
||||
<style>
|
||||
.status-row { display:flex; align-items:center; gap:8px; margin-bottom:4px; }
|
||||
.sec-title { display:block; color:#9CA3AF; margin-bottom:4px; }
|
||||
.op-grid { display:grid; grid-template-columns:repeat(3, 1fr); gap:5px; }
|
||||
</style>
|
||||
320
Lab505.Client/Pages/FlowPhasePanel.razor
Normal file
320
Lab505.Client/Pages/FlowPhasePanel.razor
Normal file
@@ -0,0 +1,320 @@
|
||||
@implements IAsyncDisposable
|
||||
|
||||
<MudPaper Elevation="0" Class="pa-2" Style="background:transparent;">
|
||||
|
||||
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
|
||||
Style="cursor:pointer" @onclick="ToggleExpand">
|
||||
<MudText Typo="Typo.subtitle1">OPERATIONS</MudText>
|
||||
<MudIcon Icon="@(_expanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
|
||||
</MudStack>
|
||||
|
||||
@if (IsLockBlocked)
|
||||
{
|
||||
<div style="background:rgba(255,100,0,0.08);border:1px solid rgba(255,100,0,0.25);border-radius:5px;padding:4px 8px;margin-bottom:4px;">
|
||||
<MudText Typo="Typo.caption" Style="color:#f90;">@Lang.T("Bạn chưa giữ quyền điều khiển. Vào CONTROL ACCESS → ACQUIRE CONTROL.", "You don't hold control. Go to CONTROL ACCESS → ACQUIRE CONTROL.")</MudText>
|
||||
</div>
|
||||
}
|
||||
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small"
|
||||
FullWidth="true" Class="my-1"
|
||||
OnClick="HardCancel"
|
||||
Disabled="@(!IsAnyRunning && _opQueue.Count == 0)">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Stop" Size="Size.Small" /> Cancel @(_opQueue.Count > 0 ? $"+{_opQueue.Count}" : "")
|
||||
</MudButton>
|
||||
|
||||
@if (_expanded)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Params</MudText>
|
||||
<div class="op-grid-4 mb-2">
|
||||
<MudNumericField T="int?" @bind-Value="_times" Placeholder="OK" Variant="Variant.Outlined" Class="pnl-num" Min="1" Max="99" />
|
||||
<MudNumericField T="int?" @bind-Value="_ng" Placeholder="NG" Variant="Variant.Outlined" Class="pnl-num" Min="0" Max="99" />
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Success" Size="Size.Small"
|
||||
StartIcon="@Icons.Material.Filled.PlayArrow" OnClick="RunAll"
|
||||
Disabled="@(IsAnyRunning || IsLockBlocked)"></MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Success" Size="Size.Small"
|
||||
OnClick="RunSelected"
|
||||
Disabled="@(_selectedSteps.Count == 0 || IsAnyRunning || IsLockBlocked)">[@_selectedSteps.Count]</MudButton>
|
||||
</div>
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title">Steps</MudText>
|
||||
<div class="op-grid-3">
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Warning" Size="Size.Small"
|
||||
OnClick='() => RunOp("HomeRb", ct => Cmd.WorkflowHomeRbAsync(ct))'
|
||||
Disabled="@(IsAnyRunning || IsLockBlocked)">Home All</MudButton>
|
||||
@OpCard(1, "Init")
|
||||
@OpCard(2, "C2 AMR")
|
||||
@OpCard(3, "→ Cap1")
|
||||
@OpCard(4, "C:AMR→IMR")
|
||||
@OpCard(5, "→ABB:PINKUP")
|
||||
@OpCard(6, "C:IMR→AMR")
|
||||
@OpCard(7, "→ Cap2")
|
||||
@OpCard(8, "AMR C2")
|
||||
</div>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Inject] StateService State { get; set; } = default!;
|
||||
[Inject] CommandService Cmd { get; set; } = default!;
|
||||
[Inject] ISnackbar Snackbar { get; set; } = default!;
|
||||
[Inject] HttpClient Http { get; set; } = default!;
|
||||
[Inject] LangService Lang { get; set; } = default!;
|
||||
[Inject] ScriptLogService Log { get; set; } = default!;
|
||||
|
||||
private bool _expanded = true;
|
||||
private void ToggleExpand() => _expanded = !_expanded;
|
||||
|
||||
private int? _times, _ng;
|
||||
private int _prevCycles = -1;
|
||||
private string _myUserId = "";
|
||||
|
||||
// True when using real stack and lock state shows we don't hold workflow lock
|
||||
private bool IsLockBlocked =>
|
||||
!State.System.IsSimulation
|
||||
&& State.LockState is not null
|
||||
&& (State.LockState.Workflow is null || State.LockState.Workflow.UserId != _myUserId);
|
||||
|
||||
private readonly HashSet<string> _runningOps = new();
|
||||
private readonly Queue<(string Name, Func<CancellationToken, Task> Action)> _opQueue = new();
|
||||
private CancellationTokenSource? _cts;
|
||||
private bool _queueRunning;
|
||||
private readonly List<int> _selectedSteps = new();
|
||||
|
||||
private bool IsAnyRunning => _queueRunning || State.Workflow.IsRunning;
|
||||
private bool IsRunning(string k) => _runningOps.Contains(k);
|
||||
private bool IsQueued(string k) => _opQueue.Any(q => q.Name == k);
|
||||
|
||||
private void ToggleStep(int n)
|
||||
{
|
||||
if (!_selectedSteps.Remove(n)) _selectedSteps.Add(n);
|
||||
}
|
||||
|
||||
private Task ExecStep(int n, CancellationToken ct) => n switch
|
||||
{
|
||||
1 => Cmd.FlowStepInitAsync(ct),
|
||||
2 => Cmd.FlowStepLoadC2Async(ct),
|
||||
3 => Cmd.FlowStepToCap1Async(ct),
|
||||
4 => Cmd.FlowStepAmrToImrAsync(ct),
|
||||
5 => Cmd.FlowStepProcessAsync(_times ?? 1, _ng ?? 0, ct),
|
||||
6 => Cmd.FlowStepImrToAmrAsync(ct),
|
||||
7 => Cmd.FlowStepToCap2Async(ct),
|
||||
8 => Cmd.FlowStepUnloadC2Async(ct),
|
||||
_ => Task.CompletedTask
|
||||
};
|
||||
|
||||
private RenderFragment OpCard(int num, string name) => __builder =>
|
||||
{
|
||||
var key = $"step{num}";
|
||||
bool running = IsRunning(key);
|
||||
bool queued = IsQueued(key);
|
||||
int selIdx = _selectedSteps.IndexOf(num);
|
||||
bool sel = selIdx >= 0;
|
||||
|
||||
var color = running ? Color.Primary : sel ? Color.Success : Color.Default;
|
||||
var variant = (running || sel) ? Variant.Filled : Variant.Outlined;
|
||||
|
||||
<MudButton Variant="@variant" Color="@color" Size="Size.Small"
|
||||
Disabled="@(IsAnyRunning)"
|
||||
Style="@(queued ? "opacity:0.55;border-style:dashed;" : "")"
|
||||
OnClick="() => { if (!IsAnyRunning) ToggleStep(num); }">
|
||||
@if (sel && !running)
|
||||
{
|
||||
<span class="sel-n">@(selIdx + 1)</span>
|
||||
}
|
||||
@(running ? "…" : name)
|
||||
</MudButton>
|
||||
};
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.WorkflowChanged += OnWorkflowChanged;
|
||||
State.LockStateChanged += OnLockChanged;
|
||||
Lang.LangChanged += OnLockChanged;
|
||||
|
||||
try
|
||||
{
|
||||
var me = await Http.GetFromJsonAsync<MeWfDto>("/api/auth/me");
|
||||
_myUserId = me?.UserId ?? "";
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.WorkflowChanged -= OnWorkflowChanged;
|
||||
State.LockStateChanged -= OnLockChanged;
|
||||
Lang.LangChanged -= OnLockChanged;
|
||||
HardCancel();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void OnWorkflowChanged()
|
||||
{
|
||||
var cycles = State.Workflow.CompletedCycles;
|
||||
if (_prevCycles >= 0 && cycles > _prevCycles)
|
||||
Snackbar.Add(Lang.T($"Hoàn thành chu kỳ {cycles}", $"Completed cycle {cycles}"), Severity.Success);
|
||||
_prevCycles = cycles;
|
||||
InvokeAsync(StateHasChanged);
|
||||
}
|
||||
private void OnLockChanged() => InvokeAsync(StateHasChanged);
|
||||
|
||||
record MeWfDto(string? UserId);
|
||||
|
||||
private void RunAll()
|
||||
{
|
||||
_selectedSteps.Clear();
|
||||
WarnStep(1); // online check
|
||||
EnqueueOp("Run All", ct => Cmd.WorkflowRunCycleAsync(_times ?? 1, _ng ?? 0, ct));
|
||||
}
|
||||
|
||||
private void RunSelected()
|
||||
{
|
||||
if (_selectedSteps.Count == 0 || IsAnyRunning) return;
|
||||
var steps = _selectedSteps.ToList();
|
||||
_selectedSteps.Clear();
|
||||
foreach (var n in steps) WarnStep(n);
|
||||
EnqueueOp("Run Sel", async ct =>
|
||||
{
|
||||
foreach (var n in steps)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await ExecStep(n, ct);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void RunOp(string n, Func<CancellationToken, Task> a) => EnqueueOp(n, a);
|
||||
|
||||
// ── Position detection (mirrors SystemCondition server-side logic) ───────────
|
||||
private static bool Near(double x, double y, double tx, double ty) =>
|
||||
Math.Abs(x - tx) < RobotPositions.POS_TOL &&
|
||||
Math.Abs(y - ty) < RobotPositions.POS_TOL;
|
||||
|
||||
private bool ImrAtC1 => Near(State.Imr.X, State.Imr.Y, RobotPositions.IMR_C1_X, RobotPositions.IMR_C1_Y);
|
||||
private bool AmrAtCap1 => Near(State.Amr.X, State.Amr.Y, RobotPositions.AMR_CAP1_X, RobotPositions.AMR_CAP1_Y);
|
||||
private bool AmrAtCap2 => Near(State.Amr.X, State.Amr.Y, RobotPositions.AMR_CAP2_X, RobotPositions.AMR_CAP2_Y);
|
||||
|
||||
/// <summary>Ghi cảnh báo ra log + snackbar nếu pre-condition của step chưa đạt.</summary>
|
||||
private void WarnStep(int n)
|
||||
{
|
||||
if (!State.Imr.IsOnline)
|
||||
PosWarn("IMR", "offline", Lang.T("Kiểm tra kết nối IMR", "Check IMR connection"));
|
||||
if (!State.Amr.IsOnline)
|
||||
PosWarn("AMR", "offline", Lang.T("Kiểm tra kết nối AMR", "Check AMR connection"));
|
||||
|
||||
switch (n)
|
||||
{
|
||||
case 2: // C2 AMR — AMR cần ở Cap2
|
||||
if (!AmrAtCap2)
|
||||
PosWarn("AMR", Lang.T("chưa ở Cap2", "not at Cap2"),
|
||||
Lang.T("→ chạy Step 1 Init trước", "→ run Step 1 Init first"));
|
||||
break;
|
||||
|
||||
case 3: // → Cap1 — AMR cần ở Cap2 để undock
|
||||
if (!AmrAtCap2)
|
||||
PosWarn("AMR", Lang.T("chưa ở Cap2", "not at Cap2"),
|
||||
Lang.T("→ chạy Step 1 Init hoặc Step 8 trước", "→ run Step 1 Init or Step 8 first"));
|
||||
break;
|
||||
|
||||
case 4: // C:AMR→IMR — IMR@C1 + AMR@Cap1
|
||||
if (!ImrAtC1)
|
||||
PosWarn("IMR", Lang.T("chưa ở C1", "not at C1"),
|
||||
Lang.T("→ chạy Step 1 Init trước", "→ run Step 1 Init first"));
|
||||
if (!AmrAtCap1)
|
||||
PosWarn("AMR", Lang.T("chưa ở Cap1", "not at Cap1"),
|
||||
Lang.T("→ chạy Step 3 → Cap1 trước", "→ run Step 3 → Cap1 first"));
|
||||
break;
|
||||
|
||||
case 5: // ABB:PICKUP — IMR cần ở C1 trước khi undock
|
||||
if (!ImrAtC1)
|
||||
PosWarn("IMR", Lang.T("chưa ở C1", "not at C1"),
|
||||
Lang.T("→ chạy Step 1 Init trước", "→ run Step 1 Init first"));
|
||||
break;
|
||||
|
||||
case 6: // C:IMR→AMR — IMR@C1 + AMR@Cap1
|
||||
if (!ImrAtC1)
|
||||
PosWarn("IMR", Lang.T("chưa ở C1", "not at C1"),
|
||||
Lang.T("→ chạy Step 1 Init trước", "→ run Step 1 Init first"));
|
||||
if (!AmrAtCap1)
|
||||
PosWarn("AMR", Lang.T("chưa ở Cap1", "not at Cap1"),
|
||||
Lang.T("→ chạy Step 4 C:AMR→IMR hoặc Step 3 trước", "→ run Step 4 or Step 3 first"));
|
||||
break;
|
||||
|
||||
case 7: // → Cap2 — AMR cần ở Cap1 để undock
|
||||
if (!AmrAtCap1)
|
||||
PosWarn("AMR", Lang.T("chưa ở Cap1", "not at Cap1"),
|
||||
Lang.T("→ chạy Step 3 → Cap1 trước", "→ run Step 3 → Cap1 first"));
|
||||
break;
|
||||
|
||||
case 8: // AMR C2 — AMR cần ở Cap2
|
||||
if (!AmrAtCap2)
|
||||
PosWarn("AMR", Lang.T("chưa ở Cap2", "not at Cap2"),
|
||||
Lang.T("→ chạy Step 7 → Cap2 trước", "→ run Step 7 → Cap2 first"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void PosWarn(string device, string condition, string guide) =>
|
||||
Log.Log(LogFormat.Line(LogFormat.CWarn, "WARN", device, condition, guide));
|
||||
|
||||
private void EnqueueOp(string name, Func<CancellationToken, Task> action)
|
||||
{
|
||||
if (IsAnyRunning || IsQueued(name)) return;
|
||||
_opQueue.Enqueue((name, action));
|
||||
if (!_queueRunning)
|
||||
{
|
||||
_cts?.Dispose();
|
||||
_cts = new CancellationTokenSource();
|
||||
_ = RunQueueAsync(_cts.Token);
|
||||
}
|
||||
}
|
||||
|
||||
private void HardCancel()
|
||||
{
|
||||
_opQueue.Clear();
|
||||
_cts?.Cancel();
|
||||
_ = Cmd.WorkflowEmergencyStopAsync();
|
||||
}
|
||||
|
||||
private async Task RunQueueAsync(CancellationToken token)
|
||||
{
|
||||
_queueRunning = true;
|
||||
try
|
||||
{
|
||||
while (_opQueue.Count > 0 && !token.IsCancellationRequested)
|
||||
{
|
||||
(string name, Func<CancellationToken, Task> action)? item = null;
|
||||
await InvokeAsync(() => { if (_opQueue.Count > 0) item = _opQueue.Dequeue(); });
|
||||
if (item == null) break;
|
||||
await ExecAsync(item.Value.name, item.Value.action, token);
|
||||
}
|
||||
}
|
||||
finally { _queueRunning = false; await InvokeAsync(StateHasChanged); }
|
||||
}
|
||||
|
||||
private async Task ExecAsync(string name, Func<CancellationToken, Task> action, CancellationToken token)
|
||||
{
|
||||
await InvokeAsync(() => { _runningOps.Add(name); StateHasChanged(); });
|
||||
try
|
||||
{
|
||||
await action(token);
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch { _ = Cmd.WorkflowEmergencyStopAsync(); }
|
||||
finally { await InvokeAsync(() => { _runningOps.Remove(name); StateHasChanged(); }); }
|
||||
}
|
||||
}
|
||||
|
||||
<style>
|
||||
.sec-title { display:block; color:#9CA3AF; margin-bottom:4px; }
|
||||
.op-grid-4 { display:grid; grid-template-columns:repeat(4, 1fr); gap:5px; }
|
||||
.op-grid-3 { display:grid; grid-template-columns:repeat(3, 1fr); gap:5px; }
|
||||
.op-grid-2 { display:grid; grid-template-columns:1fr 1fr; gap:5px; }
|
||||
.mt-1 { margin-top:5px; }
|
||||
.sel-n { display:inline-flex; align-items:center; justify-content:center;
|
||||
width:14px; height:14px; border-radius:50%;
|
||||
background:rgba(0,0,0,0.25); font-size:9px; font-weight:900;
|
||||
margin-right:4px; flex-shrink:0; }
|
||||
</style>
|
||||
224
Lab505.Client/Pages/Home.razor
Normal file
224
Lab505.Client/Pages/Home.razor
Normal file
@@ -0,0 +1,224 @@
|
||||
@page "/"
|
||||
@page "/{Username}"
|
||||
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
|
||||
@implements IAsyncDisposable
|
||||
@inject HttpClient Http
|
||||
@inject ISnackbar Snackbar
|
||||
@inject LangService Lang
|
||||
<MudThemeProvider IsDarkMode="true" />
|
||||
<MudPopoverProvider />
|
||||
<MudDialogProvider />
|
||||
<MudSnackbarProvider />
|
||||
<NotificationProvider Muted="@_notifMuted" />
|
||||
|
||||
<div class="right-top">
|
||||
<div class="right-header">
|
||||
<div style="display:flex;align-items:center;gap:6px;">
|
||||
@if (!string.IsNullOrEmpty(_username))
|
||||
{
|
||||
<span style="font-size:11px;color:#444;font-weight:500;">@_username</span>
|
||||
}
|
||||
</div>
|
||||
<div class="mode-toggle">
|
||||
<MudTooltip Text="@Lang.T("Tài khoản của tôi", "My Account")" Placement="Placement.Bottom">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.AccountCircle"
|
||||
Size="Size.Small" Style="color:#aaa;padding:4px;" Href="/profile" />
|
||||
</MudTooltip>
|
||||
@if (_isManager)
|
||||
{
|
||||
<MudTooltip Text="App Settings — Quản lý tài khoản" Placement="Placement.Bottom">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.AdminPanelSettings"
|
||||
Size="Size.Small" Style="color:#aaa;padding:4px;" Href="/users" />
|
||||
</MudTooltip>
|
||||
}
|
||||
|
||||
@* SIM / REAL toggle — chỉ hiện khi tài khoản có quyền real *@
|
||||
@if (_canUseReal)
|
||||
{
|
||||
<MudTooltip Text="@(_useReal ? Lang.T("Đang dùng Real — nhấn để chuyển Sim", "Using Real — click to switch to Sim") : Lang.T("Đang dùng Sim — nhấn để chuyển Real", "Using Sim — click to switch to Real"))"
|
||||
Placement="Placement.Bottom">
|
||||
<MudChip T="string"
|
||||
Color="@(_useReal ? Color.Warning : Color.Info)"
|
||||
Size="Size.Small"
|
||||
Style="cursor:pointer;height:24px;font-size:11px;font-weight:700;padding:0 8px;"
|
||||
OnClick="ToggleStack">
|
||||
@(_useReal ? "REAL" : "SIM")
|
||||
</MudChip>
|
||||
</MudTooltip>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span style="font-size:11px;font-weight:700;color:#3a7bbf;padding:0 6px;opacity:0.7;">SIM</span>
|
||||
}
|
||||
|
||||
<MudTooltip Text="@(_notifMuted ? Lang.T("Thông báo đang tắt", "Notifications Off") : Lang.T("Thông báo đang bật", "Notifications On"))" Placement="Placement.Bottom">
|
||||
<MudIconButton Icon="@(_notifMuted ? Icons.Material.Filled.NotificationsOff : Icons.Material.Filled.Notifications)"
|
||||
Size="Size.Small" OnClick="ToggleNotif"
|
||||
Style="@(_notifMuted ? "color:#444;padding:4px;" : "color:#f0c040;padding:4px;")" />
|
||||
</MudTooltip>
|
||||
<MudTooltip Text="@Lang.T("Đăng xuất", "Logout")" Placement="Placement.Bottom">
|
||||
<form method="post" action="/auth/do-logout" style="margin:0;display:inline;">
|
||||
<MudIconButton ButtonType="ButtonType.Submit" Icon="@Icons.Material.Filled.Logout"
|
||||
Size="Size.Small" Style="color:#666;padding:4px;" />
|
||||
</form>
|
||||
</MudTooltip>
|
||||
</div>
|
||||
</div>
|
||||
<StatusPanel />
|
||||
</div>
|
||||
|
||||
@{ var wfBlocker = WfBlocker; }
|
||||
@if (wfBlocker is not null)
|
||||
{
|
||||
<div class="wf-block-banner">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Bolt" Size="Size.Small" Style="flex-shrink:0;" />
|
||||
<span style="font-weight:800;letter-spacing:.4px;">WORKFLOW MODE</span>
|
||||
<span class="wf-block-sep">—</span>
|
||||
<strong style="color:#ffe082;">@wfBlocker.Name</strong>
|
||||
<span class="wf-block-note">@Lang.T("đang điều khiển · Bạn không thể thao tác", "is controlling · You cannot perform actions")</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div id="right-scroll" class="right-scroll @(wfBlocker is not null ? "panels-blocked" : "")">
|
||||
<div id="p-ctrl" class="panel-card"><ControlPanel /></div>
|
||||
@if (!State.System.IsSimulation || _isManager)
|
||||
{
|
||||
<div id="p-lock" class="panel-card"><LockPanel UseReal="@_useReal" MyUserId="@_userId" MyRole="@_role"
|
||||
CanWorkflow="@(_isManager || _canWorkflow)"
|
||||
CanManual="@(_isManager || (_canUseReal && !_canWorkflow))" /></div>
|
||||
}
|
||||
<div id="p-ops" class="panel-card"><FlowPhasePanel /></div>
|
||||
<div id="p-conveyor" class="panel-card"><ConveyorSectionPanel /></div>
|
||||
<div id="p-imr" class="panel-card"><ImrPanel /></div>
|
||||
<div id="p-amr" class="panel-card"><AmrPanel /></div>
|
||||
<div id="p-dobot" class="panel-card"><DobotPanel /></div>
|
||||
<div id="p-asrs" class="panel-card"><AsrsPanel /></div>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter] public string? Username { get; set; }
|
||||
|
||||
[Inject] StateService State { get; set; } = default!;
|
||||
|
||||
bool _notifMuted = true;
|
||||
bool _isManager = false;
|
||||
bool _canUseReal = false;
|
||||
bool _canWorkflow = false;
|
||||
bool _useReal = false;
|
||||
bool _stackBusy = false;
|
||||
string _username = "";
|
||||
string _userId = "";
|
||||
string _role = "";
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.SystemChanged += Refresh;
|
||||
State.LockStateChanged += Refresh;
|
||||
State.StackChanged += OnStackChanged;
|
||||
Lang.LangChanged += Refresh;
|
||||
await Lang.LoadAsync(Http);
|
||||
|
||||
try
|
||||
{
|
||||
var me = await Http.GetFromJsonAsync<MeDto>("/api/auth/me");
|
||||
_isManager = me?.Role is "Manager" or "Admin";
|
||||
_username = me?.Username ?? Username ?? "";
|
||||
_canUseReal = me?.CanUseReal == true;
|
||||
_canWorkflow = me?.CanWorkflow == true;
|
||||
_useReal = me?.UseReal == true;
|
||||
_userId = me?.UserId ?? "";
|
||||
_role = me?.Role ?? "";
|
||||
}
|
||||
catch { }
|
||||
|
||||
try
|
||||
{
|
||||
var prefs = await Http.GetFromJsonAsync<PrefsDto>("/api/prefs");
|
||||
if (prefs is not null) _notifMuted = prefs.NotifMuted;
|
||||
// Lang already loaded via Lang.LoadAsync above
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private async Task ToggleStack()
|
||||
{
|
||||
if (_stackBusy || !_canUseReal) return;
|
||||
_stackBusy = true;
|
||||
try
|
||||
{
|
||||
bool newUseReal = !_useReal;
|
||||
var url = newUseReal ? "/api/mode/real" : "/api/mode/simulation";
|
||||
var resp = await Http.PostAsync(url, null);
|
||||
if (resp.IsSuccessStatusCode)
|
||||
{
|
||||
_useReal = newUseReal;
|
||||
await State.SwitchStackAsync(newUseReal);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
finally
|
||||
{
|
||||
_stackBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void Refresh() => InvokeAsync(StateHasChanged);
|
||||
|
||||
private void OnStackChanged(bool useReal)
|
||||
{
|
||||
_useReal = useReal;
|
||||
InvokeAsync(StateHasChanged);
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.SystemChanged -= Refresh;
|
||||
State.LockStateChanged -= Refresh;
|
||||
State.StackChanged -= OnStackChanged;
|
||||
Lang.LangChanged -= Refresh;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Workflow lock holder khi KHÔNG phải mình — cần hiện banner cảnh báo.</summary>
|
||||
LockHolderDto? WfBlocker =>
|
||||
!State.System.IsSimulation && State.LockState?.Workflow is { } h && h.UserId != _userId ? h : null;
|
||||
|
||||
private async Task ToggleLang() => await Lang.ToggleAsync(Http);
|
||||
|
||||
private async Task ToggleNotif()
|
||||
{
|
||||
_notifMuted = !_notifMuted;
|
||||
try { await Http.PutAsJsonAsync("/api/prefs", new { Lang = (string?)null, NotifMuted = (bool?)_notifMuted }); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
record MeDto(string Role, string Username, bool CanUseReal, bool UseReal, string? UserId, bool CanWorkflow);
|
||||
record PrefsDto(string Lang, bool NotifMuted);
|
||||
}
|
||||
|
||||
<style>
|
||||
.right-top { flex-shrink:0; padding:12px 12px 0; background:#27292b; border-bottom:1px solid rgba(255,255,255,0.06); padding-bottom:8px; }
|
||||
.right-scroll { flex:1; overflow-y:auto; padding:10px 12px 12px; height:0; scrollbar-width:none; background:#27292b; }
|
||||
.right-scroll::-webkit-scrollbar { display:none; }
|
||||
.right-header { display:flex; justify-content:space-between; align-items:center; padding-bottom:8px; margin-bottom:8px; border-bottom:1px solid rgba(255,255,255,0.08); }
|
||||
.mode-toggle { display:flex; gap:4px; align-items:center; }
|
||||
|
||||
/* ── Workflow block banner ── */
|
||||
.wf-block-banner {
|
||||
display: flex; align-items: center; gap: 7px;
|
||||
padding: 7px 14px;
|
||||
background: rgba(243,156,18,0.13);
|
||||
border-bottom: 1px solid rgba(243,156,18,0.4);
|
||||
color: #f39c12; font-size: 11px; font-weight: 600;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.wf-block-sep { opacity: 0.5; }
|
||||
.wf-block-note { margin-left: auto; font-weight: 400; opacity: 0.75; font-size: 10px; }
|
||||
|
||||
/* dim all panels when someone else holds workflow */
|
||||
.panels-blocked .panel-card { opacity: 0.45; pointer-events: none; }
|
||||
/* but keep LockPanel interactive so user can see status / join queue */
|
||||
.panels-blocked #p-lock { opacity: 1; pointer-events: auto; }
|
||||
.panel-card { background:rgba(255,255,255,0.02); border:1px solid rgba(255,255,255,0.07); border-radius:8px; margin-bottom:8px; }
|
||||
</style>
|
||||
86
Lab505.Client/Pages/ImrAmrStatusPanel.razor
Normal file
86
Lab505.Client/Pages/ImrAmrStatusPanel.razor
Normal file
@@ -0,0 +1,86 @@
|
||||
@implements IAsyncDisposable
|
||||
|
||||
<div class="ias-3col">
|
||||
@RobotRow("IMR", State.Imr)
|
||||
@RobotRow("AMR", State.Amr)
|
||||
<div class="ias-row">
|
||||
<MudChip T="string" Size="Size.Small" Color="@(!State.Asrs.IsOffline ? Color.Success : Color.Default)"
|
||||
Variant="Variant.Text" Style="height:22px;font-size:11px;margin:0;flex-shrink:0;">ASRS</MudChip>
|
||||
<MudChip T="string" Size="Size.Small"
|
||||
Color="@(State.Asrs.SAFETY_MODE == true ? Color.Success : Color.Default)"
|
||||
Variant="@(State.Asrs.SAFETY_MODE == true ? Variant.Filled : Variant.Outlined)"
|
||||
Style="height:22px;font-size:11px;margin:0;flex-shrink:0;">Safety</MudChip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Inject] StateService State { get; set; } = default!;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.ImrChanged += Refresh;
|
||||
State.AmrChanged += Refresh;
|
||||
State.AsrsChanged += Refresh;
|
||||
State.WorkflowChanged += Refresh;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.ImrChanged -= Refresh;
|
||||
State.AmrChanged -= Refresh;
|
||||
State.AsrsChanged -= Refresh;
|
||||
State.WorkflowChanged -= Refresh;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void Refresh() => InvokeAsync(StateHasChanged);
|
||||
|
||||
private RenderFragment RobotRow(string label, RobotStateDto s) => __builder =>
|
||||
{
|
||||
bool online = s.IsOnline;
|
||||
bool ready = s.NewBaseRequest == true;
|
||||
<div class="ias-row">
|
||||
<MudChip T="string" Size="Size.Small" Color="@(online ? Color.Success : Color.Default)"
|
||||
Variant="Variant.Text" Style="height:22px;font-size:11px;margin:0;flex-shrink:0;">@label</MudChip>
|
||||
<MudChip T="string" Size="Size.Small"
|
||||
Color="@(ready ? Color.Success : Color.Default)"
|
||||
Variant="@(ready ? Variant.Filled : Variant.Outlined)"
|
||||
Style="height:22px;font-size:11px;margin:0;flex-shrink:0;">NBR</MudChip>
|
||||
<span class="@(online ? "ias-pos" : "ias-pos ias-dim")">@($"{s.X:F1}, {s.Y:F1}")</span>
|
||||
@foreach (var a in s.Actions.Take(2))
|
||||
{
|
||||
string acls = a.ActionStatus switch {
|
||||
"RUNNING" => "ias-act-run",
|
||||
"WAITING" or "INITIALIZING" => "ias-act-wait",
|
||||
"FINISHED" => "ias-act-done",
|
||||
"FAILED" or "ABORTED" => "ias-act-fail",
|
||||
_ => "ias-act-idle"
|
||||
};
|
||||
string aname = string.Equals(a.ActionID, "UndockFromStation", StringComparison.OrdinalIgnoreCase)
|
||||
? "Undock" : (a.ActionID ?? "?");
|
||||
<span class="ias-act @acls">@aname</span>
|
||||
}
|
||||
@if (s.Errors.Any())
|
||||
{
|
||||
<span class="ias-err">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Warning" Size="Size.Small" /> @string.Join(", ", s.Errors)
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
};
|
||||
}
|
||||
|
||||
<style>
|
||||
.ias-3col { display:grid; grid-template-columns:1fr 1fr auto; gap:4px 8px; align-items:center; }
|
||||
.ias-row { display:flex; gap:4px; align-items:center; flex-wrap:nowrap; overflow:hidden; min-width:0; }
|
||||
.ias-pos { font-size:11px; color:#F1F5F9; font-variant-numeric:tabular-nums; white-space:nowrap; flex-shrink:0; }
|
||||
.ias-dim { color:#9CA3AF; }
|
||||
.ias-act { font-size:10px; font-weight:600; padding:1px 5px; border-radius:4px; border:1px solid; white-space:nowrap; flex-shrink:0; }
|
||||
.ias-act-run { color:#4a9eff; border-color:rgba(74,158,255,0.5); background:rgba(74,158,255,0.08); }
|
||||
.ias-act-wait { color:#f39c12; border-color:rgba(243,156,18,0.45); background:rgba(243,156,18,0.06); }
|
||||
.ias-act-done { color:#2ecc71; border-color:rgba(46,204,113,0.25); background:transparent; }
|
||||
.ias-act-fail { color:#e74c3c; border-color:rgba(231,76,60,0.45); background:rgba(231,76,60,0.07); }
|
||||
.ias-act-idle { color:#9CA3AF; border-color:#1c1c1c; background:transparent; }
|
||||
.ias-err { font-size:10px; color:#e74c3c; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
</style>
|
||||
226
Lab505.Client/Pages/ImrPanel.razor
Normal file
226
Lab505.Client/Pages/ImrPanel.razor
Normal file
@@ -0,0 +1,226 @@
|
||||
@using Lab505.Shared
|
||||
@implements IAsyncDisposable
|
||||
|
||||
<MudPaper Elevation="0" Class="pa-3" Style="background:transparent;">
|
||||
|
||||
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
|
||||
Style="cursor:pointer" @onclick="ToggleExpand">
|
||||
<MudText Typo="Typo.subtitle1">IMR</MudText>
|
||||
<MudIcon Icon="@(_expanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
|
||||
</MudStack>
|
||||
|
||||
<div class="status-row mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Circle" Size="Size.Small" Color="@StatusColor" />
|
||||
<div>
|
||||
<MudText Typo="Typo.caption">@StatusText.ToUpper()</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color:#9a9a9a;">
|
||||
Errors: @(State.Imr.Errors is { Count: > 0 } errors ? string.Join(", ", errors) : "none")
|
||||
</MudText>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-1 mb-1">
|
||||
<MudButton FullWidth="true" Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small" OnClick="Cancel" Disabled="@(!State.CanControl)">Cancel</MudButton>
|
||||
</div>
|
||||
|
||||
@if (_expanded)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Move</MudText>
|
||||
<div class="op-grid-2">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="MoveToC1" Disabled="@IsLocked("MoveTo Bt1")">C1</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="MoveToAbb" Disabled="@IsLocked("MoveTo Abb")">ABB</MudButton>
|
||||
</div>
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Action</MudText>
|
||||
<div class="op-grid-2">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Load" Disabled="@IsLocked("Load")">Load</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Unload" Disabled="@IsLocked("Unload")">Unload</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="UndockFromC1" Disabled="@IsLocked("Undock")">MS@(RobotPositions.IMR_UNDOCK_C1)m</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="UndockFromAbb" Disabled="@IsLocked("Undock")">MS@(RobotPositions.IMR_UNDOCK_ABB)m</MudButton>
|
||||
</div>
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">NAV</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Resume">Resume</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Pause">Pause</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Reset">Reset</MudButton>
|
||||
</div>
|
||||
<div class="op-grid-4 mt-2">
|
||||
<MudNumericField T="double?" @bind-Value="_poseX" Placeholder="X" Variant="Variant.Outlined"
|
||||
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
|
||||
HideSpinButtons="true" Class="pnl-num" />
|
||||
<MudNumericField T="double?" @bind-Value="_poseY" Placeholder="Y" Variant="Variant.Outlined"
|
||||
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
|
||||
HideSpinButtons="true" Class="pnl-num" />
|
||||
<MudNumericField T="double?" @bind-Value="_poseYaw" Placeholder="Yaw" Variant="Variant.Outlined"
|
||||
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
|
||||
HideSpinButtons="true" Class="pnl-num" />
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Color="Color.Warning"
|
||||
StartIcon="@(_settingPose ? Icons.Material.Filled.HourglassBottom : null)"
|
||||
OnClick="RunInitPose" Disabled="@(_settingPose || !State.CanControl)">
|
||||
@(_settingPose ? "..." : "InitPose")
|
||||
</MudButton>
|
||||
</div>
|
||||
}
|
||||
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Inject] StateService State { get; set; } = default!;
|
||||
[Inject] CommandService Cmd { get; set; } = default!;
|
||||
[Inject] ISnackbar Snackbar { get; set; } = default!;
|
||||
[Inject] LangService Lang { get; set; } = default!;
|
||||
|
||||
private bool _expanded = true;
|
||||
private double? _poseX;
|
||||
private double? _poseY;
|
||||
private double? _poseYaw;
|
||||
private bool _settingPose;
|
||||
private CancellationTokenSource? _initPoseCts;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.ImrChanged += Refresh;
|
||||
State.WorkflowChanged += Refresh;
|
||||
Lang.LangChanged += Refresh;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.ImrChanged -= Refresh;
|
||||
State.WorkflowChanged -= Refresh;
|
||||
Lang.LangChanged -= Refresh;
|
||||
CancelInitPose();
|
||||
_initPoseCts?.Dispose();
|
||||
_initPoseCts = null;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void ToggleExpand() => _expanded = !_expanded;
|
||||
|
||||
private void Refresh() => InvokeAsync(StateHasChanged);
|
||||
|
||||
private string StatusText
|
||||
{
|
||||
get
|
||||
{
|
||||
var imr = State.Imr;
|
||||
if (!imr.IsOnline) return "off";
|
||||
if (imr.Errors.Count > 0) return "error";
|
||||
if (imr.NewBaseRequest == false) return "moving";
|
||||
return "ok";
|
||||
}
|
||||
}
|
||||
|
||||
private Color StatusColor => StatusText switch
|
||||
{
|
||||
"ok" => Color.Success,
|
||||
"moving" => Color.Info,
|
||||
"error" => Color.Error,
|
||||
_ => Color.Default
|
||||
};
|
||||
|
||||
private bool IsLocked(string label)
|
||||
=> !State.CanControl || State.Workflow.ImrBusyLabel == label || State.Workflow.ImrNextLabel == label;
|
||||
|
||||
private static bool IsNear(double x, double y, double targetX, double targetY)
|
||||
=> Math.Abs(x - targetX) < RobotPositions.POS_TOL && Math.Abs(y - targetY) < RobotPositions.POS_TOL;
|
||||
|
||||
private bool IsDocked()
|
||||
{
|
||||
var imr = State.Imr;
|
||||
return IsNear(imr.X, imr.Y, RobotPositions.IMR_C1_X, RobotPositions.IMR_C1_Y)
|
||||
|| IsNear(imr.X, imr.Y, RobotPositions.IMR_ABB_X, RobotPositions.IMR_ABB_Y);
|
||||
}
|
||||
|
||||
private bool WarnIfDocked()
|
||||
{
|
||||
if (!IsDocked() || State.Workflow.ImrCmd == "undocking")
|
||||
return false;
|
||||
|
||||
Snackbar.Add(
|
||||
Lang.T("IMR đang docked — lùi trước khi di chuyển!", "IMR is docked — undock before moving!"),
|
||||
Severity.Warning);
|
||||
return true;
|
||||
}
|
||||
|
||||
private Task MoveToC1() => WarnIfDocked() ? Task.CompletedTask : Cmd.ImrMoveToAsync("Bt1");
|
||||
|
||||
private Task MoveToAbb() => WarnIfDocked() ? Task.CompletedTask : Cmd.ImrMoveToAsync("Abb");
|
||||
|
||||
private Task UndockFromC1() => Cmd.ImrUndockAsync(-RobotPositions.IMR_UNDOCK_C1, RobotPositions.IMR_UNDOCK_VEL);
|
||||
|
||||
private Task UndockFromAbb() => Cmd.ImrUndockAsync(-RobotPositions.IMR_UNDOCK_ABB, RobotPositions.IMR_UNDOCK_VEL);
|
||||
|
||||
private Task Load() => Cmd.ImrLoadAsync();
|
||||
|
||||
private Task Unload() => Cmd.ImrUnloadAsync();
|
||||
|
||||
private Task Resume() => Cmd.ImrResumeAsync();
|
||||
|
||||
private Task Pause() => Cmd.ImrPauseAsync();
|
||||
|
||||
private Task Reset() => Cmd.ImrResetOpcAsync();
|
||||
|
||||
private Task Cancel()
|
||||
{
|
||||
CancelInitPose();
|
||||
_settingPose = false;
|
||||
StateHasChanged();
|
||||
return Cmd.ImrCancelAsync();
|
||||
}
|
||||
|
||||
private async Task RunInitPose()
|
||||
{
|
||||
_initPoseCts?.Dispose();
|
||||
_initPoseCts = new CancellationTokenSource();
|
||||
var ct = _initPoseCts.Token;
|
||||
|
||||
_settingPose = true;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
|
||||
try
|
||||
{
|
||||
var targetX = _poseX ?? 0;
|
||||
var targetY = _poseY ?? 0;
|
||||
var targetTheta = _poseYaw ?? 0;
|
||||
|
||||
// VDA initPosition instant action (thay cho OPC UA InitialPose)
|
||||
await Cmd.ImrInitPositionAsync(targetX, targetY, targetTheta, ct);
|
||||
Snackbar.Add(
|
||||
Lang.T(
|
||||
$"Đã gửi InitPosition ({targetX:F2}, {targetY:F2}, {targetTheta:F2})",
|
||||
$"InitPosition sent ({targetX:F2}, {targetY:F2}, {targetTheta:F2})"),
|
||||
Severity.Success);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Snackbar.Add(Lang.T("InitPosition đã huỷ", "InitPosition cancelled"), Severity.Info);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_settingPose = false;
|
||||
_initPoseCts?.Dispose();
|
||||
_initPoseCts = null;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
}
|
||||
|
||||
private void CancelInitPose()
|
||||
{
|
||||
try
|
||||
{
|
||||
_initPoseCts?.Cancel();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
<style>
|
||||
.status-row { display:flex; align-items:center; gap:8px; margin-bottom:4px; }
|
||||
.sec-title { display:block; color:#9CA3AF; margin-bottom:4px; }
|
||||
.op-grid { display:grid; grid-template-columns:repeat(3, 1fr); gap:5px; }
|
||||
.op-grid-2 { display:grid; grid-template-columns:1fr 1fr; gap:5px; }
|
||||
.op-grid-4 { display:grid; grid-template-columns:repeat(4, 1fr); gap:5px; }
|
||||
</style>
|
||||
404
Lab505.Client/Pages/LockPanel.razor
Normal file
404
Lab505.Client/Pages/LockPanel.razor
Normal file
@@ -0,0 +1,404 @@
|
||||
@implements IAsyncDisposable
|
||||
@inject HttpClient Http
|
||||
@inject StateService State
|
||||
@inject ISnackbar Snackbar
|
||||
@inject LangService Lang
|
||||
|
||||
<MudPaper Elevation="0" Class="pa-2" Style="background:transparent;">
|
||||
|
||||
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
|
||||
Style="cursor:pointer" @onclick="ToggleExpand">
|
||||
<MudText Typo="Typo.subtitle1">CONTROL ACCESS</MudText>
|
||||
<div style="display:flex;align-items:center;gap:6px;">
|
||||
@if (IsManager)
|
||||
{
|
||||
<a href="/users" @onclick:stopPropagation="true"
|
||||
style="font-size:10px;color:#4a9eff;text-decoration:none;opacity:0.8;display:flex;align-items:center;gap:2px;"
|
||||
title="App Settings"><MudIcon Icon="@Icons.Material.Filled.AdminPanelSettings" Size="Size.Small" /> Settings</a>
|
||||
}
|
||||
<MudIcon Icon="@(_expanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
|
||||
</div>
|
||||
</MudStack>
|
||||
|
||||
@{
|
||||
var ls = State.LockState;
|
||||
var wfActive = ls?.Workflow is not null;
|
||||
var grpActive = ls?.Groups is { } grpDict && grpDict.Values.Any(v => v is not null);
|
||||
}
|
||||
|
||||
@if (_expanded)
|
||||
{
|
||||
@* ── Mode banner ── *@
|
||||
@if (wfActive)
|
||||
{
|
||||
<div class="mode-banner mode-wf">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Bolt" Size="Size.Small" /> WF — @(ls!.Workflow!.Name)
|
||||
<span class="mode-note">@Lang.T("Manual tắt", "Manual disabled")</span>
|
||||
</div>
|
||||
}
|
||||
else if (grpActive)
|
||||
{
|
||||
<div class="mode-banner mode-manual">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Settings" Size="Size.Small" /> MANUAL
|
||||
<span class="mode-note">@Lang.T("Workflow tắt", "Workflow disabled")</span>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="mode-banner mode-free">@Lang.T("Không có ai nắm quyền", "No one holds control")</div>
|
||||
}
|
||||
|
||||
@* ── OPERATIONS CONTROL row ── *@
|
||||
<div class="ops-row @(grpActive && !IsManager ? "section-blocked" : "")">
|
||||
<span class="ops-lbl">OPS</span>
|
||||
@if (!CanWorkflow && UseReal)
|
||||
{
|
||||
<span class="mode-tag">Manual only</span>
|
||||
}
|
||||
@if (ls?.Workflow is { } wfHolder)
|
||||
{
|
||||
bool isMine = wfHolder.UserId == MyUserId;
|
||||
<MudChip T="string" Size="Size.Small" Color="@(isMine ? Color.Success : Color.Error)"
|
||||
Style="height:20px;font-size:10px;">
|
||||
@(isMine ? Lang.T("Bạn giữ", "You hold") : wfHolder.Name)
|
||||
</MudChip>
|
||||
@if (isMine)
|
||||
{
|
||||
<MudButton Size="Size.Small" Variant="Variant.Outlined" Color="Color.Default"
|
||||
Style="min-width:0;padding:1px 8px;" OnClick="ReleaseWorkflow">RELEASE</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Refresh" Size="Size.Small" Color="Color.Primary"
|
||||
Style="padding:1px;" OnClick="RenewWorkflow" />
|
||||
}
|
||||
else if (IsManager)
|
||||
{
|
||||
<MudButton Size="Size.Small" Variant="Variant.Text" Color="Color.Error"
|
||||
Style="min-width:0;padding:1px 6px;" OnClick="PreemptWorkflow">Preempt</MudButton>
|
||||
}
|
||||
else
|
||||
{
|
||||
var qPos = ls.WorkflowQueue?.ToList().FindIndex(w => w.UserId == MyUserId) ?? -1;
|
||||
@if (qPos >= 0)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Style="color:#9CA3AF;">@Lang.T("Chờ", "Queue") #@(qPos + 1)</MudText>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" Color="Color.Default"
|
||||
Style="padding:1px;" OnClick="LeaveWorkflowQueue" />
|
||||
}
|
||||
else if (CanWorkflow)
|
||||
{
|
||||
<MudButton Size="Size.Small" Variant="Variant.Outlined" Color="Color.Warning"
|
||||
Style="min-width:0;padding:1px 8px;" OnClick="JoinWorkflowQueue">JOIN</MudButton>
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (!grpActive || IsManager)
|
||||
{
|
||||
<MudChip T="string" Size="Size.Small" Color="@(CanWorkflow ? Color.Success : Color.Default)"
|
||||
Style="height:20px;font-size:10px;">Free</MudChip>
|
||||
@if (CanWorkflow)
|
||||
{
|
||||
<MudButton Size="Size.Small" Variant="Variant.Filled" Color="Color.Success"
|
||||
Style="min-width:0;padding:1px 10px;" OnClick="AcquireWorkflowControl">ACQUIRE</MudButton>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span style="font-size:10px;color:#9CA3AF;font-style:italic;">@Lang.T("Cần quyền WF", "Need WF perm")</span>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="ops-blocked-note">@Lang.T("Manual đang bật", "Manual is active")</span>
|
||||
}
|
||||
</div>
|
||||
@if (ls?.WorkflowQueue is { Count: > 0 } wfQueue)
|
||||
{
|
||||
<div class="queue-list">
|
||||
@foreach (var (w, i) in wfQueue.Select((w, i) => (w, i)))
|
||||
{
|
||||
<span class="queue-item @(w.IsPriority ? "q-priority" : "")">@(i + 1). @w.Name</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@* ── Group row ── *@
|
||||
<div class="grp-row @(wfActive ? "section-blocked" : "")">
|
||||
@foreach (var group in new[] { "ImrDobot", "AmrC1", "C2Asrs" })
|
||||
{
|
||||
var groupLabel = group switch { "ImrDobot" => "IMR·Dobot", "AmrC1" => "AMR·C1", _ => "C2·ASRS" };
|
||||
LockHolderDto? groupHolder = null;
|
||||
IReadOnlyList<WaiterDto>? groupQueue = null;
|
||||
ls?.Groups?.TryGetValue(group, out groupHolder);
|
||||
ls?.GroupQueues?.TryGetValue(group, out groupQueue);
|
||||
|
||||
<div class="grp-col">
|
||||
<span class="grp-name">@groupLabel</span>
|
||||
<div class="grp-actions">
|
||||
@if (wfActive)
|
||||
{
|
||||
<span class="grp-wf-note">WF</span>
|
||||
}
|
||||
else if (groupHolder is not null)
|
||||
{
|
||||
bool isMine = groupHolder.UserId == MyUserId;
|
||||
<MudChip T="string" Size="Size.Small" Color="@(isMine ? Color.Success : Color.Error)"
|
||||
Style="height:18px;font-size:10px;margin:0;">
|
||||
@(isMine ? Lang.T("Bạn", "You") : groupHolder.Name)
|
||||
</MudChip>
|
||||
@if (isMine)
|
||||
{
|
||||
var grp = group;
|
||||
<MudButton Size="Size.Small" Variant="Variant.Outlined" Color="Color.Default"
|
||||
Style="min-width:0;padding:1px 6px;" OnClick="() => ReleaseGroup(grp)">UNLOCK</MudButton>
|
||||
}
|
||||
else if (IsManager)
|
||||
{
|
||||
var grp = group;
|
||||
<MudButton Size="Size.Small" Variant="Variant.Text" Color="Color.Error"
|
||||
Style="min-width:0;padding:1px 4px;" OnClick="() => PreemptGroup(grp)">Unassign</MudButton>
|
||||
}
|
||||
else
|
||||
{
|
||||
var grp = group;
|
||||
var qPos2 = groupQueue?.ToList().FindIndex(w => w.UserId == MyUserId) ?? -1;
|
||||
@if (qPos2 >= 0)
|
||||
{
|
||||
<span style="font-size:10px;color:#9CA3AF;">#@(qPos2 + 1)</span>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" Color="Color.Default"
|
||||
Style="padding:1px;" OnClick="() => LeaveGroupQueue(grp)" />
|
||||
}
|
||||
else if (CanManual)
|
||||
{
|
||||
<MudButton Size="Size.Small" Variant="Variant.Text" Color="Color.Warning"
|
||||
Style="min-width:0;padding:1px 6px;" OnClick="() => JoinGroupQueue(grp)">JOIN</MudButton>
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudChip T="string" Size="Size.Small"
|
||||
Color="@(CanManual || IsManager ? Color.Success : Color.Default)"
|
||||
Style="height:18px;font-size:10px;margin:0;">Free</MudChip>
|
||||
var grp = group;
|
||||
var assignedIds = State.LockState?.Groups?
|
||||
.Where(kv => kv.Key != grp && kv.Value is not null)
|
||||
.Select(kv => kv.Value!.UserId)
|
||||
.ToHashSet() ?? new HashSet<string>();
|
||||
var availableUsers = _users.Where(u => !assignedIds.Contains(u.Id)).ToList();
|
||||
if (IsManager)
|
||||
{
|
||||
<MudMenu Icon="@Icons.Material.Filled.PersonAdd" Size="Size.Small"
|
||||
Style="min-width:0;" IconColor="Color.Success"
|
||||
>
|
||||
@if (availableUsers.Count == 0)
|
||||
{
|
||||
<MudMenuItem Disabled="true">
|
||||
<span style="font-size:11px;color:#9CA3AF;font-style:italic;">
|
||||
@Lang.T("Hết user", "All assigned")
|
||||
</span>
|
||||
</MudMenuItem>
|
||||
}
|
||||
else
|
||||
{
|
||||
@foreach (var u in availableUsers)
|
||||
{
|
||||
var uid = u.Id;
|
||||
var uname = u.Username;
|
||||
<MudMenuItem OnClick="() => AssignGroup(grp, uid, uname)">
|
||||
<span style="font-size:12px;">@u.Username</span>
|
||||
<span style="font-size:10px;color:#9CA3AF;margin-left:6px;">@u.Role</span>
|
||||
</MudMenuItem>
|
||||
}
|
||||
}
|
||||
</MudMenu>
|
||||
}
|
||||
else if (CanManual)
|
||||
{
|
||||
<MudButton Size="Size.Small" Variant="Variant.Outlined" Color="Color.Primary"
|
||||
Style="min-width:0;padding:1px 6px;" OnClick="() => LockGroup(grp)">LOCK</MudButton>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span style="font-size:10px;color:#9CA3AF;font-style:italic;">@Lang.T("Cần Manual", "Need Manual")</span>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
@if (groupQueue is { Count: > 0 })
|
||||
{
|
||||
<div class="grp-queue">
|
||||
@foreach (var (w, i) in groupQueue.Select((w, i) => (w, i)))
|
||||
{
|
||||
<span class="queue-item @(w.IsPriority ? "q-priority" : "")">@(i + 1). @w.Name</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public bool UseReal { get; set; }
|
||||
[Parameter] public string MyUserId { get; set; } = "";
|
||||
[Parameter] public string MyRole { get; set; } = "";
|
||||
[Parameter] public bool CanWorkflow { get; set; }
|
||||
[Parameter] public bool CanManual { get; set; }
|
||||
|
||||
private bool IsManager => MyRole is "Manager" or "Admin";
|
||||
|
||||
private bool _expanded = true;
|
||||
private bool _usersLoaded = false;
|
||||
private List<UserItem> _users = new();
|
||||
|
||||
private void ToggleExpand() => _expanded = !_expanded;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.LockStateChanged += OnLockChanged;
|
||||
State.SystemChanged += OnLockChanged;
|
||||
Lang.LangChanged += OnLockChanged;
|
||||
}
|
||||
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
if (IsManager && !_usersLoaded)
|
||||
{
|
||||
_usersLoaded = true;
|
||||
try
|
||||
{
|
||||
var list = await Http.GetFromJsonAsync<List<UserItem>>("/api/auth/users/active");
|
||||
if (list is not null) _users = list;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Không tải được danh sách user: {ex.Message}", Severity.Warning);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
record UserItem(string Id, string Username, string Role);
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.LockStateChanged -= OnLockChanged;
|
||||
State.SystemChanged -= OnLockChanged;
|
||||
Lang.LangChanged -= OnLockChanged;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void OnLockChanged() => InvokeAsync(StateHasChanged);
|
||||
|
||||
// ── Workflow actions ───────────────────────────────────────────────────────
|
||||
|
||||
private async Task AcquireWorkflowControl()
|
||||
{
|
||||
var resp = await Http.PostAsync("/api/lock/workflow/acquire", null);
|
||||
if ((int)resp.StatusCode == 423)
|
||||
Snackbar.Add(Lang.T("Workflow đang bị giữ bởi người khác.", "Workflow is held by another user."), Severity.Warning);
|
||||
else if ((int)resp.StatusCode == 403)
|
||||
Snackbar.Add(Lang.T("Bạn không có quyền Workflow Mode.", "You don't have Workflow Mode permission."), Severity.Error);
|
||||
else if (!resp.IsSuccessStatusCode)
|
||||
Snackbar.Add(Lang.T("Không thể lấy quyền điều khiển.", "Failed to acquire control."), Severity.Error);
|
||||
}
|
||||
|
||||
private async Task ReleaseWorkflow()
|
||||
{
|
||||
await Http.PostAsync("/api/lock/workflow/release", null);
|
||||
}
|
||||
|
||||
private async Task RenewWorkflow()
|
||||
{
|
||||
var resp = await Http.PostAsync("/api/lock/workflow/renew", null);
|
||||
if (resp.IsSuccessStatusCode) Snackbar.Add(Lang.T("Đã gia hạn quyền điều khiển.", "Control renewed."), Severity.Success);
|
||||
}
|
||||
|
||||
private async Task PreemptWorkflow()
|
||||
{
|
||||
await Http.SendAsync(new HttpRequestMessage(HttpMethod.Delete, "/api/lock/workflow"));
|
||||
Snackbar.Add(Lang.T("Đã thu hồi Workflow lock.", "Workflow lock preempted."), Severity.Info);
|
||||
}
|
||||
|
||||
private async Task JoinWorkflowQueue()
|
||||
{
|
||||
await Http.PostAsync("/api/lock/workflow/queue", null);
|
||||
Snackbar.Add(Lang.T("Đã vào hàng chờ Operations Control.", "Joined Operations Control queue."), Severity.Info);
|
||||
}
|
||||
|
||||
private async Task LeaveWorkflowQueue()
|
||||
{
|
||||
await Http.SendAsync(new HttpRequestMessage(HttpMethod.Delete, "/api/lock/workflow/queue"));
|
||||
}
|
||||
|
||||
// ── Group actions ──────────────────────────────────────────────────────────
|
||||
|
||||
private async Task LockGroup(string group)
|
||||
{
|
||||
var resp = await Http.PostAsync($"/api/lock/{group}/acquire", null);
|
||||
if ((int)resp.StatusCode == 423)
|
||||
Snackbar.Add(Lang.T($"Nhóm {group} đang bị giữ bởi người khác.", $"Group {group} is held by another user."), Severity.Warning);
|
||||
else if ((int)resp.StatusCode == 403)
|
||||
Snackbar.Add(Lang.T("Bạn không có quyền Manual Mode.", "You don't have Manual Mode permission."), Severity.Error);
|
||||
else if (!resp.IsSuccessStatusCode)
|
||||
Snackbar.Add(Lang.T($"Không thể khóa nhóm {group}.", $"Failed to lock group {group}."), Severity.Error);
|
||||
}
|
||||
|
||||
private async Task ReleaseGroup(string group)
|
||||
{
|
||||
await Http.PostAsync($"/api/lock/{group}/release", null);
|
||||
}
|
||||
|
||||
private async Task PreemptGroup(string group)
|
||||
{
|
||||
await Http.SendAsync(new HttpRequestMessage(HttpMethod.Delete, $"/api/lock/{group}"));
|
||||
Snackbar.Add(Lang.T($"Đã thu hồi lock nhóm {group}.", $"Group {group} unassigned."), Severity.Info);
|
||||
}
|
||||
|
||||
private async Task AssignGroup(string group, string userId, string displayName)
|
||||
{
|
||||
var resp = await Http.PostAsJsonAsync($"/api/lock/{group}/assign", new { UserId = userId, DisplayName = displayName });
|
||||
if (resp.IsSuccessStatusCode)
|
||||
Snackbar.Add(Lang.T($"Đã phân nhóm {group} cho {displayName}.", $"Group {group} assigned to {displayName}."), Severity.Success);
|
||||
else
|
||||
Snackbar.Add(Lang.T("Không thể phân nhóm.", "Failed to assign group."), Severity.Error);
|
||||
}
|
||||
|
||||
private async Task JoinGroupQueue(string group)
|
||||
{
|
||||
await Http.PostAsync($"/api/lock/{group}/queue", null);
|
||||
Snackbar.Add(Lang.T($"Đã vào hàng chờ nhóm {group}.", $"Joined group {group} queue."), Severity.Info);
|
||||
}
|
||||
|
||||
private async Task LeaveGroupQueue(string group)
|
||||
{
|
||||
await Http.SendAsync(new HttpRequestMessage(HttpMethod.Delete, $"/api/lock/{group}/queue"));
|
||||
}
|
||||
}
|
||||
|
||||
<style>
|
||||
.ops-row { display:flex; align-items:center; gap:5px; flex-wrap:wrap; margin-top:4px; padding-top:4px; border-top:1px solid rgba(255,255,255,0.05); }
|
||||
.ops-lbl { font-size:10px; font-weight:700; color:#9CA3AF; letter-spacing:0.5px; white-space:nowrap; }
|
||||
.ops-blocked-note { font-size:10px; color:#9CA3AF; font-style:italic; margin-left:auto; }
|
||||
|
||||
.grp-row { display:grid; grid-template-columns:1fr 1fr 1fr; gap:6px; margin-top:4px; padding-top:5px; border-top:1px solid rgba(255,255,255,0.05); }
|
||||
.grp-row.section-blocked { opacity:0.45; pointer-events:none; }
|
||||
.grp-col { display:flex; flex-direction:column; gap:3px; padding:4px 6px; border:1px solid rgba(255,255,255,0.05); border-radius:5px; }
|
||||
.grp-name { font-size:10px; font-weight:700; color:#9CA3AF; white-space:nowrap; }
|
||||
.grp-actions { display:flex; align-items:center; gap:3px; flex-wrap:wrap; }
|
||||
.grp-wf-note { font-size:10px; color:#9CA3AF; font-style:italic; }
|
||||
.grp-queue { display:flex; flex-wrap:wrap; gap:3px; padding-bottom:2px; }
|
||||
|
||||
.queue-list { display:flex; flex-wrap:wrap; gap:4px; margin-top:2px; padding-left:4px; }
|
||||
.queue-item { font-size:10px; color:#9CA3AF; background:rgba(255,255,255,0.04); padding:1px 5px; border-radius:3px; }
|
||||
.queue-item.q-priority { color:#4a9eff; }
|
||||
|
||||
.mode-banner { font-size:10px; font-weight:700; padding:3px 8px; border-radius:4px; margin:4px 0 2px;
|
||||
display:flex; align-items:center; gap:6px; }
|
||||
.mode-banner.mode-wf { background:rgba(243,156,18,0.1); border:1px solid rgba(243,156,18,0.3); color:#f39c12; }
|
||||
.mode-banner.mode-manual { background:rgba(74,158,255,0.08); border:1px solid rgba(74,158,255,0.25); color:#4a9eff; }
|
||||
.mode-banner.mode-free { background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.07); color:#9CA3AF; }
|
||||
.mode-note { font-size:9px; font-weight:400; opacity:0.7; margin-left:auto; }
|
||||
|
||||
.mode-tag { font-size:9px; font-weight:700; padding:1px 5px; border-radius:3px;
|
||||
background:rgba(74,158,255,0.1); border:1px solid rgba(74,158,255,0.2); color:#3a7bbf; }
|
||||
</style>
|
||||
330
Lab505.Client/Pages/MapPanel.razor
Normal file
330
Lab505.Client/Pages/MapPanel.razor
Normal file
@@ -0,0 +1,330 @@
|
||||
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
|
||||
@implements IAsyncDisposable
|
||||
@using Lab505.Shared
|
||||
@using Lab505.Client.Services
|
||||
@inject StateService State
|
||||
@inject IJSRuntime JS
|
||||
|
||||
<div class="mp-wrap" @ref="_el"
|
||||
@onmousedown="OnMouseDown"
|
||||
@onmousemove="OnMouseMove"
|
||||
@onmouseup="OnMouseUp"
|
||||
@onmouseleave="OnMouseLeave"
|
||||
@ontouchstart="OnTouchStart"
|
||||
@ontouchmove="OnTouchMove"
|
||||
@ontouchend="OnTouchEnd"
|
||||
style="cursor:@(_dragging?"grabbing":"grab")">
|
||||
|
||||
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" style="display:block">
|
||||
<defs>
|
||||
<!-- 1 m minor grid -->
|
||||
<pattern id="mp-g1"
|
||||
width="@F(_s)" height="@F(_s)"
|
||||
x="@F(Mod(_panX, _s))" y="@F(Mod(_panY, _s))"
|
||||
patternUnits="userSpaceOnUse">
|
||||
<path d="M @F(_s) 0 L 0 0 0 @F(_s)" fill="none" stroke="#232323" stroke-width="1"/>
|
||||
</pattern>
|
||||
<!-- 5 m major grid -->
|
||||
<pattern id="mp-g5"
|
||||
width="@F(5*_s)" height="@F(5*_s)"
|
||||
x="@F(Mod(_panX, 5*_s))" y="@F(Mod(_panY, 5*_s))"
|
||||
patternUnits="userSpaceOnUse">
|
||||
<path d="M @F(5*_s) 0 L 0 0 0 @F(5*_s)" fill="none" stroke="#2c2c2c" stroke-width="1.5"/>
|
||||
</pattern>
|
||||
</defs>
|
||||
|
||||
<!-- Background + grid layers -->
|
||||
<rect width="100%" height="100%" fill="#1a1a1a"/>
|
||||
<rect width="100%" height="100%" fill="url(#mp-g1)"/>
|
||||
<rect width="100%" height="100%" fill="url(#mp-g5)"/>
|
||||
|
||||
<!-- Axes -->
|
||||
<line x1="@F(ToX(-100))" y1="@F(ToY(0))" x2="@F(ToX(100))" y2="@F(ToY(0))"
|
||||
stroke="#2e2e2e" stroke-width="1.5"/>
|
||||
<line x1="@F(ToX(0))" y1="@F(ToY(-100))" x2="@F(ToX(0))" y2="@F(ToY(100))"
|
||||
stroke="#2e2e2e" stroke-width="1.5"/>
|
||||
|
||||
<!-- Grid coordinate labels (X axis, every 5 m) -->
|
||||
@for (int gx = -15; gx <= 15; gx += 5)
|
||||
{
|
||||
double lx = ToX(gx), ly = ToY(0) + 14;
|
||||
if (lx > 10 && lx < 3000)
|
||||
{
|
||||
@SvgTxt(lx, ly, "#383838", 10, "middle", "", gx.ToString())
|
||||
}
|
||||
}
|
||||
<!-- Grid coordinate labels (Y axis, every 5 m) -->
|
||||
@for (int gy = -15; gy <= 15; gy += 5)
|
||||
{
|
||||
if (gy == 0) continue;
|
||||
double lx = ToX(0) + 5, ly = ToY(gy);
|
||||
if (ly > 10 && ly < 3000)
|
||||
{
|
||||
@SvgTxt(lx, ly, "#383838", 10, "start", "middle", gy.ToString())
|
||||
}
|
||||
}
|
||||
|
||||
<!-- IMR trail -->
|
||||
@if (_imrTrail.Count > 1)
|
||||
{
|
||||
<polyline points="@TrailPts(_imrTrail)"
|
||||
fill="none" stroke="#4a9eff" stroke-width="2.5"
|
||||
stroke-opacity="0.35" stroke-linejoin="round" stroke-linecap="round"/>
|
||||
}
|
||||
|
||||
<!-- AMR trail -->
|
||||
@if (_amrTrail.Count > 1)
|
||||
{
|
||||
<polyline points="@TrailPts(_amrTrail)"
|
||||
fill="none" stroke="#4caf50" stroke-width="2.5"
|
||||
stroke-opacity="0.35" stroke-linejoin="round" stroke-linecap="round"/>
|
||||
}
|
||||
|
||||
<!-- Waypoints -->
|
||||
@foreach (var wp in _waypoints)
|
||||
{
|
||||
double wx = ToX(wp.X), wy = ToY(wp.Y);
|
||||
<g style="pointer-events:none">
|
||||
<line x1="@F(wx-6)" y1="@F(wy)" x2="@F(wx+6)" y2="@F(wy)"
|
||||
stroke="@wp.Color" stroke-width="1.5" opacity="0.4"/>
|
||||
<line x1="@F(wx)" y1="@F(wy-6)" x2="@F(wx)" y2="@F(wy+6)"
|
||||
stroke="@wp.Color" stroke-width="1.5" opacity="0.4"/>
|
||||
<circle cx="@F(wx)" cy="@F(wy)" r="4"
|
||||
fill="none" stroke="@wp.Color" stroke-width="1.5" opacity="0.5"/>
|
||||
@SvgTxtColor(wx, wy - 11, wp.Color, 11, "middle", "", wp.Name, "opacity:0.6;user-select:none")
|
||||
</g>
|
||||
}
|
||||
|
||||
<!-- IMR robot -->
|
||||
@{
|
||||
double ix = ToX(State.Imr.X), iy = ToY(State.Imr.Y);
|
||||
bool io = State.Imr.IsOnline;
|
||||
string ic = io ? "#4a9eff" : "#333";
|
||||
}
|
||||
<g style="pointer-events:none">
|
||||
@if (io) { <circle cx="@F(ix)" cy="@F(iy)" r="20" fill="#4a9eff" fill-opacity="0.07"/> }
|
||||
<circle cx="@F(ix)" cy="@F(iy)" r="9" fill="@ic" stroke="#111" stroke-width="2"/>
|
||||
<polygon points="@F(ix),@F(iy-15) @F(ix-4),@F(iy-9) @F(ix+4),@F(iy-9)"
|
||||
fill="@ic" opacity="0.7"/>
|
||||
<text x="@F(ix)" y="@F(iy - 20)" fill="@ic"
|
||||
font-size="11" font-weight="600" text-anchor="middle"
|
||||
style="user-select:none">IMR</text>
|
||||
<text x="@F(ix)" y="@F(iy + 26)" fill="#505050"
|
||||
font-size="9" text-anchor="middle"
|
||||
style="user-select:none">(@State.Imr.X.ToString("F2", CI),@State.Imr.Y.ToString("F2", CI))</text>
|
||||
</g>
|
||||
|
||||
<!-- AMR robot -->
|
||||
@{
|
||||
double ax = ToX(State.Amr.X), ay = ToY(State.Amr.Y);
|
||||
bool ao = State.Amr.IsOnline;
|
||||
string ac = ao ? "#4caf50" : "#333";
|
||||
}
|
||||
<g style="pointer-events:none">
|
||||
@if (ao) { <circle cx="@F(ax)" cy="@F(ay)" r="20" fill="#4caf50" fill-opacity="0.07"/> }
|
||||
<circle cx="@F(ax)" cy="@F(ay)" r="9" fill="@ac" stroke="#111" stroke-width="2"/>
|
||||
<polygon points="@F(ax),@F(ay-15) @F(ax-4),@F(ay-9) @F(ax+4),@F(ay-9)"
|
||||
fill="@ac" opacity="0.7"/>
|
||||
<text x="@F(ax)" y="@F(ay - 20)" fill="@ac"
|
||||
font-size="11" font-weight="600" text-anchor="middle"
|
||||
style="user-select:none">AMR</text>
|
||||
<text x="@F(ax)" y="@F(ay + 26)" fill="#505050"
|
||||
font-size="9" text-anchor="middle"
|
||||
style="user-select:none">(@State.Amr.X.ToString("F2", CI),@State.Amr.Y.ToString("F2", CI))</text>
|
||||
</g>
|
||||
|
||||
<!-- Legend (top-left) -->
|
||||
<g transform="translate(10,10)" style="pointer-events:none">
|
||||
<rect width="116" height="68" rx="5"
|
||||
fill="rgba(0,0,0,0.72)" stroke="#2a2a2a" stroke-width="1"/>
|
||||
<circle cx="14" cy="19" r="5" fill="@(io ? "#4a9eff" : "#333")"/>
|
||||
<text x="24" y="23" fill="#aaa" font-size="11">IMR @(State.Imr.IsOnline ? "●" : "○")</text>
|
||||
<circle cx="14" cy="39" r="5" fill="@(ao ? "#4caf50" : "#333")"/>
|
||||
<text x="24" y="43" fill="#aaa" font-size="11">AMR @(State.Amr.IsOnline ? "●" : "○")</text>
|
||||
<text x="8" y="59" fill="#3a3a3a" font-size="9">1 ô = 1 m²</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
<div class="mp-zoom-badge">×@_zoom.ToString("F1", CI)</div>
|
||||
<button class="mp-reset" @onclick="ResetView" title="Reset view">⊙</button>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
ElementReference _el;
|
||||
DotNetObjectReference<MapPanel>? _self;
|
||||
|
||||
// ── Pan / Zoom ────────────────────────────────────────────────
|
||||
double _panX = 150, _panY = 180;
|
||||
double _zoom = 1.0;
|
||||
const double CELL = 40.0;
|
||||
double _s => _zoom * CELL;
|
||||
|
||||
// ── Drag ─────────────────────────────────────────────────────
|
||||
bool _dragging;
|
||||
double _dragCX, _dragCY, _dragPX, _dragPY;
|
||||
|
||||
// ── Trail ─────────────────────────────────────────────────────
|
||||
const int MAX_TRAIL = 200;
|
||||
readonly Queue<(double X, double Y)> _imrTrail = new();
|
||||
readonly Queue<(double X, double Y)> _amrTrail = new();
|
||||
|
||||
// ── Waypoints ─────────────────────────────────────────────────
|
||||
record Wp(string Name, double X, double Y, string Color);
|
||||
static readonly Wp[] _waypoints =
|
||||
[
|
||||
new("C1", RobotPositions.IMR_C1_X, RobotPositions.IMR_C1_Y, "#5b9bd5"),
|
||||
new("ABB", RobotPositions.IMR_ABB_X, RobotPositions.IMR_ABB_Y, "#5b9bd5"),
|
||||
new("Cap1", RobotPositions.AMR_CAP1_X, RobotPositions.AMR_CAP1_Y, "#5cb85c"),
|
||||
new("Cap2", RobotPositions.AMR_CAP2_X, RobotPositions.AMR_CAP2_Y, "#5cb85c"),
|
||||
new("Home", RobotPositions.AMR_HOME_X, RobotPositions.AMR_HOME_Y, "#888"),
|
||||
];
|
||||
|
||||
static readonly System.Globalization.CultureInfo CI =
|
||||
System.Globalization.CultureInfo.InvariantCulture;
|
||||
|
||||
// ── Lifecycle ─────────────────────────────────────────────────
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
State.ImrChanged += OnImrChanged;
|
||||
State.AmrChanged += OnAmrChanged;
|
||||
}
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (!firstRender) return;
|
||||
_self = DotNetObjectReference.Create(this);
|
||||
await JS.InvokeVoidAsync("eval",
|
||||
"if(!window._mpWheelInit)window._mpWheelInit=function(el,dn){" +
|
||||
"el.addEventListener('wheel',function(e){e.preventDefault();" +
|
||||
"var r=el.getBoundingClientRect();" +
|
||||
"dn.invokeMethodAsync('OnWheelJs',e.deltaY,e.clientX-r.left,e.clientY-r.top);" +
|
||||
"},{passive:false});};");
|
||||
await JS.InvokeVoidAsync("_mpWheelInit", _el, _self);
|
||||
}
|
||||
|
||||
[JSInvokable]
|
||||
public void OnWheelJs(double deltaY, double offsetX, double offsetY)
|
||||
{
|
||||
double factor = deltaY < 0 ? 1.15 : 1.0 / 1.15;
|
||||
double newZoom = Math.Clamp(_zoom * factor, 0.12, 12.0);
|
||||
double f = newZoom / _zoom;
|
||||
_panX = offsetX + (_panX - offsetX) * f;
|
||||
_panY = offsetY + (_panY - offsetY) * f;
|
||||
_zoom = newZoom;
|
||||
InvokeAsync(StateHasChanged);
|
||||
}
|
||||
|
||||
void ResetView() { _panX = 150; _panY = 180; _zoom = 1.0; }
|
||||
|
||||
// ── Mouse pan ─────────────────────────────────────────────────
|
||||
void OnMouseDown(MouseEventArgs e)
|
||||
{
|
||||
if (e.Button != 0) return;
|
||||
_dragging = true;
|
||||
_dragCX = e.ClientX; _dragCY = e.ClientY;
|
||||
_dragPX = _panX; _dragPY = _panY;
|
||||
}
|
||||
void OnMouseMove(MouseEventArgs e)
|
||||
{
|
||||
if (!_dragging) return;
|
||||
_panX = _dragPX + (e.ClientX - _dragCX);
|
||||
_panY = _dragPY + (e.ClientY - _dragCY);
|
||||
}
|
||||
void OnMouseUp(MouseEventArgs e) { if (e.Button == 0) _dragging = false; }
|
||||
void OnMouseLeave(MouseEventArgs e) { _dragging = false; }
|
||||
|
||||
// ── Touch pan ─────────────────────────────────────────────────
|
||||
void OnTouchStart(TouchEventArgs e)
|
||||
{
|
||||
if (e.Touches.Length != 1) return;
|
||||
var t = e.Touches[0]; _dragging = true;
|
||||
_dragCX = t.ClientX; _dragCY = t.ClientY;
|
||||
_dragPX = _panX; _dragPY = _panY;
|
||||
}
|
||||
void OnTouchMove(TouchEventArgs e)
|
||||
{
|
||||
if (!_dragging || e.Touches.Length != 1) return;
|
||||
var t = e.Touches[0];
|
||||
_panX = _dragPX + (t.ClientX - _dragCX);
|
||||
_panY = _dragPY + (t.ClientY - _dragCY);
|
||||
}
|
||||
void OnTouchEnd(TouchEventArgs e) { _dragging = false; }
|
||||
|
||||
// ── State updates ─────────────────────────────────────────────
|
||||
void OnImrChanged() { AddTrail(_imrTrail, State.Imr.X, State.Imr.Y); InvokeAsync(StateHasChanged); }
|
||||
void OnAmrChanged() { AddTrail(_amrTrail, State.Amr.X, State.Amr.Y); InvokeAsync(StateHasChanged); }
|
||||
|
||||
static void AddTrail(Queue<(double, double)> q, double x, double y)
|
||||
{
|
||||
if (q.TryPeek(out var last)
|
||||
&& Math.Abs(last.Item1 - x) < 0.005
|
||||
&& Math.Abs(last.Item2 - y) < 0.005) return;
|
||||
q.Enqueue((x, y));
|
||||
while (q.Count > MAX_TRAIL) q.Dequeue();
|
||||
}
|
||||
|
||||
// ── Coordinate helpers ────────────────────────────────────────
|
||||
double ToX(double wx) => _panX + wx * _s;
|
||||
double ToY(double wy) => _panY - wy * _s; // flip Y: VDA5050 Y-up → SVG Y-down
|
||||
static double Mod(double a, double b) => ((a % b) + b) % b;
|
||||
static string F(double v) => v.ToString("F2", CI);
|
||||
|
||||
string TrailPts(Queue<(double X, double Y)> q)
|
||||
=> string.Join(" ", q.Select(p => $"{F(ToX(p.X))},{F(ToY(p.Y))}"));
|
||||
|
||||
// ── SVG <text> helpers (avoid Razor parser conflict inside code blocks) ──
|
||||
// Blazor treats <text> as a Razor directive inside @for/@foreach — use MarkupString instead.
|
||||
static MarkupString SvgTxt(double x, double y, string fill, int size,
|
||||
string anchor, string baseline, string content)
|
||||
{
|
||||
var bl = baseline.Length > 0 ? $" dominant-baseline=\"{baseline}\"" : "";
|
||||
return (MarkupString)(
|
||||
$"<text x=\"{x:F2}\" y=\"{y:F2}\" fill=\"{fill}\" font-size=\"{size}\"" +
|
||||
$" text-anchor=\"{anchor}\"{bl}" +
|
||||
$" style=\"pointer-events:none;user-select:none\">{content}</text>");
|
||||
}
|
||||
|
||||
static MarkupString SvgTxtColor(double x, double y, string fill, int size,
|
||||
string anchor, string baseline, string content, string style)
|
||||
{
|
||||
var bl = baseline.Length > 0 ? $" dominant-baseline=\"{baseline}\"" : "";
|
||||
return (MarkupString)(
|
||||
$"<text x=\"{x:F2}\" y=\"{y:F2}\" fill=\"{fill}\" font-size=\"{size}\"" +
|
||||
$" text-anchor=\"{anchor}\"{bl}" +
|
||||
$" style=\"{style}\">{content}</text>");
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.ImrChanged -= OnImrChanged;
|
||||
State.AmrChanged -= OnAmrChanged;
|
||||
_self?.Dispose();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
<style>
|
||||
.mp-wrap {
|
||||
width: 100%; height: 100%;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: #1a1a1a;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
.mp-zoom-badge {
|
||||
position: absolute; bottom: 12px; left: 12px;
|
||||
color: #383838; font-size: 10px;
|
||||
font-family: monospace; pointer-events: none;
|
||||
}
|
||||
.mp-reset {
|
||||
position: absolute; bottom: 10px; right: 10px;
|
||||
width: 28px; height: 28px;
|
||||
background: rgba(0,0,0,0.65); border: 1px solid #2e2e2e;
|
||||
border-radius: 5px; color: #555; font-size: 15px;
|
||||
cursor: pointer; padding: 0; line-height: 1;
|
||||
transition: color .15s, border-color .15s;
|
||||
}
|
||||
.mp-reset:hover { color: #aaa; border-color: #555; }
|
||||
</style>
|
||||
41
Lab505.Client/Pages/NotificationProvider.razor
Normal file
41
Lab505.Client/Pages/NotificationProvider.razor
Normal file
@@ -0,0 +1,41 @@
|
||||
@implements IAsyncDisposable
|
||||
@inject StateService State
|
||||
@inject ISnackbar Snackbar
|
||||
@inject ScriptLogService ScriptLog
|
||||
|
||||
@* Component không render gì — lắng nghe notification, ghi vào output log + Snackbar *@
|
||||
|
||||
@code {
|
||||
[Parameter] public bool Muted { get; set; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.NotificationReceived += OnNotification;
|
||||
}
|
||||
|
||||
private void OnNotification(NotificationDto n)
|
||||
{
|
||||
ScriptLog.LogNotification(n);
|
||||
|
||||
// Snackbar toast — chỉ khi chưa tắt
|
||||
if (!Muted)
|
||||
{
|
||||
var severity = n.Level switch
|
||||
{
|
||||
"success" => Severity.Success,
|
||||
"error" => Severity.Error,
|
||||
"warning" => Severity.Warning,
|
||||
"heartbeat" => Severity.Normal,
|
||||
_ => Severity.Info,
|
||||
};
|
||||
Snackbar.Add(n.Message, severity);
|
||||
}
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.NotificationReceived -= OnNotification;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
920
Lab505.Client/Pages/ScriptPanel.razor
Normal file
920
Lab505.Client/Pages/ScriptPanel.razor
Normal file
@@ -0,0 +1,920 @@
|
||||
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
|
||||
@implements IAsyncDisposable
|
||||
@using Microsoft.AspNetCore.SignalR.Client
|
||||
@inject StateService State
|
||||
@inject LangService Lang
|
||||
@inject ScriptLogService ScriptLog
|
||||
|
||||
<MudMessageBox @ref="_confirmRunBox" Title="@Lang.T("Xác nhận chạy script (REAL)", "Confirm run script (REAL)")" CancelText="@Lang.T("Hủy", "Cancel")">
|
||||
<MessageContent>
|
||||
@if (_loadedName != null)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Style="color:#4a9eff;margin-bottom:6px;"><MudIcon Icon="@Icons.Material.Filled.FiberManualRecord" Size="Size.Small" /> @_loadedName</MudText>
|
||||
}
|
||||
<MudText Typo="Typo.caption" Style="color:#aaa;margin-bottom:4px;">@Lang.T("Code sẽ được thực thi:", "Code to be executed:")</MudText>
|
||||
<pre style="max-height:300px;overflow-y:auto;background:#27292b;color:#cfc;font-size:11px;
|
||||
padding:8px;border-radius:4px;border:1px solid #333;margin:0;white-space:pre-wrap;
|
||||
word-wrap:break-word;">@_pendingCode</pre>
|
||||
</MessageContent>
|
||||
<YesButton>
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.PlayArrow">@Lang.T("Chạy", "Run")</MudButton>
|
||||
</YesButton>
|
||||
</MudMessageBox>
|
||||
|
||||
<div class="script-root">
|
||||
|
||||
<div class="script-toolbar">
|
||||
<MudText Typo="Typo.subtitle2" Style="color:#ddd;">SCRIPT</MudText>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" Size="Size.Small"
|
||||
StartIcon="@Icons.Material.Filled.PlayArrow"
|
||||
OnClick="RunScript" Disabled="@(_isRunning || IsLockBlocked)">Run</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Error" Size="Size.Small"
|
||||
StartIcon="@Icons.Material.Filled.Stop"
|
||||
OnClick="StopScript" Disabled="!_isRunning">@Lang.T("Hủy", "Cancel")</MudButton>
|
||||
@if (IsLockBlocked)
|
||||
{
|
||||
<MudChip T="string" Icon="@Icons.Material.Filled.Warning" Color="Color.Warning"
|
||||
Variant="Variant.Outlined" Size="Size.Small"
|
||||
Style="height:24px;font-size:10px;margin:0;">@Lang.T("Cần giữ lock để chạy script", "Lock required to run script")</MudChip>
|
||||
}
|
||||
else if (IsWorkflowMode)
|
||||
{
|
||||
<MudChip T="string" Icon="@Icons.Material.Filled.Bolt" Color="Color.Warning"
|
||||
Variant="Variant.Outlined" Size="Size.Small"
|
||||
Style="height:24px;font-size:10px;margin:0;opacity:0.8;">Workflow</MudChip>
|
||||
}
|
||||
else if (IsManualMode)
|
||||
{
|
||||
<MudChip T="string" Icon="@Icons.Material.Filled.Settings" Color="Color.Info"
|
||||
Variant="Variant.Outlined" Size="Size.Small"
|
||||
Style="height:24px;font-size:10px;margin:0;opacity:0.8;">Manual</MudChip>
|
||||
}
|
||||
@if (_hubOk)
|
||||
{
|
||||
<MudChip T="string" Icon="@Icons.Material.Filled.CheckCircle" Color="Color.Success"
|
||||
Variant="Variant.Text" Size="Size.Small"
|
||||
Style="height:24px;font-size:11px;margin:0;">Connected</MudChip>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Variant="Variant.Text" Color="Color.Error" Size="Size.Small"
|
||||
OnClick="ConnectHub"
|
||||
Style="font-size:11px;padding:0 4px;min-height:auto;min-width:auto;text-decoration:underline dotted;">Disconnect</MudButton>
|
||||
}
|
||||
|
||||
<div style="margin-left:auto;display:flex;align-items:center;gap:4px;">
|
||||
@if (_saveOpen)
|
||||
{
|
||||
<MudTextField @bind-Value="_saveName" Immediate="true"
|
||||
Placeholder="@Lang.T("Tên script...", "Script name...")" OnKeyDown="SaveKeyDown" AutoFocus="true"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
Style="width:140px;" />
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Check" Size="Size.Small"
|
||||
Style="color:#2ecc71;padding:4px;" OnClick="DoSave" />
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small"
|
||||
Style="color:#e74c3c;padding:4px;" OnClick="() => _saveOpen = false" />
|
||||
}
|
||||
else
|
||||
{
|
||||
@if (_loadedName != null)
|
||||
{
|
||||
<MudChip T="string" Icon="@Icons.Material.Filled.FiberManualRecord"
|
||||
Color="Color.Info" Variant="Variant.Text" Size="Size.Small"
|
||||
Style="max-width:160px;height:24px;font-size:11px;margin:0;"
|
||||
title="@_loadedName">@_loadedName</MudChip>
|
||||
}
|
||||
<MudButton Variant="Variant.Text" Size="Size.Small" OnClick="OpenSave"
|
||||
Style="color:#aaa;padding:0 6px;min-width:0;font-size:11px;">
|
||||
@Lang.T("Lưu", "Save")
|
||||
</MudButton>
|
||||
}
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small"
|
||||
Style="min-width:40px;color:#aaa;border-color:#555;padding:0 8px;"
|
||||
OnClick="ToggleLang">@Lang.Current.ToUpper()</MudButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="script-body">
|
||||
|
||||
<!-- ── File sidebar ─────────────────────────────────────── -->
|
||||
<div id="fileSidebar" class="file-sidebar @(_sidebarOpen ? "" : "collapsed")">
|
||||
<div class="sidebar-header">
|
||||
<span>FILES</span>
|
||||
<MudButton Variant="Variant.Text" Size="Size.Small" OnClick="NewScript"
|
||||
Style="color:#888;padding:0 4px;min-width:0;height:22px;font-size:12px;border:1px solid #444;border-radius:3px;">+</MudButton>
|
||||
</div>
|
||||
<div class="sidebar-list">
|
||||
@if (_scripts.Count == 0)
|
||||
{
|
||||
<div class="sidebar-empty">@Lang.T("Chưa có script", "No scripts")</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
@foreach (var s in _scripts)
|
||||
{
|
||||
var item = s;
|
||||
var isActive = _loadedId == item.Id;
|
||||
<div class="@("sidebar-item" + (isActive ? " active" : ""))"
|
||||
@onclick="() => LoadScript(item)">
|
||||
<div class="sidebar-item-name" title="@item.Name">@item.Name</div>
|
||||
<div class="sidebar-item-meta">@item.UpdatedDisplay</div>
|
||||
<span class="sidebar-del-wrap" @onclick:stopPropagation="true">
|
||||
<MudIconButton Class="sidebar-del-btn" Icon="@Icons.Material.Filled.Close"
|
||||
Size="Size.Small"
|
||||
OnClick="() => DeleteScript(item.Id)" />
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Toggle / drag strip ──────────────────────────────── -->
|
||||
<MudIconButton id="sidebarToggle" Class="sidebar-toggle"
|
||||
Icon="@(_sidebarOpen ? Icons.Material.Filled.ChevronLeft : Icons.Material.Filled.ChevronRight)"
|
||||
Size="Size.Small"
|
||||
OnClick="ToggleSidebar"
|
||||
Style="width:14px;padding:0;min-width:0;border-radius:0;height:100%;"
|
||||
title="Kéo để thay đổi kích thước · Click để thu/mở" />
|
||||
|
||||
<!-- ── Editor + output column ───────────────────────────── -->
|
||||
<div class="editor-column">
|
||||
<div id="scriptEditor" class="monaco-editor-host"></div>
|
||||
|
||||
<div id="outputResizeHandle" class="output-resize-handle"></div>
|
||||
|
||||
<div id="outputPane" class="output-pane">
|
||||
@* ── Output / History tabs ── *@
|
||||
<div class="output-tabs">
|
||||
<MudButton Variant="Variant.Text" Size="Size.Small"
|
||||
Class="@("tab-btn" + (!_historyTab ? " tab-on" : ""))"
|
||||
OnClick="() => SetTab(false)">Output</MudButton>
|
||||
@if (_isManager)
|
||||
{
|
||||
<MudButton Variant="Variant.Text" Size="Size.Small"
|
||||
Class="@("tab-btn" + (_historyTab ? " tab-on" : ""))"
|
||||
OnClick="() => SetTab(true)">
|
||||
@Lang.T("Lịch sử", "History")
|
||||
@if (_historyLoading) { <MudProgressCircular Size="Size.Small" Indeterminate="true" Style="width:10px;height:10px;margin-left:4px;" /> }
|
||||
</MudButton>
|
||||
}
|
||||
@{
|
||||
var activeFilters = _historyTab ? _histFilters : _logFilters;
|
||||
}
|
||||
<div class="lf-bar">
|
||||
@foreach (var lvl in _logLevels)
|
||||
{
|
||||
var badge = lvl.Badge;
|
||||
var color = lvl.Color;
|
||||
var isOn = activeFilters.Contains(badge);
|
||||
<MudButton Size="Size.Small" Variant="Variant.Outlined"
|
||||
Style="@($"min-width:0;padding:0 7px;height:22px;font-size:10px;font-family:Consolas,monospace;font-weight:700;letter-spacing:0.3px;flex-shrink:0;{(isOn ? $"color:{color};border-color:{color};background:rgba(255,255,255,0.05);" : "color:#555;border-color:#2a2a2a;")}")"
|
||||
OnClick="@(() => { if (!activeFilters.Add(badge)) activeFilters.Remove(badge); })">@badge</MudButton>
|
||||
}
|
||||
@if (!_historyTab)
|
||||
{
|
||||
<MudTextField @bind-Value="_logSearch" Immediate="true"
|
||||
Placeholder="search log..."
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
Class="lf-field" Style="flex:1;min-width:60px;" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTextField @bind-Value="_histSearch" Immediate="true"
|
||||
Placeholder="search log..."
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
Class="lf-field" Style="flex:1;min-width:60px;" />
|
||||
@if (_isManager)
|
||||
{
|
||||
<MudTextField @bind-Value="_searchUsername" Immediate="true"
|
||||
Placeholder="search user..."
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
Class="lf-field" Style="width:110px;flex-shrink:0;"
|
||||
OnKeyDown="SearchKeyDown" />
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<MudTooltip Text="@Lang.T("Xóa", "Clear")" Placement="Placement.Left">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.DeleteSweep" Size="Size.Small"
|
||||
OnClick="ClearActive"
|
||||
Style="color:#3a3a3a;padding:0 8px;flex-shrink:0;" />
|
||||
</MudTooltip>
|
||||
</div>
|
||||
|
||||
@if (!_historyTab)
|
||||
{
|
||||
<div class="output-area" @ref="_outputPanel">
|
||||
|
||||
@foreach (var line in FilteredLines)
|
||||
{
|
||||
<div class="log-line">@((MarkupString)line)</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="output-area history-area">
|
||||
@if (_historyLoading)
|
||||
{
|
||||
<div style="display:flex;align-items:center;gap:8px;padding:12px;">
|
||||
<MudProgressCircular Size="Size.Small" Indeterminate="true" Color="Color.Default" />
|
||||
<MudText Typo="Typo.caption" Style="color:#444;">@Lang.T("Đang tải...", "Loading...")</MudText>
|
||||
</div>
|
||||
}
|
||||
else if (_historyLogs.Count == 0)
|
||||
{
|
||||
<div style="padding:16px;text-align:center;">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Inbox" Style="color:#2a2a2a;font-size:32px;" />
|
||||
<MudText Typo="Typo.caption" Style="color:#444;display:block;margin-top:4px;">@Lang.T("Chưa có lịch sử.", "No history yet.")</MudText>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
@foreach (var log in FilteredHistory)
|
||||
{
|
||||
<div class="history-row">
|
||||
<span class="hist-time">@log.StartedAt</span>
|
||||
@if (_isManager)
|
||||
{
|
||||
<span class="hist-user">@log.Username</span>
|
||||
}
|
||||
<span class="hist-name" title="@log.ScriptName">
|
||||
@(string.IsNullOrEmpty(log.ScriptName) ? "(anonymous)" : log.ScriptName)
|
||||
</span>
|
||||
<MudChip T="string" Color="@StatusColor(log.Status)" Size="Size.Small"
|
||||
Variant="Variant.Text" Class="hist-chip">@log.Status</MudChip>
|
||||
@if (!string.IsNullOrEmpty(log.Error))
|
||||
{
|
||||
<MudTooltip Text="@log.Error" Placement="Placement.Left">
|
||||
<MudIcon Icon="@Icons.Material.Filled.ErrorOutline"
|
||||
Size="Size.Small" Color="Color.Error" Style="font-size:14px;" />
|
||||
</MudTooltip>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div> @* end outputPane *@
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Inject] HttpClient Http { get; set; } = default!;
|
||||
[Inject] IJSRuntime JS { get; set; } = default!;
|
||||
|
||||
// ── Output filter ─────────────────────────────────────────────────────────
|
||||
private ElementReference _outputPanel;
|
||||
private readonly HashSet<string> _logFilters = new();
|
||||
private readonly HashSet<string> _histFilters = new();
|
||||
private string _logSearch = "";
|
||||
private string _histSearch = "";
|
||||
|
||||
private static readonly (string Badge, string Color)[] _logLevels =
|
||||
[
|
||||
("INFO", "#42a5f5"), ("DONE", "#66bb6a"), ("WARN", "#ffa726"),
|
||||
("ERR", "#ef5350"), ("DEV", "#9575cd")
|
||||
];
|
||||
|
||||
private IEnumerable<string> FilteredLines
|
||||
{
|
||||
get
|
||||
{
|
||||
var lines = (IEnumerable<string>)ScriptLog.Lines;
|
||||
if (_logFilters.Count > 0)
|
||||
lines = lines.Where(l => _logFilters.Any(f => l.Contains($">{f}<")));
|
||||
if (!string.IsNullOrEmpty(_logSearch))
|
||||
lines = lines.Where(l => l.Contains(_logSearch, StringComparison.OrdinalIgnoreCase));
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
|
||||
private static string StatusToLevel(string s) => s switch
|
||||
{
|
||||
"Success" => "DONE",
|
||||
"Cancelled" => "WARN",
|
||||
"Running" => "INFO",
|
||||
_ => "ERR"
|
||||
};
|
||||
|
||||
private IEnumerable<LogItem> FilteredHistory
|
||||
{
|
||||
get
|
||||
{
|
||||
var items = (IEnumerable<LogItem>)_historyLogs;
|
||||
if (_histFilters.Count > 0)
|
||||
items = items.Where(l => _histFilters.Contains(StatusToLevel(l.Status)));
|
||||
if (!string.IsNullOrEmpty(_histSearch))
|
||||
items = items.Where(l =>
|
||||
(l.ScriptName ?? "").Contains(_histSearch, StringComparison.OrdinalIgnoreCase) ||
|
||||
l.StartedAt.Contains(_histSearch, StringComparison.OrdinalIgnoreCase));
|
||||
if (!string.IsNullOrEmpty(_searchUsername))
|
||||
items = items.Where(l =>
|
||||
(l.Username ?? "").Contains(_searchUsername, StringComparison.OrdinalIgnoreCase));
|
||||
return items;
|
||||
}
|
||||
}
|
||||
|
||||
private void ClearActive()
|
||||
{
|
||||
if (_historyTab) _historyLogs.Clear();
|
||||
else ScriptLog.Clear();
|
||||
}
|
||||
|
||||
private Color StatusColor(string s) => s switch
|
||||
{
|
||||
"Success" => Color.Success,
|
||||
"Cancelled" => Color.Warning,
|
||||
"Running" => Color.Info,
|
||||
_ => Color.Error
|
||||
};
|
||||
private bool _isRunning;
|
||||
private bool _hubOk;
|
||||
private CancellationTokenSource? _cts;
|
||||
private HubConnection? _hub;
|
||||
|
||||
// ── History ───────────────────────────────────────────────────────────────
|
||||
private bool _isManager;
|
||||
private bool _historyTab;
|
||||
private bool _historyLoading;
|
||||
private string _searchUsername = "";
|
||||
private List<LogItem> _historyLogs = [];
|
||||
record LogItem(string StartedAt, string Username, string ScriptName, string Status, string? Error);
|
||||
|
||||
private async Task SetTab(bool history)
|
||||
{
|
||||
_historyTab = history;
|
||||
if (history && _historyLogs.Count == 0) await LoadHistory();
|
||||
}
|
||||
|
||||
private async Task SearchKeyDown(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key == "Enter") await LoadHistory();
|
||||
}
|
||||
|
||||
private async Task LoadHistory()
|
||||
{
|
||||
_historyLoading = true;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
string url = _isManager
|
||||
? $"/api/script/logs{(string.IsNullOrWhiteSpace(_searchUsername) ? "" : $"?username={Uri.EscapeDataString(_searchUsername)}")}"
|
||||
: "/api/script/logs/me";
|
||||
var list = await Http.GetFromJsonAsync<List<LogItem>>(url);
|
||||
_historyLogs = list ?? [];
|
||||
}
|
||||
catch { }
|
||||
_historyLoading = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
// ── Lock awareness ────────────────────────────────────────────────────────
|
||||
private string _myUserId = "";
|
||||
|
||||
/// Script chạy trên real hardware → phải giữ workflow lock hoặc ít nhất 1 group lock
|
||||
private bool IsLockBlocked
|
||||
{
|
||||
get
|
||||
{
|
||||
if (State.System.IsSimulation) return false; // sim: không cần lock
|
||||
var ls = State.LockState;
|
||||
if (ls is null) return false; // real nhưng chưa có snapshot
|
||||
bool hasWorkflow = ls.Workflow?.UserId == _myUserId;
|
||||
bool hasGroup = ls.Groups?.Values.Any(h => h?.UserId == _myUserId) == true;
|
||||
return !hasWorkflow && !hasGroup;
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsWorkflowMode =>
|
||||
!State.System.IsSimulation && State.LockState?.Workflow?.UserId == _myUserId;
|
||||
|
||||
private bool IsManualMode =>
|
||||
!State.System.IsSimulation && !IsWorkflowMode
|
||||
&& (State.LockState?.Groups?.Values.Any(h => h?.UserId == _myUserId) == true);
|
||||
|
||||
// ── Script storage ────────────────────────────────────────────────────────
|
||||
private List<ScriptItem> _scripts = [];
|
||||
private int? _loadedId;
|
||||
private string? _loadedName;
|
||||
private bool _saveOpen;
|
||||
private string _saveName = "";
|
||||
private bool _sidebarOpen = true;
|
||||
|
||||
MudMessageBox? _confirmRunBox;
|
||||
private string _pendingCode = "";
|
||||
|
||||
record ScriptItem(int Id, string Name, string UpdatedDisplay);
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.LockStateChanged += OnStateChanged;
|
||||
State.SystemChanged += OnStateChanged;
|
||||
|
||||
Lang.LangChanged += OnLangChanged;
|
||||
ScriptLog.LogChanged += OnLogChanged;
|
||||
await ConnectHub();
|
||||
await RefreshScriptList();
|
||||
try
|
||||
{
|
||||
var me = await Http.GetFromJsonAsync<MeDto>("/api/auth/me");
|
||||
_myUserId = me?.UserId ?? "";
|
||||
_isManager = me?.Role is "Manager" or "Admin";
|
||||
ScriptLog.IsDevMode = me?.Role is "Admin";
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void OnStateChanged() => InvokeAsync(StateHasChanged);
|
||||
private void OnLogChanged() => InvokeAsync(async () =>
|
||||
{
|
||||
StateHasChanged();
|
||||
try { await JS.InvokeVoidAsync("eval",
|
||||
"var el=document.querySelector('.output-area');if(el)el.scrollTop=0;"); }
|
||||
catch { }
|
||||
});
|
||||
|
||||
private void OnLangChanged() => _ = InvokeAsync(async () =>
|
||||
{
|
||||
try { await JS.InvokeVoidAsync("setEditorLang", Lang.Current); } catch { }
|
||||
StateHasChanged();
|
||||
});
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (firstRender)
|
||||
{
|
||||
await JS.InvokeVoidAsync("initScriptEditor");
|
||||
await JS.InvokeVoidAsync("splitter.initSidebarSplit");
|
||||
await JS.InvokeVoidAsync("splitter.initOutputSplit");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ToggleSidebar()
|
||||
{
|
||||
// Skip toggle if the mousedown was actually a drag
|
||||
bool wasDrag = false;
|
||||
try { wasDrag = await JS.InvokeAsync<bool>("(function(){ var h=document.getElementById('sidebarToggle'); return h && h._wasDragged ? h._wasDragged() : false; })"); }
|
||||
catch { }
|
||||
if (wasDrag) return;
|
||||
|
||||
_sidebarOpen = !_sidebarOpen;
|
||||
var w = _sidebarOpen ? "180px" : "0px";
|
||||
try { await JS.InvokeVoidAsync("eval", $"var s=document.getElementById('fileSidebar');if(s)s.style.width='{w}';"); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
// ── Hub connections ───────────────────────────────────────────────────────
|
||||
private async Task ConnectHub()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_hub != null)
|
||||
{
|
||||
await _hub.DisposeAsync();
|
||||
_hub = null;
|
||||
}
|
||||
_hub = new HubConnectionBuilder()
|
||||
.WithUrl(new Uri(Http.BaseAddress!, "/scriptHub"))
|
||||
.WithAutomaticReconnect()
|
||||
.Build();
|
||||
|
||||
_hub.On<string>("scriptLog", line =>
|
||||
{
|
||||
ScriptLog.Log(line); // fires LogChanged → OnLogChanged → StateHasChanged
|
||||
});
|
||||
|
||||
_hub.Reconnected += async _ => { _hubOk = true; await InvokeAsync(StateHasChanged); };
|
||||
_hub.Closed += async _ => { _hubOk = false; await InvokeAsync(StateHasChanged); };
|
||||
|
||||
await _hub.StartAsync();
|
||||
_hubOk = true;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ScriptLog.Log($"❌ Hub: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Run / Stop ────────────────────────────────────────────────────────────
|
||||
private async Task RunScript()
|
||||
{
|
||||
if (!_hubOk) { ScriptLog.Log(Lang.T("❌ Hub chưa kết nối.", "❌ Hub not connected.")); return; }
|
||||
|
||||
string code;
|
||||
try { code = await JS.InvokeAsync<string>("getEditorValue"); }
|
||||
catch { ScriptLog.Log(Lang.T("❌ Không đọc được code.", "❌ Failed to read code.")); return; }
|
||||
|
||||
// SIM mode: run immediately without confirmation
|
||||
// REAL mode: show code in dialog for review before executing
|
||||
if (!State.System.IsSimulation)
|
||||
{
|
||||
_pendingCode = code;
|
||||
var confirmed = await _confirmRunBox!.ShowAsync();
|
||||
if (confirmed != true) return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(code))
|
||||
{
|
||||
ScriptLog.Log(Lang.T("⚠️ Không có code.", "⚠️ No code."));
|
||||
return;
|
||||
}
|
||||
|
||||
_cts = new CancellationTokenSource();
|
||||
_isRunning = true;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
|
||||
try
|
||||
{
|
||||
var resp = await Http.PostAsJsonAsync("/api/script/run",
|
||||
new { Code = code, Name = _loadedName ?? "" }, _cts.Token);
|
||||
|
||||
if ((int)resp.StatusCode == 423)
|
||||
ScriptLog.Log(Lang.T("⚠ Cần giữ lock (CONTROL ACCESS → TAKE CONTROL) trước khi chạy script.", "⚠ Lock required (CONTROL ACCESS → TAKE CONTROL) before running script."));
|
||||
else if (!resp.IsSuccessStatusCode)
|
||||
ScriptLog.Log($"❌ Server: {resp.StatusCode}");
|
||||
}
|
||||
catch (OperationCanceledException) { ScriptLog.Log(Lang.T("⛔ Đã dừng.", "⛔ Stopped.")); }
|
||||
catch (Exception ex) { ScriptLog.Log($"❌ {ex.Message}"); }
|
||||
finally
|
||||
{
|
||||
_isRunning = false;
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StopScript()
|
||||
{
|
||||
_cts?.Cancel();
|
||||
try { await Http.PostAsync("/api/script/cancel", null); } catch { }
|
||||
}
|
||||
|
||||
// ── Language toggle ───────────────────────────────────────────────────────
|
||||
private Task ToggleLang() => Lang.ToggleAsync(Http); // OnLangChanged fires setEditorLang
|
||||
|
||||
// ── Script save / load ────────────────────────────────────────────────────
|
||||
private async Task RefreshScriptList()
|
||||
{
|
||||
try
|
||||
{
|
||||
var list = await Http.GetFromJsonAsync<List<ScriptDto>>("/api/scripts");
|
||||
_scripts = (list ?? []).Select(s => new ScriptItem(
|
||||
s.Id, s.Name,
|
||||
DateTime.TryParse(s.Updated, out var dt)
|
||||
? dt.ToLocalTime().ToString("dd/MM HH:mm")
|
||||
: "")).ToList();
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void OpenSave()
|
||||
{
|
||||
_saveName = _loadedName ?? "";
|
||||
_saveOpen = true;
|
||||
}
|
||||
|
||||
private void NewScript()
|
||||
{
|
||||
_loadedId = null;
|
||||
_loadedName = null;
|
||||
_saveName = "";
|
||||
_saveOpen = true;
|
||||
}
|
||||
|
||||
private async Task DoSave()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_saveName)) return;
|
||||
string code;
|
||||
try { code = await JS.InvokeAsync<string>("getEditorValue"); }
|
||||
catch { return; }
|
||||
|
||||
var resp = await Http.PostAsJsonAsync("/api/scripts",
|
||||
new { Id = _loadedId, Name = _saveName.Trim(), Content = code });
|
||||
|
||||
if (resp.IsSuccessStatusCode)
|
||||
{
|
||||
var saved = await resp.Content.ReadFromJsonAsync<ScriptDto>();
|
||||
_loadedId = saved?.Id;
|
||||
_loadedName = _saveName.Trim();
|
||||
_saveOpen = false;
|
||||
await RefreshScriptList();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveKeyDown(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key == "Enter") await DoSave();
|
||||
if (e.Key == "Escape") _saveOpen = false;
|
||||
}
|
||||
|
||||
private async Task LoadScript(ScriptItem item)
|
||||
{
|
||||
try
|
||||
{
|
||||
var resp = await Http.GetFromJsonAsync<ScriptContentDto>($"/api/scripts/{item.Id}");
|
||||
if (resp is null) return;
|
||||
await JS.InvokeVoidAsync("setEditorValue", resp.Content);
|
||||
_loadedId = item.Id;
|
||||
_loadedName = item.Name;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private async Task DeleteScript(int id)
|
||||
{
|
||||
await Http.DeleteAsync($"/api/scripts/{id}");
|
||||
if (_loadedId == id) { _loadedId = null; _loadedName = null; }
|
||||
await RefreshScriptList();
|
||||
}
|
||||
|
||||
record ScriptDto(int Id, string Name, string Updated);
|
||||
record ScriptContentDto(int Id, string Name, string Content, string Updated);
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
State.LockStateChanged -= OnStateChanged;
|
||||
State.SystemChanged -= OnStateChanged;
|
||||
Lang.LangChanged -= OnLangChanged;
|
||||
ScriptLog.LogChanged -= OnLogChanged;
|
||||
_cts?.Cancel();
|
||||
_cts?.Dispose();
|
||||
if (_hub != null) await _hub.DisposeAsync();
|
||||
}
|
||||
|
||||
record MeDto(string? UserId, string? Role);
|
||||
}
|
||||
|
||||
<style>
|
||||
.script-root {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #27292b;
|
||||
}
|
||||
|
||||
.script-toolbar {
|
||||
flex-shrink: 0;
|
||||
min-height: 42px;
|
||||
background: #27292b;
|
||||
border-bottom: 1px solid #444;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 0 10px;
|
||||
}
|
||||
|
||||
/* ── body: sidebar + editor side by side ── */
|
||||
.script-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
/* ── file sidebar ── */
|
||||
.file-sidebar {
|
||||
width: 180px;
|
||||
flex-shrink: 0;
|
||||
background: #27292b;
|
||||
border-right: 1px solid #333;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
transition: width 0.18s ease;
|
||||
}
|
||||
.file-sidebar.collapsed {
|
||||
width: 0;
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 7px 10px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
color: #555;
|
||||
letter-spacing: 0.8px;
|
||||
border-bottom: 1px solid #252525;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sidebar-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
.sidebar-empty {
|
||||
padding: 12px 10px;
|
||||
font-size: 11px;
|
||||
color: #9CA3AF;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.sidebar-item {
|
||||
position: relative;
|
||||
padding: 7px 28px 7px 10px;
|
||||
cursor: pointer;
|
||||
border-left: 2px solid transparent;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
.sidebar-item:hover { background: #2f3235; }
|
||||
.sidebar-item.active {
|
||||
background: #27292b;
|
||||
border-left-color: #4a9eff;
|
||||
}
|
||||
|
||||
.sidebar-item-name {
|
||||
font-size: 12px;
|
||||
color: #F1F5F9;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.sidebar-item.active .sidebar-item-name { color: #F1F5F9; font-weight: 700; }
|
||||
|
||||
.sidebar-item-meta {
|
||||
font-size: 10px;
|
||||
color: #9CA3AF;
|
||||
margin-top: 1px;
|
||||
}
|
||||
|
||||
.sidebar-del-wrap {
|
||||
position: absolute;
|
||||
right: 2px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
.sidebar-item:hover .sidebar-del-wrap { opacity: 1; }
|
||||
.sidebar-del-btn {
|
||||
color: #9CA3AF !important;
|
||||
padding: 2px !important;
|
||||
min-width: 0 !important;
|
||||
width: 22px !important;
|
||||
height: 22px !important;
|
||||
border-radius: 3px !important;
|
||||
}
|
||||
.sidebar-del-btn:hover { color: #e74c3c !important; }
|
||||
|
||||
.sidebar-toggle {
|
||||
flex-shrink: 0 !important;
|
||||
width: 14px !important;
|
||||
background: #27292b !important;
|
||||
border: none !important;
|
||||
border-left: 1px solid #2a2a2a !important;
|
||||
border-right: 1px solid #2a2a2a !important;
|
||||
color: #9CA3AF !important;
|
||||
cursor: pointer !important;
|
||||
padding: 0 !important;
|
||||
border-radius: 0 !important;
|
||||
min-width: 0 !important;
|
||||
height: 100% !important;
|
||||
transition: color 0.15s, background 0.15s !important;
|
||||
}
|
||||
.sidebar-toggle:hover { color: #4a9eff !important; background: #2f3235 !important; }
|
||||
|
||||
/* ── editor + output column ── */
|
||||
.editor-column {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.monaco-editor-host {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
border-bottom: 1px solid #333;
|
||||
}
|
||||
|
||||
.output-resize-handle {
|
||||
flex-shrink: 0;
|
||||
height: 5px;
|
||||
background: #27292b;
|
||||
cursor: row-resize;
|
||||
position: relative;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.output-resize-handle::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 36px;
|
||||
height: 2px;
|
||||
border-radius: 1px;
|
||||
background: #2a2a2a;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.output-resize-handle:hover { background: #27292b; }
|
||||
.output-resize-handle:hover::after { background: #4a9eff; }
|
||||
|
||||
.output-pane {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
height: 210px;
|
||||
min-height: 80px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.output-tabs {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: #27292b;
|
||||
border-top: 1px solid #222;
|
||||
border-bottom: 1px solid #1a1a1a;
|
||||
}
|
||||
.tab-btn {
|
||||
padding: 5px 14px !important;
|
||||
font-size: 11px !important;
|
||||
color: #9CA3AF !important;
|
||||
border-bottom: 2px solid transparent !important;
|
||||
border-radius: 0 !important;
|
||||
min-height: 0 !important;
|
||||
height: auto !important;
|
||||
text-transform: none !important;
|
||||
font-weight: 400 !important;
|
||||
letter-spacing: 0 !important;
|
||||
line-height: 1.4 !important;
|
||||
transition: color 0.15s !important;
|
||||
user-select: none;
|
||||
}
|
||||
.tab-btn:hover { color: #9CA3AF !important; }
|
||||
.tab-on { color: #F1F5F9 !important; border-bottom-color: #4a9eff !important; }
|
||||
|
||||
.lf-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: auto;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 0 4px;
|
||||
}
|
||||
/* Compact MudTextField inside tab bar */
|
||||
.lf-field { margin: 0 !important; }
|
||||
.lf-field .mud-input-root-outlined { height: 22px !important; min-height: 22px !important; }
|
||||
.lf-field .mud-input-outlined { padding: 0 6px !important; height: 22px !important; font-size: 11px !important; font-family: Consolas, 'Cascadia Code', monospace; color: #9CA3AF !important; }
|
||||
.lf-field fieldset { top: 0 !important; border-color: #2a2a2a !important; }
|
||||
.lf-field .mud-input-outlined:focus { color: #F1F5F9 !important; }
|
||||
.lf-field:focus-within fieldset { border-color: #4a9eff !important; }
|
||||
.lf-field .mud-input-slot-helper-text { display: none; }
|
||||
.lf-field input::placeholder { color: #3a3a3a; font-size: 11px; }
|
||||
|
||||
.output-area {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
background: #27292b;
|
||||
font-family: Consolas, 'Cascadia Code', monospace;
|
||||
font-size: 11.5px;
|
||||
padding: 4px 0;
|
||||
overflow-y: auto;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
.log-line {
|
||||
padding: 1.5px 10px;
|
||||
line-height: 1.55;
|
||||
border-left: 2px solid transparent;
|
||||
transition: background 0.1s, border-color 0.1s;
|
||||
}
|
||||
.log-line:hover {
|
||||
background: rgba(255,255,255,0.025);
|
||||
border-left-color: #2a2a2a;
|
||||
}
|
||||
|
||||
.history-area { font-family: Consolas, monospace; }
|
||||
|
||||
.history-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 10px;
|
||||
border-bottom: 1px solid #131313;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
.history-row:hover { background: rgba(255,255,255,0.02); }
|
||||
.hist-time { color: #9CA3AF; font-size: 10px; min-width: 128px; font-family: Consolas, monospace; flex-shrink: 0; }
|
||||
.hist-user { color: #4a9eff; font-size: 11px; min-width: 80px; flex-shrink: 0; }
|
||||
.hist-name { color: #9CA3AF; font-size: 11px; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.hist-chip { height: 18px !important; min-height: 18px !important; font-size: 10px !important; padding: 0 6px !important; flex-shrink: 0; }
|
||||
</style>
|
||||
105
Lab505.Client/Pages/StatusPanel.razor
Normal file
105
Lab505.Client/Pages/StatusPanel.razor
Normal file
@@ -0,0 +1,105 @@
|
||||
@implements IAsyncDisposable
|
||||
@inject IJSRuntime JS
|
||||
|
||||
<MudPaper Elevation="0" Class="pa-2" Style="background:transparent;">
|
||||
|
||||
<MudStack Row="true" AlignItems="AlignItems.Center" Style="cursor:pointer" @onclick="ToggleExpand">
|
||||
<MudText Typo="Typo.subtitle1">STATUS</MudText>
|
||||
<MudText Typo="Typo.caption" Style="@($"font-weight:800;letter-spacing:0.5px;margin-left:20px;white-space:nowrap;{WfColor}")">@WfPhaseText</MudText>
|
||||
@if (State.Workflow.CompletedCycles > 0)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Style="color:#5a8a6a;font-weight:700;white-space:nowrap;">@State.Workflow.CompletedCycles ×</MudText>
|
||||
}
|
||||
<MudSpacer />
|
||||
<MudIcon Icon="@(_expanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
|
||||
</MudStack>
|
||||
@if (!string.IsNullOrEmpty(State.Workflow.LastError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Dense="true" Class="mt-1" Style="font-size:0.7rem;">@State.Workflow.LastError</MudAlert>
|
||||
}
|
||||
|
||||
@if (_expanded)
|
||||
{
|
||||
|
||||
@* ── IMR + AMR ── *@
|
||||
<ImrAmrStatusPanel />
|
||||
|
||||
<MudDivider Class="mt-2 mb-1" />
|
||||
|
||||
@* ── ASRS grid ── *@
|
||||
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:4px;">
|
||||
@foreach (var row in AsrsRows)
|
||||
{
|
||||
@foreach (var cell in row.Cells)
|
||||
{
|
||||
bool on = cell.Val == true && !State.Asrs.IsOffline;
|
||||
<MudChip T="string" Size="Size.Small"
|
||||
Color="@(on ? Color.Info : Color.Default)"
|
||||
Variant="@(on ? Variant.Filled : Variant.Outlined)"
|
||||
Style="width:100%;margin:0;justify-content:center;height:25px;font-size:13px;font-weight:700;">@cell.Label</MudChip>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@* ── Nav ── *@
|
||||
<MudStack Row="true" Spacing="1" Class="mt-2">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-ctrl")'>CTRL</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-ops")'>OPS</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-conveyor")'>CV</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-imr")'>IMR</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-amr")'>AMR</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-dobot")'>Dobot</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-asrs")'>ASRS</MudButton>
|
||||
</MudStack>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Inject] StateService State { get; set; } = default!;
|
||||
|
||||
private bool _expanded = true;
|
||||
void ToggleExpand() => _expanded = !_expanded;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.AsrsChanged += Refresh;
|
||||
State.WorkflowChanged += Refresh;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.AsrsChanged -= Refresh;
|
||||
State.WorkflowChanged -= Refresh;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void Refresh() => InvokeAsync(StateHasChanged);
|
||||
|
||||
private Task ScrollTo(string id) =>
|
||||
JS.InvokeVoidAsync("eval", $"document.getElementById('{id}')?.scrollIntoView({{behavior:'smooth'}})").AsTask();
|
||||
|
||||
private string WfPhaseText
|
||||
{
|
||||
get
|
||||
{
|
||||
var wf = State.Workflow;
|
||||
if (!string.IsNullOrEmpty(wf.LastError)) return "ERROR";
|
||||
if (wf.IsRunning) return "RUNNING";
|
||||
return "IDLE";
|
||||
}
|
||||
}
|
||||
|
||||
private string WfColor =>
|
||||
!string.IsNullOrEmpty(State.Workflow.LastError) ? "color:#e74c3c;" :
|
||||
State.Workflow.IsRunning ? "color:#4a9eff;" : "color:#9CA3AF;";
|
||||
|
||||
private (string RowLabel, (string Label, bool? Val)[] Cells)[] AsrsRows => new[]
|
||||
{
|
||||
("L4", new (string, bool?)[] { ("41", State.Asrs.X41), ("42", State.Asrs.X42), ("43", State.Asrs.X43) }),
|
||||
("L3", new (string, bool?)[] { ("31", State.Asrs.X31), ("32", State.Asrs.X32), ("33", State.Asrs.X33) }),
|
||||
("L2", new (string, bool?)[] { ("21", State.Asrs.X21), ("22", State.Asrs.X22), ("23", State.Asrs.X23) }),
|
||||
("L1", new (string, bool?)[] { ("11", State.Asrs.X11), ("12", State.Asrs.X12), ("13", State.Asrs.X13) }),
|
||||
};
|
||||
|
||||
}
|
||||
24
Lab505.Client/Program.cs
Normal file
24
Lab505.Client/Program.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using Lab505.Client.Services;
|
||||
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
|
||||
using MudBlazor.Services;
|
||||
|
||||
var builder = WebAssemblyHostBuilder.CreateDefault(args);
|
||||
|
||||
// ── HTTP client (base address = server origin) ────────────────────────────
|
||||
builder.Services.AddScoped(sp => new HttpClient
|
||||
{
|
||||
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress),
|
||||
Timeout = System.Threading.Timeout.InfiniteTimeSpan // allow long workflow calls
|
||||
});
|
||||
|
||||
// ── MudBlazor ─────────────────────────────────────────────────────────────
|
||||
builder.Services.AddMudServices();
|
||||
|
||||
// ── Client services ───────────────────────────────────────────────────────
|
||||
builder.Services.AddScoped<StateService>();
|
||||
builder.Services.AddScoped<ScriptLogService>();
|
||||
builder.Services.AddScoped<CommandService>();
|
||||
builder.Services.AddScoped<ImrInitialPoseService>();
|
||||
builder.Services.AddScoped<LangService>();
|
||||
|
||||
await builder.Build().RunAsync();
|
||||
12
Lab505.Client/Properties/launchSettings.json
Normal file
12
Lab505.Client/Properties/launchSettings.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Lab505.Client": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "https://localhost:55515;http://localhost:55516"
|
||||
}
|
||||
}
|
||||
}
|
||||
338
Lab505.Client/Services/CommandService.cs
Normal file
338
Lab505.Client/Services/CommandService.cs
Normal file
@@ -0,0 +1,338 @@
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
public class CommandService
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
private readonly ScriptLogService _log;
|
||||
|
||||
public CommandService(HttpClient http, ScriptLogService log)
|
||||
{
|
||||
_http = http;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
// ── IMR ───────────────────────────────────────────────────────────────
|
||||
public Task ImrMoveToAsync(string target, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "MoveTo", isMove: true, $"Target={target}");
|
||||
return PostAsync("/api/imr/vda/move-to", new { Target = target }, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrLoadAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Load");
|
||||
return PostAsync("/api/imr/vda/load", null, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrUnloadAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Unload");
|
||||
return PostAsync("/api/imr/vda/unload", null, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrCancelAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Cancel");
|
||||
return PostAsync("/api/imr/vda/cancel", null, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrPickupAsync(int ok, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Pickup", @params: $"OK={ok} NG={ng}");
|
||||
return PostAsync("/api/imr/vda/pickup", new { CountOk = ok, CountNg = ng }, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrUndockAsync(double distance, double velocity, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Undock", isMove: true, $"Dist={distance:F2} Vel={velocity:F2}");
|
||||
return PostAsync("/api/imr/vda/undock", new { Distance = distance, Velocity = velocity }, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrPauseAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Pause");
|
||||
return PostAsync("/api/imr/vda/pause", null, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrResumeAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Resume");
|
||||
return PostAsync("/api/imr/vda/resume", null, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrInitPositionAsync(double x, double y, double theta, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "InitPosition", @params: $"X={x:F2} Y={y:F2} θ={theta:F2}");
|
||||
return PostAsync("/api/imr/vda/init-position", new { X = x, Y = y, Theta = theta }, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrResetOpcAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Reset(OPC)");
|
||||
return PostAsync("/api/imr/opc/reset", null, ct, "IMR");
|
||||
}
|
||||
|
||||
// ── AMR ───────────────────────────────────────────────────────────────
|
||||
public Task AmrMoveToAsync(string target, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "MoveTo", isMove: true, $"Target={target}");
|
||||
return PostAsync("/api/amr/vda/move-to", new { Target = target }, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrLoadAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Load");
|
||||
return PostAsync("/api/amr/vda/load", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrUnloadAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Unload");
|
||||
return PostAsync("/api/amr/vda/unload", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrCancelAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Cancel");
|
||||
return PostAsync("/api/amr/vda/cancel", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrUndockAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Undock", isMove: true);
|
||||
return PostAsync("/api/amr/vda/undock", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrPauseAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Pause");
|
||||
return PostAsync("/api/amr/vda/pause", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrResumeAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Resume");
|
||||
return PostAsync("/api/amr/vda/resume", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrInitPositionAsync(double x, double y, double theta, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "InitPosition", @params: $"X={x:F2} Y={y:F2} θ={theta:F2}");
|
||||
return PostAsync("/api/amr/vda/init-position", new { X = x, Y = y, Theta = theta }, ct, "AMR");
|
||||
}
|
||||
|
||||
// ── Conveyor ──────────────────────────────────────────────────────────
|
||||
public async Task ConveyorSetCoilAsync(string c, string coil, bool state, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogConveyorSetCoil(c, coil, state);
|
||||
var (ok, err) = await PostConveyorAsync($"/api/conveyor/{c}/{coil}", new { State = state }, ct);
|
||||
_log.LogConveyorWriteResult(c, coil, state, ok, err);
|
||||
}
|
||||
|
||||
// ── Dobot ─────────────────────────────────────────────────────────────
|
||||
public Task DobotPowerOnAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("Dobot", "PowerOn");
|
||||
return PostAsync("/api/dobot/power-on", null, ct, "Dobot");
|
||||
}
|
||||
|
||||
public Task DobotGoHomeAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("Dobot", "GoHome");
|
||||
return PostAsync("/api/dobot/go-home", null, ct, "Dobot");
|
||||
}
|
||||
|
||||
public Task DobotContinueAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("Dobot", "Continue");
|
||||
return PostAsync("/api/dobot/continue", null, ct, "Dobot");
|
||||
}
|
||||
|
||||
public Task DobotCancelAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("Dobot", "Cancel");
|
||||
return PostAsync("/api/dobot/cancel", null, ct, "Dobot");
|
||||
}
|
||||
|
||||
// ── ASRS ──────────────────────────────────────────────────────────────
|
||||
public Task AsrsHomingAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("ASRS", "Homing");
|
||||
return PostAsync("/api/asrs/homing", null, ct, "ASRS");
|
||||
}
|
||||
|
||||
public Task AsrsWorkflowAsync(string op, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("ASRS", $"Workflow", @params: $"op={op}");
|
||||
return PostAsync($"/api/asrs/workflow/{op}", null, ct, "ASRS");
|
||||
}
|
||||
|
||||
// ── Workflow ──────────────────────────────────────────────────────────
|
||||
public Task WorkflowX1AAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X1A", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x1a", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowX2AAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X2A", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x2a", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowX3AAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X3A", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x3a", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowX1BAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X1B", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x1b", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowX2BAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X2B", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x2b", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowX3BAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X3B", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x3b", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowRunCycleAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "RunCycle", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/run-cycle", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowRunStepsAsync(IEnumerable<int> steps, int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "RunSteps", @params: $"Steps=[{string.Join(",", steps)}] Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/run-steps", new { Steps = steps, Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepInitAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:Init");
|
||||
return PostAsync("/api/workflow/step/init", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepLoadC2Async(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:LoadC2");
|
||||
return PostAsync("/api/workflow/step/load-c2", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepToCap1Async(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:ToCap1");
|
||||
return PostAsync("/api/workflow/step/to-cap1", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepAmrToImrAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:AmrToImr");
|
||||
return PostAsync("/api/workflow/step/amr-to-imr", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepProcessAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:Process", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/step/process", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepImrToAmrAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:ImrToAmr");
|
||||
return PostAsync("/api/workflow/step/imr-to-amr", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepToCap2Async(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:ToCap2");
|
||||
return PostAsync("/api/workflow/step/to-cap2", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepUnloadC2Async(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:UnloadC2");
|
||||
return PostAsync("/api/workflow/step/unload-c2", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowHomeRbAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "HomeAll");
|
||||
return PostAsync("/api/workflow/home-rb", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowEmergencyStopAsync()
|
||||
{
|
||||
_log.LogCommand("WF", "EMERGENCY STOP");
|
||||
return PostAsync("/api/workflow/emergency-stop", null, default, "WF");
|
||||
}
|
||||
|
||||
// ── Internal ──────────────────────────────────────────────────────────
|
||||
private async Task PostAsync(string url, object? body, CancellationToken ct, string? device = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, url);
|
||||
if (body != null)
|
||||
request.Content = JsonContent.Create(body);
|
||||
var resp = await _http.SendAsync(request, ct);
|
||||
if (!resp.IsSuccessStatusCode && device != null)
|
||||
_log.CancelPending(device, $"HTTP {(int)resp.StatusCode}");
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (device != null) _log.CancelPending(device, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Conveyor write — trả về (success, errorMessage).</summary>
|
||||
private async Task<(bool ok, string? err)> PostConveyorAsync(string url, object? body, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, url);
|
||||
if (body != null)
|
||||
request.Content = JsonContent.Create(body);
|
||||
var resp = await _http.SendAsync(request, ct);
|
||||
var result = await TryReadCommandResultAsync(resp, ct);
|
||||
|
||||
if (resp.IsSuccessStatusCode)
|
||||
return result is { Success: false }
|
||||
? (false, result.Error ?? "Modbus write failed")
|
||||
: (true, null);
|
||||
|
||||
return (false, result?.Error ?? $"HTTP {(int)resp.StatusCode}");
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex) { return (false, ex.Message); }
|
||||
}
|
||||
|
||||
private static async Task<ApiCommandResult?> TryReadCommandResultAsync(HttpResponseMessage resp, CancellationToken ct)
|
||||
{
|
||||
if (resp.Content is null)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
return await resp.Content.ReadFromJsonAsync<ApiCommandResult>(cancellationToken: ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record ApiCommandResult(bool Success, string? Error);
|
||||
}
|
||||
151
Lab505.Client/Services/ImrInitialPoseService.cs
Normal file
151
Lab505.Client/Services/ImrInitialPoseService.cs
Normal file
@@ -0,0 +1,151 @@
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
public sealed class ImrInitialPoseService
|
||||
{
|
||||
private const int OperationPollAttempts = 15;
|
||||
private const int PositionPollAttempts = 20;
|
||||
private const int PollDelayMs = 300;
|
||||
private const double PositionTolerance = 0.1;
|
||||
|
||||
private readonly HttpClient _http;
|
||||
private readonly ScriptLogService _log;
|
||||
|
||||
public ImrInitialPoseService(HttpClient http, ScriptLogService log)
|
||||
{
|
||||
_http = http;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
public async Task<ImrInitialPoseResult> RunAsync(double x, double y, double yaw, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "InitPose(OPC)", isMove: true, $"x={x:F2} y={y:F2} yaw={yaw:F2}");
|
||||
|
||||
var operationId = await StartAsync(x, y, yaw, ct);
|
||||
if (operationId is null)
|
||||
return new(ImrInitialPoseOutcome.SendFailed);
|
||||
|
||||
var operation = await WaitForOperationAsync(operationId, ct);
|
||||
if (operation.Status == "Failed")
|
||||
return new(ImrInitialPoseOutcome.OperationFailed, operation.Error);
|
||||
|
||||
var position = await WaitForPositionAsync(x, y, ct);
|
||||
return position.IsMatched
|
||||
? new(ImrInitialPoseOutcome.Success, ActualX: position.ActualX, ActualY: position.ActualY)
|
||||
: new(ImrInitialPoseOutcome.PositionMismatch,
|
||||
ActualX: position.ActualX,
|
||||
ActualY: position.ActualY,
|
||||
WaitSeconds: PositionPollAttempts * PollDelayMs / 1000);
|
||||
}
|
||||
|
||||
private async Task<string?> StartAsync(double x, double y, double yaw, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await _http.PostAsJsonAsync("/api/imr/opc/init-pose", new { X = x, Y = y, Yaw = yaw }, ct);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
return null;
|
||||
|
||||
var body = await response.Content.ReadFromJsonAsync<OperationAcceptedDto>(cancellationToken: ct);
|
||||
return body?.OperationId;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<OperationStatusDto> WaitForOperationAsync(string operationId, CancellationToken ct)
|
||||
{
|
||||
for (var i = 0; i < OperationPollAttempts; i++)
|
||||
{
|
||||
await Task.Delay(PollDelayMs, ct);
|
||||
|
||||
try
|
||||
{
|
||||
var operation = await _http.GetFromJsonAsync<OperationStatusDto>($"/api/operations/{operationId}", ct);
|
||||
if (operation?.Status is "Completed" or "Failed")
|
||||
return operation;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return new(operationId, "Completed", null);
|
||||
}
|
||||
|
||||
private async Task<PositionCheckResult> WaitForPositionAsync(double expectedX, double expectedY, CancellationToken ct)
|
||||
{
|
||||
double? actualX = null;
|
||||
double? actualY = null;
|
||||
|
||||
for (var i = 0; i < PositionPollAttempts; i++)
|
||||
{
|
||||
await Task.Delay(PollDelayMs, ct);
|
||||
|
||||
try
|
||||
{
|
||||
var status = await _http.GetFromJsonAsync<ImrStatusDto>("/api/imr/status", ct);
|
||||
if (status is null)
|
||||
continue;
|
||||
|
||||
actualX = status.X_Opc;
|
||||
actualY = status.Y_Opc;
|
||||
|
||||
if (Math.Abs(status.X_Opc - expectedX) <= PositionTolerance &&
|
||||
Math.Abs(status.Y_Opc - expectedY) <= PositionTolerance)
|
||||
return new(true, actualX, actualY);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return new(false, actualX, actualY);
|
||||
}
|
||||
|
||||
private sealed record OperationAcceptedDto(string OperationId);
|
||||
private sealed record OperationStatusDto(string Id, string Status, string? Error);
|
||||
private sealed record ImrStatusDto(
|
||||
double X_Opc,
|
||||
double Y_Opc,
|
||||
double Theta_Opc,
|
||||
string NavStatus,
|
||||
string DobotStatus,
|
||||
string ConveyorStatus,
|
||||
double X_Vda,
|
||||
double Y_Vda,
|
||||
bool IsOnline,
|
||||
string[] Errors);
|
||||
|
||||
private sealed record PositionCheckResult(bool IsMatched, double? ActualX, double? ActualY);
|
||||
}
|
||||
|
||||
public enum ImrInitialPoseOutcome
|
||||
{
|
||||
Success,
|
||||
SendFailed,
|
||||
OperationFailed,
|
||||
PositionMismatch
|
||||
}
|
||||
|
||||
public sealed record ImrInitialPoseResult(
|
||||
ImrInitialPoseOutcome Outcome,
|
||||
string? Error = null,
|
||||
double? ActualX = null,
|
||||
double? ActualY = null,
|
||||
int WaitSeconds = 0);
|
||||
38
Lab505.Client/Services/LangService.cs
Normal file
38
Lab505.Client/Services/LangService.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
public class LangService
|
||||
{
|
||||
public string Current { get; private set; } = "vi";
|
||||
|
||||
public event Action? LangChanged;
|
||||
|
||||
public string T(string vi, string en) => Current == "en" ? en : vi;
|
||||
|
||||
public void Set(string lang)
|
||||
{
|
||||
if (Current == lang) return;
|
||||
Current = lang;
|
||||
LangChanged?.Invoke();
|
||||
}
|
||||
|
||||
public async Task LoadAsync(HttpClient http)
|
||||
{
|
||||
try
|
||||
{
|
||||
var prefs = await http.GetFromJsonAsync<PrefsDto>("/api/prefs");
|
||||
if (prefs?.Lang is { } l) Set(l);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public async Task ToggleAsync(HttpClient http)
|
||||
{
|
||||
Set(Current == "vi" ? "en" : "vi");
|
||||
try { await http.PutAsJsonAsync("/api/prefs", new { Lang = (string?)Current, NotifMuted = (bool?)null }); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
private record PrefsDto(string? Lang);
|
||||
}
|
||||
68
Lab505.Client/Services/LogFormat.cs
Normal file
68
Lab505.Client/Services/LogFormat.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Single source of truth for output-log HTML rendering.
|
||||
/// Badges: INFO · DONE · ERR · WARN · DEV
|
||||
/// Columns: [ts]=75px BADGE=46px DEVICE=54px COMMAND=220px STATUS=flexible
|
||||
/// </summary>
|
||||
public static class LogFormat
|
||||
{
|
||||
// ── Severity colors (MudBlazor-aligned) ──────────────────────────────
|
||||
public const string CInfo = "#42a5f5"; // INFO blue
|
||||
public const string CWarn = "#ffa726"; // WARN orange
|
||||
public const string CSuccess = "#66bb6a"; // DONE green
|
||||
public const string CError = "#ef5350"; // ERR red
|
||||
public const string CDev = "#9575cd"; // DEV purple
|
||||
|
||||
// ── Column styles ─────────────────────────────────────────────────────
|
||||
public const string ColTs = "display:inline-block;width:75px;color:#484848";
|
||||
public const string ColDev = "display:inline-block;width:54px;color:#9e9e9e";
|
||||
public const string ColCmd = "display:inline-block;width:350px;color:#c8c8c8";
|
||||
|
||||
public static string Ts() => DateTime.Now.ToString("HH:mm:ss");
|
||||
|
||||
// ── Level → (color, badge) ────────────────────────────────────────────
|
||||
public static (string color, string badge) LevelBadge(string level) => level switch
|
||||
{
|
||||
"success" => (CSuccess, "DONE"),
|
||||
"error" => (CError, "ERR"),
|
||||
"warning" => (CWarn, "WARN"),
|
||||
"dev" => (CDev, "DEV"),
|
||||
"heartbeat" => (CInfo, "HB"),
|
||||
_ => (CInfo, "INFO"),
|
||||
};
|
||||
|
||||
// ── Level → status HTML ───────────────────────────────────────────────
|
||||
public static string LevelStatus(string level) => level switch
|
||||
{
|
||||
"success" => $"<span style='color:{CSuccess}'>✓</span>",
|
||||
"error" => $"<span style='color:{CError}'>✗</span>",
|
||||
"warning" => $"<span style='color:{CWarn}'>⚠</span>",
|
||||
_ => "",
|
||||
};
|
||||
|
||||
/// <summary>5-column line: [ts] BADGE DEVICE COMMAND STATUS │ detail</summary>
|
||||
public static string Line(string color, string badge, string device, string command, string status, string? detail = null)
|
||||
{
|
||||
var badgeStyle = $"display:inline-block;width:46px;color:{color};font-weight:700";
|
||||
var detPart = detail != null
|
||||
? $"<span style='color:#606060'> │ </span><span style='color:#a0a0a0'>{detail}</span>"
|
||||
: "";
|
||||
return $"<span style='{ColTs}'>[{Ts()}]</span>" +
|
||||
$"<span style='{badgeStyle}'>{badge}</span>" +
|
||||
$"<span style='{ColDev}'>{device}</span>" +
|
||||
$"<span style='{ColCmd}'>{command}</span>" +
|
||||
$"<span style='color:#c8c8c8'>{status}</span>" +
|
||||
detPart;
|
||||
}
|
||||
|
||||
/// <summary>3-column line for DEV state changes: [ts] BADGE DEVICE message</summary>
|
||||
public static string LineRaw(string color, string badge, string device, string msg)
|
||||
{
|
||||
var badgeStyle = $"display:inline-block;width:46px;color:{color};font-weight:700";
|
||||
return $"<span style='{ColTs}'>[{Ts()}]</span>" +
|
||||
$"<span style='{badgeStyle}'>{badge}</span>" +
|
||||
$"<span style='{ColDev}'>{device}</span>" +
|
||||
$"<span style='color:#c8c8c8'>{msg}</span>";
|
||||
}
|
||||
}
|
||||
794
Lab505.Client/Services/ScriptLogService.cs
Normal file
794
Lab505.Client/Services/ScriptLogService.cs
Normal file
@@ -0,0 +1,794 @@
|
||||
using Lab505.Shared;
|
||||
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Singleton (per WASM session) log bus.
|
||||
/// Mỗi lệnh sinh ra tối đa 3 dòng:
|
||||
/// 1. → gửi (ngay khi CommandService gọi LogCommand)
|
||||
/// 2. ✓ robot nhận (khi NBR đổi sang true hoặc busy bắt đầu)
|
||||
/// 3. ✓ hoàn thành / ✗ lỗi (khi busy trở về false hoặc action FINISHED/FAILED)
|
||||
/// </summary>
|
||||
public class ScriptLogService : IDisposable
|
||||
{
|
||||
private readonly StateService _state;
|
||||
private readonly LangService _lang;
|
||||
private readonly List<string> _lines = new();
|
||||
private readonly System.Timers.Timer _timeoutTimer;
|
||||
private const int TimeoutSeconds = 1200; // 20 phút
|
||||
|
||||
// Aliases → LogFormat (single source of truth)
|
||||
private const string CInfo = LogFormat.CInfo;
|
||||
private const string CWarn = LogFormat.CWarn;
|
||||
private const string CSuccess = LogFormat.CSuccess;
|
||||
private const string CError = LogFormat.CError;
|
||||
private const string CDev = LogFormat.CDev;
|
||||
|
||||
public IReadOnlyList<string> Lines => _lines;
|
||||
public event Action? LogChanged;
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_lines.Clear();
|
||||
LogChanged?.Invoke();
|
||||
}
|
||||
|
||||
// ── Pending command per device ────────────────────────────────────────
|
||||
private PendingCmd? _imrPending;
|
||||
private PendingCmd? _amrPending;
|
||||
private PendingCmd? _dobotPending;
|
||||
private PendingCmd? _asrsPending;
|
||||
private PendingCmd? _wfPending;
|
||||
private PendingConveyorCmd? _conveyorPending;
|
||||
private bool? _conveyorTargetPrev;
|
||||
// Last command sent per robot (for NBR context after pending clears)
|
||||
private string? _lastImrCmd;
|
||||
private string? _lastAmrCmd;
|
||||
|
||||
// ── Previous state snapshots (for delta detection) ────────────────────
|
||||
private bool? _prevImrNBR;
|
||||
private bool? _prevAmrNBR;
|
||||
private bool _prevImrBusy;
|
||||
private bool _prevAmrBusy;
|
||||
private bool _prevDobotBusy;
|
||||
private bool _prevAsrsBusy;
|
||||
private bool _prevWfRunning;
|
||||
private string? _prevImrErr;
|
||||
private string? _prevAmrErr;
|
||||
private string? _prevDobotErr;
|
||||
private string? _prevAsrsErr;
|
||||
private string? _prevWfErr;
|
||||
private string? _prevImrActionId;
|
||||
private string? _prevImrActionStatus;
|
||||
private string? _prevAmrActionId;
|
||||
private string? _prevAmrActionStatus;
|
||||
private string? _prevConveyorWriteError;
|
||||
|
||||
// ── Dev mode ──────────────────────────────────────────────────────────
|
||||
public bool IsDevMode { get; set; }
|
||||
|
||||
private bool? _devImrNBR, _devAmrNBR;
|
||||
private bool _devImrOnline, _devAmrOnline;
|
||||
private string? _devImrActId, _devImrActStatus;
|
||||
private string? _devAmrActId, _devAmrActStatus;
|
||||
private bool _devImrBusy, _devAmrBusy, _devDobotBusy, _devAsrsBusy;
|
||||
private bool _devWfRunning;
|
||||
private bool? _devAsrsSafety, _devAsrsOffline;
|
||||
// Conveyor coils
|
||||
private bool? _devC1In, _devC1Out, _devC1IMRin, _devC1IMRout;
|
||||
private bool? _devC1HasGoods, _devC1NotGoods, _devC1Ready;
|
||||
private bool? _devC2In, _devC2Out, _devC2HasGoods, _devC2NotGoods, _devC2Ready;
|
||||
// ASRS slots
|
||||
private bool? _devX11, _devX12, _devX13;
|
||||
private bool? _devX21, _devX22, _devX23;
|
||||
private bool? _devX31, _devX32, _devX33;
|
||||
private bool? _devX41, _devX42, _devX43;
|
||||
|
||||
public ScriptLogService(StateService state, LangService lang)
|
||||
{
|
||||
_state = state;
|
||||
_lang = lang;
|
||||
state.ImrChanged += OnImrChanged;
|
||||
state.AmrChanged += OnAmrChanged;
|
||||
state.WorkflowChanged += OnWorkflowChanged;
|
||||
state.AsrsChanged += OnAsrsChanged;
|
||||
state.ConveyorChanged += OnConveyorChanged;
|
||||
|
||||
// snapshot initial state
|
||||
_prevImrNBR = state.Imr.NewBaseRequest;
|
||||
_prevAmrNBR = state.Amr.NewBaseRequest;
|
||||
_prevImrBusy = state.Workflow.ImrBusy;
|
||||
_prevAmrBusy = state.Workflow.AmrBusy;
|
||||
_prevDobotBusy = state.Workflow.DobotBusy;
|
||||
_prevAsrsBusy = state.Asrs.IsBusy;
|
||||
_prevWfRunning = state.Workflow.IsRunning;
|
||||
_prevImrErr = state.Workflow.ImrExecError;
|
||||
_prevAmrErr = state.Workflow.AmrExecError;
|
||||
_prevDobotErr = state.Workflow.DobotExecError;
|
||||
_prevAsrsErr = state.Asrs.LastError;
|
||||
_prevWfErr = state.Workflow.LastError;
|
||||
_prevConveyorWriteError = state.Conveyor.WriteError;
|
||||
|
||||
// Dev snapshots
|
||||
var _di = state.Imr; var _da = state.Amr; var _dw = state.Workflow;
|
||||
var _ds = state.Asrs; var _dc = state.Conveyor;
|
||||
_devImrNBR = _di.NewBaseRequest; _devAmrNBR = _da.NewBaseRequest;
|
||||
_devImrOnline = _di.IsOnline; _devAmrOnline = _da.IsOnline;
|
||||
_devImrActId = _di.Actions.Length > 0 ? _di.Actions[0].ActionID : null;
|
||||
_devImrActStatus = _di.Actions.Length > 0 ? _di.Actions[0].ActionStatus : null;
|
||||
_devAmrActId = _da.Actions.Length > 0 ? _da.Actions[0].ActionID : null;
|
||||
_devAmrActStatus = _da.Actions.Length > 0 ? _da.Actions[0].ActionStatus : null;
|
||||
_devImrBusy = _dw.ImrBusy; _devAmrBusy = _dw.AmrBusy; _devDobotBusy = _dw.DobotBusy;
|
||||
_devAsrsBusy = _ds.IsBusy; _devWfRunning = _dw.IsRunning;
|
||||
_devAsrsSafety = _ds.SAFETY_MODE; _devAsrsOffline = _ds.IsOffline;
|
||||
_devC1In = _dc.C1In; _devC1Out = _dc.C1Out; _devC1IMRin = _dc.C1IMRin; _devC1IMRout = _dc.C1IMRout;
|
||||
_devC1HasGoods = _dc.C1HasGoods; _devC1NotGoods = _dc.C1NotGoods; _devC1Ready = _dc.C1Ready;
|
||||
_devC2In = _dc.C2In; _devC2Out = _dc.C2Out;
|
||||
_devC2HasGoods = _dc.C2HasGoods; _devC2NotGoods = _dc.C2NotGoods; _devC2Ready = _dc.C2Ready;
|
||||
_devX11 = _ds.X11; _devX12 = _ds.X12; _devX13 = _ds.X13;
|
||||
_devX21 = _ds.X21; _devX22 = _ds.X22; _devX23 = _ds.X23;
|
||||
_devX31 = _ds.X31; _devX32 = _ds.X32; _devX33 = _ds.X33;
|
||||
_devX41 = _ds.X41; _devX42 = _ds.X42; _devX43 = _ds.X43;
|
||||
|
||||
_timeoutTimer = new System.Timers.Timer(15_000);
|
||||
_timeoutTimer.Elapsed += (_, _) => CheckTimeouts();
|
||||
_timeoutTimer.AutoReset = true;
|
||||
_timeoutTimer.Start();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_timeoutTimer.Dispose();
|
||||
}
|
||||
|
||||
// ── Timeout check ─────────────────────────────────────────────────────
|
||||
private void CheckTimeouts()
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
if (_imrPending != null && (now - _imrPending.SentAt).TotalSeconds > TimeoutSeconds)
|
||||
CancelPending("IMR", _lang.T("⏱ không phản hồi", "⏱ no response"));
|
||||
if (_amrPending != null && (now - _amrPending.SentAt).TotalSeconds > TimeoutSeconds)
|
||||
CancelPending("AMR", _lang.T("⏱ không phản hồi", "⏱ no response"));
|
||||
if (_dobotPending != null && (now - _dobotPending.SentAt).TotalSeconds > TimeoutSeconds)
|
||||
CancelPending("Dobot", _lang.T("⏱ không phản hồi", "⏱ no response"));
|
||||
if (_asrsPending != null && (now - _asrsPending.SentAt).TotalSeconds > TimeoutSeconds)
|
||||
CancelPending("ASRS", _lang.T("⏱ không phản hồi", "⏱ no response"));
|
||||
if (_wfPending != null && (now - _wfPending.SentAt).TotalSeconds > TimeoutSeconds)
|
||||
CancelPending("WF", _lang.T("⏱ không phản hồi", "⏱ no response"));
|
||||
}
|
||||
|
||||
// ── Cancel pending (HTTP error hoặc timeout) ──────────────────────────
|
||||
public void CancelPending(string device, string reason)
|
||||
{
|
||||
PendingCmd? p = device switch
|
||||
{
|
||||
"IMR" => _imrPending,
|
||||
"AMR" => _amrPending,
|
||||
"Dobot" => _dobotPending,
|
||||
"ASRS" => _asrsPending,
|
||||
"WF" => _wfPending,
|
||||
_ => null
|
||||
};
|
||||
if (p == null) return;
|
||||
|
||||
Push(Line(CError, "ERR", device, p.Command, _lang.T("✗ lỗi", "✗ error"), reason));
|
||||
|
||||
switch (device)
|
||||
{
|
||||
case "IMR": _imrPending = null; break;
|
||||
case "AMR": _amrPending = null; break;
|
||||
case "Dobot": _dobotPending = null; break;
|
||||
case "ASRS": _asrsPending = null; break;
|
||||
case "WF": _wfPending = null; break;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Raw line (script hub hoặc caller khác) ────────────────────────────
|
||||
public void Log(string htmlLine)
|
||||
{
|
||||
_lines.Insert(0, htmlLine);
|
||||
Trim();
|
||||
LogChanged?.Invoke();
|
||||
}
|
||||
|
||||
public void LogNotification(NotificationDto notification)
|
||||
{
|
||||
var (color, badge) = LogFormat.LevelBadge(notification.Level);
|
||||
var status = LogFormat.LevelStatus(notification.Level);
|
||||
var source = string.IsNullOrWhiteSpace(notification.Source)
|
||||
? TryExtractSource(notification.Message)
|
||||
: notification.Source;
|
||||
var device = MapNotificationDevice(source);
|
||||
var command = string.IsNullOrWhiteSpace(notification.Command)
|
||||
? notification.Message
|
||||
: notification.Command!;
|
||||
var detail = notification.Detail;
|
||||
|
||||
Log(Line(color, badge, device, command, status, detail));
|
||||
|
||||
if (IsDevMode && ShouldCaptureSystemSnapshot(notification, source))
|
||||
LogSystemSnapshot($"{device}:{command}");
|
||||
}
|
||||
|
||||
// ── Ghi lệnh vừa gửi ─────────────────────────────────────────────────
|
||||
public void LogCommand(string device, string command, bool isMove = false, string? @params = null)
|
||||
{
|
||||
Push(Line(CInfo, "INFO", device, command, _lang.T("→ gửi", "→ sent"), @params));
|
||||
|
||||
var wf = _state.Workflow;
|
||||
var imr = _state.Imr;
|
||||
var amr = _state.Amr;
|
||||
|
||||
switch (device)
|
||||
{
|
||||
case "IMR":
|
||||
_lastImrCmd = command;
|
||||
_imrPending = new(command, @params, isMove, DateTime.Now);
|
||||
_prevImrNBR = imr.NewBaseRequest;
|
||||
_prevImrErr = wf.ImrExecError;
|
||||
_prevImrActionId = imr.Actions.Length > 0 ? imr.Actions[0].ActionID : null;
|
||||
_prevImrActionStatus = imr.Actions.Length > 0 ? imr.Actions[0].ActionStatus : null;
|
||||
break;
|
||||
|
||||
case "AMR":
|
||||
_lastAmrCmd = command;
|
||||
_amrPending = new(command, @params, isMove, DateTime.Now);
|
||||
_prevAmrNBR = amr.NewBaseRequest;
|
||||
_prevAmrErr = wf.AmrExecError;
|
||||
_prevAmrActionId = amr.Actions.Length > 0 ? amr.Actions[0].ActionID : null;
|
||||
_prevAmrActionStatus = amr.Actions.Length > 0 ? amr.Actions[0].ActionStatus : null;
|
||||
break;
|
||||
|
||||
case "Dobot":
|
||||
_dobotPending = new(command, @params, false, DateTime.Now);
|
||||
_prevDobotErr = wf.DobotExecError;
|
||||
break;
|
||||
|
||||
case "ASRS":
|
||||
_asrsPending = new(command, @params, false, DateTime.Now);
|
||||
_prevAsrsErr = _state.Asrs.LastError;
|
||||
break;
|
||||
|
||||
case "WF":
|
||||
if (command != "EMERGENCY STOP" && !IsXCycleCommand(command))
|
||||
{
|
||||
_wfPending = new(command, @params, false, DateTime.Now);
|
||||
_prevWfErr = wf.LastError;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void LogConveyorSetCoil(string c, string coil, bool expectedValue)
|
||||
{
|
||||
var key = c + coil;
|
||||
Push(Line(CInfo, "INFO", "CV", "SetCoil", _lang.T("→ gửi", "→ sent"), $"{key}={expectedValue}"));
|
||||
_conveyorPending = new(key, expectedValue);
|
||||
_conveyorTargetPrev = GetCoil(_state.Conveyor, key);
|
||||
_prevConveyorWriteError = _state.Conveyor.WriteError;
|
||||
}
|
||||
|
||||
public void LogConveyorWriteResult(string c, string coil, bool expectedValue, bool ok, string? error)
|
||||
{
|
||||
var key = c + coil;
|
||||
if (ok)
|
||||
Push(Line(CSuccess, "DONE", "CV", "SetCoil", _lang.T("✓ PLC write OK", "✓ PLC write OK"), $"{key}={expectedValue}"));
|
||||
else
|
||||
Push(Line(CError, "ERR", "CV", "SetCoil", _lang.T("✗ write error", "✗ write error"), $"{key}={expectedValue} | {error}"));
|
||||
|
||||
if (!ok) _conveyorPending = null;
|
||||
}
|
||||
|
||||
// ── State handlers ────────────────────────────────────────────────────
|
||||
|
||||
private void OnImrChanged()
|
||||
{
|
||||
var imr = _state.Imr;
|
||||
|
||||
if (_imrPending != null)
|
||||
{
|
||||
if (imr.NewBaseRequest == true && _prevImrNBR != true)
|
||||
Push(Line(CWarn, "WARN", "IMR", _imrPending.Command, "✓ New Base Request"));
|
||||
|
||||
if (imr.Actions.Length > 0)
|
||||
{
|
||||
var a = imr.Actions[0];
|
||||
if (a.ActionID != _prevImrActionId || a.ActionStatus != _prevImrActionStatus)
|
||||
{
|
||||
var statusStr = a.ActionStatus ?? "?";
|
||||
if (statusStr is "RUNNING" or "INITIALIZING")
|
||||
Push(Line(CWarn, "WARN", "IMR", _imrPending.Command, $"action {a.ActionID}", statusStr));
|
||||
else if (statusStr == "FINISHED")
|
||||
Push(Line(CSuccess, "DONE", "IMR", _imrPending.Command, $"action {a.ActionID}", _lang.T("hoàn thành", "done")));
|
||||
else if (statusStr is "FAILED" or "FAILED_FATAL")
|
||||
Push(Line(CError, "ERR", "IMR", _imrPending.Command, $"action {a.ActionID}", _lang.T("thất bại", "failed")));
|
||||
|
||||
_prevImrActionId = a.ActionID;
|
||||
_prevImrActionStatus = a.ActionStatus;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_prevImrNBR = imr.NewBaseRequest;
|
||||
|
||||
if (IsDevMode)
|
||||
{
|
||||
bool noPending = _imrPending == null;
|
||||
if (imr.IsOnline != _devImrOnline)
|
||||
{ DevPush("IMR", $"online={imr.IsOnline}"); _devImrOnline = imr.IsOnline; }
|
||||
if (imr.NewBaseRequest != _devImrNBR)
|
||||
{
|
||||
if (noPending)
|
||||
DevPush("IMR", _lastImrCmd ?? "", $"New Base Request={imr.NewBaseRequest}");
|
||||
_devImrNBR = imr.NewBaseRequest;
|
||||
}
|
||||
if (imr.Actions.Length > 0)
|
||||
{
|
||||
var a = imr.Actions[0];
|
||||
if (a.ActionID != _devImrActId || a.ActionStatus != _devImrActStatus)
|
||||
{ if (noPending) DevPush("IMR", a.ActionID ?? "", a.ActionStatus ?? "?"); _devImrActId = a.ActionID; _devImrActStatus = a.ActionStatus; }
|
||||
}
|
||||
else if (_devImrActId != null)
|
||||
{ if (noPending) DevPush("IMR", "actions cleared"); _devImrActId = null; _devImrActStatus = null; }
|
||||
}
|
||||
}
|
||||
|
||||
private void OnAmrChanged()
|
||||
{
|
||||
var amr = _state.Amr;
|
||||
|
||||
if (_amrPending != null)
|
||||
{
|
||||
if (amr.NewBaseRequest == true && _prevAmrNBR != true)
|
||||
Push(Line(CWarn, "WARN", "AMR", _amrPending.Command, "✓ New Base Request"));
|
||||
|
||||
if (amr.Actions.Length > 0)
|
||||
{
|
||||
var a = amr.Actions[0];
|
||||
if (a.ActionID != _prevAmrActionId || a.ActionStatus != _prevAmrActionStatus)
|
||||
{
|
||||
var statusStr = a.ActionStatus ?? "?";
|
||||
if (statusStr is "RUNNING" or "INITIALIZING")
|
||||
Push(Line(CWarn, "WARN", "AMR", _amrPending.Command, $"action {a.ActionID}", statusStr));
|
||||
else if (statusStr == "FINISHED")
|
||||
Push(Line(CSuccess, "DONE", "AMR", _amrPending.Command, $"action {a.ActionID}", _lang.T("hoàn thành", "done")));
|
||||
else if (statusStr is "FAILED" or "FAILED_FATAL")
|
||||
Push(Line(CError, "ERR", "AMR", _amrPending.Command, $"action {a.ActionID}", _lang.T("thất bại", "failed")));
|
||||
|
||||
_prevAmrActionId = a.ActionID;
|
||||
_prevAmrActionStatus = a.ActionStatus;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_prevAmrNBR = amr.NewBaseRequest;
|
||||
|
||||
if (IsDevMode)
|
||||
{
|
||||
bool noPending = _amrPending == null;
|
||||
if (amr.IsOnline != _devAmrOnline)
|
||||
{ DevPush("AMR", $"online={amr.IsOnline}"); _devAmrOnline = amr.IsOnline; }
|
||||
if (amr.NewBaseRequest != _devAmrNBR)
|
||||
{
|
||||
if (noPending)
|
||||
DevPush("AMR", _lastAmrCmd ?? "", $"New Base Request={amr.NewBaseRequest}");
|
||||
_devAmrNBR = amr.NewBaseRequest;
|
||||
}
|
||||
if (amr.Actions.Length > 0)
|
||||
{
|
||||
var a = amr.Actions[0];
|
||||
if (a.ActionID != _devAmrActId || a.ActionStatus != _devAmrActStatus)
|
||||
{ if (noPending) DevPush("AMR", a.ActionID ?? "", a.ActionStatus ?? "?"); _devAmrActId = a.ActionID; _devAmrActStatus = a.ActionStatus; }
|
||||
}
|
||||
else if (_devAmrActId != null)
|
||||
{ if (noPending) DevPush("AMR", "actions cleared"); _devAmrActId = null; _devAmrActStatus = null; }
|
||||
}
|
||||
}
|
||||
|
||||
private void OnWorkflowChanged()
|
||||
{
|
||||
var wf = _state.Workflow;
|
||||
|
||||
// ── IMR busy ──────────────────────────────────────────────────────
|
||||
if (_imrPending != null)
|
||||
{
|
||||
if (!_prevImrBusy && wf.ImrBusy)
|
||||
{
|
||||
var fromPos = _imrPending.IsMove ? $"from x={_state.Imr.X:F2} y={_state.Imr.Y:F2}" : null;
|
||||
Push(Line(CWarn, "WARN", "IMR", _imrPending.Command, _lang.T("đang thực hiện", "executing"), fromPos));
|
||||
}
|
||||
else if (_prevImrBusy && !wf.ImrBusy)
|
||||
{
|
||||
var newErr = wf.ImrExecError != null && wf.ImrExecError != _prevImrErr ? wf.ImrExecError : null;
|
||||
if (newErr != null)
|
||||
Push(Line(CError, "ERR", "IMR", _imrPending.Command, newErr));
|
||||
else
|
||||
{
|
||||
var elapsed = $"{(DateTime.Now - _imrPending.SentAt).TotalSeconds:F1}s";
|
||||
var pos = _imrPending.IsMove ? $"x={_state.Imr.X:F2} y={_state.Imr.Y:F2}" : null;
|
||||
var detail = pos != null ? $"{elapsed} │ {pos}" : elapsed;
|
||||
Push(Line(CSuccess, "DONE", "IMR", _imrPending.Command, _lang.T("hoàn thành", "done"), detail));
|
||||
}
|
||||
_imrPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── AMR busy ──────────────────────────────────────────────────────
|
||||
if (_amrPending != null)
|
||||
{
|
||||
if (!_prevAmrBusy && wf.AmrBusy)
|
||||
{
|
||||
var fromPos = _amrPending.IsMove ? $"from x={_state.Amr.X:F2} y={_state.Amr.Y:F2}" : null;
|
||||
Push(Line(CWarn, "WARN", "AMR", _amrPending.Command, _lang.T("đang thực hiện", "executing"), fromPos));
|
||||
}
|
||||
else if (_prevAmrBusy && !wf.AmrBusy)
|
||||
{
|
||||
var newErr = wf.AmrExecError != null && wf.AmrExecError != _prevAmrErr ? wf.AmrExecError : null;
|
||||
if (newErr != null)
|
||||
Push(Line(CError, "ERR", "AMR", _amrPending.Command, newErr));
|
||||
else
|
||||
{
|
||||
var elapsed = $"{(DateTime.Now - _amrPending.SentAt).TotalSeconds:F1}s";
|
||||
var pos = _amrPending.IsMove ? $"x={_state.Amr.X:F2} y={_state.Amr.Y:F2}" : null;
|
||||
var detail = pos != null ? $"{elapsed} │ {pos}" : elapsed;
|
||||
Push(Line(CSuccess, "DONE", "AMR", _amrPending.Command, _lang.T("hoàn thành", "done"), detail));
|
||||
}
|
||||
_amrPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Dobot busy ────────────────────────────────────────────────────
|
||||
if (_dobotPending != null)
|
||||
{
|
||||
if (!_prevDobotBusy && wf.DobotBusy)
|
||||
{
|
||||
Push(Line(CWarn, "WARN", "Dobot", _dobotPending.Command, _lang.T("đang thực hiện", "executing")));
|
||||
}
|
||||
else if (_prevDobotBusy && !wf.DobotBusy)
|
||||
{
|
||||
var newErr = wf.DobotExecError != null && wf.DobotExecError != _prevDobotErr ? wf.DobotExecError : null;
|
||||
if (newErr != null)
|
||||
Push(Line(CError, "ERR", "Dobot", _dobotPending.Command, newErr));
|
||||
else
|
||||
{
|
||||
var elapsed = $"{(DateTime.Now - _dobotPending.SentAt).TotalSeconds:F1}s";
|
||||
Push(Line(CSuccess, "DONE", "Dobot", _dobotPending.Command, _lang.T("hoàn thành", "done"), elapsed));
|
||||
}
|
||||
_dobotPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Workflow cycle ────────────────────────────────────────────────
|
||||
if (_wfPending != null)
|
||||
{
|
||||
if (!_prevWfRunning && wf.IsRunning)
|
||||
{
|
||||
Push(Line(CWarn, "WARN", "WF", _wfPending.Command, _lang.T("đang chạy", "running")));
|
||||
}
|
||||
else if (_prevWfRunning && !wf.IsRunning)
|
||||
{
|
||||
var newErr = wf.LastError != null && wf.LastError != _prevWfErr ? wf.LastError : null;
|
||||
if (newErr != null)
|
||||
Push(Line(CError, "ERR", "WF", _wfPending.Command, newErr));
|
||||
else
|
||||
{
|
||||
var elapsed = $"{(DateTime.Now - _wfPending.SentAt).TotalSeconds:F1}s";
|
||||
Push(Line(CSuccess, "DONE", "WF", _wfPending.Command, _lang.T("hoàn thành", "done"), $"{elapsed} │ cycles={wf.CompletedCycles}"));
|
||||
}
|
||||
_wfPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
_prevImrBusy = wf.ImrBusy;
|
||||
_prevAmrBusy = wf.AmrBusy;
|
||||
_prevDobotBusy = wf.DobotBusy;
|
||||
_prevWfRunning = wf.IsRunning;
|
||||
_prevImrErr = wf.ImrExecError;
|
||||
_prevAmrErr = wf.AmrExecError;
|
||||
_prevDobotErr = wf.DobotExecError;
|
||||
_prevWfErr = wf.LastError;
|
||||
|
||||
if (IsDevMode)
|
||||
{
|
||||
if (wf.IsRunning != _devWfRunning)
|
||||
{
|
||||
DevPush("WF", wf.IsRunning ? "started" : "stopped");
|
||||
LogSystemSnapshot(wf.IsRunning ? "wf-start" : "wf-stop");
|
||||
_devWfRunning = wf.IsRunning;
|
||||
}
|
||||
if (wf.ImrBusy != _devImrBusy)
|
||||
{ if (_imrPending == null) DevPush("IMR", $"busy={wf.ImrBusy}" + (wf.ImrBusyLabel != null ? $" [{wf.ImrBusyLabel}]" : "")); _devImrBusy = wf.ImrBusy; }
|
||||
if (wf.AmrBusy != _devAmrBusy)
|
||||
{ if (_amrPending == null) DevPush("AMR", $"busy={wf.AmrBusy}" + (wf.AmrBusyLabel != null ? $" [{wf.AmrBusyLabel}]" : "")); _devAmrBusy = wf.AmrBusy; }
|
||||
if (wf.DobotBusy != _devDobotBusy)
|
||||
{ if (_dobotPending == null) DevPush("Dobot", $"busy={wf.DobotBusy}" + (wf.DobotBusyLabel != null ? $" [{wf.DobotBusyLabel}]" : "")); _devDobotBusy = wf.DobotBusy; }
|
||||
}
|
||||
}
|
||||
|
||||
private void OnAsrsChanged()
|
||||
{
|
||||
var asrs = _state.Asrs;
|
||||
|
||||
if (_asrsPending != null)
|
||||
{
|
||||
if (!_prevAsrsBusy && asrs.IsBusy)
|
||||
{
|
||||
Push(Line(CWarn, "WARN", "ASRS", _asrsPending.Command, _lang.T("đang thực hiện", "executing")));
|
||||
}
|
||||
else if (_prevAsrsBusy && !asrs.IsBusy)
|
||||
{
|
||||
var newErr = asrs.LastError != null && asrs.LastError != _prevAsrsErr ? asrs.LastError : null;
|
||||
if (newErr != null)
|
||||
Push(Line(CError, "ERR", "ASRS", _asrsPending.Command, newErr));
|
||||
else
|
||||
{
|
||||
var elapsed = $"{(DateTime.Now - _asrsPending.SentAt).TotalSeconds:F1}s";
|
||||
Push(Line(CSuccess, "DONE", "ASRS", _asrsPending.Command, _lang.T("hoàn thành", "done"), elapsed));
|
||||
}
|
||||
_asrsPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
_prevAsrsBusy = asrs.IsBusy;
|
||||
_prevAsrsErr = asrs.LastError;
|
||||
|
||||
if (IsDevMode)
|
||||
{
|
||||
if (asrs.IsBusy != _devAsrsBusy)
|
||||
{ DevPush("ASRS", $"busy={asrs.IsBusy}"); _devAsrsBusy = asrs.IsBusy; }
|
||||
if (asrs.SAFETY_MODE != _devAsrsSafety)
|
||||
{
|
||||
DevPush("ASRS", $"safety={asrs.SAFETY_MODE}");
|
||||
LogSystemSnapshot($"asrs-safety={FormatBool(asrs.SAFETY_MODE)}");
|
||||
_devAsrsSafety = asrs.SAFETY_MODE;
|
||||
}
|
||||
DevSlot("X11", asrs.X11, ref _devX11); DevSlot("X12", asrs.X12, ref _devX12); DevSlot("X13", asrs.X13, ref _devX13);
|
||||
DevSlot("X21", asrs.X21, ref _devX21); DevSlot("X22", asrs.X22, ref _devX22); DevSlot("X23", asrs.X23, ref _devX23);
|
||||
DevSlot("X31", asrs.X31, ref _devX31); DevSlot("X32", asrs.X32, ref _devX32); DevSlot("X33", asrs.X33, ref _devX33);
|
||||
DevSlot("X41", asrs.X41, ref _devX41); DevSlot("X42", asrs.X42, ref _devX42); DevSlot("X43", asrs.X43, ref _devX43);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnConveyorChanged()
|
||||
{
|
||||
var conv = _state.Conveyor;
|
||||
|
||||
if (IsDevMode)
|
||||
{
|
||||
var pendingKey = _conveyorPending?.CoilKey; // skip coil already tracked by pending section
|
||||
DevCoil("C1.In", conv.C1In, ref _devC1In, pendingKey);
|
||||
DevCoil("C1.Out", conv.C1Out, ref _devC1Out, pendingKey);
|
||||
DevCoil("C1.IMRin", conv.C1IMRin, ref _devC1IMRin, pendingKey);
|
||||
DevCoil("C1.IMRout", conv.C1IMRout, ref _devC1IMRout, pendingKey);
|
||||
DevCoil("C1.Goods", conv.C1HasGoods, ref _devC1HasGoods, pendingKey);
|
||||
DevCoil("C1.Empty", conv.C1NotGoods, ref _devC1NotGoods, pendingKey);
|
||||
DevCoil("C1.Ready", conv.C1Ready, ref _devC1Ready, pendingKey);
|
||||
DevCoil("C2.In", conv.C2In, ref _devC2In, pendingKey);
|
||||
DevCoil("C2.Out", conv.C2Out, ref _devC2Out, pendingKey);
|
||||
DevCoil("C2.Goods", conv.C2HasGoods, ref _devC2HasGoods, pendingKey);
|
||||
DevCoil("C2.Empty", conv.C2NotGoods, ref _devC2NotGoods, pendingKey);
|
||||
DevCoil("C2.Ready", conv.C2Ready, ref _devC2Ready, pendingKey);
|
||||
}
|
||||
|
||||
if (_conveyorPending == null) return;
|
||||
|
||||
var key = _conveyorPending.CoilKey;
|
||||
var current = GetCoil(conv, key);
|
||||
var prev = _conveyorTargetPrev;
|
||||
|
||||
if (current.HasValue)
|
||||
{
|
||||
if (_conveyorPending.ExpectedValue)
|
||||
{
|
||||
if (!_conveyorPending.CoilReached && current.Value)
|
||||
{
|
||||
Push(Line(CWarn, "WARN", "CV", "SetCoil", $"{key}=true"));
|
||||
_conveyorPending = _conveyorPending with { CoilReached = true };
|
||||
}
|
||||
else if (_conveyorPending.CoilReached && !current.Value)
|
||||
{
|
||||
Push(Line(CSuccess, "DONE", "CV", "SetCoil", $"{key} reset"));
|
||||
_conveyorPending = null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (prev != false && !current.Value)
|
||||
{
|
||||
Push(Line(CSuccess, "DONE", "CV", "SetCoil", $"{key}=false"));
|
||||
_conveyorPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
_conveyorTargetPrev = current;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool? GetCoil(ConveyorPushDto conv, string key) =>
|
||||
key.ToLowerInvariant().Replace("-", "") switch
|
||||
{
|
||||
"c1in" => conv.C1In,
|
||||
"c1out" => conv.C1Out,
|
||||
"c1imrin" => conv.C1IMRin,
|
||||
"c1imrout" => conv.C1IMRout,
|
||||
"c1hasgoods" => conv.C1HasGoods,
|
||||
"c1notgoods" => conv.C1NotGoods,
|
||||
"c1ready" => conv.C1Ready,
|
||||
"c2in" => conv.C2In,
|
||||
"c2out" => conv.C2Out,
|
||||
"c2hasgoods" => conv.C2HasGoods,
|
||||
"c2notgoods" => conv.C2NotGoods,
|
||||
"c2ready" => conv.C2Ready,
|
||||
_ => null
|
||||
};
|
||||
|
||||
// ── Dev helpers ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>DEV line without a specific command (state change, online, busy…).</summary>
|
||||
private void DevPush(string device, string msg) =>
|
||||
Push(LineRaw(CDev, "DEV", device, msg));
|
||||
|
||||
/// <summary>DEV line with command context (NBR, action status…).</summary>
|
||||
private void DevPush(string device, string command, string status) =>
|
||||
Push(Line(CDev, "DEV", device, command, status));
|
||||
|
||||
private void DevCoil(string name, bool? current, ref bool? prev, string? pendingKey = null)
|
||||
{
|
||||
if (current == prev) return;
|
||||
var key = name.Replace(".", "").Replace("IMR", "imr").ToLowerInvariant();
|
||||
if (pendingKey == null || !pendingKey.Equals(key, StringComparison.OrdinalIgnoreCase))
|
||||
Push(LineRaw(CDev, "DEV", "CV", $"{name}={current}"));
|
||||
prev = current;
|
||||
}
|
||||
|
||||
private void DevSlot(string name, bool? current, ref bool? prev)
|
||||
{
|
||||
if (current == prev) return;
|
||||
Push(LineRaw(CDev, "DEV", "ASRS", $"{name}={current}"));
|
||||
prev = current;
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
private void LogSystemSnapshot(string trigger)
|
||||
{
|
||||
var mode = _state.System.IsSimulation ? "SIM" : "REAL";
|
||||
var wf = _state.Workflow;
|
||||
var imr = _state.Imr;
|
||||
var amr = _state.Amr;
|
||||
var conv = _state.Conveyor;
|
||||
var asrs = _state.Asrs;
|
||||
|
||||
DevPush("SYS",
|
||||
$"snapshot={trigger} | mode={mode} | wf={DescribeWorkflow(wf)}");
|
||||
DevPush("SYS",
|
||||
$"IMR[{DescribeRobot(imr)}] | AMR[{DescribeRobot(amr)}] | CV[{DescribeConveyor(conv)}] | ASRS[{DescribeAsrs(asrs)}]");
|
||||
}
|
||||
|
||||
private static bool ShouldCaptureSystemSnapshot(NotificationDto notification, string? source)
|
||||
{
|
||||
if (notification.Level is "warning" or "error")
|
||||
return true;
|
||||
|
||||
var normalized = (source ?? notification.Source ?? string.Empty).ToUpperInvariant();
|
||||
if (normalized.Contains("FLOW") || normalized == "WF")
|
||||
{
|
||||
var command = notification.Command ?? notification.Message;
|
||||
return command.Contains("Start", StringComparison.OrdinalIgnoreCase)
|
||||
|| command.Contains("Done", StringComparison.OrdinalIgnoreCase)
|
||||
|| command.Contains("Hủy", StringComparison.OrdinalIgnoreCase)
|
||||
|| command.Contains("Cancel", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string? TryExtractSource(string message)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message))
|
||||
return null;
|
||||
|
||||
var text = message.Trim();
|
||||
if (text.StartsWith('['))
|
||||
{
|
||||
var end = text.IndexOf(']');
|
||||
if (end > 1)
|
||||
return text[1..end].Trim();
|
||||
}
|
||||
|
||||
var colon = text.IndexOf(": ", StringComparison.Ordinal);
|
||||
if (colon > 0)
|
||||
{
|
||||
var head = text[..colon].Trim();
|
||||
if (head.Length <= 24)
|
||||
return head;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string MapNotificationDevice(string? source)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(source))
|
||||
return "Sys";
|
||||
|
||||
var prefix = source.Trim().ToUpperInvariant();
|
||||
return prefix switch
|
||||
{
|
||||
"IMR" => "IMR",
|
||||
"AMR" => "AMR",
|
||||
"DOBOT" => "Dobot",
|
||||
"ASRS" => "ASRS",
|
||||
"WF" or "FLOW" => "WF",
|
||||
"OPC" => "OPC",
|
||||
"VDA" => "VDA",
|
||||
"SIM" => "Sim",
|
||||
"T3" => "T3",
|
||||
"WAIT" => "Wait",
|
||||
"INIT" => "Init",
|
||||
var p when p.StartsWith("FLOW+ASRS") => "WF+AS",
|
||||
var p when p.StartsWith("CONV") => "Conv",
|
||||
var p when p.StartsWith("CONVEYOR") => "Conv",
|
||||
var p when p.StartsWith("STEP") => "WF",
|
||||
var p => p.Length > 6 ? p[..6] : p,
|
||||
};
|
||||
}
|
||||
|
||||
private static string DescribeWorkflow(WorkflowStateDto workflow)
|
||||
{
|
||||
var state = workflow.IsRunning ? "running" : "idle";
|
||||
var last = string.IsNullOrWhiteSpace(workflow.LastError) ? "ok" : $"err={workflow.LastError}";
|
||||
return $"{state} cycles={workflow.CompletedCycles} imrBusy={workflow.ImrBusy} amrBusy={workflow.AmrBusy} dobotBusy={workflow.DobotBusy} {last}";
|
||||
}
|
||||
|
||||
private static string DescribeRobot(RobotStateDto robot)
|
||||
{
|
||||
var action = robot.Actions.Length > 0
|
||||
? $"{robot.Actions[0].ActionID}/{robot.Actions[0].ActionStatus ?? "?"}"
|
||||
: "-";
|
||||
var errors = robot.Errors.Count > 0 ? robot.Errors.Count.ToString() : "0";
|
||||
return $"on={robot.IsOnline} nbr={FormatBool(robot.NewBaseRequest)} pos=({robot.X:F2},{robot.Y:F2}) act={action} err={errors}";
|
||||
}
|
||||
|
||||
private static string DescribeConveyor(ConveyorPushDto conveyor)
|
||||
=> $"C1[in={FormatBool(conveyor.C1In)},out={FormatBool(conveyor.C1Out)},goods={FormatBool(conveyor.C1HasGoods)},empty={FormatBool(conveyor.C1NotGoods)},ready={FormatBool(conveyor.C1Ready)}] " +
|
||||
$"C2[in={FormatBool(conveyor.C2In)},out={FormatBool(conveyor.C2Out)},goods={FormatBool(conveyor.C2HasGoods)},empty={FormatBool(conveyor.C2NotGoods)},ready={FormatBool(conveyor.C2Ready)}]" +
|
||||
$"{(string.IsNullOrWhiteSpace(conveyor.WriteError) ? string.Empty : $" writeErr={conveyor.WriteError}")}";
|
||||
|
||||
private static string DescribeAsrs(AsrsPushDto asrs)
|
||||
{
|
||||
var locks = asrs.LockedOps.Length > 0 ? string.Join(",", asrs.LockedOps) : "-";
|
||||
var error = string.IsNullOrWhiteSpace(asrs.LastError) ? "ok" : asrs.LastError;
|
||||
return $"busy={asrs.IsBusy} offline={asrs.IsOffline} safety={FormatBool(asrs.SAFETY_MODE)} locks={locks} err={error}";
|
||||
}
|
||||
|
||||
private static string FormatBool(bool? value) => value switch
|
||||
{
|
||||
true => "T",
|
||||
false => "F",
|
||||
null => "?"
|
||||
};
|
||||
|
||||
private void Push(string html)
|
||||
{
|
||||
_lines.Insert(0, html);
|
||||
Trim();
|
||||
LogChanged?.Invoke();
|
||||
}
|
||||
|
||||
private void Trim() { while (_lines.Count > 1000) _lines.RemoveAt(_lines.Count - 1); }
|
||||
|
||||
// Delegates → LogFormat (single source of truth)
|
||||
private static string Line(string color, string badge, string device, string command, string status, string? detail = null)
|
||||
=> LogFormat.Line(color, badge, device, command, status, detail);
|
||||
|
||||
private static string LineRaw(string color, string badge, string device, string msg)
|
||||
=> LogFormat.LineRaw(color, badge, device, msg);
|
||||
|
||||
/// X1A / X2A / X3A / X1B / X2B / X3B — fire-and-forget, không cần track pending
|
||||
private static bool IsXCycleCommand(string cmd) =>
|
||||
cmd.Length == 3 && cmd[0] == 'X' && cmd[1] is '1' or '2' or '3' && cmd[2] is 'A' or 'B';
|
||||
|
||||
private record PendingCmd(string Command, string? Params, bool IsMove, DateTime SentAt);
|
||||
private record PendingConveyorCmd(string CoilKey, bool ExpectedValue, bool CoilReached = false);
|
||||
}
|
||||
147
Lab505.Client/Services/StateService.cs
Normal file
147
Lab505.Client/Services/StateService.cs
Normal file
@@ -0,0 +1,147 @@
|
||||
using Lab505.Shared;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
public class StateService : IAsyncDisposable
|
||||
{
|
||||
private HubConnection? _hub;
|
||||
private readonly HttpClient _http;
|
||||
|
||||
public RobotStateDto Imr { get; private set; } = EmptyRobot;
|
||||
public RobotStateDto Amr { get; private set; } = EmptyRobot;
|
||||
public ConveyorPushDto Conveyor { get; private set; } = EmptyConveyor;
|
||||
public AsrsPushDto Asrs { get; private set; } = EmptyAsrs;
|
||||
public WorkflowStateDto Workflow { get; private set; } = EmptyWorkflow;
|
||||
public SystemStateDto System { get; private set; } = new(false, false);
|
||||
|
||||
public LockStateDto? LockState { get; private set; }
|
||||
|
||||
public bool CanControl => true;
|
||||
public bool IsConnected => _hub?.State == HubConnectionState.Connected;
|
||||
|
||||
public event Action? ImrChanged;
|
||||
public event Action? AmrChanged;
|
||||
public event Action? ConveyorChanged;
|
||||
public event Action? AsrsChanged;
|
||||
public event Action? WorkflowChanged;
|
||||
public event Action? SystemChanged;
|
||||
public event Action? LockStateChanged;
|
||||
public event Action<NotificationDto>? NotificationReceived;
|
||||
|
||||
/// <summary>Fires khi stack thay đổi do T3 push ModeChangedEvent — UI dùng để update nút SIM/REAL.</summary>
|
||||
public event Action<bool>? StackChanged;
|
||||
|
||||
public StateService(HttpClient http) => _http = http;
|
||||
|
||||
/// <summary>
|
||||
/// Chuyển client sang đúng SignalR group sau khi user thay đổi stack (real ↔ sim).
|
||||
/// Gọi sau khi POST /api/mode/real hoặc /api/mode/simulation thành công.
|
||||
/// </summary>
|
||||
public async Task SwitchStackAsync(bool useReal)
|
||||
{
|
||||
if (_hub?.State == HubConnectionState.Connected)
|
||||
await _hub.InvokeAsync("JoinStack", useReal);
|
||||
}
|
||||
|
||||
public async Task StartAsync()
|
||||
{
|
||||
if (_hub != null) return;
|
||||
if (!OperatingSystem.IsBrowser()) return;
|
||||
|
||||
_hub = new HubConnectionBuilder()
|
||||
.WithUrl(new Uri(_http.BaseAddress!, HubContracts.StateHubRoute))
|
||||
.WithAutomaticReconnect()
|
||||
.Build();
|
||||
|
||||
RegisterHubHandlers();
|
||||
await _hub.StartAsync();
|
||||
}
|
||||
|
||||
private void RegisterHubHandlers()
|
||||
{
|
||||
if (_hub is null)
|
||||
return;
|
||||
|
||||
_hub.On<RobotStateDto>(HubContracts.ImrStateEvent, dto =>
|
||||
{
|
||||
Imr = dto;
|
||||
ImrChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<RobotStateDto>(HubContracts.AmrStateEvent, dto =>
|
||||
{
|
||||
Amr = dto;
|
||||
AmrChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<ConveyorPushDto>(HubContracts.ConveyorStateEvent, dto =>
|
||||
{
|
||||
Conveyor = dto;
|
||||
ConveyorChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<AsrsPushDto>(HubContracts.AsrsStateEvent, dto =>
|
||||
{
|
||||
Asrs = dto;
|
||||
AsrsChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<WorkflowStateDto>(HubContracts.WorkflowStateEvent, dto =>
|
||||
{
|
||||
Workflow = dto;
|
||||
WorkflowChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<SystemStateDto>(HubContracts.SystemStateEvent, dto =>
|
||||
{
|
||||
System = dto;
|
||||
SystemChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<NotificationDto>(HubContracts.NotificationEvent, dto =>
|
||||
{
|
||||
NotificationReceived?.Invoke(dto);
|
||||
});
|
||||
|
||||
_hub.On<LockStateDto>(HubContracts.LockStateEvent, dto =>
|
||||
{
|
||||
LockState = dto;
|
||||
LockStateChanged?.Invoke();
|
||||
});
|
||||
|
||||
// T3 đổi mode server-side → server push event → client tự JoinStack đúng group + notify UI
|
||||
_hub.On<bool>(HubContracts.ModeChangedEvent, async useReal =>
|
||||
{
|
||||
await SwitchStackAsync(useReal);
|
||||
StackChanged?.Invoke(useReal);
|
||||
});
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_hub != null)
|
||||
{
|
||||
await _hub.DisposeAsync();
|
||||
_hub = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────
|
||||
|
||||
public bool AsrsIsLocked(string key) => Asrs.LockedOps.Contains(key);
|
||||
|
||||
// ── Defaults ─────────────────────────────────────────────────
|
||||
|
||||
private static readonly RobotStateDto EmptyRobot =
|
||||
new(0, 0, false, null, new(), Array.Empty<ActionStateDto>(), "", 9999, Array.Empty<RobotErrorDto>());
|
||||
|
||||
private static readonly ConveyorPushDto EmptyConveyor =
|
||||
new(null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
|
||||
private static readonly AsrsPushDto EmptyAsrs =
|
||||
new(null, null, null, null, null, null, null, null, null, null, null, null, null, true, false, Array.Empty<string>(), null);
|
||||
|
||||
private static readonly WorkflowStateDto EmptyWorkflow =
|
||||
new(false, null, 0, "", "", false, null, null, false, null, null, null, null, false, null, null, null);
|
||||
}
|
||||
13
Lab505.Client/_Imports.razor
Normal file
13
Lab505.Client/_Imports.razor
Normal file
@@ -0,0 +1,13 @@
|
||||
@using System.Net.Http
|
||||
@using System.Net.Http.Json
|
||||
@using Microsoft.AspNetCore.Components
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
@using Microsoft.AspNetCore.Components.Routing
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using static Microsoft.AspNetCore.Components.Web.RenderMode
|
||||
@using Microsoft.AspNetCore.Components.WebAssembly.Http
|
||||
@using Microsoft.JSInterop
|
||||
@using Lab505.Client.Services
|
||||
@using Lab505.Client.Pages
|
||||
@using Lab505.Shared
|
||||
@using MudBlazor
|
||||
590
Lab505.Client/thiet ke .txt
Normal file
590
Lab505.Client/thiet ke .txt
Normal file
@@ -0,0 +1,590 @@
|
||||
Đọc xong kiến trúc này có cảm giác như bạn đã dựng một “mini cloud cho robot” rồi đấy 😄 — mỗi user có sandbox riêng, event push realtime, phân quyền rõ ràng. Nói thẳng: **thiết kế rất chín**, không còn ở level project demo nữa.
|
||||
|
||||
Tôi sẽ đánh giá theo kiểu **kiến trúc sư production**:
|
||||
✔ cái nào mạnh thật
|
||||
⚠ cái nào sẽ đau khi scale
|
||||
🔥 cái nào nên fix sớm
|
||||
|
||||
---
|
||||
|
||||
# 🧠 1. Simulation per-user sandbox — 🟢 RẤT MẠNH
|
||||
|
||||
## ✔ Điểm ăn tiền nhất
|
||||
|
||||
```text
|
||||
User → UserSimSession → full stack riêng
|
||||
```
|
||||
|
||||
👉 Bạn đã đạt:
|
||||
|
||||
* Isolation tuyệt đối ✔
|
||||
* Không shared state ✔
|
||||
* Không race giữa user ✔
|
||||
|
||||
---
|
||||
|
||||
## 💡 Insight quan trọng
|
||||
|
||||
Bạn không chỉ làm simulation, bạn đã làm:
|
||||
|
||||
> **multi-tenant simulation architecture**
|
||||
|
||||
---
|
||||
|
||||
## 🔥 Điểm cực hay (hiếm người làm đúng)
|
||||
|
||||
* Port theo index (7300 + index…) ✔
|
||||
* Lazy create ✔
|
||||
* Reuse index ✔
|
||||
|
||||
👉 Tránh được:
|
||||
|
||||
* port leak
|
||||
* resource leak
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Risk khi scale
|
||||
|
||||
### ❗ Port exhaustion (khi user tăng mạnh)
|
||||
|
||||
```text
|
||||
100 user → 300 port
|
||||
1000 user → 💥
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Gợi ý (nếu scale lớn)
|
||||
|
||||
* chuyển sang **in-memory sim server** (không bind port)
|
||||
* hoặc multiplex nhiều session trong 1 server
|
||||
|
||||
👉 hiện tại: **OK cho lab / trường học / demo lớn**
|
||||
|
||||
---
|
||||
|
||||
# 🔄 2. SignalR push — 🟢 THIẾT KẾ SẠCH
|
||||
|
||||
## ✔ Rất chuẩn
|
||||
|
||||
```text
|
||||
real-stack → broadcast
|
||||
sim-{userId} → isolate
|
||||
```
|
||||
|
||||
👉 Đây là pattern đúng textbook:
|
||||
|
||||
> **pub-sub by group**
|
||||
|
||||
---
|
||||
|
||||
## ✔ Snapshot khi connect
|
||||
|
||||
👉 cực kỳ quan trọng, bạn đã làm đúng
|
||||
|
||||
→ tránh UI bị “trắng vài giây”
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Risk
|
||||
|
||||
### ❗ Event spam
|
||||
|
||||
Bạn đang:
|
||||
|
||||
```text
|
||||
State change → push ngay
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💥 Khi nhiều event:
|
||||
|
||||
* UI lag
|
||||
* network flood
|
||||
* CPU tăng
|
||||
|
||||
---
|
||||
|
||||
## ✅ Nâng cấp nhẹ
|
||||
|
||||
Thêm debounce:
|
||||
|
||||
```text
|
||||
push mỗi 50–100ms (batch)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Nếu muốn xịn hơn
|
||||
|
||||
```text
|
||||
State diff push (chỉ gửi phần thay đổi)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 🧩 3. StateDtoFactory — 🟢 thiết kế tốt
|
||||
|
||||
👉 bạn đã tách:
|
||||
|
||||
```text
|
||||
Domain → DTO
|
||||
```
|
||||
|
||||
✔ không leak internal state
|
||||
✔ giảm payload
|
||||
|
||||
---
|
||||
|
||||
## 💡 Insight
|
||||
|
||||
Bạn đang đi đúng hướng:
|
||||
|
||||
> **CQRS-lite (read model riêng)**
|
||||
|
||||
---
|
||||
|
||||
# 🔐 4. Auth + Role + Lock — 🟢 RẤT CHẮC
|
||||
|
||||
## ✔ Role hierarchy
|
||||
|
||||
```text
|
||||
Admin > Manager > Operator
|
||||
```
|
||||
|
||||
👉 chuẩn, không có gì phải bàn
|
||||
|
||||
---
|
||||
|
||||
## ✔ Claim logic
|
||||
|
||||
```csharp
|
||||
CanUseReal = user.CanUseReal || Role >= Manager
|
||||
CanWorkflow = Role >= Manager || (CanUseReal && user.CanWorkflow)
|
||||
```
|
||||
|
||||
👉 logic rất sạch
|
||||
|
||||
---
|
||||
|
||||
## 🔥 Điểm mạnh nhất
|
||||
|
||||
### 👉 Workflow Lock + Group Lock
|
||||
|
||||
Bạn đã tách:
|
||||
|
||||
```text
|
||||
Workflow lock → full control
|
||||
Group lock → granular control
|
||||
```
|
||||
|
||||
👉 Đây chính là:
|
||||
|
||||
> **industrial resource arbitration**
|
||||
|
||||
---
|
||||
|
||||
## 💡 Insight cực giá trị
|
||||
|
||||
Bạn đã implement đúng:
|
||||
|
||||
> **exclusive control vs shared control**
|
||||
|
||||
---
|
||||
|
||||
# ⚠️ 5. Lock system — hidden risk
|
||||
|
||||
## ❗ Lock không có TTL
|
||||
|
||||
Nếu:
|
||||
|
||||
```text
|
||||
user disconnect / crash
|
||||
```
|
||||
|
||||
👉 lock vẫn giữ
|
||||
|
||||
💥 → hệ bị “treo mềm”
|
||||
|
||||
---
|
||||
|
||||
## ✅ Fix (nên có)
|
||||
|
||||
```text
|
||||
Lock TTL (30s–5min)
|
||||
+ heartbeat refresh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ❗ Race khi xin lock
|
||||
|
||||
Nếu 2 user cùng lúc:
|
||||
|
||||
👉 cần đảm bảo atomic (có thể bạn đã có, nhưng chưa thấy rõ)
|
||||
|
||||
---
|
||||
|
||||
# 🔁 6. Workflow vs Manual — 🟢 design rất đẹp
|
||||
|
||||
Bạn chia:
|
||||
|
||||
```text
|
||||
Workflow mode → lock toàn bộ
|
||||
Manual mode → lock từng group
|
||||
```
|
||||
|
||||
👉 đây là UX + architecture rất tốt
|
||||
|
||||
---
|
||||
|
||||
## 💡 Insight
|
||||
|
||||
Bạn đã giải bài toán:
|
||||
|
||||
> “1 người auto, nhiều người manual cùng lúc”
|
||||
|
||||
---
|
||||
|
||||
# ⚠️ 7. Simulation bỏ qua lock — ⚠️ cần để ý
|
||||
|
||||
```text
|
||||
Sim user → bypass lock
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💥 Risk
|
||||
|
||||
Nếu:
|
||||
|
||||
* UI logic reuse giữa sim + real
|
||||
* dev test trên sim
|
||||
|
||||
👉 có thể:
|
||||
|
||||
> chạy được trên sim nhưng fail trên real
|
||||
|
||||
---
|
||||
|
||||
## ✅ Fix nhẹ
|
||||
|
||||
Cho sim vẫn có lock (optional flag):
|
||||
|
||||
```text
|
||||
SimStrictMode = true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 📡 8. State consistency (quan trọng nhưng bạn đang accept)
|
||||
|
||||
Bạn có nhiều nguồn:
|
||||
|
||||
* VDA
|
||||
* OPC
|
||||
* Modbus
|
||||
|
||||
---
|
||||
|
||||
## ❗ Không đồng bộ thời gian
|
||||
|
||||
👉 nhưng bạn đang:
|
||||
|
||||
```text
|
||||
event-driven + eventual consistency
|
||||
```
|
||||
|
||||
👉 OK ✔
|
||||
|
||||
---
|
||||
|
||||
## 💡 Nếu muốn nâng cấp
|
||||
|
||||
Thêm:
|
||||
|
||||
```text
|
||||
timestamp per state
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 🔥 9. Security — 🟢 khá tốt
|
||||
|
||||
✔ PBKDF2 + salt
|
||||
✔ TOTP
|
||||
✔ token reset
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Missing nhỏ
|
||||
|
||||
* rate limit login
|
||||
* lock account brute-force
|
||||
|
||||
---
|
||||
|
||||
# 🧠 Tổng kết
|
||||
|
||||
## 🟢 Điểm mạnh
|
||||
|
||||
* Multi-tenant simulation ✔
|
||||
* Event-driven state ✔
|
||||
* Lock system đúng bản chất công nghiệp ✔
|
||||
* Workflow engine rõ ràng ✔
|
||||
* Auth + role sạch ✔
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Những thứ nên cải thiện
|
||||
|
||||
| Vấn đề | Mức |
|
||||
| ----------------------- | --- |
|
||||
| Lock không có TTL | 🔥 |
|
||||
| Event push spam | ⚠️ |
|
||||
| Port scale simulation | ⚠️ |
|
||||
| Sim bypass lock | ⚠️ |
|
||||
| Missing rate limit auth | ⚠️ |
|
||||
|
||||
---
|
||||
|
||||
# 🎯 Đánh giá cuối
|
||||
|
||||
👉 Nếu chấm kiểu kỹ sư:
|
||||
|
||||
```text
|
||||
Architecture: 8.8 / 10
|
||||
Production readiness: 8 / 10
|
||||
Scalability: 7.5 / 10
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 🧠 Câu chốt
|
||||
|
||||
System của bạn không còn là “control code” nữa
|
||||
mà là:
|
||||
|
||||
> **một platform điều khiển thiết bị có multi-user, multi-mode, real-time sync**
|
||||
|
||||
---
|
||||
|
||||
409 không phải lỗi “random” đâu 😄 — nó là kiểu lỗi rất **có ý đồ** của server:
|
||||
|
||||
> **HTTP 409 = Conflict (xung đột trạng thái)**
|
||||
|
||||
---
|
||||
|
||||
# 🧠 Nói theo hệ của bạn (Lab505)
|
||||
|
||||
👉 99% là do:
|
||||
|
||||
```text
|
||||
Bạn gửi command → nhưng state hiện tại KHÔNG cho phép
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 🔥 Những nguyên nhân rất sát hệ của bạn
|
||||
|
||||
## 1. ❗ Gửi lệnh khi robot chưa “Ready”
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```csharp
|
||||
await IMR.Load(); // nhưng NBR = false (đang busy)
|
||||
```
|
||||
|
||||
👉 server (VDA / API) trả:
|
||||
|
||||
```text
|
||||
409 Conflict
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. ❗ Gửi 2 lệnh liên tiếp quá nhanh
|
||||
|
||||
```text
|
||||
Command A chưa Accepted
|
||||
Command B đã gửi
|
||||
```
|
||||
|
||||
👉 xung đột action
|
||||
|
||||
---
|
||||
|
||||
## 3. ❗ Workflow lock / group lock
|
||||
|
||||
Bạn đã có:
|
||||
|
||||
```text
|
||||
DeviceGroupLock / WorkflowLock
|
||||
```
|
||||
|
||||
👉 nếu API check và reject:
|
||||
|
||||
```text
|
||||
user khác đang giữ lock → 409
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. ❗ State chưa update kịp (rất hay gặp)
|
||||
|
||||
Flow:
|
||||
|
||||
```text
|
||||
Send command → TriggerRefresh → Poll chưa kịp chạy
|
||||
→ bạn gửi command tiếp
|
||||
```
|
||||
|
||||
👉 bạn nghĩ robot ready
|
||||
👉 nhưng server nghĩ chưa
|
||||
|
||||
💥 → 409
|
||||
|
||||
---
|
||||
|
||||
## 5. ❗ Action trùng / duplicate
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
Load → Load lại lần nữa
|
||||
```
|
||||
|
||||
👉 robot hoặc backend reject
|
||||
|
||||
---
|
||||
|
||||
## 6. ❗ Sai context (IMR vs AMR)
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
IMR đang chạy action
|
||||
AMR gửi đúng
|
||||
nhưng API dùng chung resource
|
||||
```
|
||||
|
||||
👉 conflict logic
|
||||
|
||||
---
|
||||
|
||||
# ⚠️ Dấu hiệu nhận biết nhanh
|
||||
|
||||
Nếu bạn thấy:
|
||||
|
||||
```text
|
||||
- Thỉnh thoảng mới bị
|
||||
- Retry lại thì OK
|
||||
```
|
||||
|
||||
👉 gần như chắc chắn là:
|
||||
|
||||
> **timing issue (race giữa command và state)**
|
||||
|
||||
---
|
||||
|
||||
# 🧪 Debug nhanh (rất hiệu quả)
|
||||
|
||||
Log 3 thứ:
|
||||
|
||||
```text
|
||||
1. State trước khi gửi command
|
||||
2. Thời điểm gửi command
|
||||
3. State ngay sau (poll)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ví dụ bạn sẽ thấy:
|
||||
|
||||
```text
|
||||
t=1000ms: NBR=true (ready)
|
||||
t=1001ms: send command A
|
||||
t=1002ms: send command B ❌
|
||||
t=1200ms: poll update → NBR=false
|
||||
```
|
||||
|
||||
👉 command B bị 409
|
||||
|
||||
---
|
||||
|
||||
# ✅ Cách fix chuẩn (theo kiến trúc của bạn)
|
||||
|
||||
## ✔ 1. Luôn guard trước khi gửi lệnh
|
||||
|
||||
```csharp
|
||||
State.Assert(s => s.ImrReady, "IMR chưa sẵn sàng");
|
||||
```
|
||||
|
||||
👉 bạn đã có sẵn 👍
|
||||
|
||||
---
|
||||
|
||||
## ✔ 2. Hoặc dùng Wait
|
||||
|
||||
```csharp
|
||||
await State.WaitUntil(s => s.ImrReady);
|
||||
await IMR.Load();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✔ 3. Không gửi 2 command cùng device song song
|
||||
|
||||
👉 đã có:
|
||||
|
||||
```text
|
||||
DeviceCommandQueue
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✔ 4. Sau khi send → đợi Accepted
|
||||
|
||||
```csharp
|
||||
using var cmd = await IMR.Load();
|
||||
await cmd.Accepted; // 🔥 cực quan trọng
|
||||
```
|
||||
|
||||
👉 bạn đã có DualCommandMonitor rồi
|
||||
|
||||
---
|
||||
|
||||
## ✔ 5. Retry nhẹ (nếu cần)
|
||||
|
||||
```csharp
|
||||
try
|
||||
{
|
||||
await IMR.Load();
|
||||
}
|
||||
catch (409)
|
||||
{
|
||||
await Task.Delay(200);
|
||||
retry
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 🧠 Câu chốt (rất chuẩn bản chất)
|
||||
|
||||
👉 409 trong system của bạn gần như luôn là:
|
||||
|
||||
> **“Bạn đang ra lệnh nhanh hơn hệ thống kịp cập nhật trạng thái”**
|
||||
|
||||
---
|
||||
|
||||
# 🎯 Checklist fix nhanh
|
||||
|
||||
* [ ] Có `WaitUntil` trước command chưa?
|
||||
* [ ] Có `await Accepted` chưa?
|
||||
* [ ] Có gửi 2 lệnh cùng device không?
|
||||
* [ ] Có rely vào state cũ không?
|
||||
|
||||
---
|
||||
15
Lab505.Client/wwwroot/index.html
Normal file
15
Lab505.Client/wwwroot/index.html
Normal file
@@ -0,0 +1,15 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Lab505</title>
|
||||
<base href="/" />
|
||||
<link rel="stylesheet" href="_content/MudBlazor/MudBlazor.min.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">Loading...</div>
|
||||
<script src="_content/MudBlazor/MudBlazor.min.js"></script>
|
||||
<script src="_framework/blazor.webassembly.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
75
Lab505.Script/AmrFacade.cs
Normal file
75
Lab505.Script/AmrFacade.cs
Normal file
@@ -0,0 +1,75 @@
|
||||
using Lab505.Script.Facades;
|
||||
using Lab505.Shared;
|
||||
|
||||
namespace Lab505.Script;
|
||||
|
||||
/// <summary>Script facade for AMR — maps named positions to driver calls.</summary>
|
||||
public class AmrFacade : IAmrFacade
|
||||
{
|
||||
private readonly IAmrRaw _drv;
|
||||
|
||||
// Timeout khớp với FlowService — script tuần tự chờ action/NBR trước khi trả về.
|
||||
private const int ACTION_TIMEOUT_MS = 20 * 60 * 1000;
|
||||
private const int POS_TIMEOUT_MS = 30 * 60 * 1000;
|
||||
|
||||
private static readonly Dictionary<string, (string vda, double x, double y)> _pos =
|
||||
new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Cap1"] = ("Cap1", RobotPositions.AMR_CAP1_X, RobotPositions.AMR_CAP1_Y),
|
||||
["Cap2"] = ("Cap2", RobotPositions.AMR_CAP2_X, RobotPositions.AMR_CAP2_Y),
|
||||
};
|
||||
|
||||
public AmrFacade(IAmrRaw drv) => _drv = drv;
|
||||
|
||||
public async Task GoTo(string position, CancellationToken ct = default)
|
||||
{
|
||||
if (!_pos.TryGetValue(position, out var p))
|
||||
throw new ArgumentException($"AMR: unknown position '{position}'. Valid: {string.Join(", ", _pos.Keys)}");
|
||||
await _drv.DockToStation(p.vda, ct);
|
||||
await _drv.WaitMoveTo(POS_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task Undock(CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.UndockFromStation_AMR(ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task Load(CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.Load_Vda(ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task Unload(CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.Unload_Vda(ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task Pause(CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.StartPause(ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task Resume(CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.StopPause(ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task InitPosition(double x, double y, double theta, CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.InitPosition(x, y, theta, ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public Task Cancel(CancellationToken ct = default) => _drv.Cancel_Vda(ct);
|
||||
|
||||
public bool IsAt(string position, double tol = 0.2)
|
||||
{
|
||||
if (!_pos.TryGetValue(position, out var p)) return false;
|
||||
return _drv.IsAtPosition(p.x, p.y, tol);
|
||||
}
|
||||
}
|
||||
24
Lab505.Script/DobotFacade.cs
Normal file
24
Lab505.Script/DobotFacade.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using Lab505.Script.Facades;
|
||||
|
||||
namespace Lab505.Script;
|
||||
|
||||
/// <summary>Script facade for Dobot — Pickup delegates to IMR VDA.</summary>
|
||||
public class DobotFacade : IDobotFacade
|
||||
{
|
||||
private readonly IDobotRaw _dobot;
|
||||
private readonly IImrRaw _imr;
|
||||
|
||||
public DobotFacade(IDobotRaw dobot, IImrRaw imr)
|
||||
{
|
||||
_dobot = dobot;
|
||||
_imr = imr;
|
||||
}
|
||||
|
||||
public Task PowerOn(CancellationToken t = default) => _dobot.PowerOn(t);
|
||||
public Task GoHome(CancellationToken t = default) => _dobot.GoHome(t);
|
||||
public Task Continue(CancellationToken t = default) => _dobot.Continue(t);
|
||||
public Task Cancel(CancellationToken t = default) => _dobot.Cancel(t);
|
||||
|
||||
public Task Pickup(int ok, int ng, CancellationToken t = default)
|
||||
=> _imr.PickUp_Vda(ok, ng, t);
|
||||
}
|
||||
32
Lab505.Script/Facades/IAmrFacade.cs
Normal file
32
Lab505.Script/Facades/IAmrFacade.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
namespace Lab505.Script.Facades;
|
||||
|
||||
/// <summary>Script facade for the AMR robot — use named positions instead of raw coordinates.</summary>
|
||||
public interface IAmrFacade
|
||||
{
|
||||
/// <summary>Move to named position. Positions: "Cap1", "Cap2"</summary>
|
||||
Task GoTo(string position, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Undock from current docked station</summary>
|
||||
Task Undock(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Load items onto the robot via VDA</summary>
|
||||
Task Load(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Unload items from the robot via VDA</summary>
|
||||
Task Unload(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Pause the robot's current task (VDA startPause)</summary>
|
||||
Task Pause(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Resume a paused task (VDA stopPause)</summary>
|
||||
Task Resume(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Re-initialize the robot's pose (x, y in metres, theta in radians)</summary>
|
||||
Task InitPosition(double x, double y, double theta, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Cancel current task</summary>
|
||||
Task Cancel(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Check if robot is currently at named position</summary>
|
||||
bool IsAt(string position, double tol = 0.2);
|
||||
}
|
||||
21
Lab505.Script/Facades/IAmrRaw.cs
Normal file
21
Lab505.Script/Facades/IAmrRaw.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
namespace Lab505.Script.Facades;
|
||||
|
||||
/// <summary>Subset of AmrVdaDriver methods needed by AmrFacade — breaks circular dependency.</summary>
|
||||
public interface IAmrRaw
|
||||
{
|
||||
Task DockToStation(string target, CancellationToken t = default);
|
||||
Task<string> UndockFromStation_AMR(CancellationToken t = default);
|
||||
Task<string> Load_Vda(CancellationToken t = default);
|
||||
Task<string> Unload_Vda(CancellationToken t = default);
|
||||
Task<string> StartPause(CancellationToken t = default);
|
||||
Task<string> StopPause(CancellationToken t = default);
|
||||
Task<string> InitPosition(double x, double y, double theta, CancellationToken t = default);
|
||||
Task Cancel_Vda(CancellationToken t = default);
|
||||
bool IsAtPosition(double tx, double ty, double tol = 0.2);
|
||||
|
||||
/// <summary>Chờ action có ActionID cụ thể đạt FINISHED. Throw nếu FAILED/ABORTED hoặc timeout.</summary>
|
||||
Task WaitActionIdCompleted(string actionId, int timeoutMs, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Chờ MoveTo hoàn thành — dựa vào NBR false→true.</summary>
|
||||
Task WaitMoveTo(int timeoutMs, CancellationToken ct = default);
|
||||
}
|
||||
25
Lab505.Script/Facades/IAsrsFacade.cs
Normal file
25
Lab505.Script/Facades/IAsrsFacade.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
namespace Lab505.Script.Facades;
|
||||
|
||||
/// <summary>Script-friendly ASRS interface — no dependency on ASRSState class.</summary>
|
||||
public interface IAsrsFacade
|
||||
{
|
||||
bool IsBusy { get; }
|
||||
bool IsLocked(string key);
|
||||
event Action? OnOperationStateChanged;
|
||||
|
||||
Task SYSTEM_HOMING(CancellationToken token = default);
|
||||
Task X1_S12(CancellationToken token = default);
|
||||
Task X2_S12(CancellationToken token = default);
|
||||
Task X3_S12(CancellationToken token = default);
|
||||
Task X1_S34(CancellationToken token = default);
|
||||
Task X2_S34(CancellationToken token = default);
|
||||
Task X3_S34(CancellationToken token = default);
|
||||
Task X1_R12(CancellationToken token = default);
|
||||
Task X2_R12(CancellationToken token = default);
|
||||
Task X3_R12(CancellationToken token = default);
|
||||
Task X1_R43(CancellationToken token = default);
|
||||
Task X2_R43(CancellationToken token = default);
|
||||
Task X3_R43(CancellationToken token = default);
|
||||
|
||||
Task<bool> WaitCoil(Func<bool?> selector, bool target, int timeoutMs = 10000);
|
||||
}
|
||||
24
Lab505.Script/Facades/IConveyorFacade.cs
Normal file
24
Lab505.Script/Facades/IConveyorFacade.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
namespace Lab505.Script.Facades;
|
||||
|
||||
/// <summary>
|
||||
/// Script-friendly conveyor interface — no dependency on ConveyorState class.
|
||||
/// Use State.WaitUntil(s => s.C1InOn) for condition waits.
|
||||
/// </summary>
|
||||
public interface IConveyorFacade
|
||||
{
|
||||
// ── Coil commands ──────────────────────────────────────────────
|
||||
bool C1In(bool state);
|
||||
bool C1Out(bool state);
|
||||
bool C1IMRin(bool state);
|
||||
bool C1IMRout(bool state);
|
||||
bool C1Ready(bool state);
|
||||
bool C2Ready(bool state);
|
||||
bool C2In(bool state);
|
||||
bool C2Out(bool state);
|
||||
bool C1HasGoods(bool state);
|
||||
bool C1NotGoods(bool state);
|
||||
bool C2HasGoods(bool state);
|
||||
bool C2NotGoods(bool state);
|
||||
|
||||
void StopAll();
|
||||
}
|
||||
11
Lab505.Script/Facades/IDobotFacade.cs
Normal file
11
Lab505.Script/Facades/IDobotFacade.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace Lab505.Script.Facades;
|
||||
|
||||
/// <summary>Script-friendly Dobot interface.</summary>
|
||||
public interface IDobotFacade
|
||||
{
|
||||
Task PowerOn(CancellationToken t = default);
|
||||
Task GoHome(CancellationToken t = default);
|
||||
Task Continue(CancellationToken t = default);
|
||||
Task Cancel(CancellationToken t = default);
|
||||
Task Pickup(int ok, int ng, CancellationToken t = default);
|
||||
}
|
||||
10
Lab505.Script/Facades/IDobotRaw.cs
Normal file
10
Lab505.Script/Facades/IDobotRaw.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace Lab505.Script.Facades;
|
||||
|
||||
/// <summary>Subset of DobotOpcDriver methods needed by DobotFacade — breaks circular dependency.</summary>
|
||||
public interface IDobotRaw
|
||||
{
|
||||
Task PowerOn(CancellationToken t = default);
|
||||
Task GoHome(CancellationToken t = default);
|
||||
Task Continue(CancellationToken t = default);
|
||||
Task Cancel(CancellationToken t = default);
|
||||
}
|
||||
35
Lab505.Script/Facades/IImrFacade.cs
Normal file
35
Lab505.Script/Facades/IImrFacade.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
namespace Lab505.Script.Facades;
|
||||
|
||||
/// <summary>Script facade for the IMR robot — use named positions instead of raw coordinates.</summary>
|
||||
public interface IImrFacade
|
||||
{
|
||||
/// <summary>Move to named position. Positions: "C1", "ABB"</summary>
|
||||
Task GoTo(string position, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Undock from a named docked position. Positions: "C1", "ABB"</summary>
|
||||
Task Undock(string fromPosition, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Load items onto the robot via VDA</summary>
|
||||
Task Load(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Unload items from the robot via VDA</summary>
|
||||
Task Unload(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Pick up items. ok = number of OK items, ng = number of NG items</summary>
|
||||
Task PickUp(int ok, int ng = 0, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Pause the robot's current task (VDA startPause)</summary>
|
||||
Task Pause(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Resume a paused task (VDA stopPause)</summary>
|
||||
Task Resume(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Re-initialize the robot's pose (x, y in metres, theta in radians)</summary>
|
||||
Task InitPosition(double x, double y, double theta, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Cancel current task</summary>
|
||||
Task Cancel(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Check if robot is currently at named position</summary>
|
||||
bool IsAt(string position, double tol = 0.2);
|
||||
}
|
||||
22
Lab505.Script/Facades/IImrRaw.cs
Normal file
22
Lab505.Script/Facades/IImrRaw.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
namespace Lab505.Script.Facades;
|
||||
|
||||
/// <summary>Subset of ImrVdaDriver methods needed by ImrFacade — breaks circular dependency.</summary>
|
||||
public interface IImrRaw
|
||||
{
|
||||
Task DockToStation(string target, CancellationToken t = default);
|
||||
Task<string> UndockFromStation_IMR(double d, double v, CancellationToken t = default);
|
||||
Task<string> Load_Vda(CancellationToken t = default);
|
||||
Task<string> Unload_Vda(CancellationToken t = default);
|
||||
Task<string> PickUp_Vda(int ok, int ng, CancellationToken t = default);
|
||||
Task<string> StartPause(CancellationToken t = default);
|
||||
Task<string> StopPause(CancellationToken t = default);
|
||||
Task<string> InitPosition(double x, double y, double theta, CancellationToken t = default);
|
||||
Task Cancel_Vda(CancellationToken t = default);
|
||||
bool IsAtPosition(double tx, double ty, double tol = 0.2);
|
||||
|
||||
/// <summary>Chờ action có ActionID cụ thể đạt FINISHED. Throw nếu FAILED/ABORTED hoặc timeout.</summary>
|
||||
Task WaitActionIdCompleted(string actionId, int timeoutMs, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Chờ MoveTo hoàn thành — dựa vào NBR false→true.</summary>
|
||||
Task WaitMoveTo(int timeoutMs, CancellationToken ct = default);
|
||||
}
|
||||
32
Lab505.Script/FlowContext.cs
Normal file
32
Lab505.Script/FlowContext.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using Lab505.Script.Facades;
|
||||
|
||||
namespace Lab505.Script;
|
||||
|
||||
public class FlowContext
|
||||
{
|
||||
/// <summary>System condition checker — Assert(instant) / WaitUntil(async wait) / Require(wait+throw)</summary>
|
||||
public required ICondition State { get; set; }
|
||||
|
||||
/// <summary>IMR facade — GoTo, Undock, Load, Unload, PickUp, IsAt</summary>
|
||||
public required IImrFacade IMR { get; set; }
|
||||
|
||||
/// <summary>AMR facade — GoTo, Undock, Load, Unload, IsAt</summary>
|
||||
public required IAmrFacade AMR { get; set; }
|
||||
|
||||
/// <summary>Conveyor — C1In/C1Out/C2In/C2Out coil commands</summary>
|
||||
public required IConveyorFacade Conveyor { get; set; }
|
||||
|
||||
/// <summary>ASRS — X1_S12…X3_R43 operations + WaitCoil</summary>
|
||||
public required IAsrsFacade ASRS { get; set; }
|
||||
|
||||
/// <summary>Dobot — PowerOn, GoHome, Continue, Cancel, Pickup</summary>
|
||||
public required IDobotFacade Dobot { get; set; }
|
||||
|
||||
/// <summary>Workflow — read-only state: IsRunning, LastError, CompletedCycles</summary>
|
||||
public required IFlowFacade Workflow { get; set; }
|
||||
|
||||
/// <summary>Per-user output writer — use Log.WriteLine(...) in scripts instead of Console.WriteLine</summary>
|
||||
public required TextWriter Log { get; set; }
|
||||
|
||||
public CancellationToken Token { get; set; }
|
||||
}
|
||||
61
Lab505.Script/ICondition.cs
Normal file
61
Lab505.Script/ICondition.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
namespace Lab505.Script;
|
||||
|
||||
/// <summary>
|
||||
/// Unified condition checker exposed to user scripts.
|
||||
/// Type 1 — instant: State.Assert(s => s.ImrReady, "msg")
|
||||
/// Type 2 — async wait: await State.WaitUntil(s => s.ImrReadyAtC1)
|
||||
/// await State.Require(s => s.C1HasGoods, "msg")
|
||||
/// </summary>
|
||||
public interface ICondition
|
||||
{
|
||||
// ── IMR ──────────────────────────────────────────────────────────────
|
||||
bool ImrOnline { get; }
|
||||
bool ImrReady { get; }
|
||||
bool ImrBusy { get; }
|
||||
bool ImrAtC1 { get; }
|
||||
bool ImrAtABB { get; }
|
||||
bool ImrReadyAtC1 { get; }
|
||||
bool ImrReadyAtABB { get; }
|
||||
|
||||
// ── AMR ──────────────────────────────────────────────────────────────
|
||||
bool AmrOnline { get; }
|
||||
bool AmrReady { get; }
|
||||
bool AmrBusy { get; }
|
||||
bool AmrAtCap1 { get; }
|
||||
bool AmrAtCap2 { get; }
|
||||
bool AmrReadyAtCap1 { get; }
|
||||
bool AmrReadyAtCap2 { get; }
|
||||
|
||||
// ── C1 ───────────────────────────────────────────────────────────────
|
||||
bool C1Online { get; }
|
||||
bool C1HasGoods { get; }
|
||||
bool C1NotGoods { get; }
|
||||
bool C1Ready { get; }
|
||||
bool C1Idle { get; }
|
||||
bool C1InOn { get; }
|
||||
bool C1OutOn { get; }
|
||||
bool C1IMRinOn { get; }
|
||||
bool C1IMRoutOn { get; }
|
||||
|
||||
// ── C2 ───────────────────────────────────────────────────────────────
|
||||
bool C2Online { get; }
|
||||
bool C2HasGoods { get; }
|
||||
bool C2Ready { get; }
|
||||
bool C2Idle { get; }
|
||||
bool C2InOn { get; }
|
||||
bool C2OutOn { get; }
|
||||
|
||||
// ── Dobot ────────────────────────────────────────────────────────────
|
||||
bool DobotOnline { get; }
|
||||
|
||||
// ── Condition methods ─────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Instant check — throws InvalidOperationException if false. Use before sending a command.</summary>
|
||||
void Assert(Func<ICondition, bool> condition, string errorMessage);
|
||||
|
||||
/// <summary>Event-driven wait. Returns false on timeout, throws on cancellation.</summary>
|
||||
Task<bool> WaitUntil(Func<ICondition, bool> condition, int timeoutMs = 1_200_000, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Event-driven wait. Throws TimeoutException if condition not met in time.</summary>
|
||||
Task Require(Func<ICondition, bool> condition, string errorMessage, int timeoutMs = 1_200_000, CancellationToken ct = default);
|
||||
}
|
||||
10
Lab505.Script/IWorkflowFacade.cs
Normal file
10
Lab505.Script/IWorkflowFacade.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace Lab505.Script;
|
||||
|
||||
/// <summary>Read-only view of FlowService state for use in scripts.</summary>
|
||||
public interface IFlowFacade
|
||||
{
|
||||
bool IsRunning { get; }
|
||||
string? LastError { get; }
|
||||
int CompletedCycles { get; }
|
||||
event Action? RunningStateChanged;
|
||||
}
|
||||
90
Lab505.Script/ImrFacade.cs
Normal file
90
Lab505.Script/ImrFacade.cs
Normal file
@@ -0,0 +1,90 @@
|
||||
using Lab505.Script.Facades;
|
||||
using Lab505.Shared;
|
||||
|
||||
namespace Lab505.Script;
|
||||
|
||||
/// <summary>Script facade for IMR — maps named positions to driver calls.</summary>
|
||||
public class ImrFacade : IImrFacade
|
||||
{
|
||||
private readonly IImrRaw _drv;
|
||||
|
||||
// Timeout khớp với FlowService — script tuần tự chờ action/NBR trước khi trả về.
|
||||
private const int ACTION_TIMEOUT_MS = 20 * 60 * 1000;
|
||||
private const int POS_TIMEOUT_MS = 30 * 60 * 1000;
|
||||
|
||||
private static readonly Dictionary<string, (string vda, double x, double y)> _pos =
|
||||
new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["C1"] = ("Bt1", RobotPositions.IMR_C1_X, RobotPositions.IMR_C1_Y),
|
||||
["ABB"] = ("Abb", RobotPositions.IMR_ABB_X, RobotPositions.IMR_ABB_Y),
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, double> _undockDist =
|
||||
new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["C1"] = RobotPositions.IMR_UNDOCK_C1,
|
||||
["ABB"] = RobotPositions.IMR_UNDOCK_ABB,
|
||||
};
|
||||
|
||||
public ImrFacade(IImrRaw drv) => _drv = drv;
|
||||
|
||||
public async Task GoTo(string position, CancellationToken ct = default)
|
||||
{
|
||||
if (!_pos.TryGetValue(position, out var p))
|
||||
throw new ArgumentException($"IMR: unknown position '{position}'. Valid: {string.Join(", ", _pos.Keys)}");
|
||||
await _drv.DockToStation(p.vda, ct);
|
||||
await _drv.WaitMoveTo(POS_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task Undock(string fromPosition, CancellationToken ct = default)
|
||||
{
|
||||
if (!_undockDist.TryGetValue(fromPosition, out double dist))
|
||||
throw new ArgumentException($"IMR: unknown undock position '{fromPosition}'. Valid: {string.Join(", ", _undockDist.Keys)}");
|
||||
var id = await _drv.UndockFromStation_IMR(-dist, RobotPositions.IMR_UNDOCK_VEL, ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task Load(CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.Load_Vda(ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task Unload(CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.Unload_Vda(ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task PickUp(int ok, int ng = 0, CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.PickUp_Vda(ok, ng, ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task Pause(CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.StartPause(ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task Resume(CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.StopPause(ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public async Task InitPosition(double x, double y, double theta, CancellationToken ct = default)
|
||||
{
|
||||
var id = await _drv.InitPosition(x, y, theta, ct);
|
||||
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
|
||||
}
|
||||
|
||||
public Task Cancel(CancellationToken ct = default) => _drv.Cancel_Vda(ct);
|
||||
|
||||
public bool IsAt(string position, double tol = 0.2)
|
||||
{
|
||||
if (!_pos.TryGetValue(position, out var p)) return false;
|
||||
return _drv.IsAtPosition(p.x, p.y, tol);
|
||||
}
|
||||
}
|
||||
23
Lab505.Script/Lab505.Script.csproj
Normal file
23
Lab505.Script/Lab505.Script.csproj
Normal file
@@ -0,0 +1,23 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<NoWarn>1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="5.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Lab505.Shared\Lab505.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
48
Lab505.Script/RealSessionService.cs
Normal file
48
Lab505.Script/RealSessionService.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
namespace Lab505.Script;
|
||||
|
||||
/// <summary>
|
||||
/// Ensures only one user runs a script in REAL mode at a time.
|
||||
/// Thread-safe lock with owner info for display.
|
||||
/// </summary>
|
||||
public sealed class RealSessionService
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
|
||||
public record SessionInfo(int UserId, string Username, DateTime AcquiredAt);
|
||||
|
||||
public SessionInfo? Current { get; private set; }
|
||||
|
||||
public event Action? OnChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Try to acquire the real-mode lock for a user.
|
||||
/// Returns true if acquired (or user already holds it), false if someone else holds it.
|
||||
/// </summary>
|
||||
public bool TryAcquire(int userId, string username)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (Current is null)
|
||||
{
|
||||
Current = new SessionInfo(userId, username, DateTime.Now);
|
||||
OnChanged?.Invoke();
|
||||
return true;
|
||||
}
|
||||
return Current.UserId == userId; // same user can re-acquire
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Release the lock. Only the owner or a forced release.</summary>
|
||||
public void Release(int userId, bool force = false)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (Current is null) return;
|
||||
if (!force && Current.UserId != userId) return;
|
||||
Current = null;
|
||||
OnChanged?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsLocked => Current is not null;
|
||||
}
|
||||
29
Lab505.Script/RealtimeWriter.cs
Normal file
29
Lab505.Script/RealtimeWriter.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
|
||||
namespace Lab505.Script;
|
||||
|
||||
public class RealtimeWriter : TextWriter
|
||||
{
|
||||
private readonly IHubContext<ScriptHub> _hub;
|
||||
private readonly string? _userGroup; // "user-{uid}" — routes to all tabs of one user
|
||||
|
||||
public override Encoding Encoding => Encoding.UTF8;
|
||||
|
||||
public RealtimeWriter(IHubContext<ScriptHub> hub, string? userId = null)
|
||||
{
|
||||
_hub = hub;
|
||||
_userGroup = userId is not null ? $"user-{userId}" : null;
|
||||
}
|
||||
|
||||
public override void WriteLine(string? value) => Send(value ?? "");
|
||||
public override void Write(string? value) => Send(value ?? "");
|
||||
|
||||
private void Send(string value)
|
||||
{
|
||||
var target = _userGroup is not null
|
||||
? _hub.Clients.Group(_userGroup)
|
||||
: _hub.Clients.All; // fallback only (should not happen in practice)
|
||||
target.SendAsync("scriptLog", value);
|
||||
}
|
||||
}
|
||||
39
Lab505.Script/ScriptCancelService.cs
Normal file
39
Lab505.Script/ScriptCancelService.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
namespace Lab505.Script;
|
||||
|
||||
/// <summary>Per-user CancellationTokenSource registry. Thread-safe.</summary>
|
||||
public sealed class ScriptCancelService
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
private readonly Dictionary<int, CancellationTokenSource> _map = new();
|
||||
|
||||
public CancellationToken Register(int userId, out CancellationTokenSource cts)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_map.TryGetValue(userId, out var old)) { old.Cancel(); old.Dispose(); }
|
||||
cts = new CancellationTokenSource();
|
||||
_map[userId] = cts;
|
||||
return cts.Token;
|
||||
}
|
||||
}
|
||||
|
||||
public void Cancel(int userId)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_map.TryGetValue(userId, out var cts)) cts.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
public void Clear(int userId)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_map.TryGetValue(userId, out var cts)) { cts.Dispose(); _map.Remove(userId); }
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy single-user helpers (kept for backward compat)
|
||||
public void Cancel() { lock (_lock) { foreach (var c in _map.Values) c.Cancel(); } }
|
||||
public void Clear() { lock (_lock) { foreach (var c in _map.Values) c.Dispose(); _map.Clear(); } }
|
||||
}
|
||||
90
Lab505.Script/ScriptEngine.cs
Normal file
90
Lab505.Script/ScriptEngine.cs
Normal file
@@ -0,0 +1,90 @@
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.CodeAnalysis.CSharp.Scripting;
|
||||
using Microsoft.CodeAnalysis.Scripting;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Lab505.Script;
|
||||
|
||||
public class ScriptEngine
|
||||
{
|
||||
private readonly ScriptOptions _baseOptions;
|
||||
private readonly IHubContext<ScriptHub> _hub;
|
||||
|
||||
public ScriptEngine(IHubContext<ScriptHub> hub, string[]? extraImports = null, Assembly[]? extraAssemblies = null)
|
||||
{
|
||||
_hub = hub;
|
||||
|
||||
var imports = new List<string>
|
||||
{
|
||||
"System",
|
||||
"System.Threading",
|
||||
"System.Threading.Tasks",
|
||||
"Lab505.Script.Facades",
|
||||
"Lab505.Shared",
|
||||
};
|
||||
if (extraImports != null) imports.AddRange(extraImports);
|
||||
|
||||
var refs = new List<Assembly>
|
||||
{
|
||||
typeof(Task).Assembly,
|
||||
typeof(ScriptEngine).Assembly, // Lab505.Script itself
|
||||
};
|
||||
if (extraAssemblies != null) refs.AddRange(extraAssemblies);
|
||||
|
||||
_baseOptions = ScriptOptions.Default
|
||||
.WithImports(imports)
|
||||
.WithReferences(refs);
|
||||
}
|
||||
|
||||
public async Task<string> ExecuteAsync(string code, object? globals = null, CancellationToken token = default,
|
||||
string? userId = null)
|
||||
{
|
||||
var options = globals != null
|
||||
? _baseOptions.AddReferences(globals.GetType().Assembly)
|
||||
: _baseOptions;
|
||||
|
||||
var script = CSharpScript.Create(
|
||||
code,
|
||||
options: options,
|
||||
globalsType: globals?.GetType()
|
||||
);
|
||||
|
||||
var writer = new RealtimeWriter(_hub, userId);
|
||||
|
||||
// Set per-user Log on the globals (thread-safe — no global Console mutation)
|
||||
if (globals is FlowContext sg) sg.Log = writer;
|
||||
|
||||
try
|
||||
{
|
||||
ScriptState<object>? state = globals != null
|
||||
? await script.RunAsync(globals, token)
|
||||
: await script.RunAsync(cancellationToken: token);
|
||||
|
||||
return state?.ReturnValue != null ? Pretty(state.ReturnValue) : "";
|
||||
}
|
||||
catch (CompilationErrorException ex)
|
||||
{
|
||||
writer.WriteLine("❌ Compile error:");
|
||||
foreach (var d in ex.Diagnostics)
|
||||
writer.WriteLine(" " + d);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static string Pretty(object value)
|
||||
{
|
||||
var type = value.GetType();
|
||||
if (type.IsPrimitive || value is string || value is decimal)
|
||||
return value.ToString() ?? "";
|
||||
if (type.IsArray)
|
||||
return "[" + string.Join(", ", ((Array)value).Cast<object>()) + "]";
|
||||
if (value is System.Collections.IEnumerable en)
|
||||
{
|
||||
var items = new List<string>();
|
||||
foreach (var item in en) items.Add(item?.ToString() ?? "");
|
||||
return "[" + string.Join(", ", items) + "]";
|
||||
}
|
||||
return JsonSerializer.Serialize(value);
|
||||
}
|
||||
}
|
||||
27
Lab505.Script/ScriptHub.cs
Normal file
27
Lab505.Script/ScriptHub.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Lab505.Script;
|
||||
|
||||
/// <summary>
|
||||
/// SignalR hub for script execution. Each user's connection is added to group "user-{uid}"
|
||||
/// so the server can push sim-panel state to a specific user via Clients.Group.
|
||||
/// </summary>
|
||||
public class ScriptHub : Hub
|
||||
{
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
var uid = Context.User?.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (uid is not null)
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"user-{uid}");
|
||||
await base.OnConnectedAsync();
|
||||
}
|
||||
|
||||
public override async Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
var uid = Context.User?.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (uid is not null)
|
||||
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"user-{uid}");
|
||||
await base.OnDisconnectedAsync(exception);
|
||||
}
|
||||
}
|
||||
47
Lab505.Script/Sim/SimAmr.cs
Normal file
47
Lab505.Script/Sim/SimAmr.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
using Lab505.Script.Facades;
|
||||
|
||||
namespace Lab505.Script.Sim;
|
||||
|
||||
/// <summary>Per-user in-memory AMR simulation. All operations complete after a fixed delay.</summary>
|
||||
public sealed class SimAmr : IAmrFacade
|
||||
{
|
||||
private const int MoveDelayMs = 1500;
|
||||
private const int ActionDelayMs = 800;
|
||||
|
||||
private string _position = "Cap1";
|
||||
|
||||
public string Position => _position;
|
||||
public event Action<string>? OnMoved;
|
||||
|
||||
public bool IsAt(string position, double tol = 0.2) =>
|
||||
string.Equals(_position, position, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public async Task GoTo(string position, CancellationToken ct = default)
|
||||
{
|
||||
await Task.Delay(MoveDelayMs, ct);
|
||||
_position = position;
|
||||
OnMoved?.Invoke(_position);
|
||||
}
|
||||
|
||||
public async Task Undock(CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task Load(CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task Unload(CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task Pause(CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task Resume(CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task InitPosition(double x, double y, double theta, CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task Cancel(CancellationToken ct = default) =>
|
||||
await Task.Delay(200, ct);
|
||||
|
||||
}
|
||||
43
Lab505.Script/Sim/SimAsrs.cs
Normal file
43
Lab505.Script/Sim/SimAsrs.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using Lab505.Script.Facades;
|
||||
|
||||
namespace Lab505.Script.Sim;
|
||||
|
||||
/// <summary>Per-user in-memory ASRS simulation. All operations complete after a fixed delay.</summary>
|
||||
public sealed class SimAsrs : IAsrsFacade
|
||||
{
|
||||
private const int OpDelayMs = 1200;
|
||||
|
||||
public bool IsBusy { get; private set; }
|
||||
public event Action? OnOperationStateChanged;
|
||||
|
||||
public bool IsLocked(string key) => false;
|
||||
|
||||
private async Task RunOp(CancellationToken token)
|
||||
{
|
||||
IsBusy = true;
|
||||
OnOperationStateChanged?.Invoke();
|
||||
try { await Task.Delay(OpDelayMs, token); }
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
OnOperationStateChanged?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public Task SYSTEM_HOMING(CancellationToken token = default) => RunOp(token);
|
||||
public Task X1_S12(CancellationToken token = default) => RunOp(token);
|
||||
public Task X2_S12(CancellationToken token = default) => RunOp(token);
|
||||
public Task X3_S12(CancellationToken token = default) => RunOp(token);
|
||||
public Task X1_S34(CancellationToken token = default) => RunOp(token);
|
||||
public Task X2_S34(CancellationToken token = default) => RunOp(token);
|
||||
public Task X3_S34(CancellationToken token = default) => RunOp(token);
|
||||
public Task X1_R12(CancellationToken token = default) => RunOp(token);
|
||||
public Task X2_R12(CancellationToken token = default) => RunOp(token);
|
||||
public Task X3_R12(CancellationToken token = default) => RunOp(token);
|
||||
public Task X1_R43(CancellationToken token = default) => RunOp(token);
|
||||
public Task X2_R43(CancellationToken token = default) => RunOp(token);
|
||||
public Task X3_R43(CancellationToken token = default) => RunOp(token);
|
||||
|
||||
public Task<bool> WaitCoil(Func<bool?> selector, bool target, int timeoutMs = 10000) =>
|
||||
Task.FromResult(true);
|
||||
}
|
||||
26
Lab505.Script/Sim/SimContext.cs
Normal file
26
Lab505.Script/Sim/SimContext.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
namespace Lab505.Script.Sim;
|
||||
|
||||
/// <summary>
|
||||
/// Isolated per-user simulation context.
|
||||
/// Each FlowContext built from this context has its own independent robot state.
|
||||
/// </summary>
|
||||
public sealed class SimContext
|
||||
{
|
||||
public SimConveyor Conveyor { get; } = new();
|
||||
public SimImr IMR { get; } = new();
|
||||
public SimAmr AMR { get; } = new();
|
||||
public SimAsrs ASRS { get; } = new();
|
||||
public SimDobot Dobot { get; } = new();
|
||||
public SimFlow Workflow { get; }
|
||||
|
||||
/// <summary>Fires whenever any simulated robot/device changes state.</summary>
|
||||
public event Action? OnChanged;
|
||||
|
||||
public SimContext()
|
||||
{
|
||||
Workflow = new SimFlow(this);
|
||||
IMR.OnMoved += _ => OnChanged?.Invoke();
|
||||
AMR.OnMoved += _ => OnChanged?.Invoke();
|
||||
Conveyor.OnChanged += () => OnChanged?.Invoke();
|
||||
}
|
||||
}
|
||||
68
Lab505.Script/Sim/SimConveyor.cs
Normal file
68
Lab505.Script/Sim/SimConveyor.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
using Lab505.Script.Facades;
|
||||
|
||||
namespace Lab505.Script.Sim;
|
||||
|
||||
/// <summary>
|
||||
/// Per-user in-memory conveyor simulation.
|
||||
/// Coil commands set state immediately then fire "feedback" after a short delay
|
||||
/// (simulating the physical conveyor responding). WaitCx methods watch for feedback.
|
||||
/// </summary>
|
||||
public sealed class SimConveyor : IConveyorFacade
|
||||
{
|
||||
// Feedback state (what WaitCx methods watch)
|
||||
private bool? _c1In, _c1Out, _c1IMRin, _c1IMRout, _c1Ready, _c2Ready;
|
||||
private bool? _c2In, _c2Out;
|
||||
private bool? _c1HasGoods, _c1NotGoods, _c2HasGoods, _c2NotGoods;
|
||||
|
||||
// Read-only accessors for state snapshot
|
||||
public bool? StateC1In => _c1In;
|
||||
public bool? StateC1Out => _c1Out;
|
||||
public bool? StateC1IMRin => _c1IMRin;
|
||||
public bool? StateC1IMRout => _c1IMRout;
|
||||
public bool? StateC1Ready => _c1Ready;
|
||||
public bool? StateC2Ready => _c2Ready;
|
||||
public bool? StateC2In => _c2In;
|
||||
public bool? StateC2Out => _c2Out;
|
||||
public bool? StateC1HasGoods => _c1HasGoods;
|
||||
public bool? StateC1NotGoods => _c1NotGoods;
|
||||
public bool? StateC2HasGoods => _c2HasGoods;
|
||||
public bool? StateC2NotGoods => _c2NotGoods;
|
||||
|
||||
public event Action? OnChanged;
|
||||
|
||||
private const int FeedbackDelayMs = 600;
|
||||
|
||||
// ── Coil commands ──────────────────────────────────────────────────────────
|
||||
|
||||
public bool C1In(bool v) => FireFeedback(v, x => _c1In = x);
|
||||
public bool C1Out(bool v) => FireFeedback(v, x => _c1Out = x);
|
||||
public bool C1IMRin(bool v) => FireFeedback(v, x => _c1IMRin = x);
|
||||
public bool C1IMRout(bool v) => FireFeedback(v, x => _c1IMRout = x);
|
||||
public bool C1Ready(bool v) => FireFeedback(v, x => _c1Ready = x);
|
||||
public bool C2Ready(bool v) => FireFeedback(v, x => _c2Ready = x);
|
||||
public bool C2In(bool v) => FireFeedback(v, x => _c2In = x);
|
||||
public bool C2Out(bool v) => FireFeedback(v, x => _c2Out = x);
|
||||
public bool C1HasGoods(bool v) => FireFeedback(v, x => _c1HasGoods = x);
|
||||
public bool C1NotGoods(bool v) => FireFeedback(v, x => _c1NotGoods = x);
|
||||
public bool C2HasGoods(bool v) => FireFeedback(v, x => _c2HasGoods = x);
|
||||
public bool C2NotGoods(bool v) => FireFeedback(v, x => _c2NotGoods = x);
|
||||
|
||||
public void StopAll()
|
||||
{
|
||||
C1In(false); C1Out(false); C1IMRin(false); C1IMRout(false);
|
||||
C2In(false); C2Out(false);
|
||||
}
|
||||
|
||||
// ── Internal helpers ───────────────────────────────────────────────────────
|
||||
|
||||
private bool FireFeedback(bool value, Action<bool> setter)
|
||||
{
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(FeedbackDelayMs);
|
||||
setter(value);
|
||||
OnChanged?.Invoke();
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
15
Lab505.Script/Sim/SimDobot.cs
Normal file
15
Lab505.Script/Sim/SimDobot.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using Lab505.Script.Facades;
|
||||
|
||||
namespace Lab505.Script.Sim;
|
||||
|
||||
/// <summary>Per-user in-memory Dobot simulation. All operations complete after a fixed delay.</summary>
|
||||
public sealed class SimDobot : IDobotFacade
|
||||
{
|
||||
private const int OpDelayMs = 800;
|
||||
|
||||
public Task PowerOn(CancellationToken t = default) => Task.Delay(OpDelayMs, t);
|
||||
public Task GoHome(CancellationToken t = default) => Task.Delay(OpDelayMs, t);
|
||||
public Task Continue(CancellationToken t = default) => Task.Delay(OpDelayMs, t);
|
||||
public Task Cancel(CancellationToken t = default) => Task.Delay(200, t);
|
||||
public Task Pickup(int ok, int ng, CancellationToken t = default) => Task.Delay(OpDelayMs, t);
|
||||
}
|
||||
126
Lab505.Script/Sim/SimFlow.cs
Normal file
126
Lab505.Script/Sim/SimFlow.cs
Normal file
@@ -0,0 +1,126 @@
|
||||
using Lab505.Script;
|
||||
|
||||
namespace Lab505.Script.Sim;
|
||||
|
||||
/// <summary>
|
||||
/// Per-user in-memory workflow simulation.
|
||||
/// Each X_A/X_B call runs a full 8-step cycle using SimContext robots with fixed delays.
|
||||
/// </summary>
|
||||
public sealed class SimFlow : IFlowFacade
|
||||
{
|
||||
private readonly SimImr _imr;
|
||||
private readonly SimAmr _amr;
|
||||
private readonly SimConveyor _conv;
|
||||
private readonly SimAsrs _asrs;
|
||||
private readonly SimDobot _dobot;
|
||||
|
||||
public bool IsRunning { get; private set; }
|
||||
public string? LastError { get; private set; }
|
||||
public int CompletedCycles { get; private set; }
|
||||
public event Action? RunningStateChanged;
|
||||
|
||||
internal SimFlow(SimContext ctx)
|
||||
{
|
||||
_imr = ctx.IMR;
|
||||
_amr = ctx.AMR;
|
||||
_conv = ctx.Conveyor;
|
||||
_asrs = ctx.ASRS;
|
||||
_dobot = ctx.Dobot;
|
||||
}
|
||||
|
||||
// ── X_A: S34 pick → workflow → S34 return ────────────────────────────────
|
||||
|
||||
public Task X1A(int times, int ng, CancellationToken ct = default)
|
||||
=> RunCycle(times, ng, ct => _asrs.X1_S34(ct), ct => _asrs.X1_R43(ct), ct);
|
||||
public Task X2A(int times, int ng, CancellationToken ct = default)
|
||||
=> RunCycle(times, ng, ct => _asrs.X2_S34(ct), ct => _asrs.X2_R43(ct), ct);
|
||||
public Task X3A(int times, int ng, CancellationToken ct = default)
|
||||
=> RunCycle(times, ng, ct => _asrs.X3_S34(ct), ct => _asrs.X3_R43(ct), ct);
|
||||
|
||||
// ── X_B: S12 pick → workflow → S12 return ────────────────────────────────
|
||||
|
||||
public Task X1B(int times, int ng, CancellationToken ct = default)
|
||||
=> RunCycle(times, ng, ct => _asrs.X1_S12(ct), ct => _asrs.X1_R12(ct), ct);
|
||||
public Task X2B(int times, int ng, CancellationToken ct = default)
|
||||
=> RunCycle(times, ng, ct => _asrs.X2_S12(ct), ct => _asrs.X2_R12(ct), ct);
|
||||
public Task X3B(int times, int ng, CancellationToken ct = default)
|
||||
=> RunCycle(times, ng, ct => _asrs.X3_S12(ct), ct => _asrs.X3_R12(ct), ct);
|
||||
|
||||
// ── Run cycle (no ASRS) ───────────────────────────────────────────────────
|
||||
|
||||
public Task RunCycle(int times, int ng, CancellationToken ct = default)
|
||||
=> RunCycle(times, ng, _ => Task.CompletedTask, _ => Task.CompletedTask, ct);
|
||||
|
||||
// ── Core cycle loop ───────────────────────────────────────────────────────
|
||||
|
||||
private async Task RunCycle(
|
||||
int times, int ng,
|
||||
Func<CancellationToken, Task> startOp,
|
||||
Func<CancellationToken, Task> endOp,
|
||||
CancellationToken ct)
|
||||
{
|
||||
IsRunning = true;
|
||||
LastError = null;
|
||||
RunningStateChanged?.Invoke();
|
||||
try
|
||||
{
|
||||
for (int i = 0; i < times; i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
// Step 1: Init — IMR→C1 + AMR→Cap2 + ASRS pick (parallel)
|
||||
await Task.WhenAll(_imr.GoTo("C1", ct), _amr.GoTo("Cap2", ct), startOp(ct));
|
||||
|
||||
// Step 2: AMR load from C2
|
||||
_conv.C2Out(true);
|
||||
await _amr.Load(ct);
|
||||
_conv.C2Out(false);
|
||||
|
||||
// Step 3: AMR undock → Cap1
|
||||
await _amr.Undock(ct);
|
||||
await _amr.GoTo("Cap1", ct);
|
||||
|
||||
// Step 4: AMR→IMR exchange via C1
|
||||
_conv.C1In(true);
|
||||
await _imr.Load(ct);
|
||||
_conv.C1In(false);
|
||||
_conv.C1Out(true);
|
||||
await Task.Delay(300, ct);
|
||||
_conv.C1Out(false);
|
||||
|
||||
// Step 5: IMR process @ ABB
|
||||
await _imr.GoTo("ABB", ct);
|
||||
await _dobot.Pickup(1, ng, ct);
|
||||
await _imr.GoTo("C1", ct);
|
||||
|
||||
// Step 6: IMR→AMR exchange via C1
|
||||
_conv.C1IMRin(true);
|
||||
await _imr.Unload(ct);
|
||||
_conv.C1IMRin(false);
|
||||
await _amr.Load(ct);
|
||||
|
||||
// Step 7: AMR → Cap2
|
||||
await _amr.GoTo("Cap2", ct);
|
||||
|
||||
// Step 8: AMR unload to C2 + ASRS return
|
||||
_conv.C2In(true);
|
||||
await _amr.Unload(ct);
|
||||
_conv.C2In(false);
|
||||
await endOp(ct);
|
||||
|
||||
CompletedCycles++;
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
LastError = ex.Message;
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsRunning = false;
|
||||
RunningStateChanged?.Invoke();
|
||||
}
|
||||
}
|
||||
}
|
||||
50
Lab505.Script/Sim/SimImr.cs
Normal file
50
Lab505.Script/Sim/SimImr.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using Lab505.Script.Facades;
|
||||
|
||||
namespace Lab505.Script.Sim;
|
||||
|
||||
/// <summary>Per-user in-memory IMR simulation. All operations complete after a fixed delay.</summary>
|
||||
public sealed class SimImr : IImrFacade
|
||||
{
|
||||
private const int MoveDelayMs = 1500;
|
||||
private const int ActionDelayMs = 800;
|
||||
|
||||
private string _position = "C1";
|
||||
|
||||
public string Position => _position;
|
||||
public event Action<string>? OnMoved;
|
||||
|
||||
public bool IsAt(string position, double tol = 0.2) =>
|
||||
string.Equals(_position, position, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public async Task GoTo(string position, CancellationToken ct = default)
|
||||
{
|
||||
await Task.Delay(MoveDelayMs, ct);
|
||||
_position = position;
|
||||
OnMoved?.Invoke(_position);
|
||||
}
|
||||
|
||||
public async Task Undock(string fromPosition, CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task Load(CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task Unload(CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task PickUp(int ok, int ng = 0, CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task Pause(CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task Resume(CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task InitPosition(double x, double y, double theta, CancellationToken ct = default) =>
|
||||
await Task.Delay(ActionDelayMs, ct);
|
||||
|
||||
public async Task Cancel(CancellationToken ct = default) =>
|
||||
await Task.Delay(200, ct);
|
||||
|
||||
}
|
||||
76
Lab505.Shared/AsrsCoilAddress.cs
Normal file
76
Lab505.Shared/AsrsCoilAddress.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
public enum AsrsCoilAddress : ushort
|
||||
{
|
||||
// AUTO MODE
|
||||
AUTO_MODE = 0x0BB6, // M950
|
||||
|
||||
// START System
|
||||
START_SYSTEM = 0x0834, // M52
|
||||
|
||||
// MODE for picking up from conveyor to trays 3 and 4
|
||||
MODE_PICK_FROM_CONVEYOR_3_4 = 0x08C8, // M200
|
||||
|
||||
// MODE for picking empty boxes from conveyor to trays 1 and 2
|
||||
MODE_PICK_FROM_CONVEYOR_1_2 = 0x0ACB, // M715
|
||||
|
||||
// Return items to trays
|
||||
RETURN_TRAY_X3 = 0x08CA, // M202
|
||||
RETURN_TRAY_X3_SUCCESS = 0x08CF, // M207
|
||||
|
||||
RETURN_TRAY_X2 = 0x08DE, // M222
|
||||
RETURN_TRAY_X2_SUCCESS = 0x08E3, // M227
|
||||
|
||||
RETURN_TRAY_X1 = 0x08F2, // M242
|
||||
RETURN_TRAY_X1_SUCCESS = 0x08F7, // M247
|
||||
|
||||
// MODE for picking empty boxes from trays 1 and 2
|
||||
MODE_PICK_EMPTY_BOX_1_2 = 0x092C, // M300
|
||||
|
||||
// MODE for picking up from trays 3 and 4 to conveyor
|
||||
MODE_PICK_EMPTY_BOX_3_4 = 0x0ACA, // M714
|
||||
|
||||
// Pick empty boxes from trays
|
||||
PICK_EMPTY_BOX_X3 = 0x092E, // M302
|
||||
PICK_EMPTY_BOX_X3_SUCCESS = 0x0933, // M307
|
||||
|
||||
M314 = 0x093A, // M314
|
||||
|
||||
PICK_EMPTY_BOX_X2 = 0x0942, // M322
|
||||
PICK_EMPTY_BOX_X2_SUCCESS = 0x08E3, // M227
|
||||
|
||||
PICK_EMPTY_BOX_X1 = 0x0956, // M342
|
||||
PICK_EMPTY_BOX_X1_SUCCESS = 0x095B, // M347
|
||||
|
||||
FULL_TRAY_ALERT_13 = 0x093E, //M318
|
||||
FULL_TRAY_ALERT_12 = 0x0952, //M338
|
||||
FULL_TRAY_ALERT_11 = 0x0966, //M358
|
||||
FULL_TRAY_ALERT_23 = 0x093F, //M319
|
||||
FULL_TRAY_ALERT_22 = 0x0953, //M339
|
||||
FULL_TRAY_ALERT_21 = 0x0967, //M359
|
||||
|
||||
FULL_TRAY_ALERT_33 = 0x08D0, // M208
|
||||
FULL_TRAY_ALERT_32 = 0x08E4, // M228
|
||||
FULL_TRAY_ALERT_31 = 0x08F8, // M248
|
||||
FULL_TRAY_ALERT_43 = 0x08D1, // M209
|
||||
FULL_TRAY_ALERT_42 = 0x08E5, // M229
|
||||
FULL_TRAY_ALERT_41 = 0x08F9, // M249
|
||||
|
||||
// Reset full tray alerts
|
||||
RESET_FULL_TRAY_ALERT = 0x08FB, // M251
|
||||
|
||||
// Cancel selection and clear tray
|
||||
CANCEL_SELECTION = 0x0833, // M51
|
||||
|
||||
// Emergency Stop (Red Light)
|
||||
EMERGENCY_STOP = 0x0990, // M400
|
||||
|
||||
// LIDAR (Front and Rear)
|
||||
LIDAR_FRONT = 0x09B8, // M430
|
||||
LIDAR_REAR = 0x09BB, // M443
|
||||
|
||||
// Safety Mode
|
||||
SAFETY_MODE = 0x09C2, // M450
|
||||
SYSTEM_HOMING = 0x0B20, // M451
|
||||
SYSTEM_HOMING_SUCCESS = 0x0B2F // M815
|
||||
}
|
||||
19
Lab505.Shared/AsrsPushDto.cs
Normal file
19
Lab505.Shared/AsrsPushDto.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Full ASRS state pushed via SignalR.
|
||||
/// Includes tray coils, safety mode, busy/locked status.
|
||||
/// LockedOps contains the set of operation keys currently locked by the driver
|
||||
/// (e.g. "X1_S34", "X2_S12" — one lock held during each ASRS operation).
|
||||
/// </summary>
|
||||
public record AsrsPushDto(
|
||||
bool? X11, bool? X12, bool? X13,
|
||||
bool? X21, bool? X22, bool? X23,
|
||||
bool? X31, bool? X32, bool? X33,
|
||||
bool? X41, bool? X42, bool? X43,
|
||||
bool? SAFETY_MODE,
|
||||
bool IsOffline,
|
||||
bool IsBusy,
|
||||
string[] LockedOps,
|
||||
string? LastError // lỗi thực thi lệnh ASRS gần nhất (null = OK)
|
||||
);
|
||||
23
Lab505.Shared/ConveyorCoilAddress.cs
Normal file
23
Lab505.Shared/ConveyorCoilAddress.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Conveyor coil addresses
|
||||
/// </summary>
|
||||
public enum ConveyorCoilAddress : ushort
|
||||
{
|
||||
C1IMRin = 0x0864, //100
|
||||
C1In = 0x0867, //103
|
||||
C1Out = 0x0869, //105 2153
|
||||
C1IMRout = 0x086C, //108
|
||||
C1HasGoods = 0x088C,//140
|
||||
C1NotGoods = 0x088D,//141
|
||||
|
||||
C1Ready = 0x08C6,//198
|
||||
|
||||
C2In = 0x086E, //110
|
||||
C2Out = 0x0871, //113
|
||||
C2HasGoods = 0x0891,//145
|
||||
C2NotGoods = 0x0892,//146
|
||||
|
||||
C2Ready = 0x08C5,//197
|
||||
}
|
||||
21
Lab505.Shared/ConveyorPushDto.cs
Normal file
21
Lab505.Shared/ConveyorPushDto.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Full conveyor state pushed via SignalR.
|
||||
/// Uses nullable bool: null = not yet read (offline), true/false = actual coil state.
|
||||
/// </summary>
|
||||
public record ConveyorPushDto(
|
||||
bool? C1In,
|
||||
bool? C1Out,
|
||||
bool? C1IMRin,
|
||||
bool? C1IMRout,
|
||||
bool? C1HasGoods,
|
||||
bool? C1NotGoods,
|
||||
bool? C1Ready,
|
||||
bool? C2In,
|
||||
bool? C2Out,
|
||||
bool? C2HasGoods,
|
||||
bool? C2NotGoods,
|
||||
bool? C2Ready,
|
||||
string? WriteError // lỗi ghi coil gần nhất (null = OK)
|
||||
);
|
||||
32
Lab505.Shared/HubContracts.cs
Normal file
32
Lab505.Shared/HubContracts.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Shared constants for SignalR hubs — used by both server and WASM client.
|
||||
/// </summary>
|
||||
public static class HubContracts
|
||||
{
|
||||
// ── Hub routes ────────────────────────────────────────────────
|
||||
public const string StateHubRoute = "/stateHub";
|
||||
public const string ScriptHubRoute = "/scriptHub";
|
||||
|
||||
// ── StateHub: server → client push events ─────────────────────
|
||||
public const string ImrStateEvent = "imr-state";
|
||||
public const string AmrStateEvent = "amr-state";
|
||||
public const string ConveyorStateEvent = "conveyor-state";
|
||||
public const string AsrsStateEvent = "asrs-state";
|
||||
public const string WorkflowStateEvent = "workflow-state";
|
||||
public const string SystemStateEvent = "system-state";
|
||||
|
||||
// ── Notification: server → client (lệnh gửi / hoàn thành / lỗi) ──
|
||||
public const string NotificationEvent = "notification";
|
||||
|
||||
// ── Lock state: server → client push events ───────────────────
|
||||
public const string LockStateEvent = "lock-state";
|
||||
|
||||
// ── Mode change: server → specific user (T3 remote switch) ───
|
||||
public const string ModeChangedEvent = "mode-changed";
|
||||
|
||||
// ── ScriptHub: server → client push events ────────────────────
|
||||
public const string ScriptLogEvent = "scriptLog";
|
||||
public const string SimPanelStateEvent = "sim-panel-state";
|
||||
}
|
||||
16
Lab505.Shared/Lab505.Shared.csproj
Normal file
16
Lab505.Shared/Lab505.Shared.csproj
Normal file
@@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.3.9" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="5.3.0" />
|
||||
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
10
Lab505.Shared/LockStateDto.cs
Normal file
10
Lab505.Shared/LockStateDto.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
public record LockStateDto(
|
||||
LockHolderDto? Workflow,
|
||||
IReadOnlyList<WaiterDto> WorkflowQueue,
|
||||
Dictionary<string, LockHolderDto?> Groups,
|
||||
Dictionary<string, IReadOnlyList<WaiterDto>> GroupQueues);
|
||||
|
||||
public record LockHolderDto(string UserId, string Name, long ExpiresMs, long RemainingMs);
|
||||
public record WaiterDto(string UserId, string Name, bool IsPriority);
|
||||
16
Lab505.Shared/NotificationDto.cs
Normal file
16
Lab505.Shared/NotificationDto.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
/// <summary>Một thông báo ngắn được push từ server xuống client qua SignalR.</summary>
|
||||
/// <param name="Message">Nội dung thông báo gốc.</param>
|
||||
/// <param name="Level">Mức độ: "info" | "success" | "error" | "warning".</param>
|
||||
/// <param name="Toast">Cho phép hiện snackbar/toast.</param>
|
||||
/// <param name="Source">Nguồn phát sinh: IMR, AMR, WF, ASRS, OPC...</param>
|
||||
/// <param name="Command">Sự kiện/chủ đề chính để render cột command.</param>
|
||||
/// <param name="Detail">Chi tiết bổ sung đi kèm command.</param>
|
||||
public record NotificationDto(
|
||||
string Message,
|
||||
string Level = "info",
|
||||
bool Toast = false,
|
||||
string? Source = null,
|
||||
string? Command = null,
|
||||
string? Detail = null);
|
||||
35
Lab505.Shared/RobotPositions.cs
Normal file
35
Lab505.Shared/RobotPositions.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Hằng số vị trí và tham số lùi robot — nguồn duy nhất cho toàn hệ thống.
|
||||
/// Thay đổi ở đây tự động áp dụng vào SystemCondition, FlowService, drivers và simulation.
|
||||
/// </summary>
|
||||
public static class RobotPositions
|
||||
{
|
||||
// ── IMR docked positions ───────────────────────────────────────
|
||||
public const double IMR_C1_X = -0.1, IMR_C1_Y = -5.2;
|
||||
public const double IMR_ABB_X = 1.35, IMR_ABB_Y = -0.8;
|
||||
|
||||
// ── IMR undock parameters ──────────────────────────────────────
|
||||
/// Khoảng lùi khỏi C1 (m) — gửi âm: UndockFromStation_IMR(-IMR_UNDOCK_C1, ...)
|
||||
public const double IMR_UNDOCK_C1 = 2.2;
|
||||
/// Khoảng lùi khỏi ABB (m)
|
||||
public const double IMR_UNDOCK_ABB = 1.2;
|
||||
/// Vận tốc lùi mặc định (m/s)
|
||||
public const double IMR_UNDOCK_VEL = 0.2;
|
||||
|
||||
// ── AMR docked positions ───────────────────────────────────────
|
||||
public const double AMR_CAP1_X = 6.0, AMR_CAP1_Y = 0.2;
|
||||
public const double AMR_CAP2_X = -0.7, AMR_CAP2_Y = -3.19;
|
||||
public const double AMR_HOME_X = 0.0, AMR_HOME_Y = 0.0;
|
||||
|
||||
// ── AMR undocked positions ─────────────────────────────────────
|
||||
/// Vị trí AMR sau khi UndockFromStation khỏi Cap1 (NBR=true / ActionState=FINISHED).
|
||||
/// Đọc X_Vda, Y_Vda tại thời điểm đó để lấy giá trị thực tế.
|
||||
public const double AMR_UNDOCK_CAP1_X = 5.1, AMR_UNDOCK_CAP1_Y = 0.2; // TODO: đo thực tế
|
||||
/// Vị trí AMR sau khi UndockFromStation khỏi Cap2.
|
||||
public const double AMR_UNDOCK_CAP2_X = -0.71, AMR_UNDOCK_CAP2_Y = -2.19;
|
||||
|
||||
// ── Position matching tolerance ────────────────────────────────
|
||||
public const double POS_TOL = 0.2;
|
||||
}
|
||||
27
Lab505.Shared/RobotStateDto.cs
Normal file
27
Lab505.Shared/RobotStateDto.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Robot state pushed via SignalR for both IMR and AMR.
|
||||
/// DobotStatus_Opc / CodeDobotStatus_Opc are only meaningful for the IMR.
|
||||
/// </summary>
|
||||
public record RobotStateDto(
|
||||
double X,
|
||||
double Y,
|
||||
bool IsOnline,
|
||||
bool? NewBaseRequest,
|
||||
List<string> Errors,
|
||||
ActionStateDto[] Actions,
|
||||
// IMR-only OPC fields (zero-value for AMR)
|
||||
string DobotStatus_Opc,
|
||||
uint CodeDobotStatus_Opc,
|
||||
RobotErrorDto[] RawErrors
|
||||
);
|
||||
|
||||
public record ActionStateDto(string ActionID, string? ActionStatus);
|
||||
|
||||
/// <summary>VDA 5050 error với đầy đủ ErrorType, ErrorLevel, ErrorDescription.</summary>
|
||||
public record RobotErrorDto(
|
||||
string? ErrorType,
|
||||
string? ErrorLevel,
|
||||
string? ErrorDescription
|
||||
);
|
||||
12
Lab505.Shared/SimPanelStateDto.cs
Normal file
12
Lab505.Shared/SimPanelStateDto.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Sim panel state snapshot pushed to a specific user's ScriptHub connection
|
||||
/// so their panels reflect their isolated simulation state.
|
||||
/// </summary>
|
||||
public record SimPanelStateDto(
|
||||
string ImrPosition,
|
||||
string AmrPosition,
|
||||
bool IsRunning,
|
||||
ConveyorPushDto Conveyor
|
||||
);
|
||||
6
Lab505.Shared/SystemStateDto.cs
Normal file
6
Lab505.Shared/SystemStateDto.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// System-level state pushed via SignalR (operation mode + connection status).
|
||||
/// </summary>
|
||||
public record SystemStateDto(bool IsSimulation, bool OpcUaConnected);
|
||||
24
Lab505.Shared/WorkflowStateDto.cs
Normal file
24
Lab505.Shared/WorkflowStateDto.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Workflow state pushed via SignalR.
|
||||
/// </summary>
|
||||
public record WorkflowStateDto(
|
||||
bool IsRunning,
|
||||
string? LastError,
|
||||
int CompletedCycles,
|
||||
string ImrCmd, // "" = idle, "undocking" = undock in progress
|
||||
string AmrCmd, // "" = idle, "undocking" = undock in progress
|
||||
bool ImrBusy, // manual command đang chạy
|
||||
string? ImrBusyLabel, // label lệnh đang chạy (nút nào bị khóa)
|
||||
string? ImrNextLabel, // lệnh đang xếp hàng chờ (null = không có)
|
||||
bool AmrBusy,
|
||||
string? AmrBusyLabel, // label lệnh đang chạy AMR
|
||||
string? AmrNextLabel,
|
||||
string? ImrExecError, // lỗi thực thi lệnh thủ công IMR gần nhất
|
||||
string? AmrExecError, // lỗi thực thi lệnh thủ công AMR gần nhất
|
||||
bool DobotBusy,
|
||||
string? DobotBusyLabel,
|
||||
string? DobotNextLabel,
|
||||
string? DobotExecError
|
||||
);
|
||||
134
Lab505.Sim/ApiModels.cs
Normal file
134
Lab505.Sim/ApiModels.cs
Normal file
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
|
||||
#region API Models
|
||||
|
||||
/// <summary>
|
||||
/// Base API result
|
||||
/// </summary>
|
||||
public class ApiResult
|
||||
{
|
||||
public bool IsSuccess { get; set; }
|
||||
public string Message { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Robot state result
|
||||
/// </summary>
|
||||
public class RobotStateResult : ApiResult
|
||||
{
|
||||
public RobotStateData? Data { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Robot state data
|
||||
/// </summary>
|
||||
public class RobotStateData
|
||||
{
|
||||
public string RobotId { get; set; } = string.Empty;
|
||||
public Guid MapId { get; set; }
|
||||
public bool IsOnline { get; set; }
|
||||
public string State { get; set; } = string.Empty;
|
||||
public VdaStateMsg StateMsg { get; set; } = new();
|
||||
public VdaVisualizationMsg VisualizationMsg { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// VDA5050 State message
|
||||
/// </summary>
|
||||
public class VdaStateMsg
|
||||
{
|
||||
public uint HeaderId { get; set; }
|
||||
public string? Timestamp { get; set; }
|
||||
public string? Version { get; set; }
|
||||
public string? Manufacturer { get; set; }
|
||||
public string? SerialNumber { get; set; }
|
||||
public string? OrderId { get; set; }
|
||||
public int OrderUpdateId { get; set; }
|
||||
public string? LastNodeId { get; set; }
|
||||
public int LastNodeSequenceId { get; set; }
|
||||
public bool Driving { get; set; }
|
||||
public bool Paused { get; set; }
|
||||
public bool NewBaseRequest { get; set; }
|
||||
public double DistanceSinceLastNode { get; set; }
|
||||
public string? OperatingMode { get; set; }
|
||||
public VdaAgvPosition AgvPosition { get; set; } = new();
|
||||
public VdaActionState[] ActionStates { get; set; } = [];
|
||||
public VdaError[] Errors { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// VDA5050 Visualization message
|
||||
/// </summary>
|
||||
public class VdaVisualizationMsg
|
||||
{
|
||||
public uint HeaderId { get; set; }
|
||||
public string? Timestamp { get; set; }
|
||||
public string? Version { get; set; }
|
||||
public string? Manufacturer { get; set; }
|
||||
public string? SerialNumber { get; set; }
|
||||
public VdaAgvPosition AgvPosition { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AGV Position
|
||||
/// </summary>
|
||||
public class VdaAgvPosition
|
||||
{
|
||||
public double X { get; set; }
|
||||
public double Y { get; set; }
|
||||
public double Theta { get; set; }
|
||||
public string? MapId { get; set; }
|
||||
public bool PositionInitialized { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Action state
|
||||
/// </summary>
|
||||
public class VdaActionState
|
||||
{
|
||||
// VDA5050 field name là "actionId" (camelCase) — robot báo về với key này.
|
||||
[JsonPropertyName("actionId")]
|
||||
public string ActionID { get; set; } = string.Empty;
|
||||
public string ActionType { get; set; } = string.Empty;
|
||||
public string? ActionDescription { get; set; }
|
||||
public string ActionStatus { get; set; } = string.Empty; // WAITING, INITIALIZING, RUNNING, FINISHED, FAILED, PAUSED
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// VDA Error
|
||||
/// </summary>
|
||||
public class VdaError
|
||||
{
|
||||
public string ErrorType { get; set; } = string.Empty;
|
||||
public string? ErrorDescription { get; set; }
|
||||
public string ErrorLevel { get; set; } = string.Empty; // WARNING, FATAL
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Instant action request
|
||||
/// </summary>
|
||||
public class VdaInstantAction
|
||||
{
|
||||
public string ActionId { get; set; } = string.Empty;
|
||||
public string ActionType { get; set; } = string.Empty;
|
||||
public string ActionDescription { get; set; } = string.Empty;
|
||||
public string BlockingType { get; set; } = "NONE";
|
||||
public List<VdaActionParameter> ActionParameters { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Action parameter
|
||||
/// </summary>
|
||||
public class VdaActionParameter
|
||||
{
|
||||
public string Key { get; set; } = string.Empty;
|
||||
public string Value { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
#endregion
|
||||
451
Lab505.Sim/ConveyorModbusServer.cs
Normal file
451
Lab505.Sim/ConveyorModbusServer.cs
Normal file
@@ -0,0 +1,451 @@
|
||||
using Lab505.Shared;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
public class ConveyorModbusServer(int port = 503) : IDisposable
|
||||
{
|
||||
private TcpListener? _listener;
|
||||
private CancellationTokenSource? _cts;
|
||||
private readonly bool[] Coils = new bool[70000];
|
||||
private readonly ushort[] HoldingRegisters = new ushort[70000];
|
||||
private readonly Lock _lock = new();
|
||||
private readonly Dictionary<ushort, CancellationTokenSource> _autoOffMap = [];
|
||||
private bool _isRunning;
|
||||
// Rising-edge tracking — only fire sensor task when a coil transitions false→true
|
||||
private bool _prevC1Active;
|
||||
private bool _prevC2Active;
|
||||
|
||||
public int Port { get; } = port;
|
||||
public bool IsRunning => _isRunning;
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
//Console.WriteLine($"[Conveyor ModbusSim:{Port}] Already running");
|
||||
return;
|
||||
}
|
||||
|
||||
_cts = new CancellationTokenSource();
|
||||
_listener = new TcpListener(IPAddress.Any, Port);
|
||||
_listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
_listener.Start();
|
||||
_isRunning = true;
|
||||
//Console.WriteLine($"[Conveyor ModbusSim:{Port}] Server started");
|
||||
|
||||
// NReady = true by default (conveyor ready to receive)
|
||||
Coils[(ushort)ConveyorCoilAddress.C1Ready] = true;
|
||||
Coils[(ushort)ConveyorCoilAddress.C2Ready] = true;
|
||||
|
||||
// Start sensor simulation tasks
|
||||
StartSensorSimulation();
|
||||
|
||||
Task.Run(async () =>
|
||||
{
|
||||
while (!_cts.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var client = await _listener.AcceptTcpClientAsync(_cts.Token);
|
||||
_ = Task.Run(() => HandleClient(client));
|
||||
}
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch { }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void StartSensorSimulation()
|
||||
{
|
||||
// Simulate C1 sensors
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
while (!_cts?.IsCancellationRequested ?? false)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
SimulateC1Sensors();
|
||||
}
|
||||
});
|
||||
|
||||
// Simulate C2 sensors
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
while (!_cts?.IsCancellationRequested ?? false)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
SimulateC2Sensors();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void SimulateC1Sensors()
|
||||
{
|
||||
bool c1Active = GetCoil(ConveyorCoilAddress.C1In)
|
||||
|| GetCoil(ConveyorCoilAddress.C1Out)
|
||||
|| GetCoil(ConveyorCoilAddress.C1IMRin)
|
||||
|| GetCoil(ConveyorCoilAddress.C1IMRout);
|
||||
|
||||
// Only fire once per rising edge (false → true) to avoid spawning duplicate tasks
|
||||
bool risingEdge = c1Active && !_prevC1Active;
|
||||
_prevC1Active = c1Active;
|
||||
|
||||
if (!risingEdge) return;
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(5000);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[(ushort)ConveyorCoilAddress.C1HasGoods] = true;
|
||||
Coils[(ushort)ConveyorCoilAddress.C1NotGoods] = false;
|
||||
}
|
||||
|
||||
await Task.Delay(5000);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[(ushort)ConveyorCoilAddress.C1HasGoods] = false;
|
||||
Coils[(ushort)ConveyorCoilAddress.C1NotGoods] = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void SimulateC2Sensors()
|
||||
{
|
||||
bool c2Active = GetCoil(ConveyorCoilAddress.C2In)
|
||||
|| GetCoil(ConveyorCoilAddress.C2Out);
|
||||
|
||||
// Only fire once per rising edge (false → true) to avoid spawning duplicate tasks
|
||||
bool risingEdge = c2Active && !_prevC2Active;
|
||||
_prevC2Active = c2Active;
|
||||
|
||||
if (!risingEdge) return;
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(5000);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[(ushort)ConveyorCoilAddress.C2HasGoods] = true;
|
||||
Coils[(ushort)ConveyorCoilAddress.C2NotGoods] = false;
|
||||
}
|
||||
|
||||
await Task.Delay(5000);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[(ushort)ConveyorCoilAddress.C2HasGoods] = false;
|
||||
Coils[(ushort)ConveyorCoilAddress.C2NotGoods] = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ScheduleAutoOff(ushort addr, int ms = 5000)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_autoOffMap.TryGetValue(addr, out var old))
|
||||
old.Cancel();
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
_autoOffMap[addr] = cts;
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(ms, cts.Token);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[addr] = false;
|
||||
_autoOffMap.Remove(addr);
|
||||
//Console.WriteLine($"[Conveyor ModbusSim:{Port}] Auto-off coil 0x{addr:X4}");
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
//Console.WriteLine($"[Conveyor ModbusSim:{Port}] Not running");
|
||||
return;
|
||||
}
|
||||
|
||||
_cts?.Cancel();
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
|
||||
try
|
||||
{
|
||||
_listener?.Stop();
|
||||
_listener?.Server?.Close();
|
||||
_listener?.Server?.Dispose();
|
||||
}
|
||||
catch { }
|
||||
_listener = null;
|
||||
|
||||
_isRunning = false;
|
||||
//Console.WriteLine($"[Conveyor ModbusSim:{Port}] Server stopped");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public void SetCoil(ushort addr, bool val)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[addr] = val;
|
||||
|
||||
if (val)
|
||||
{
|
||||
// Check if this coil should auto-off
|
||||
if (ShouldAutoOff(addr))
|
||||
{
|
||||
ScheduleAutoOff(addr, 5000);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"[Conveyor ModbusSim:{Port}] Set coil 0x{addr:X4} = TRUE (persistent)");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Cancel auto-off nếu đang chờ
|
||||
if (_autoOffMap.TryGetValue(addr, out var cts))
|
||||
{
|
||||
cts.Cancel();
|
||||
_autoOffMap.Remove(addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kiểm tra coil có cần auto-off không
|
||||
/// Loại trừ: HasGoods, NotGoods, NReady, C2Out
|
||||
/// </summary>
|
||||
private static bool ShouldAutoOff(ushort addr)
|
||||
{
|
||||
return addr switch
|
||||
{
|
||||
// C1 - Không auto-off
|
||||
(ushort)ConveyorCoilAddress.C1HasGoods => false,
|
||||
(ushort)ConveyorCoilAddress.C1NotGoods => false,
|
||||
(ushort)ConveyorCoilAddress.C1Ready => false,
|
||||
|
||||
// C2 - Không auto-off
|
||||
(ushort)ConveyorCoilAddress.C2Out => false,
|
||||
(ushort)ConveyorCoilAddress.C2HasGoods => false,
|
||||
(ushort)ConveyorCoilAddress.C2NotGoods => false,
|
||||
(ushort)ConveyorCoilAddress.C2Ready => false,
|
||||
|
||||
// Tất cả các coil khác đều auto-off
|
||||
_ => true
|
||||
};
|
||||
}
|
||||
|
||||
public void SetCoil(ConveyorCoilAddress addr, bool val) => SetCoil((ushort)addr, val);
|
||||
public bool GetCoil(ushort addr) { lock (_lock) return Coils[addr]; }
|
||||
public bool GetCoil(ConveyorCoilAddress addr) => GetCoil((ushort)addr);
|
||||
public void SetRegister(ushort addr, ushort val) { lock (_lock) HoldingRegisters[addr] = val; }
|
||||
public ushort GetRegister(ushort addr) { lock (_lock) return HoldingRegisters[addr]; }
|
||||
|
||||
private void HandleClient(TcpClient client)
|
||||
{
|
||||
using var stream = client.GetStream();
|
||||
var buf = new byte[260];
|
||||
|
||||
try
|
||||
{
|
||||
while (client.Connected)
|
||||
{
|
||||
int len = stream.Read(buf, 0, buf.Length);
|
||||
if (len <= 0) break;
|
||||
if (len < 8) continue;
|
||||
|
||||
byte fc = buf[7];
|
||||
byte[] res;
|
||||
|
||||
try
|
||||
{
|
||||
res = fc switch
|
||||
{
|
||||
0x01 => HandleReadCoils(buf),
|
||||
0x02 => HandleReadCoils(buf),
|
||||
0x03 => HandleReadRegisters(buf),
|
||||
0x04 => HandleReadRegisters(buf),
|
||||
0x05 => HandleWriteSingleCoil(buf),
|
||||
0x06 => HandleWriteSingleRegister(buf),
|
||||
0x0F => HandleWriteMultiCoils(buf),
|
||||
0x10 => HandleWriteMultiRegisters(buf),
|
||||
_ => BuildException(buf, 0x01)
|
||||
};
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
res = BuildException(buf, 0x04);
|
||||
}
|
||||
|
||||
stream.Write(res);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[Conveyor ModbusSim:{Port}] Client error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] HandleReadCoils(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
int byteCount = (qty + 7) / 8;
|
||||
var payload = new byte[byteCount];
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort addr = (ushort)(start + i);
|
||||
bool value = Coils[addr];
|
||||
|
||||
if (value)
|
||||
payload[i / 8] |= (byte)(1 << (i % 8));
|
||||
}
|
||||
}
|
||||
|
||||
return BuildResponse(req, payload);
|
||||
}
|
||||
|
||||
private byte[] HandleReadRegisters(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
var payload = new byte[qty * 2];
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort val = HoldingRegisters[start + i];
|
||||
payload[i * 2] = (byte)(val >> 8);
|
||||
payload[i * 2 + 1] = (byte)(val & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
return BuildResponse(req, payload);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteSingleCoil(byte[] req)
|
||||
{
|
||||
ushort addr = (ushort)(req[8] << 8 | req[9]);
|
||||
bool val = req[10] == 0xFF;
|
||||
|
||||
SetCoil(addr, val);
|
||||
|
||||
return EchoWithCorrectLength(req);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteSingleRegister(byte[] req)
|
||||
{
|
||||
ushort addr = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort val = (ushort)(req[10] << 8 | req[11]);
|
||||
lock (_lock) HoldingRegisters[addr] = val;
|
||||
return EchoWithCorrectLength(req);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteMultiCoils(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
int mask = 1 << (i % 8);
|
||||
int byteIndex = 13 + i / 8;
|
||||
bool val = (req[byteIndex] & mask) != 0;
|
||||
SetCoil((ushort)(start + i), val);
|
||||
}
|
||||
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
Buffer.BlockCopy(req, 8, res, 8, 4);
|
||||
return res;
|
||||
}
|
||||
|
||||
private byte[] HandleWriteMultiRegisters(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort v = (ushort)(req[13 + i * 2] << 8 | req[14 + i * 2]);
|
||||
HoldingRegisters[start + i] = v;
|
||||
}
|
||||
}
|
||||
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
Buffer.BlockCopy(req, 8, res, 8, 4);
|
||||
return res;
|
||||
}
|
||||
|
||||
private static byte[] BuildResponse(byte[] req, byte[] data)
|
||||
{
|
||||
byte[] res = new byte[9 + data.Length];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
|
||||
int length = 1 + 1 + 1 + data.Length;
|
||||
res[4] = (byte)(length >> 8);
|
||||
res[5] = (byte)(length & 0xFF);
|
||||
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
res[8] = (byte)data.Length;
|
||||
|
||||
Buffer.BlockCopy(data, 0, res, 9, data.Length);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
private static byte[] EchoWithCorrectLength(byte[] req)
|
||||
{
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 12);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
return res;
|
||||
}
|
||||
|
||||
private static byte[] BuildException(byte[] req, byte code)
|
||||
{
|
||||
return
|
||||
[
|
||||
req[0], req[1],
|
||||
0x00, 0x00,
|
||||
0x00, 0x03,
|
||||
req[6],
|
||||
(byte)(req[7] | 0x80),
|
||||
code
|
||||
];
|
||||
}
|
||||
}
|
||||
25
Lab505.Sim/Lab505.Sim.csproj
Normal file
25
Lab505.Sim/Lab505.Sim.csproj
Normal file
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifiers>linux-x64</RuntimeIdentifiers>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<UseAppHost>false</UseAppHost>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.6" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.6" />
|
||||
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Configuration" Version="1.5.378.134" />
|
||||
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Core" Version="1.5.378.134" />
|
||||
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Server" Version="1.5.378.134" />
|
||||
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Lab505.Shared\Lab505.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
62
Lab505.Sim/ModbusSimulationHostedService.cs
Normal file
62
Lab505.Sim/ModbusSimulationHostedService.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
/// <summary>
|
||||
/// Hosted service để start/stop các Modbus simulation servers
|
||||
/// Port 502: ASRS
|
||||
/// Port 503: Conveyor
|
||||
/// </summary>
|
||||
public class ModbusSimulationHostedService : IHostedService
|
||||
{
|
||||
private readonly ModbusSimulationServer_ASRS _asrsServer;
|
||||
private readonly ConveyorModbusServer _conveyorServer;
|
||||
private readonly ILogger<ModbusSimulationHostedService> _logger;
|
||||
|
||||
public ModbusSimulationHostedService(ILogger<ModbusSimulationHostedService> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_asrsServer = new ModbusSimulationServer_ASRS(502);
|
||||
_conveyorServer = new ConveyorModbusServer(503);
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Starting Modbus Simulation Servers...");
|
||||
|
||||
try
|
||||
{
|
||||
_asrsServer.Start();
|
||||
_logger.LogInformation("✅ ASRS Modbus Simulation Server started on port 502");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "❌ Failed to start ASRS Modbus server on port 502");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_conveyorServer.Start();
|
||||
_logger.LogInformation("✅ Conveyor Modbus Simulation Server started on port 503");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "❌ Failed to start Conveyor Modbus server on port 503");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Stopping Modbus Simulation Servers...");
|
||||
|
||||
_asrsServer.Stop();
|
||||
_conveyorServer.Stop();
|
||||
|
||||
_logger.LogInformation("✅ All Modbus Simulation Servers stopped");
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
557
Lab505.Sim/ModbusSimulationServer.cs
Normal file
557
Lab505.Sim/ModbusSimulationServer.cs
Normal file
@@ -0,0 +1,557 @@
|
||||
using Lab505.Shared;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
public class ModbusSimulationServer_ASRS : IDisposable
|
||||
{
|
||||
private TcpListener? _listener;
|
||||
private CancellationTokenSource? _cts;
|
||||
private readonly bool[] Coils = new bool[70000];
|
||||
private readonly ushort[] HoldingRegisters = new ushort[70000];
|
||||
private readonly Lock _lock = new();
|
||||
private readonly Dictionary<ushort, CancellationTokenSource> _autoOffMap = [];
|
||||
private bool _isRunning;
|
||||
|
||||
public int Port { get; }
|
||||
public bool IsRunning => _isRunning;
|
||||
|
||||
public ModbusSimulationServer_ASRS(int port = 502) => Port = port;
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
Console.WriteLine($"[ASRS ModbusSim:{Port}] Already running");
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialize safety mode (required for operations)
|
||||
SetCoil((ushort)AsrsCoilAddress.SAFETY_MODE, true);
|
||||
|
||||
// Initialize all trays as FULL by default
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_11, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_12, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_13, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_21, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_22, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_23, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_31, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_32, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_33, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_41, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_42, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_43, true);
|
||||
|
||||
_cts = new CancellationTokenSource();
|
||||
_listener = new TcpListener(IPAddress.Any, Port);
|
||||
_listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
_listener.Start();
|
||||
_isRunning = true;
|
||||
|
||||
Task.Run(async () =>
|
||||
{
|
||||
while (!_cts.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var client = await _listener.AcceptTcpClientAsync(_cts.Token);
|
||||
_ = Task.Run(() => HandleClient(client));
|
||||
}
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch { }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ScheduleAutoOff(ushort addr, int ms = 5000)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_autoOffMap.TryGetValue(addr, out var old))
|
||||
old.Cancel();
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
_autoOffMap[addr] = cts;
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(ms, cts.Token);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[addr] = false;
|
||||
_autoOffMap.Remove(addr);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
Console.WriteLine($"[ASRS ModbusSim:{Port}] Not running");
|
||||
return;
|
||||
}
|
||||
|
||||
_cts?.Cancel();
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
|
||||
try
|
||||
{
|
||||
_listener?.Stop();
|
||||
_listener?.Server?.Close();
|
||||
_listener?.Server?.Dispose();
|
||||
}
|
||||
catch { }
|
||||
_listener = null;
|
||||
|
||||
_isRunning = false;
|
||||
Console.WriteLine($"[ASRS ModbusSim:{Port}] Stopped");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public void SetCoil(ushort addr, bool val)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[addr] = val;
|
||||
|
||||
if (val)
|
||||
{
|
||||
if (IsPulseCoil(addr))
|
||||
{
|
||||
ScheduleAutoOff(addr, 5000);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_autoOffMap.TryGetValue(addr, out var cts))
|
||||
{
|
||||
cts.Cancel();
|
||||
_autoOffMap.Remove(addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void SetCoil(AsrsCoilAddress addr, bool val) => SetCoil((ushort)addr, val);
|
||||
public bool GetCoil(ushort addr) { lock (_lock) return Coils[addr]; }
|
||||
public bool GetCoil(AsrsCoilAddress addr) => GetCoil((ushort)addr);
|
||||
public void SetRegister(ushort addr, ushort val) { lock (_lock) HoldingRegisters[addr] = val; }
|
||||
public ushort GetRegister(ushort addr) { lock (_lock) return HoldingRegisters[addr]; }
|
||||
|
||||
private void HandleClient(TcpClient client)
|
||||
{
|
||||
using var stream = client.GetStream();
|
||||
var buf = new byte[260];
|
||||
|
||||
try
|
||||
{
|
||||
while (client.Connected)
|
||||
{
|
||||
int len = stream.Read(buf, 0, buf.Length);
|
||||
if (len <= 0) break;
|
||||
if (len < 8) continue;
|
||||
|
||||
byte fc = buf[7];
|
||||
byte[] res;
|
||||
|
||||
try
|
||||
{
|
||||
res = fc switch
|
||||
{
|
||||
0x01 => HandleReadCoils(buf),
|
||||
0x02 => HandleReadCoils(buf),
|
||||
0x03 => HandleReadRegisters(buf),
|
||||
0x04 => HandleReadRegisters(buf),
|
||||
0x05 => HandleWriteSingleCoil(buf),
|
||||
0x06 => HandleWriteSingleRegister(buf),
|
||||
0x0F => HandleWriteMultiCoils(buf),
|
||||
0x10 => HandleWriteMultiRegisters(buf),
|
||||
_ => BuildException(buf, 0x01)
|
||||
};
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
res = BuildException(buf, 0x04);
|
||||
}
|
||||
|
||||
stream.Write(res);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[ASRS ModbusSim:{Port}] Client error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] HandleReadCoils(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
int byteCount = (qty + 7) / 8;
|
||||
var payload = new byte[byteCount];
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort addr = (ushort)(start + i);
|
||||
bool value = Coils[addr];
|
||||
|
||||
if (value)
|
||||
payload[i / 8] |= (byte)(1 << (i % 8));
|
||||
}
|
||||
}
|
||||
|
||||
return BuildResponse(req, payload);
|
||||
}
|
||||
|
||||
private byte[] HandleReadRegisters(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
var payload = new byte[qty * 2];
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort val = HoldingRegisters[start + i];
|
||||
payload[i * 2] = (byte)(val >> 8);
|
||||
payload[i * 2 + 1] = (byte)(val & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
return BuildResponse(req, payload);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteSingleCoil(byte[] req)
|
||||
{
|
||||
ushort addr = (ushort)(req[8] << 8 | req[9]);
|
||||
bool val = req[10] == 0xFF;
|
||||
|
||||
SetCoil(addr, val);
|
||||
|
||||
// ASRS TRIGGER HANDLING
|
||||
if (val)
|
||||
{
|
||||
bool mode_S12 = GetCoil((ushort)AsrsCoilAddress.MODE_PICK_EMPTY_BOX_1_2);
|
||||
bool mode_S34 = GetCoil((ushort)AsrsCoilAddress.MODE_PICK_EMPTY_BOX_3_4);
|
||||
bool mode_R12 = GetCoil((ushort)AsrsCoilAddress.MODE_PICK_FROM_CONVEYOR_1_2);
|
||||
bool mode_R43 = GetCoil((ushort)AsrsCoilAddress.MODE_PICK_FROM_CONVEYOR_3_4);
|
||||
|
||||
if (addr == (ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X1)
|
||||
{
|
||||
if (mode_S12) Trigger_X1_S12();
|
||||
if (mode_S34) Trigger_X1_S34();
|
||||
}
|
||||
if (addr == (ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X2)
|
||||
{
|
||||
if (mode_S12) Trigger_X2_S12();
|
||||
if (mode_S34) Trigger_X2_S34();
|
||||
}
|
||||
if (addr == (ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X3)
|
||||
{
|
||||
if (mode_S12) Trigger_X3_S12();
|
||||
if (mode_S34) Trigger_X3_S34();
|
||||
}
|
||||
|
||||
if (addr == (ushort)AsrsCoilAddress.RETURN_TRAY_X1)
|
||||
{
|
||||
if (mode_R12) Trigger_X1_R12();
|
||||
if (mode_R43) Trigger_X1_R43();
|
||||
}
|
||||
if (addr == (ushort)AsrsCoilAddress.RETURN_TRAY_X2)
|
||||
{
|
||||
if (mode_R12) Trigger_X2_R12();
|
||||
if (mode_R43) Trigger_X2_R43();
|
||||
}
|
||||
if (addr == (ushort)AsrsCoilAddress.RETURN_TRAY_X3)
|
||||
{
|
||||
if (mode_R12) Trigger_X3_R12();
|
||||
if (mode_R43) Trigger_X3_R43();
|
||||
}
|
||||
|
||||
// SYSTEM HOMING
|
||||
if (addr == (ushort)AsrsCoilAddress.SYSTEM_HOMING)
|
||||
{
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
SetCoil((ushort)AsrsCoilAddress.SYSTEM_HOMING_SUCCESS, true);
|
||||
});
|
||||
}
|
||||
|
||||
// RESET FULL TRAY ALERTS
|
||||
if (addr == (ushort)AsrsCoilAddress.RESET_FULL_TRAY_ALERT)
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_11, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_12, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_13, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_21, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_22, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_23, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_31, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_32, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_33, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_41, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_42, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_43, false);
|
||||
}
|
||||
}
|
||||
|
||||
return EchoWithCorrectLength(req);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteSingleRegister(byte[] req)
|
||||
{
|
||||
ushort addr = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort val = (ushort)(req[10] << 8 | req[11]);
|
||||
lock (_lock) HoldingRegisters[addr] = val;
|
||||
return EchoWithCorrectLength(req);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteMultiCoils(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
int mask = 1 << (i % 8);
|
||||
int byteIndex = 13 + i / 8;
|
||||
bool val = (req[byteIndex] & mask) != 0;
|
||||
SetCoil((ushort)(start + i), val);
|
||||
}
|
||||
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
Buffer.BlockCopy(req, 8, res, 8, 4);
|
||||
return res;
|
||||
}
|
||||
|
||||
private byte[] HandleWriteMultiRegisters(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort v = (ushort)(req[13 + i * 2] << 8 | req[14 + i * 2]);
|
||||
HoldingRegisters[start + i] = v;
|
||||
}
|
||||
}
|
||||
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
Buffer.BlockCopy(req, 8, res, 8, 4);
|
||||
return res;
|
||||
}
|
||||
|
||||
private byte[] BuildResponse(byte[] req, byte[] data)
|
||||
{
|
||||
byte[] res = new byte[9 + data.Length];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
|
||||
int length = 1 + 1 + 1 + data.Length;
|
||||
res[4] = (byte)(length >> 8);
|
||||
res[5] = (byte)(length & 0xFF);
|
||||
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
res[8] = (byte)data.Length;
|
||||
|
||||
Buffer.BlockCopy(data, 0, res, 9, data.Length);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
private byte[] EchoWithCorrectLength(byte[] req)
|
||||
{
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 12);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
return res;
|
||||
}
|
||||
|
||||
private byte[] BuildException(byte[] req, byte code)
|
||||
{
|
||||
return new byte[]
|
||||
{
|
||||
req[0], req[1],
|
||||
0x00, 0x00,
|
||||
0x00, 0x03,
|
||||
req[6],
|
||||
(byte)(req[7] | 0x80),
|
||||
code
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// PICK OPERATIONS - S12 (Shelf 1-2)
|
||||
// ============================================================
|
||||
private Task Run_X1_S12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_21, false);
|
||||
Console.WriteLine("[ASRS Sim] X1_S12: X21 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_11, false);
|
||||
Console.WriteLine("[ASRS Sim] X1_S12: X11 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X2_S12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_22, false);
|
||||
Console.WriteLine("[ASRS Sim] X2_S12: X22 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_12, false);
|
||||
Console.WriteLine("[ASRS Sim] X2_S12: X12 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X3_S12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_23, false);
|
||||
Console.WriteLine("[ASRS Sim] X3_S12: X23 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_13, false);
|
||||
Console.WriteLine("[ASRS Sim] X3_S12: X13 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// PICK OPERATIONS - S34 (Shelf 3-4)
|
||||
// ============================================================
|
||||
private Task Run_X1_S34() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_41, false);
|
||||
Console.WriteLine("[ASRS Sim] X1_S34: X41 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_31, false);
|
||||
Console.WriteLine("[ASRS Sim] X1_S34: X31 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X2_S34() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_42, false);
|
||||
Console.WriteLine("[ASRS Sim] X2_S34: X42 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_32, false);
|
||||
Console.WriteLine("[ASRS Sim] X2_S34: X32 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X3_S34() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_43, false);
|
||||
Console.WriteLine("[ASRS Sim] X3_S34: X43 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_33, false);
|
||||
Console.WriteLine("[ASRS Sim] X3_S34: X33 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// RETURN OPERATIONS - R12 (Return to Shelf 1-2)
|
||||
// ============================================================
|
||||
private Task Run_X1_R12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_21, true);
|
||||
Console.WriteLine("[ASRS Sim] X1_R12: X21 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_11, true);
|
||||
Console.WriteLine("[ASRS Sim] X1_R12: X11 → FULL (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X2_R12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_22, true);
|
||||
Console.WriteLine("[ASRS Sim] X2_R12: X22 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_12, true);
|
||||
Console.WriteLine("[ASRS Sim] X2_R12: X12 → FULL (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X3_R12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_23, true);
|
||||
Console.WriteLine("[ASRS Sim] X3_R12: X23 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_13, true);
|
||||
Console.WriteLine("[ASRS Sim] X3_R12: X13 → FULL (Complete)");
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// RETURN OPERATIONS - R43 (Return to Shelf 3-4)
|
||||
// ============================================================
|
||||
private Task Run_X1_R43() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_41, true);
|
||||
Console.WriteLine("[ASRS Sim] X1_R43: X41 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_31, true);
|
||||
Console.WriteLine("[ASRS Sim] X1_R43: X31 → FULL (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X2_R43() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_42, true);
|
||||
Console.WriteLine("[ASRS Sim] X2_R43: X42 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_32, true);
|
||||
Console.WriteLine("[ASRS Sim] X2_R43: X32 → FULL (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X3_R43() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_43, true);
|
||||
Console.WriteLine("[ASRS Sim] X3_R43: X43 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_33, true);
|
||||
Console.WriteLine("[ASRS Sim] X3_R43: X33 → FULL (Complete)");
|
||||
});
|
||||
|
||||
public void Trigger_X1_S12() { _ = Run_X1_S12(); }
|
||||
public void Trigger_X2_S12() { _ = Run_X2_S12(); }
|
||||
public void Trigger_X3_S12() { _ = Run_X3_S12(); }
|
||||
public void Trigger_X1_S34() { _ = Run_X1_S34(); }
|
||||
public void Trigger_X2_S34() { _ = Run_X2_S34(); }
|
||||
public void Trigger_X3_S34() { _ = Run_X3_S34(); }
|
||||
public void Trigger_X1_R12() { _ = Run_X1_R12(); }
|
||||
public void Trigger_X2_R12() { _ = Run_X2_R12(); }
|
||||
public void Trigger_X3_R12() { _ = Run_X3_R12(); }
|
||||
public void Trigger_X1_R43() { _ = Run_X1_R43(); }
|
||||
public void Trigger_X2_R43() { _ = Run_X2_R43(); }
|
||||
public void Trigger_X3_R43() { _ = Run_X3_R43(); }
|
||||
|
||||
private bool IsPulseCoil(ushort addr) => addr switch
|
||||
{
|
||||
(ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X1 => true,
|
||||
(ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X2 => true,
|
||||
(ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X3 => true,
|
||||
(ushort)AsrsCoilAddress.RETURN_TRAY_X1 => true,
|
||||
(ushort)AsrsCoilAddress.RETURN_TRAY_X2 => true,
|
||||
(ushort)AsrsCoilAddress.RETURN_TRAY_X3 => true,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
38
Lab505.Sim/OpcUaHostedService.cs
Normal file
38
Lab505.Sim/OpcUaHostedService.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
public class OpcUaHostedService : IHostedService
|
||||
{
|
||||
private readonly OpcUaSimulationServer _server;
|
||||
private readonly ILogger<OpcUaHostedService> _logger;
|
||||
|
||||
public OpcUaHostedService(
|
||||
OpcUaSimulationServer server,
|
||||
ILogger<OpcUaHostedService> logger)
|
||||
{
|
||||
_server = server;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Starting OPC UA Simulation Server on port 4840");
|
||||
try
|
||||
{
|
||||
await _server.StartAsync();
|
||||
_logger.LogInformation("OPC UA Simulation Server started on port 4840");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning("OPC UA Simulation Server failed to start (port 4840 may already be in use): {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Stopping OPC UA Simulation Server");
|
||||
await _server.StopAsync();
|
||||
}
|
||||
}
|
||||
104
Lab505.Sim/OpcUaSimulationServer.cs
Normal file
104
Lab505.Sim/OpcUaSimulationServer.cs
Normal file
@@ -0,0 +1,104 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Configuration;
|
||||
using Opc.Ua.Server;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
public class OpcUaSimulationServer : IDisposable
|
||||
{
|
||||
private ApplicationInstance? _app;
|
||||
private bool _isRunning;
|
||||
private readonly object _lock = new();
|
||||
|
||||
public bool IsRunning
|
||||
{
|
||||
get { lock (_lock) return _isRunning; }
|
||||
}
|
||||
|
||||
public async Task StartAsync()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
Console.WriteLine("[OpcUaSim:4840] Already running");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning disable CS0618
|
||||
_app = new ApplicationInstance
|
||||
{
|
||||
ApplicationName = "Lab505OpcUaSim",
|
||||
ApplicationType = ApplicationType.Server,
|
||||
ConfigSectionName = "OpcUaClient"
|
||||
};
|
||||
#pragma warning restore CS0618
|
||||
|
||||
// Load XML
|
||||
await _app.LoadApplicationConfigurationAsync("Quickstarts.ReferenceServer.Config.xml", false);
|
||||
|
||||
// Không cần certificate khi security = None
|
||||
await _app.CheckApplicationInstanceCertificatesAsync(silent: true);
|
||||
|
||||
// Start server custom
|
||||
await _app.StartAsync(new SimulationServer());
|
||||
|
||||
lock (_lock) _isRunning = true;
|
||||
Console.WriteLine("[OpcUaSim:4840] Server started");
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
Console.WriteLine("[OpcUaSim:4840] Not running");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_app != null)
|
||||
{
|
||||
await _app.StopAsync();
|
||||
|
||||
// Give the server time to fully release the port
|
||||
await Task.Delay(500);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[OpcUaSim:4840] Error stopping: {ex.Message}");
|
||||
}
|
||||
|
||||
_app = null;
|
||||
lock (_lock) _isRunning = false;
|
||||
Console.WriteLine("[OpcUaSim:4840] Server stopped");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
StopAsync().GetAwaiter().GetResult();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
|
||||
public class SimulationServer : StandardServer
|
||||
{
|
||||
protected override MasterNodeManager CreateMasterNodeManager(
|
||||
IServerInternal server,
|
||||
ApplicationConfiguration config)
|
||||
{
|
||||
return new MasterNodeManager(
|
||||
server,
|
||||
config,
|
||||
null,
|
||||
[
|
||||
new RcsNodeManager(server, config)
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
34
Lab505.Sim/Program.cs
Normal file
34
Lab505.Sim/Program.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
Console.WriteLine("=== Lab505 WAS Simulators ===");
|
||||
Console.WriteLine("Starting VDA5050 API Simulator...\n");
|
||||
|
||||
var builder = Host.CreateApplicationBuilder(args);
|
||||
|
||||
// Add logging
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.AddConsole();
|
||||
builder.Logging.SetMinimumLevel(LogLevel.Information);
|
||||
|
||||
// Register simulator
|
||||
|
||||
var host = builder.Build();
|
||||
|
||||
// Wait for cancellation
|
||||
var cts = new CancellationTokenSource();
|
||||
Console.CancelKeyPress += (s, e) =>
|
||||
{
|
||||
e.Cancel = true;
|
||||
cts.Cancel();
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, cts.Token);
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
Console.WriteLine("\nShutting down...");
|
||||
}
|
||||
1005
Lab505.Sim/RcsNodeManager.cs
Normal file
1005
Lab505.Sim/RcsNodeManager.cs
Normal file
File diff suppressed because it is too large
Load Diff
157
Lab505.Sim/SimulationManager.cs
Normal file
157
Lab505.Sim/SimulationManager.cs
Normal file
@@ -0,0 +1,157 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
/// <summary>
|
||||
/// Quản lý tất cả simulation services - có thể start/stop tại runtime
|
||||
/// </summary>
|
||||
public interface ISimulationManager
|
||||
{
|
||||
bool IsRunning { get; }
|
||||
Task StartAllAsync();
|
||||
Task StopAllAsync();
|
||||
}
|
||||
|
||||
public class SimulationManager : ISimulationManager
|
||||
{
|
||||
private readonly ILogger<SimulationManager> _logger;
|
||||
private readonly VdaSimulationHostedService? _vdaServer;
|
||||
private readonly OpcUaSimulationServer? _opcUaServer;
|
||||
private readonly ModbusSimulationServer_ASRS? _asrsServer;
|
||||
private readonly ConveyorModbusServer? _conveyorServer;
|
||||
|
||||
private bool _isRunning;
|
||||
private readonly object _lock = new();
|
||||
|
||||
public bool IsRunning
|
||||
{
|
||||
get { lock (_lock) return _isRunning; }
|
||||
}
|
||||
|
||||
public SimulationManager(
|
||||
ILogger<SimulationManager> logger,
|
||||
VdaSimulationHostedService? vdaServer = null,
|
||||
OpcUaSimulationServer? opcUaServer = null,
|
||||
ModbusSimulationServer_ASRS? asrsServer = null,
|
||||
ConveyorModbusServer? conveyorServer = null)
|
||||
{
|
||||
_logger = logger;
|
||||
_vdaServer = vdaServer;
|
||||
_opcUaServer = opcUaServer;
|
||||
_asrsServer = asrsServer;
|
||||
_conveyorServer = conveyorServer;
|
||||
}
|
||||
|
||||
public async Task StartAllAsync()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
_logger.LogWarning("Simulation services already running");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("Starting all simulation services...");
|
||||
|
||||
try
|
||||
{
|
||||
// Start Modbus servers
|
||||
if (_asrsServer != null)
|
||||
{
|
||||
_asrsServer.Start();
|
||||
_logger.LogInformation("✅ ASRS Modbus Simulation Server started");
|
||||
}
|
||||
|
||||
if (_conveyorServer != null)
|
||||
{
|
||||
_conveyorServer.Start();
|
||||
_logger.LogInformation("✅ Conveyor Modbus Simulation Server started");
|
||||
}
|
||||
|
||||
// Start OPC UA server
|
||||
if (_opcUaServer != null)
|
||||
{
|
||||
await _opcUaServer.StartAsync();
|
||||
_logger.LogInformation("✅ OPC UA Simulation Server started");
|
||||
}
|
||||
|
||||
// Start VDA server
|
||||
if (_vdaServer != null)
|
||||
{
|
||||
_vdaServer.Start();
|
||||
_logger.LogInformation("✅ VDA Mock Server started");
|
||||
}
|
||||
|
||||
lock (_lock) _isRunning = true;
|
||||
_logger.LogInformation("All simulation services started successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to start simulation services");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StopAllAsync()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
_logger.LogWarning("Simulation services not running");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("Stopping all simulation services...");
|
||||
|
||||
try
|
||||
{
|
||||
// Stop VDA server
|
||||
if (_vdaServer != null)
|
||||
{
|
||||
_vdaServer.Stop();
|
||||
_logger.LogInformation("✅ VDA Mock Server stopped");
|
||||
}
|
||||
|
||||
// Stop OPC UA server
|
||||
if (_opcUaServer != null)
|
||||
{
|
||||
await _opcUaServer.StopAsync();
|
||||
_logger.LogInformation("✅ OPC UA Simulation Server stopped");
|
||||
}
|
||||
|
||||
// Stop Modbus servers
|
||||
if (_conveyorServer != null)
|
||||
{
|
||||
_conveyorServer.Stop();
|
||||
_logger.LogInformation("✅ Conveyor Modbus Simulation Server stopped");
|
||||
}
|
||||
|
||||
if (_asrsServer != null)
|
||||
{
|
||||
_asrsServer.Stop();
|
||||
_logger.LogInformation("✅ ASRS Modbus Simulation Server stopped");
|
||||
}
|
||||
|
||||
lock (_lock) _isRunning = false;
|
||||
_logger.LogInformation("All simulation services stopped successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error stopping simulation services");
|
||||
lock (_lock) _isRunning = false;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stub dùng khi tắt toàn bộ simulation servers.</summary>
|
||||
public class NullSimulationManager : ISimulationManager
|
||||
{
|
||||
public bool IsRunning => false;
|
||||
public Task StartAllAsync() => Task.CompletedTask;
|
||||
public Task StopAllAsync() => Task.CompletedTask;
|
||||
}
|
||||
632
Lab505.Sim/VdaSimulationHostedService.cs
Normal file
632
Lab505.Sim/VdaSimulationHostedService.cs
Normal file
@@ -0,0 +1,632 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using static Lab505.Shared.RobotPositions;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
/// <summary>
|
||||
/// Mock HTTP Server mô phỏng VDA5050 API
|
||||
/// </summary>
|
||||
public class VdaSimulationHostedService : IHostedService, IDisposable
|
||||
{
|
||||
private HttpListener? _listener;
|
||||
private readonly ILogger<VdaSimulationHostedService> _logger;
|
||||
private readonly Dictionary<string, RobotState> _robots;
|
||||
private readonly JsonSerializerOptions _jsonOptions;
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _serverTask;
|
||||
private readonly int _port;
|
||||
private bool _isRunning;
|
||||
|
||||
public bool IsRunning => _isRunning;
|
||||
|
||||
public VdaSimulationHostedService(ILogger<VdaSimulationHostedService> logger, int port = 7333)
|
||||
{
|
||||
_logger = logger;
|
||||
_port = port;
|
||||
|
||||
_jsonOptions = new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
// Initialize mock robots with their default positions
|
||||
_robots = new Dictionary<string, RobotState>
|
||||
{
|
||||
["AMR2WS"] = new RobotState
|
||||
{
|
||||
RobotId = "AMR2WS",
|
||||
X = AMR_CAP2_X,
|
||||
Y = AMR_CAP2_Y,
|
||||
Theta = 0,
|
||||
IsOnline = true,
|
||||
NewBaseRequest = true
|
||||
},
|
||||
["IMR"] = new RobotState
|
||||
{
|
||||
RobotId = "IMR",
|
||||
X = IMR_C1_X,
|
||||
Y = IMR_C1_Y,
|
||||
Theta = 0,
|
||||
IsOnline = true,
|
||||
NewBaseRequest = true
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken) { Start(); return Task.CompletedTask; }
|
||||
public Task StopAsync(CancellationToken cancellationToken) { Stop(); return Task.CompletedTask; }
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
_logger.LogWarning("VDA Mock Server already running");
|
||||
return;
|
||||
}
|
||||
|
||||
_listener = new HttpListener();
|
||||
_listener.Prefixes.Add($"http://127.0.0.1:{_port}/");
|
||||
_listener.Start();
|
||||
_cts = new CancellationTokenSource();
|
||||
_serverTask = Task.Run(() => HandleRequestsAsync(_cts.Token));
|
||||
_isRunning = true;
|
||||
_logger.LogInformation("VDA Mock Server started on {Prefixes}",
|
||||
string.Join(", ", _listener.Prefixes));
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
_logger.LogWarning("VDA Mock Server not running");
|
||||
return;
|
||||
}
|
||||
|
||||
_cts?.Cancel();
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
|
||||
_serverTask?.Wait(TimeSpan.FromSeconds(5));
|
||||
_serverTask = null;
|
||||
|
||||
try
|
||||
{
|
||||
_listener?.Stop();
|
||||
_listener?.Close();
|
||||
}
|
||||
catch { }
|
||||
_listener = null;
|
||||
|
||||
_isRunning = false;
|
||||
_logger.LogInformation("VDA Mock Server stopped");
|
||||
}
|
||||
|
||||
private async Task HandleRequestsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested && _listener != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var context = await _listener.GetContextAsync();
|
||||
_ = Task.Run(() => ProcessRequestAsync(context), cancellationToken);
|
||||
}
|
||||
catch (HttpListenerException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!cancellationToken.IsCancellationRequested)
|
||||
_logger.LogError(ex, "Error accepting request");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ProcessRequestAsync(HttpListenerContext context)
|
||||
{
|
||||
var request = context.Request;
|
||||
var response = context.Response;
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogDebug("{Method} {Url}", request.HttpMethod, request.Url?.PathAndQuery);
|
||||
|
||||
var path = request.Url?.AbsolutePath ?? "";
|
||||
var method = request.HttpMethod;
|
||||
|
||||
object? result = null;
|
||||
|
||||
// Route handling
|
||||
if (method == "GET" && path.StartsWith("/api/robotmanager/State/"))
|
||||
{
|
||||
var robotId = path.Split('/').Last();
|
||||
result = HandleGetState(robotId);
|
||||
}
|
||||
else if (method == "POST" && path == "/api/AWC200/MoveTo")
|
||||
{
|
||||
var body = await ReadRequestBodyAsync(request);
|
||||
result = await HandleMoveToAsync(body);
|
||||
}
|
||||
else if (method == "POST" && path == "/api/robotmanager/instantactions")
|
||||
{
|
||||
var body = await ReadRequestBodyAsync(request);
|
||||
result = await HandleInstantActionAsync(body);
|
||||
}
|
||||
else if (method == "DELETE" && path.StartsWith("/api/AWC200/MoveTo/"))
|
||||
{
|
||||
var robotId = path.Split('/').Last();
|
||||
result = HandleCancel(robotId);
|
||||
}
|
||||
else
|
||||
{
|
||||
response.StatusCode = 404;
|
||||
result = new { error = "Endpoint not found" };
|
||||
}
|
||||
|
||||
// Send response
|
||||
if (result != null)
|
||||
{
|
||||
response.ContentType = "application/json";
|
||||
response.StatusCode = response.StatusCode == 0 ? 200 : response.StatusCode;
|
||||
|
||||
var json = JsonSerializer.Serialize(result, _jsonOptions);
|
||||
var buffer = Encoding.UTF8.GetBytes(json);
|
||||
|
||||
response.ContentLength64 = buffer.Length;
|
||||
await response.OutputStream.WriteAsync(buffer);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error processing request");
|
||||
response.StatusCode = 500;
|
||||
|
||||
var error = new { error = ex.Message };
|
||||
var json = JsonSerializer.Serialize(error, _jsonOptions);
|
||||
var buffer = Encoding.UTF8.GetBytes(json);
|
||||
|
||||
response.ContentLength64 = buffer.Length;
|
||||
await response.OutputStream.WriteAsync(buffer);
|
||||
}
|
||||
finally
|
||||
{
|
||||
response.Close();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> ReadRequestBodyAsync(HttpListenerRequest request)
|
||||
{
|
||||
using var reader = new StreamReader(request.InputStream, request.ContentEncoding);
|
||||
return await reader.ReadToEndAsync();
|
||||
}
|
||||
|
||||
#region Handlers
|
||||
|
||||
private object HandleGetState(string robotId)
|
||||
{
|
||||
if (!_robots.TryGetValue(robotId, out var state))
|
||||
{
|
||||
return new ApiResult
|
||||
{
|
||||
IsSuccess = false,
|
||||
Message = $"Robot {robotId} not found"
|
||||
};
|
||||
}
|
||||
|
||||
// Snapshot dưới lock — tránh "Collection was modified" khi task nền Add/Remove
|
||||
// đúng lúc poller đọc state.
|
||||
VdaActionState[] actionStatesSnapshot;
|
||||
lock (state.ActionStates)
|
||||
actionStatesSnapshot = state.ActionStates.ToArray();
|
||||
|
||||
return new RobotStateResult
|
||||
{
|
||||
IsSuccess = true,
|
||||
Message = "OK",
|
||||
Data = new RobotStateData
|
||||
{
|
||||
RobotId = robotId,
|
||||
MapId = Guid.NewGuid(),
|
||||
IsOnline = state.IsOnline,
|
||||
State = "READY",
|
||||
StateMsg = new VdaStateMsg
|
||||
{
|
||||
HeaderId = (uint)DateTime.UtcNow.Ticks,
|
||||
Timestamp = DateTime.UtcNow.ToString("o"),
|
||||
Version = "2.0",
|
||||
Manufacturer = "MockManufacturer",
|
||||
SerialNumber = robotId,
|
||||
OrderId = state.CurrentOrderId,
|
||||
OrderUpdateId = state.OrderUpdateId,
|
||||
LastNodeId = state.LastNodeId,
|
||||
LastNodeSequenceId = 0,
|
||||
Driving = state.IsDriving,
|
||||
Paused = state.Paused,
|
||||
NewBaseRequest = state.NewBaseRequest,
|
||||
DistanceSinceLastNode = 0,
|
||||
OperatingMode = "AUTOMATIC",
|
||||
AgvPosition = new VdaAgvPosition
|
||||
{
|
||||
X = state.X,
|
||||
Y = state.Y,
|
||||
Theta = state.Theta,
|
||||
MapId = "map001",
|
||||
PositionInitialized = true
|
||||
},
|
||||
ActionStates = actionStatesSnapshot,
|
||||
Errors = []
|
||||
},
|
||||
VisualizationMsg = new VdaVisualizationMsg
|
||||
{
|
||||
HeaderId = (uint)DateTime.UtcNow.Ticks,
|
||||
Timestamp = DateTime.UtcNow.ToString("o"),
|
||||
Version = "2.0",
|
||||
Manufacturer = "MockManufacturer",
|
||||
SerialNumber = robotId,
|
||||
AgvPosition = new VdaAgvPosition
|
||||
{
|
||||
X = state.X,
|
||||
Y = state.Y,
|
||||
Theta = state.Theta,
|
||||
MapId = "map001",
|
||||
PositionInitialized = true
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<object> HandleMoveToAsync(string requestBody)
|
||||
{
|
||||
var request = JsonSerializer.Deserialize<MoveToRequest>(requestBody, _jsonOptions);
|
||||
|
||||
if (request == null || string.IsNullOrEmpty(request.RobotId))
|
||||
{
|
||||
return new ApiResult { IsSuccess = false, Message = "Invalid request" };
|
||||
}
|
||||
|
||||
if (!_robots.TryGetValue(request.RobotId, out var state))
|
||||
{
|
||||
return new ApiResult { IsSuccess = false, Message = $"Robot {request.RobotId} not found" };
|
||||
}
|
||||
|
||||
_logger.LogInformation("Mock: Moving {RobotId} to {Target}", request.RobotId, request.RoomName);
|
||||
|
||||
// VDA5050: NewBaseRequest = false when movement starts (robot busy)
|
||||
state.NewBaseRequest = false;
|
||||
state.CurrentOrderId = Guid.NewGuid().ToString();
|
||||
state.OrderUpdateId++;
|
||||
state.LastNodeId = request.RoomName;
|
||||
state.IsDriving = true;
|
||||
|
||||
// Simulate movement (~3s total)
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
// Get target position from robot-specific predefined locations
|
||||
var (targetX, targetY) = GetLocationCoordinates(request.RoomName, request.RobotId);
|
||||
|
||||
// Simulate gradual movement over ~10 seconds
|
||||
var steps = 100;
|
||||
for (int i = 0; i < steps; i++)
|
||||
{
|
||||
await Task.Delay(100); // 100 x 100ms = 10s
|
||||
|
||||
// Pause (startPause): đóng băng vị trí, không tiến bước cho tới khi resume.
|
||||
// Thoát nếu bị cancel (HandleCancel đặt IsDriving=false / Paused=false).
|
||||
while (state.Paused && state.IsDriving)
|
||||
await Task.Delay(100);
|
||||
|
||||
// Cancel: dừng tại chỗ, không snap tới đích (HandleCancel đã set NBR=true).
|
||||
if (!state.IsDriving)
|
||||
return;
|
||||
|
||||
state.X = state.X + (targetX - state.X) / (steps - i);
|
||||
state.Y = state.Y + (targetY - state.Y) / (steps - i);
|
||||
}
|
||||
|
||||
state.X = targetX;
|
||||
state.Y = targetY;
|
||||
state.IsDriving = false;
|
||||
|
||||
// VDA5050: NewBaseRequest = true when movement complete (robot ready)
|
||||
state.NewBaseRequest = true;
|
||||
|
||||
_logger.LogInformation("Mock: {RobotId} arrived at {Target} ({X}, {Y}), NewBaseRequest=true",
|
||||
request.RobotId, request.RoomName, targetX, targetY);
|
||||
});
|
||||
|
||||
return new ApiResult { IsSuccess = true, Message = "MoveTo command accepted" };
|
||||
}
|
||||
|
||||
private async Task<object> HandleInstantActionAsync(string requestBody)
|
||||
{
|
||||
var request = JsonSerializer.Deserialize<InstantActionRequest>(requestBody, _jsonOptions);
|
||||
|
||||
if (request == null || string.IsNullOrEmpty(request.RobotId) || request.Action == null)
|
||||
{
|
||||
return new ApiResult { IsSuccess = false, Message = "Invalid request" };
|
||||
}
|
||||
|
||||
if (!_robots.TryGetValue(request.RobotId, out var state))
|
||||
{
|
||||
return new ApiResult { IsSuccess = false, Message = $"Robot {request.RobotId} not found" };
|
||||
}
|
||||
|
||||
var action = request.Action;
|
||||
_logger.LogInformation("Mock: {RobotId} executing {ActionType}", request.RobotId, action.ActionType);
|
||||
|
||||
// VDA5050: NewBaseRequest stays TRUE during WAITING and INITIALIZING.
|
||||
// Only movement-type actions (UnDockFromStation) set it FALSE during RUNNING.
|
||||
// Station-type actions (Load, UnLoad, DockToStation, PickUp, MutedSafety) keep it TRUE.
|
||||
|
||||
// Movement actions: robot physically moves → blocks new base requests during RUNNING
|
||||
static bool IsMovementAction(string actionType) => actionType is
|
||||
"UnDockFromStation" or "UndockFromStation";
|
||||
|
||||
var actionState = new VdaActionState
|
||||
{
|
||||
ActionID = action.ActionId,
|
||||
ActionType = action.ActionType,
|
||||
ActionDescription = action.ActionDescription,
|
||||
ActionStatus = "WAITING"
|
||||
};
|
||||
|
||||
lock (state.ActionStates)
|
||||
state.ActionStates.Add(actionState);
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(200);
|
||||
actionState.ActionStatus = "INITIALIZING";
|
||||
// NewBaseRequest still TRUE here — robot is preparing but not yet blocking
|
||||
|
||||
await Task.Delay(300);
|
||||
actionState.ActionStatus = "RUNNING";
|
||||
|
||||
// Only movement actions set NewBaseRequest = false during RUNNING
|
||||
if (IsMovementAction(action.ActionType))
|
||||
state.NewBaseRequest = false;
|
||||
|
||||
switch (action.ActionType)
|
||||
{
|
||||
case "UnDockFromStation":
|
||||
case "UndockFromStation":
|
||||
// IMR: dùng distance param (lùi theo trục X, Theta=0)
|
||||
// AMR: dùng vị trí undock được định nghĩa sẵn theo trạm đang đậu
|
||||
// (tránh sai hướng do Theta=0 cố định trong sim)
|
||||
if (request.RobotId == "IMR")
|
||||
{
|
||||
var distance = GetActionParameter(action, "distance", -0.5);
|
||||
state.X += distance * Math.Cos(state.Theta);
|
||||
state.Y += distance * Math.Sin(state.Theta);
|
||||
}
|
||||
else // AMR
|
||||
{
|
||||
if (Math.Abs(state.X - AMR_CAP1_X) < POS_TOL && Math.Abs(state.Y - AMR_CAP1_Y) < POS_TOL)
|
||||
{ state.X = AMR_UNDOCK_CAP1_X; state.Y = AMR_UNDOCK_CAP1_Y; }
|
||||
else if (Math.Abs(state.X - AMR_CAP2_X) < POS_TOL && Math.Abs(state.Y - AMR_CAP2_Y) < POS_TOL)
|
||||
{ state.X = AMR_UNDOCK_CAP2_X; state.Y = AMR_UNDOCK_CAP2_Y; }
|
||||
else
|
||||
{
|
||||
// Vị trí không xác định — fallback theta-based
|
||||
var distance = GetActionParameter(action, "distance", -0.5);
|
||||
state.X += distance * Math.Cos(state.Theta);
|
||||
state.Y += distance * Math.Sin(state.Theta);
|
||||
}
|
||||
}
|
||||
await Task.Delay(9500);
|
||||
break;
|
||||
|
||||
case "DockToStation":
|
||||
// Robot drives forward by 'distance' meters (reverse of undock)
|
||||
var dockDist = GetActionParameter(action, "distance", 1.2);
|
||||
state.X += dockDist * Math.Cos(state.Theta);
|
||||
state.Y += dockDist * Math.Sin(state.Theta);
|
||||
await Task.Delay(9500);
|
||||
break;
|
||||
|
||||
case "startPause":
|
||||
// Robot tạm dừng — đặt cờ Paused, hoàn thành nhanh
|
||||
state.Paused = true;
|
||||
await Task.Delay(200);
|
||||
break;
|
||||
|
||||
case "stopPause":
|
||||
// Robot tiếp tục — bỏ cờ Paused, hoàn thành nhanh
|
||||
state.Paused = false;
|
||||
await Task.Delay(200);
|
||||
break;
|
||||
|
||||
case "initPosition":
|
||||
// Đặt lại pose (x, y, theta) tức thì
|
||||
state.X = GetActionParameter(action, "x", state.X);
|
||||
state.Y = GetActionParameter(action, "y", state.Y);
|
||||
state.Theta = GetActionParameter(action, "theta", state.Theta);
|
||||
await Task.Delay(200);
|
||||
break;
|
||||
|
||||
case "Load":
|
||||
case "UpLoad":
|
||||
case "UnLoad":
|
||||
case "PickUp":
|
||||
case "MutedSafety":
|
||||
case "Muted Safety":
|
||||
case "MuteOn":
|
||||
case "MuteOff":
|
||||
// Station actions — robot stays put, NewBaseRequest stays TRUE
|
||||
await Task.Delay(9500);
|
||||
break;
|
||||
|
||||
default:
|
||||
await Task.Delay(9500);
|
||||
break;
|
||||
}
|
||||
|
||||
actionState.ActionStatus = "FINISHED";
|
||||
state.NewBaseRequest = true;
|
||||
|
||||
_logger.LogInformation(
|
||||
"Mock: {RobotId} {ActionType} FINISHED, NewBaseRequest=true",
|
||||
request.RobotId, action.ActionType);
|
||||
|
||||
// Keep FINISHED state long enough for the 300 ms VDA poller to catch it
|
||||
await Task.Delay(5000);
|
||||
lock (state.ActionStates)
|
||||
state.ActionStates.Remove(actionState);
|
||||
});
|
||||
|
||||
return new ApiResult { IsSuccess = true, Message = $"{action.ActionType} command accepted" };
|
||||
}
|
||||
|
||||
private object HandleCancel(string robotId)
|
||||
{
|
||||
if (!_robots.TryGetValue(robotId, out var state))
|
||||
return new ApiResult { IsSuccess = false, Message = $"Robot {robotId} not found" };
|
||||
|
||||
_logger.LogInformation("Mock: Canceling order for {RobotId}", robotId);
|
||||
|
||||
// VDA5050: chuyển tất cả action đang active → ABORTED
|
||||
// DualCommandMonitor đang chờ sẽ nhận được ABORTED trong lần poll tiếp theo (~300ms)
|
||||
lock (state.ActionStates)
|
||||
{
|
||||
foreach (var a in state.ActionStates)
|
||||
{
|
||||
if (a.ActionStatus is "WAITING" or "INITIALIZING" or "RUNNING")
|
||||
a.ActionStatus = "ABORTED";
|
||||
}
|
||||
}
|
||||
|
||||
state.IsDriving = false;
|
||||
state.CurrentOrderId = null;
|
||||
state.NewBaseRequest = true;
|
||||
state.Paused = false; // hủy lệnh thì bỏ luôn trạng thái pause
|
||||
|
||||
// Xóa action ABORTED sau 2s — đủ để VDA poller (300ms) đọc được vài lần
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(2000);
|
||||
lock (state.ActionStates)
|
||||
state.ActionStates.RemoveAll(a => a.ActionStatus == "ABORTED");
|
||||
});
|
||||
|
||||
return new ApiResult { IsSuccess = true, Message = "Order cancelled" };
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Helpers
|
||||
|
||||
/// <summary>
|
||||
/// AMR specific positions — must match FlowService constants
|
||||
/// AMR_CAP1_X=6.0, AMR_CAP1_Y=0.23 | AMR_CAP2_X=-0.7, AMR_CAP2_Y=-3.19
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, (double X, double Y)> AmrLocations = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Cap1"] = (AMR_CAP1_X, AMR_CAP1_Y),
|
||||
["Cap2"] = (AMR_CAP2_X, AMR_CAP2_Y),
|
||||
["Home"] = (0.0, 0.0)
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, (double X, double Y)> ImrLocations = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Bt1"] = (IMR_C1_X, IMR_C1_Y),
|
||||
["BT1"] = (IMR_C1_X, IMR_C1_Y),
|
||||
["Abb"] = (IMR_ABB_X, IMR_ABB_Y),
|
||||
["ABB"] = (IMR_ABB_X, IMR_ABB_Y),
|
||||
["Home"] = (0.0, 0.0),
|
||||
["HOME"] = (0.0, 0.0)
|
||||
};
|
||||
|
||||
private (double X, double Y) GetLocationCoordinates(string locationName, string? robotId = null)
|
||||
{
|
||||
// Try robot-specific locations first
|
||||
if (!string.IsNullOrEmpty(robotId))
|
||||
{
|
||||
if (robotId.Equals("AMR2WS", StringComparison.OrdinalIgnoreCase) ||
|
||||
robotId.StartsWith("AMR", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (AmrLocations.TryGetValue(locationName, out var amrCoords))
|
||||
return amrCoords;
|
||||
}
|
||||
else if (robotId.Equals("IMR", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (ImrLocations.TryGetValue(locationName, out var imrCoords))
|
||||
return imrCoords;
|
||||
}
|
||||
}
|
||||
|
||||
// Try AMR locations (case insensitive)
|
||||
if (AmrLocations.TryGetValue(locationName, out var coords))
|
||||
return coords;
|
||||
|
||||
// Try IMR locations (case insensitive)
|
||||
if (ImrLocations.TryGetValue(locationName, out coords))
|
||||
return coords;
|
||||
|
||||
// Default to (0, 0) for unknown locations
|
||||
_logger.LogWarning("Unknown location '{Location}' for robot '{RobotId}', defaulting to (0,0)", locationName, robotId);
|
||||
return (0, 0);
|
||||
}
|
||||
|
||||
private double GetActionParameter(VdaInstantAction action, string key, double defaultValue)
|
||||
{
|
||||
var param = action.ActionParameters?.FirstOrDefault(p => p.Key == key);
|
||||
// VDA5050 dùng dấu chấm thập phân — parse InvariantCulture để khớp với driver,
|
||||
// không phụ thuộc locale máy chạy sim.
|
||||
if (param != null && double.TryParse(param.Value,
|
||||
NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
|
||||
return value;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
_cts?.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
|
||||
#region Mock Models
|
||||
|
||||
internal class RobotState
|
||||
{
|
||||
public string RobotId { get; set; } = string.Empty;
|
||||
public double X { get; set; }
|
||||
public double Y { get; set; }
|
||||
public double Theta { get; set; }
|
||||
public bool IsOnline { get; set; }
|
||||
public bool NewBaseRequest { get; set; }
|
||||
public bool IsDriving { get; set; }
|
||||
public bool Paused { get; set; }
|
||||
public string? CurrentOrderId { get; set; }
|
||||
public int OrderUpdateId { get; set; }
|
||||
public string? LastNodeId { get; set; }
|
||||
public List<VdaActionState> ActionStates { get; set; } = new();
|
||||
}
|
||||
|
||||
internal class MoveToRequest
|
||||
{
|
||||
public string RobotId { get; set; } = string.Empty;
|
||||
public string RoomName { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
internal class InstantActionRequest
|
||||
{
|
||||
public string RobotId { get; set; } = string.Empty;
|
||||
public VdaInstantAction? Action { get; set; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
53
Lab505.Sim/VdaSimulationServer.cs
Normal file
53
Lab505.Sim/VdaSimulationServer.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
/// <summary>
|
||||
/// Hosted Service để chạy VDA Mock Server ở background
|
||||
/// </summary>
|
||||
public class VdaSimulationServer : IHostedService
|
||||
{
|
||||
private readonly VdaSimulationHostedService _server;
|
||||
private readonly ILogger<VdaSimulationServer> _logger;
|
||||
|
||||
public VdaSimulationServer(
|
||||
VdaSimulationHostedService server,
|
||||
ILogger<VdaSimulationServer> logger)
|
||||
{
|
||||
_server = server ?? throw new ArgumentNullException(nameof(server));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Starting VDA Simulation Hosted Service");
|
||||
_server.Start();
|
||||
_logger.LogInformation("VDA Simulation Hosted Service started successfully");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to start VDA Simulation Hosted Service");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Stopping VDA Simulation Hosted Service");
|
||||
_server.Stop();
|
||||
_logger.LogInformation("VDA Simulation Hosted Service stopped successfully");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error stopping VDA Simulation Hosted Service");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
93
Lab505.sln
Normal file
93
Lab505.sln
Normal file
@@ -0,0 +1,93 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 18
|
||||
VisualStudioVersion = 18.0.11205.157
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lab505", "Lab505\Lab505.csproj", "{356C86AB-A964-48C0-8D31-7C41F051D6FB}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lab505.Sim", "Lab505.Sim\Lab505.Sim.csproj", "{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lab505.Shared", "Lab505.Shared\Lab505.Shared.csproj", "{B2C3D4E5-F6A7-8901-BCDE-F12345678901}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lab505.Script", "Lab505.Script\Lab505.Script.csproj", "{DD385C97-28CF-4D6C-9629-C23823DBAAC8}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lab505.Client", "Lab505.Client\Lab505.Client.csproj", "{E3875B58-A8C3-451B-B049-D91D8D98DDD6}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Release|x64.Build.0 = Release|Any CPU
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{356C86AB-A964-48C0-8D31-7C41F051D6FB}.Release|x86.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|x64.Build.0 = Release|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|x86.Build.0 = Release|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Release|x64.Build.0 = Release|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Release|x86.Build.0 = Release|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Release|x64.Build.0 = Release|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{DD385C97-28CF-4D6C-9629-C23823DBAAC8}.Release|x86.Build.0 = Release|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Release|x64.Build.0 = Release|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{E3875B58-A8C3-451B-B049-D91D8D98DDD6}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {C221CEF9-DB4A-4206-B5BF-4AC9B59DBC14}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
13
Lab505/.config/dotnet-tools.json
Normal file
13
Lab505/.config/dotnet-tools.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"dotnet-ef": {
|
||||
"version": "10.0.0",
|
||||
"commands": [
|
||||
"dotnet-ef"
|
||||
],
|
||||
"rollForward": false
|
||||
}
|
||||
}
|
||||
}
|
||||
121
Lab505/Application/Condition/AmrCommandGuard.cs
Normal file
121
Lab505/Application/Condition/AmrCommandGuard.cs
Normal file
@@ -0,0 +1,121 @@
|
||||
using Lab505.Application.Condition;
|
||||
using Lab505.Domain.Entities;
|
||||
|
||||
namespace Lab505.Infrastructure.Drivers.Amr;
|
||||
|
||||
/// <summary>
|
||||
/// Guard kiểm tra điều kiện TẠI THỜI ĐIỂM gọi trước khi cho phép gửi lệnh xuống AMR.
|
||||
/// Throw InvalidOperationException ngay nếu không đạt — không chờ.
|
||||
/// </summary>
|
||||
public class AmrCommandGuard : RobotCommandGuard
|
||||
{
|
||||
private readonly SystemCondition _sys;
|
||||
|
||||
public AmrCommandGuard(SystemCondition sys, RobotState amr) : base(amr, "AMR")
|
||||
{
|
||||
_sys = sys;
|
||||
}
|
||||
|
||||
protected override bool IsOnline => _sys.AmrOnline;
|
||||
protected override bool HasErrors => _sys.AmrHasErrors;
|
||||
|
||||
private AmrKnownPos CurrentPosition => _sys.DetectAmr();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Undock guards
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
/// <summary>
|
||||
/// AMR muốn lùi:
|
||||
/// - Phải đang docked tại Cap1 hoặc Cap2
|
||||
/// - Ở Home → không có station để lùi
|
||||
/// - Đã lùi rồi → không lùi nữa
|
||||
/// </summary>
|
||||
public void RequireCanUndock()
|
||||
{
|
||||
RequireReadyNoErrors();
|
||||
|
||||
switch (CurrentPosition)
|
||||
{
|
||||
case AmrKnownPos.AtCap1:
|
||||
case AmrKnownPos.AtCap2:
|
||||
return;
|
||||
case AmrKnownPos.AtHome:
|
||||
throw new InvalidOperationException("AMR đang ở Home — không có station để lùi");
|
||||
case AmrKnownPos.BackFromCap1:
|
||||
case AmrKnownPos.BackFromCap2:
|
||||
throw new InvalidOperationException(
|
||||
$"AMR đã lùi ra rồi {FormatPosition()} — không cần lùi nữa");
|
||||
default:
|
||||
throw new InvalidOperationException(
|
||||
$"AMR không ở vị trí dock hợp lệ để lùi {FormatPosition()}");
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// MoveTo guards
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
/// <summary>
|
||||
/// AMR muốn di chuyển (MoveTo bất kỳ):
|
||||
/// - Phải đã lùi ra khỏi station (BackFromCap1/BackFromCap2) hoặc đang ở Home
|
||||
/// - Đang docked tại Cap1/Cap2 → phải lùi trước
|
||||
/// </summary>
|
||||
public void RequireCanMoveTo()
|
||||
{
|
||||
RequireReadyNoErrors();
|
||||
|
||||
switch (CurrentPosition)
|
||||
{
|
||||
case AmrKnownPos.AtCap1:
|
||||
throw new InvalidOperationException(
|
||||
"AMR đang docked tại Cap1 — phải UndockFromStation trước khi di chuyển");
|
||||
case AmrKnownPos.AtCap2:
|
||||
throw new InvalidOperationException(
|
||||
"AMR đang docked tại Cap2 — phải UndockFromStation trước khi di chuyển");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True khi AMR đang ở vị trí không xác định (không phải Home, BackFromCap1/2, AtCap1/2).</summary>
|
||||
public bool IsPositionUnknown => CurrentPosition == AmrKnownPos.Unknown;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Action guards
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
/// <summary>
|
||||
/// AMR muốn Load:
|
||||
/// - Phải đang docked tại Cap1 hoặc Cap2
|
||||
/// - Ở Home hoặc đã lùi ra → không có conveyor để Load
|
||||
/// </summary>
|
||||
public void RequireCanLoad() => RequireCapTransfer("Load");
|
||||
|
||||
/// <summary>
|
||||
/// AMR muốn Unload:
|
||||
/// - Phải đang docked tại Cap1 hoặc Cap2
|
||||
/// - Ở Home hoặc đã lùi ra → không có conveyor để Unload
|
||||
/// </summary>
|
||||
public void RequireCanUnload() => RequireCapTransfer("Unload");
|
||||
|
||||
private void RequireCapTransfer(string actionName)
|
||||
{
|
||||
RequireReadyNoErrors();
|
||||
|
||||
switch (CurrentPosition)
|
||||
{
|
||||
case AmrKnownPos.AtCap1:
|
||||
case AmrKnownPos.AtCap2:
|
||||
return;
|
||||
case AmrKnownPos.AtHome:
|
||||
throw new InvalidOperationException(
|
||||
$"AMR đang ở Home — không thể {actionName}, phải di chuyển đến Cap trước");
|
||||
case AmrKnownPos.BackFromCap1:
|
||||
case AmrKnownPos.BackFromCap2:
|
||||
throw new InvalidOperationException(
|
||||
$"AMR đã lùi ra {FormatPosition()} — phải dock vào Cap trước khi {actionName}");
|
||||
default:
|
||||
throw new InvalidOperationException(
|
||||
$"AMR không ở vị trí dock hợp lệ để {actionName} {FormatPosition()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
84
Lab505/Application/Condition/FlowStep.cs
Normal file
84
Lab505/Application/Condition/FlowStep.cs
Normal file
@@ -0,0 +1,84 @@
|
||||
namespace Lab505.Application.Condition;
|
||||
|
||||
/// <summary>
|
||||
/// Một bước trong workflow được định nghĩa hoàn toàn bằng điều kiện trạng thái.
|
||||
/// Mỗi bước có: tiền điều kiện → thực thi → điều kiện hoàn thành.
|
||||
/// </summary>
|
||||
public record FlowStep(
|
||||
string Name,
|
||||
Func<SystemCondition, bool> Precondition,
|
||||
Func<CancellationToken, Task> Execute,
|
||||
Func<SystemCondition, bool>? Done = null
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Chạy một chuỗi FlowStep dựa trên SystemCondition.
|
||||
/// </summary>
|
||||
public class StepRunner(SystemCondition sys)
|
||||
{
|
||||
private int _preconditionMs = 1_200_000;
|
||||
private int _completionMs = 1_200_000;
|
||||
|
||||
public StepRunner WithPreconditionTimeout(int ms) { _preconditionMs = ms; return this; }
|
||||
public StepRunner WithCompletionTimeout(int ms) { _completionMs = ms; return this; }
|
||||
|
||||
public async Task Run(FlowStep step, CancellationToken ct)
|
||||
{
|
||||
// 1. Chờ precondition
|
||||
if (!await sys.WaitUntil(step.Precondition, _preconditionMs, ct))
|
||||
throw new TimeoutException($"[{step.Name}] Precondition không thỏa trong {_preconditionMs}ms");
|
||||
|
||||
// 2. Thực thi lệnh
|
||||
await step.Execute(ct);
|
||||
|
||||
// 3. Chờ hoàn thành (nếu có)
|
||||
if (step.Done != null && !await sys.WaitUntil(step.Done, _completionMs, ct))
|
||||
throw new TimeoutException($"[{step.Name}] Không hoàn thành trong {_completionMs}ms");
|
||||
}
|
||||
|
||||
public async Task RunAll(IEnumerable<FlowStep> steps, CancellationToken ct)
|
||||
{
|
||||
foreach (var step in steps)
|
||||
await Run(step, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Chạy nhiều branch song song (Task.WhenAll).
|
||||
/// Nếu bất kỳ branch nào fail/timeout → tất cả branch còn lại bị cancel ngay.
|
||||
/// Tránh treo vô hạn khi device conflict giữa các branch.
|
||||
/// </summary>
|
||||
public async Task RunParallel(IEnumerable<IEnumerable<FlowStep>> branches, CancellationToken ct)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
|
||||
var tasks = branches.Select(branch => RunBranch(branch, linked)).ToList();
|
||||
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Nếu có exception chưa cancel → cancel các branch còn lại
|
||||
await linked.CancelAsync();
|
||||
|
||||
// Ném exception đầu tiên (bỏ AggregateException)
|
||||
await Task.WhenAll(tasks).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunBranch(IEnumerable<FlowStep> steps, CancellationTokenSource cts)
|
||||
{
|
||||
try
|
||||
{
|
||||
await RunAll(steps, cts.Token);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Branch này fail → cancel tất cả branch khác
|
||||
await cts.CancelAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
145
Lab505/Application/Condition/ImrCommandGuard.cs
Normal file
145
Lab505/Application/Condition/ImrCommandGuard.cs
Normal file
@@ -0,0 +1,145 @@
|
||||
using Lab505.Application.Condition;
|
||||
using Lab505.Domain.Entities;
|
||||
using Lab505.Shared;
|
||||
|
||||
namespace Lab505.Infrastructure.Drivers.Imr;
|
||||
|
||||
/// <summary>
|
||||
/// Guard kiểm tra điều kiện TẠI THỜI ĐIỂM gọi trước khi cho phép gửi lệnh xuống IMR.
|
||||
/// Throw InvalidOperationException ngay nếu không đạt — không chờ.
|
||||
/// Bất kỳ class nào muốn dùng ImrVdaDriver phải qua đây trước.
|
||||
/// </summary>
|
||||
public class ImrCommandGuard : RobotCommandGuard
|
||||
{
|
||||
private readonly SystemCondition _sys;
|
||||
|
||||
public ImrCommandGuard(SystemCondition sys, RobotState imr) : base(imr, "IMR")
|
||||
{
|
||||
_sys = sys;
|
||||
}
|
||||
|
||||
protected override bool IsOnline => _sys.ImrOnline;
|
||||
protected override bool HasErrors => _sys.ImrHasErrors;
|
||||
|
||||
private ImrKnownPos CurrentPosition => _sys.DetectImr();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// MoveTo guards
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
/// <summary>
|
||||
/// IMR muốn di chuyển đến ABB:
|
||||
/// - Phải đang ở vị trí BackFromC1 (đã lùi đủ -2.2m khỏi C1)
|
||||
/// - Hoặc đang ở BackFromABB (đã lùi khỏi ABB, chạy lại)
|
||||
/// </summary>
|
||||
public void RequireCanMoveToABB()
|
||||
{
|
||||
RequireReadyNoErrors();
|
||||
|
||||
switch (CurrentPosition)
|
||||
{
|
||||
case ImrKnownPos.AtC1:
|
||||
throw new InvalidOperationException(
|
||||
$"IMR đang docked tại C1 — phải lùi -{RobotPositions.IMR_UNDOCK_C1}m trước khi di chuyển đến ABB");
|
||||
case ImrKnownPos.AtABB:
|
||||
throw new InvalidOperationException(
|
||||
"IMR đang docked tại ABB — gọi UndockFromStation trước");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IMR muốn di chuyển đến C1:
|
||||
/// - Phải đang ở BackFromABB (đã lùi đủ -1.2m khỏi ABB)
|
||||
/// - Hoặc đang ở BackFromC1 (đã lùi khỏi C1, chạy lại)
|
||||
/// </summary>
|
||||
public void RequireCanMoveToC1()
|
||||
{
|
||||
RequireReadyNoErrors();
|
||||
|
||||
switch (CurrentPosition)
|
||||
{
|
||||
case ImrKnownPos.AtABB:
|
||||
throw new InvalidOperationException(
|
||||
$"IMR đang docked tại ABB — phải lùi -{RobotPositions.IMR_UNDOCK_ABB}m trước khi di chuyển đến C1");
|
||||
case ImrKnownPos.AtC1:
|
||||
throw new InvalidOperationException(
|
||||
"IMR đang docked tại C1 — gọi UndockFromStation trước");
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Undock guards
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
/// <summary>IMR muốn lùi khỏi C1 (-2.2m) — phải đang docked tại C1.</summary>
|
||||
public void RequireCanUndockFromC1() => RequireDockedAt(
|
||||
_sys.ImrAtC1,
|
||||
$"IMR không ở C1 {FormatPosition()} — không thể lùi khỏi C1");
|
||||
|
||||
/// <summary>IMR muốn lùi khỏi ABB (-1.2m) — phải đang docked tại ABB.</summary>
|
||||
public void RequireCanUndockFromABB() => RequireDockedAt(
|
||||
_sys.ImrAtABB,
|
||||
$"IMR không ở ABB {FormatPosition()} — không thể lùi khỏi ABB");
|
||||
|
||||
/// <summary>IMR muốn lùi — tự động phát hiện đang ở C1 hay ABB.</summary>
|
||||
public void RequireCanUndock()
|
||||
{
|
||||
RequireReadyNoErrors();
|
||||
|
||||
if (CurrentPosition is not (ImrKnownPos.AtC1 or ImrKnownPos.AtABB))
|
||||
throw new InvalidOperationException(
|
||||
$"IMR không ở vị trí dock hợp lệ để lùi {FormatPosition()}");
|
||||
}
|
||||
|
||||
/// <summary>True khi IMR đang ở vị trí không xác định (không phải docked hoặc đã lùi ra).</summary>
|
||||
public bool IsPositionUnknown => CurrentPosition == ImrKnownPos.Unknown;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Action guards
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
/// <summary>IMR muốn Load — phải đang docked tại C1 và ready.</summary>
|
||||
public void RequireCanLoad() => RequireReadyAt(
|
||||
_sys.ImrReadyAtC1,
|
||||
"C1",
|
||||
"Load");
|
||||
|
||||
/// <summary>IMR muốn Unload — phải đang docked tại C1 và ready.</summary>
|
||||
public void RequireCanUnload() => RequireReadyAt(
|
||||
_sys.ImrReadyAtC1,
|
||||
"C1",
|
||||
"Unload");
|
||||
|
||||
/// <summary>IMR muốn PickUp — phải đang docked tại ABB và ready.</summary>
|
||||
public void RequireCanPickUp() => RequireReadyAt(
|
||||
_sys.ImrReadyAtABB,
|
||||
"ABB",
|
||||
"PickUp");
|
||||
|
||||
/// <summary>
|
||||
/// Dobot chỉ được gọi khi IMR đang docked tại ABB và ready.
|
||||
/// Áp dụng cho: Pickup, Continue — không áp dụng cho GoHome/Cancel (lệnh reset).
|
||||
/// </summary>
|
||||
public void RequireCanCallDobot()
|
||||
{
|
||||
RequireReadyNoErrors();
|
||||
if (!_sys.ImrReadyAtABB)
|
||||
throw new InvalidOperationException(
|
||||
$"Dobot chỉ hoạt động khi IMR docked tại ABB — hiện tại {FormatPosition()}");
|
||||
}
|
||||
|
||||
private void RequireDockedAt(bool isDocked, string errorMessage)
|
||||
{
|
||||
RequireReadyNoErrors();
|
||||
if (!isDocked)
|
||||
throw new InvalidOperationException(errorMessage);
|
||||
}
|
||||
|
||||
private void RequireReadyAt(bool isReadyAtStation, string station, string actionName)
|
||||
{
|
||||
RequireReadyNoErrors();
|
||||
if (!isReadyAtStation)
|
||||
throw new InvalidOperationException(
|
||||
$"IMR phải ở {station} để {actionName} — hiện tại {FormatPosition()}");
|
||||
}
|
||||
}
|
||||
50
Lab505/Application/Condition/RobotCommandGuard.cs
Normal file
50
Lab505/Application/Condition/RobotCommandGuard.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using Lab505.Domain.Entities;
|
||||
|
||||
namespace Lab505.Application.Condition;
|
||||
|
||||
/// <summary>
|
||||
/// Shared preconditions for robot commands.
|
||||
/// </summary>
|
||||
public abstract class RobotCommandGuard
|
||||
{
|
||||
protected readonly RobotState State;
|
||||
private readonly string _name;
|
||||
|
||||
protected RobotCommandGuard(RobotState state, string name)
|
||||
{
|
||||
State = state;
|
||||
_name = name;
|
||||
}
|
||||
|
||||
protected abstract bool IsOnline { get; }
|
||||
protected abstract bool HasErrors { get; }
|
||||
|
||||
public void RequireOnline()
|
||||
{
|
||||
if (!IsOnline)
|
||||
throw new InvalidOperationException($"{_name} offline — không thể gửi lệnh");
|
||||
}
|
||||
|
||||
public void RequireReady()
|
||||
{
|
||||
RequireOnline();
|
||||
if (State.NewBaseRequest == false)
|
||||
throw new InvalidOperationException(
|
||||
$"{_name} đang bận (NBR=false) — chờ lệnh hiện tại hoàn thành");
|
||||
}
|
||||
|
||||
public void RequireNoErrors()
|
||||
{
|
||||
if (HasErrors)
|
||||
throw new InvalidOperationException(
|
||||
$"{_name} có lỗi: [{string.Join(", ", State.Errors)}] — không thể gửi lệnh mới");
|
||||
}
|
||||
|
||||
protected void RequireReadyNoErrors()
|
||||
{
|
||||
RequireReady();
|
||||
RequireNoErrors();
|
||||
}
|
||||
|
||||
protected string FormatPosition() => $"({State.X_Vda:F2}, {State.Y_Vda:F2})";
|
||||
}
|
||||
480
Lab505/Application/Condition/RobotConditionWaiter.cs
Normal file
480
Lab505/Application/Condition/RobotConditionWaiter.cs
Normal file
@@ -0,0 +1,480 @@
|
||||
namespace Lab505.Domain.Entities;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// VDA5050 Action Status
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
public enum VdaActionStatus
|
||||
{
|
||||
Initializing,
|
||||
Running,
|
||||
Finished,
|
||||
Failed,
|
||||
Aborted
|
||||
}
|
||||
|
||||
public static class VdaActionStatusExtensions
|
||||
{
|
||||
public static string ToVdaString(this VdaActionStatus s) => s switch
|
||||
{
|
||||
VdaActionStatus.Initializing => "INITIALIZING",
|
||||
VdaActionStatus.Running => "RUNNING",
|
||||
VdaActionStatus.Finished => "FINISHED",
|
||||
VdaActionStatus.Failed => "FAILED",
|
||||
VdaActionStatus.Aborted => "ABORTED",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(s))
|
||||
};
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// VDA5050 Action Types
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
public static class VdaActionType
|
||||
{
|
||||
// MoveTo không phải action → không có ở đây
|
||||
public const string Load = "load";
|
||||
public const string Unload = "unload";
|
||||
public const string PickUp = "pickup";
|
||||
public const string UndockFromStation = "UnDockFromStation";
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Result types
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
public enum VdaCompletionPath { Action, NewBaseRequest, Timeout }
|
||||
|
||||
public record VdaWaitResult(
|
||||
VdaCompletionPath Path,
|
||||
string? ActionType = null,
|
||||
string? ActionStatus = null,
|
||||
string? TimeoutSnapshot = null
|
||||
)
|
||||
{
|
||||
public bool IsTimeout => Path == VdaCompletionPath.Timeout;
|
||||
public bool IsAction => Path == VdaCompletionPath.Action;
|
||||
public bool IsNbr => Path == VdaCompletionPath.NewBaseRequest;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Exceptions
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
public class RobotStateTimeoutException : Exception
|
||||
{
|
||||
public RobotStateTimeoutException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
public class RobotStateErrorException : Exception
|
||||
{
|
||||
public RobotStateErrorException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// RobotStateWatcher
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
public class RobotConditionWaiter : IDisposable
|
||||
{
|
||||
private readonly RobotState _state;
|
||||
|
||||
public RobotConditionWaiter(RobotState state) => _state = state;
|
||||
|
||||
// ── Fluent entry points ──────────────────────────────────────
|
||||
|
||||
/// <summary>Tổng quát — actionType thẳng từ VDA5050 protocol.</summary>
|
||||
public VdaCommandAwaiter ActionStates(string actionType)
|
||||
=> new(this, actionType);
|
||||
|
||||
/// <summary>Semantic wrappers.</summary>
|
||||
public VdaCommandAwaiter Load_Vda() => ActionStates(VdaActionType.Load);
|
||||
public VdaCommandAwaiter Unload_Vda() => ActionStates(VdaActionType.Unload);
|
||||
public VdaCommandAwaiter PickUp_Vda() => ActionStates(VdaActionType.PickUp);
|
||||
public VdaCommandAwaiter UndockFromStation_Vda() => ActionStates(VdaActionType.UndockFromStation);
|
||||
|
||||
// ── Internal: check chung ActionStates + NewBaseRequest ───────
|
||||
|
||||
internal async Task<VdaWaitResult> WaitActionOrNbrAsync(
|
||||
string actionType,
|
||||
string[] targetStatuses,
|
||||
TimeSpan timeout,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
int sawNbrBusy = (_state.NewBaseRequest ?? false) ? 0 : 1;
|
||||
|
||||
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
||||
throw new RobotStateErrorException(BuildErrorMessage(_state));
|
||||
|
||||
var tcs = new TaskCompletionSource<VdaWaitResult>(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
void OnUpdated()
|
||||
{
|
||||
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
||||
{
|
||||
tcs.TrySetException(new RobotStateErrorException(BuildErrorMessage(_state)));
|
||||
return;
|
||||
}
|
||||
|
||||
// Chỉ chốt theo NBR sau khi đã thấy robot bận (NBR=false) ít nhất 1 lần.
|
||||
// Tránh ăn nhầm NBR=true cũ còn sót từ lệnh trước.
|
||||
bool current = _state.NewBaseRequest ?? false;
|
||||
if (!current)
|
||||
{
|
||||
Interlocked.Exchange(ref sawNbrBusy, 1);
|
||||
}
|
||||
else if (Volatile.Read(ref sawNbrBusy) == 1)
|
||||
{
|
||||
tcs.TrySetResult(new VdaWaitResult(VdaCompletionPath.NewBaseRequest));
|
||||
return;
|
||||
}
|
||||
|
||||
// ActionStates match
|
||||
var action = _state.ActionStates
|
||||
.FirstOrDefault(a => a.ActionType == actionType
|
||||
&& targetStatuses.Contains(a.ActionStatus));
|
||||
if (action != null)
|
||||
tcs.TrySetResult(new VdaWaitResult(
|
||||
VdaCompletionPath.Action,
|
||||
ActionType: action.ActionType,
|
||||
ActionStatus: action.ActionStatus));
|
||||
}
|
||||
|
||||
_state.OnUpdated += OnUpdated;
|
||||
try
|
||||
{
|
||||
OnUpdated(); // Re-check sau subscribe — tránh miss nếu state đã đạt trước khi subscribe
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(timeout);
|
||||
return await tcs.Task.WaitAsync(cts.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
return new VdaWaitResult(VdaCompletionPath.Timeout,
|
||||
TimeoutSnapshot: BuildTimeoutMessage(_state, timeout));
|
||||
}
|
||||
finally { _state.OnUpdated -= OnUpdated; }
|
||||
}
|
||||
|
||||
// ── Internal: chỉ check ActionStates ─────────────────────────
|
||||
|
||||
internal async Task<VdaWaitResult> WaitActionOnlyAsync(
|
||||
string actionType,
|
||||
string targetStatus,
|
||||
TimeSpan timeout,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
||||
throw new RobotStateErrorException(BuildErrorMessage(_state));
|
||||
|
||||
var tcs = new TaskCompletionSource<VdaWaitResult>(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
void OnUpdated()
|
||||
{
|
||||
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
||||
{
|
||||
tcs.TrySetException(new RobotStateErrorException(BuildErrorMessage(_state)));
|
||||
return;
|
||||
}
|
||||
|
||||
var action = _state.ActionStates
|
||||
.FirstOrDefault(a => a.ActionType == actionType
|
||||
&& a.ActionStatus == targetStatus);
|
||||
if (action != null)
|
||||
tcs.TrySetResult(new VdaWaitResult(
|
||||
VdaCompletionPath.Action,
|
||||
ActionType: action.ActionType,
|
||||
ActionStatus: action.ActionStatus));
|
||||
}
|
||||
|
||||
_state.OnUpdated += OnUpdated;
|
||||
try
|
||||
{
|
||||
OnUpdated(); // Re-check sau subscribe — tránh miss nếu state đã đạt trước khi subscribe
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(timeout);
|
||||
return await tcs.Task.WaitAsync(cts.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
return new VdaWaitResult(VdaCompletionPath.Timeout,
|
||||
TimeoutSnapshot: BuildTimeoutMessage(_state, timeout));
|
||||
}
|
||||
finally { _state.OnUpdated -= OnUpdated; }
|
||||
}
|
||||
|
||||
// ── Internal: chờ ActionId cụ thể đạt terminal status ────────
|
||||
|
||||
/// <summary>
|
||||
/// Chờ action CÓ ActionID cụ thể đạt FINISHED (hoặc throw nếu FAILED/ABORTED).
|
||||
/// Tránh bắt nhầm action FINISHED cũ còn sót lại trong ActionStates.
|
||||
/// </summary>
|
||||
internal async Task WaitActionIdCompletedAsync(
|
||||
string actionId,
|
||||
TimeSpan timeout,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
||||
throw new RobotStateErrorException(BuildErrorMessage(_state));
|
||||
|
||||
var tcs = new TaskCompletionSource(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
void OnUpdated()
|
||||
{
|
||||
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
||||
{
|
||||
tcs.TrySetException(new RobotStateErrorException(BuildErrorMessage(_state)));
|
||||
return;
|
||||
}
|
||||
|
||||
var action = _state.ActionStates.FirstOrDefault(a => a.ActionID == actionId);
|
||||
if (action is null) return; // chưa thấy — robot chưa nhận lệnh
|
||||
|
||||
switch (action.ActionStatus)
|
||||
{
|
||||
case "FINISHED":
|
||||
tcs.TrySetResult();
|
||||
break;
|
||||
case "FAILED":
|
||||
case "ABORTED":
|
||||
tcs.TrySetException(new RobotStateErrorException(
|
||||
$"[{action.ActionType}#{actionId}] kết thúc với trạng thái {action.ActionStatus}"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
_state.OnUpdated += OnUpdated;
|
||||
try
|
||||
{
|
||||
OnUpdated();
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(timeout);
|
||||
await tcs.Task.WaitAsync(cts.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
var seen = _state.ActionStates.Any(a => a.ActionID == actionId);
|
||||
throw new RobotStateTimeoutException(
|
||||
$"Action#{actionId} {(seen ? "chưa hoàn thành" : "robot chưa nhận lệnh (không thấy ActionID trong state)")} — " +
|
||||
BuildTimeoutMessage(_state, timeout));
|
||||
}
|
||||
finally { _state.OnUpdated -= OnUpdated; }
|
||||
}
|
||||
|
||||
public Task WaitActionIdCompleted(string actionId, TimeSpan timeout, CancellationToken ct = default)
|
||||
=> WaitActionIdCompletedAsync(actionId, timeout, ct);
|
||||
|
||||
// ── Internal: chỉ check NewBaseRequest ───────────────────────
|
||||
|
||||
internal async Task WaitNbrOnlyAsync(
|
||||
TimeSpan timeout,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
// Chỉ hoàn thành khi thấy đủ chu kỳ NBR: true -> false -> true.
|
||||
// Như vậy sẽ không dính NBR=true cũ của lệnh trước.
|
||||
|
||||
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
||||
throw new RobotStateErrorException(BuildErrorMessage(_state));
|
||||
|
||||
var tcs = new TaskCompletionSource(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
var phase = _state.NewBaseRequest == true ? 1 : 0;
|
||||
// phase 0: chờ trạng thái sẵn sàng ban đầu (NBR=true)
|
||||
// phase 1: đã thấy true, chờ robot bận (NBR=false)
|
||||
// phase 2: đã thấy false, chờ robot ready lại (NBR=true)
|
||||
|
||||
void OnUpdated()
|
||||
{
|
||||
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
||||
{
|
||||
tcs.TrySetException(new RobotStateErrorException(BuildErrorMessage(_state)));
|
||||
return;
|
||||
}
|
||||
|
||||
bool current = _state.NewBaseRequest ?? false;
|
||||
switch (Volatile.Read(ref phase))
|
||||
{
|
||||
case 0:
|
||||
if (current)
|
||||
Interlocked.CompareExchange(ref phase, 1, 0);
|
||||
return;
|
||||
|
||||
case 1:
|
||||
if (!current)
|
||||
Interlocked.CompareExchange(ref phase, 2, 1);
|
||||
return;
|
||||
|
||||
case 2:
|
||||
if (current)
|
||||
tcs.TrySetResult();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_state.OnUpdated += OnUpdated;
|
||||
try
|
||||
{
|
||||
OnUpdated(); // Re-check sau subscribe — bắt race nếu NBR chuyển false→true đúng lúc subscribe
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(timeout);
|
||||
await tcs.Task.WaitAsync(cts.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
throw new RobotStateTimeoutException(
|
||||
BuildTimeoutMessage(_state, timeout));
|
||||
}
|
||||
finally { _state.OnUpdated -= OnUpdated; }
|
||||
}
|
||||
|
||||
|
||||
public void Dispose() { }
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────
|
||||
|
||||
private static string BuildErrorMessage(RobotState s)
|
||||
{
|
||||
var rawErrs = s.RawErrors.Select(e =>
|
||||
$"[{e.ErrorLevel}] {e.ErrorType}: {e.ErrorDescription}" +
|
||||
(e.ErrorReferences?.Length > 0
|
||||
? " (" + string.Join(", ",
|
||||
e.ErrorReferences.Select(r => $"{r.ReferenceKey}={r.ReferenceValue}")) + ")"
|
||||
: ""));
|
||||
var actions = s.ActionStates.Select(a => $"{a.ActionType}:{a.ActionStatus}");
|
||||
return $"Errors=[{string.Join(" | ", rawErrs)}] Actions=[{string.Join(", ", actions)}]";
|
||||
}
|
||||
|
||||
private static string BuildTimeoutMessage(RobotState s, TimeSpan timeout)
|
||||
{
|
||||
var rawErrs = s.RawErrors.Select(e => $"[{e.ErrorLevel}] {e.ErrorType}: {e.ErrorDescription}");
|
||||
var actions = s.ActionStates.Select(a => $"{a.ActionType}:{a.ActionStatus}");
|
||||
return $"Timeout {timeout.TotalSeconds}s — " +
|
||||
$"Online={s.IsOnline_Vda}, " +
|
||||
$"Pos=({s.X_Vda:F3}, {s.Y_Vda:F3}, θ={s.Theta_Vda:F3}), " +
|
||||
$"NewBaseRequest={s.NewBaseRequest}, " +
|
||||
$"Actions=[{string.Join(", ", actions)}], " +
|
||||
$"Errors=[{string.Join(" | ", rawErrs)}]";
|
||||
}
|
||||
// Trong RobotStateWatcher
|
||||
/// <summary>Chờ MoveTo/Undock hoàn thành theo chu kỳ NBR: true -> false -> true.</summary>
|
||||
public Task WaitMoveTo(TimeSpan timeout, CancellationToken ct = default)
|
||||
=> WaitNbrOnlyAsync(timeout, ct);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// VdaCommandAwaiter
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
/// <summary>
|
||||
/// 3 cách check:
|
||||
/// 1. .WaitAction(status) — chỉ ActionStates
|
||||
/// 2. .WaitNbr() — chỉ NewBaseRequest
|
||||
/// 3. .WaitEither(status) — chung cả 2, cái nào đến trước
|
||||
/// </summary>
|
||||
public class VdaCommandAwaiter
|
||||
{
|
||||
private readonly RobotConditionWaiter _watcher;
|
||||
private readonly string _actionType;
|
||||
|
||||
internal VdaCommandAwaiter(RobotConditionWaiter watcher, string actionType)
|
||||
{
|
||||
_watcher = watcher;
|
||||
_actionType = actionType;
|
||||
}
|
||||
|
||||
// ── 1. Chỉ ActionStates ───────────────────────────────────────
|
||||
|
||||
/// <summary>Chỉ check ActionStates với status cụ thể. Throw nếu timeout.</summary>
|
||||
public async Task WaitAction(VdaActionStatus status, TimeSpan timeout, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _watcher.WaitActionOnlyAsync(_actionType, status.ToVdaString(), timeout, ct);
|
||||
if (result.IsTimeout)
|
||||
throw new TimeoutException(
|
||||
$"[{_actionType}] không đạt '{status}' — {result.TimeoutSnapshot}");
|
||||
}
|
||||
|
||||
// Shorthand properties — gõ . là ra ngay
|
||||
public VdaStatusAwaiter Initializing => new(_watcher, _actionType, VdaActionStatus.Initializing);
|
||||
public VdaStatusAwaiter Running => new(_watcher, _actionType, VdaActionStatus.Running);
|
||||
public VdaStatusAwaiter Finished => new(_watcher, _actionType, VdaActionStatus.Finished);
|
||||
public VdaStatusAwaiter Failed => new(_watcher, _actionType, VdaActionStatus.Failed);
|
||||
public VdaStatusAwaiter Aborted => new(_watcher, _actionType, VdaActionStatus.Aborted);
|
||||
|
||||
// ── 2. Chỉ NewBaseRequest ─────────────────────────────────────
|
||||
|
||||
/// <summary>Chỉ check chu kỳ NewBaseRequest: phải thấy true -> false -> true.</summary>
|
||||
public Task WaitNbr(TimeSpan timeout, CancellationToken ct = default)
|
||||
=> _watcher.WaitNbrOnlyAsync(timeout, ct);
|
||||
|
||||
// ── 3. Chung cả 2 ─────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Check ActionStates + NewBaseRequest — cái nào đến trước.
|
||||
/// NewBaseRequest ưu tiên nếu cả 2 cùng lúc.
|
||||
/// Throw nếu timeout.
|
||||
/// Return VdaCompletionPath để caller biết path nào thắng nếu cần.
|
||||
/// </summary>
|
||||
public async Task<VdaCompletionPath> WaitEither(VdaActionStatus status, TimeSpan timeout, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _watcher.WaitActionOrNbrAsync(
|
||||
_actionType, [status.ToVdaString()], timeout, ct);
|
||||
|
||||
if (result.IsTimeout)
|
||||
throw new TimeoutException(
|
||||
$"[{_actionType}] WaitEither '{status}' — {result.TimeoutSnapshot}");
|
||||
|
||||
return result.Path;
|
||||
}
|
||||
|
||||
/// <summary>WaitEither với terminal statuses (Finished/Failed/Aborted).
|
||||
/// Throw RobotStateErrorException nếu action kết thúc bằng FAILED hoặc ABORTED.</summary>
|
||||
public async Task<VdaCompletionPath> WaitEitherCompleted(TimeSpan timeout, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _watcher.WaitActionOrNbrAsync(
|
||||
_actionType,
|
||||
[VdaActionStatus.Finished.ToVdaString(), VdaActionStatus.Failed.ToVdaString(), VdaActionStatus.Aborted.ToVdaString()],
|
||||
timeout, ct);
|
||||
|
||||
if (result.IsTimeout)
|
||||
throw new TimeoutException(
|
||||
$"[{_actionType}] WaitEitherCompleted — {result.TimeoutSnapshot}");
|
||||
|
||||
if (result.IsAction && result.ActionStatus is "FAILED" or "ABORTED")
|
||||
throw new RobotStateErrorException(
|
||||
$"[{_actionType}] action kết thúc với trạng thái {result.ActionStatus}");
|
||||
|
||||
return result.Path;
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// VdaStatusAwaiter — shorthand cho .Running.Wait() etc.
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
public class VdaStatusAwaiter
|
||||
{
|
||||
private readonly RobotConditionWaiter _watcher;
|
||||
private readonly string _actionType;
|
||||
private readonly VdaActionStatus _status;
|
||||
|
||||
internal VdaStatusAwaiter(RobotConditionWaiter watcher, string actionType, VdaActionStatus status)
|
||||
{
|
||||
_watcher = watcher;
|
||||
_actionType = actionType;
|
||||
_status = status;
|
||||
}
|
||||
|
||||
/// <summary>Chỉ check ActionStates. Throw nếu timeout.</summary>
|
||||
public async Task Wait(TimeSpan timeout, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _watcher.WaitActionOnlyAsync(
|
||||
_actionType, _status.ToVdaString(), timeout, ct);
|
||||
if (result.IsTimeout)
|
||||
throw new TimeoutException(
|
||||
$"[{_actionType}] không đạt '{_status}' — {result.TimeoutSnapshot}");
|
||||
}
|
||||
}
|
||||
255
Lab505/Application/Condition/SystemCondition.cs
Normal file
255
Lab505/Application/Condition/SystemCondition.cs
Normal file
@@ -0,0 +1,255 @@
|
||||
using Lab505.Domain.Entities;
|
||||
using Lab505.Infrastructure.Protocols.OpcUa;
|
||||
using Lab505.Infrastructure.Drivers.Conveyor;
|
||||
using Lab505.Script;
|
||||
using Lab505.Shared;
|
||||
|
||||
namespace Lab505.Application.Condition;
|
||||
|
||||
// ── Position enums ─────────────────────────────────────────────────────────
|
||||
|
||||
public enum ImrKnownPos
|
||||
{
|
||||
Unknown,
|
||||
AtC1, // (-0.05, -5.2) — docked tại C1
|
||||
BackFromC1, // Y≈-5.2, X < IMR_C1_X - IMR_UNDOCK_C1/2 — đã lùi khỏi C1
|
||||
AtABB, // ( 1.35, -0.8) — docked tại ABB
|
||||
BackFromABB // Y≈-0.8, X < IMR_ABB_X - IMR_UNDOCK_ABB/2 — đã lùi khỏi ABB
|
||||
}
|
||||
|
||||
public enum AmrKnownPos
|
||||
{
|
||||
Unknown,
|
||||
AtCap1, // ( 6.0, 0.2) — docked tại Cap1
|
||||
BackFromCap1, // Y≈0.2, X < CAP1_X - UNDOCK_CAP1/2 — đã lùi khỏi Cap1 (-X)
|
||||
AtCap2, // (-0.7, -3.19) — docked tại Cap2
|
||||
BackFromCap2, // X≈-0.7, Y > CAP2_Y + UNDOCK_CAP2/2 — đã lùi khỏi Cap2 (+Y)
|
||||
AtHome, // ( 0.0, 0.0) — tại vị trí Home
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Aggregates all raw device states into a single computed view.
|
||||
/// Subscribe to OnChanged to react when anything in the system changes.
|
||||
/// Use WaitUntil(...) for event-driven condition waiting instead of polling.
|
||||
/// </summary>
|
||||
public class SystemCondition : ICondition, IDisposable
|
||||
{
|
||||
// ── Position constants (aliased từ RobotPositions) ─────────────
|
||||
public const double IMR_C1_X = RobotPositions.IMR_C1_X, IMR_C1_Y = RobotPositions.IMR_C1_Y;
|
||||
public const double IMR_ABB_X = RobotPositions.IMR_ABB_X, IMR_ABB_Y = RobotPositions.IMR_ABB_Y;
|
||||
public const double AMR_CAP1_X = RobotPositions.AMR_CAP1_X, AMR_CAP1_Y = RobotPositions.AMR_CAP1_Y;
|
||||
public const double AMR_CAP2_X = RobotPositions.AMR_CAP2_X, AMR_CAP2_Y = RobotPositions.AMR_CAP2_Y;
|
||||
public const double AMR_HOME_X = RobotPositions.AMR_HOME_X, AMR_HOME_Y = RobotPositions.AMR_HOME_Y;
|
||||
public const double POS_TOL = RobotPositions.POS_TOL;
|
||||
/// Robot coi là "đã lùi" khi X lùi qua ít nhất UNDOCK_THRESHOLD × khoảng lùi thực tế
|
||||
public const double UNDOCK_THRESHOLD = 0.5;
|
||||
|
||||
// ── Raw state references ───────────────────────────────────────
|
||||
public RobotState Imr { get; }
|
||||
public RobotState Amr { get; }
|
||||
public ConveyorState Conveyor { get; }
|
||||
private readonly OpcUaClient _ua;
|
||||
|
||||
public event Action? OnChanged;
|
||||
|
||||
// Lưu delegate để unsubscribe chính xác trong Dispose
|
||||
private readonly Action<bool> _uaConnectHandler;
|
||||
|
||||
public SystemCondition(RobotState imr, RobotState amr, ConveyorState conveyor, OpcUaClient ua)
|
||||
{
|
||||
Imr = imr; Amr = amr; Conveyor = conveyor; _ua = ua;
|
||||
_uaConnectHandler = _ => Fire();
|
||||
imr.OnUpdated += Fire;
|
||||
amr.OnUpdated += Fire;
|
||||
conveyor.OnStateChanged += Fire;
|
||||
ua.ConnectChanged += _uaConnectHandler;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Imr.OnUpdated -= Fire;
|
||||
Amr.OnUpdated -= Fire;
|
||||
Conveyor.OnStateChanged -= Fire;
|
||||
_ua.ConnectChanged -= _uaConnectHandler;
|
||||
}
|
||||
|
||||
private void Fire() => OnChanged?.Invoke();
|
||||
|
||||
// ── IMR ────────────────────────────────────────────────────────
|
||||
public bool ImrOnline => Imr.IsOnline_Vda;
|
||||
public bool ImrReady => ImrOnline && Imr.NewBaseRequest == true;
|
||||
public bool ImrBusy => ImrOnline && Imr.NewBaseRequest == false;
|
||||
public bool ImrHasErrors => Imr.Errors.Count > 0;
|
||||
|
||||
public bool ImrAtC1 => PosMatch(Imr, IMR_C1_X, IMR_C1_Y);
|
||||
public bool ImrAtABB => PosMatch(Imr, IMR_ABB_X, IMR_ABB_Y);
|
||||
|
||||
// Đã lùi khỏi C1: đúng hàng Y, và X lùi qua ít nhất nửa khoảng lùi thực tế
|
||||
public bool ImrBackFromC1 => Math.Abs(Imr.Y_Vda - IMR_C1_Y) < POS_TOL
|
||||
&& Imr.X_Vda < IMR_C1_X - RobotPositions.IMR_UNDOCK_C1 * UNDOCK_THRESHOLD;
|
||||
// Đã lùi khỏi ABB: đúng hàng Y, và X lùi qua ít nhất nửa khoảng lùi thực tế
|
||||
public bool ImrBackFromABB => Math.Abs(Imr.Y_Vda - IMR_ABB_Y) < POS_TOL
|
||||
&& Imr.X_Vda < IMR_ABB_X - RobotPositions.IMR_UNDOCK_ABB * UNDOCK_THRESHOLD;
|
||||
|
||||
/// IMR đã dừng hẳn tại C1 (vị trí + NBR = true)
|
||||
public bool ImrReadyAtC1 => ImrReady && ImrAtC1;
|
||||
/// IMR đã dừng hẳn tại ABB
|
||||
public bool ImrReadyAtABB => ImrReady && ImrAtABB;
|
||||
|
||||
// ── AMR ────────────────────────────────────────────────────────
|
||||
public bool AmrOnline => Amr.IsOnline_Vda;
|
||||
public bool AmrReady => AmrOnline && Amr.NewBaseRequest == true;
|
||||
public bool AmrBusy => AmrOnline && Amr.NewBaseRequest == false;
|
||||
public bool AmrHasErrors => Amr.Errors.Count > 0;
|
||||
|
||||
public bool AmrAtCap1 => PosMatch(Amr, AMR_CAP1_X, AMR_CAP1_Y);
|
||||
public bool AmrAtCap2 => PosMatch(Amr, AMR_CAP2_X, AMR_CAP2_Y);
|
||||
public bool AmrAtHome => PosMatch(Amr, AMR_HOME_X, AMR_HOME_Y);
|
||||
|
||||
/// Vị trí AMR sau khi lùi khỏi Cap1 (đọc X_Vda/Y_Vda khi NBR=true / ActionState=FINISHED)
|
||||
public bool AmrBackFromCap1 => PosMatch(Amr, RobotPositions.AMR_UNDOCK_CAP1_X, RobotPositions.AMR_UNDOCK_CAP1_Y);
|
||||
/// Vị trí AMR sau khi lùi khỏi Cap2
|
||||
public bool AmrBackFromCap2 => PosMatch(Amr, RobotPositions.AMR_UNDOCK_CAP2_X, RobotPositions.AMR_UNDOCK_CAP2_Y);
|
||||
|
||||
/// AMR đã dừng hẳn tại Cap1
|
||||
public bool AmrReadyAtCap1 => AmrReady && AmrAtCap1;
|
||||
/// AMR đã dừng hẳn tại Cap2
|
||||
public bool AmrReadyAtCap2 => AmrReady && AmrAtCap2;
|
||||
|
||||
// ── C1 ─────────────────────────────────────────────────────────
|
||||
/// Kết nối Modbus C1 đang hoạt động (đã đọc được ít nhất 1 lần)
|
||||
public bool C1Online => Conveyor.C1Out != null;
|
||||
public bool C1OutOn => Conveyor.C1Out == true;
|
||||
public bool C1InOn => Conveyor.C1In == true;
|
||||
public bool C1IMRoutOn => Conveyor.C1IMRout == true;
|
||||
public bool C1IMRinOn => Conveyor.C1IMRin == true;
|
||||
|
||||
/// Không có băng tải C1 nào đang chạy
|
||||
public bool C1Idle => C1Online && !C1OutOn && !C1InOn && !C1IMRoutOn && !C1IMRinOn;
|
||||
public bool C1HasGoods => Conveyor.C1HasGoods == true;
|
||||
public bool C1NotGoods => Conveyor.C1NotGoods == true;
|
||||
public bool C1Ready => Conveyor.C1Ready == true;
|
||||
|
||||
// ── C2 ─────────────────────────────────────────────────────────
|
||||
public bool C2Online => Conveyor.C2Out != null;
|
||||
public bool C2OutOn => Conveyor.C2Out == true;
|
||||
public bool C2InOn => Conveyor.C2In == true;
|
||||
|
||||
public bool C2Idle => C2Online && !C2OutOn && !C2InOn;
|
||||
public bool C2HasGoods => Conveyor.C2HasGoods == true;
|
||||
public bool C2Ready => Conveyor.C2Ready == true;
|
||||
|
||||
// ── Device online ──────────────────────────────────────────────
|
||||
public bool DobotOnline => _ua.IsConnected;
|
||||
|
||||
// ── Composite readiness ────────────────────────────────────────
|
||||
/// Cả IMR lẫn AMR đều sẵn sàng tại vị trí trao đổi C1
|
||||
public bool BothReadyAtC1 => ImrReadyAtC1 && AmrReadyAtCap1;
|
||||
|
||||
/// Hệ thống sẵn sàng để trao đổi AMR→IMR qua C1 (C1 rỗng, AMR chuẩn bị giao hàng lên C1)
|
||||
public bool ReadyForAmrToImr => BothReadyAtC1 && C1Idle && C1NotGoods;
|
||||
|
||||
/// Hệ thống sẵn sàng để trao đổi IMR→AMR qua C1 (C1 có hàng từ IMR, AMR chuẩn bị nhận)
|
||||
public bool ReadyForImrToAmr => BothReadyAtC1 && C1Idle && C1HasGoods;
|
||||
|
||||
// ── Position detection ────────────────────────────────────────
|
||||
|
||||
public ImrKnownPos DetectImr()
|
||||
{
|
||||
if (ImrAtC1) return ImrKnownPos.AtC1;
|
||||
if (ImrAtABB) return ImrKnownPos.AtABB;
|
||||
if (ImrBackFromC1) return ImrKnownPos.BackFromC1;
|
||||
if (ImrBackFromABB) return ImrKnownPos.BackFromABB;
|
||||
return ImrKnownPos.Unknown;
|
||||
}
|
||||
|
||||
public AmrKnownPos DetectAmr()
|
||||
{
|
||||
if (AmrAtCap1) return AmrKnownPos.AtCap1;
|
||||
if (AmrAtCap2) return AmrKnownPos.AtCap2;
|
||||
if (AmrBackFromCap1) return AmrKnownPos.BackFromCap1;
|
||||
if (AmrBackFromCap2) return AmrKnownPos.BackFromCap2;
|
||||
if (AmrAtHome) return AmrKnownPos.AtHome;
|
||||
return AmrKnownPos.Unknown;
|
||||
}
|
||||
|
||||
// ── Condition waiting ──────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Chờ cho đến khi điều kiện <paramref name="condition"/> trả về true.
|
||||
/// Trả về false nếu timeout, ném OperationCanceledException nếu token bị cancel.
|
||||
/// </summary>
|
||||
public async Task<bool> WaitUntil(
|
||||
Func<SystemCondition, bool> condition,
|
||||
int timeoutMs = 1_200_000,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (condition(this)) return true;
|
||||
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
using var timer = new CancellationTokenSource(timeoutMs);
|
||||
|
||||
void handler()
|
||||
{
|
||||
if (condition(this)) tcs.TrySetResult(true);
|
||||
}
|
||||
|
||||
OnChanged += handler;
|
||||
try
|
||||
{
|
||||
// Re-check after subscribing to avoid race
|
||||
if (condition(this)) return true;
|
||||
|
||||
using (ct.Register(() => tcs.TrySetCanceled(ct)))
|
||||
using (timer.Token.Register(() => tcs.TrySetResult(false)))
|
||||
return await tcs.Task;
|
||||
}
|
||||
finally
|
||||
{
|
||||
OnChanged -= handler;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Chờ điều kiện, ném TimeoutException nếu không đạt trong thời gian cho phép.
|
||||
/// </summary>
|
||||
public async Task Require(
|
||||
Func<SystemCondition, bool> condition,
|
||||
string errorMessage,
|
||||
int timeoutMs = 1_200_000,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (!await WaitUntil(condition, timeoutMs, ct))
|
||||
throw new TimeoutException(errorMessage);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kiểm tra ngay lập tức — ném InvalidOperationException nếu điều kiện chưa đúng.
|
||||
/// Dùng để guard trước khi gửi lệnh khi không muốn chờ.
|
||||
/// </summary>
|
||||
public void Assert(Func<SystemCondition, bool> condition, string errorMessage)
|
||||
{
|
||||
if (!condition(this)) throw new InvalidOperationException(errorMessage);
|
||||
}
|
||||
|
||||
// ── ICondition explicit interface implementations ────────────────
|
||||
|
||||
void ICondition.Assert(Func<ICondition, bool> condition, string errorMessage)
|
||||
{
|
||||
if (!condition(this)) throw new InvalidOperationException(errorMessage);
|
||||
}
|
||||
|
||||
async Task<bool> ICondition.WaitUntil(Func<ICondition, bool> condition, int timeoutMs, CancellationToken ct)
|
||||
=> await WaitUntil(s => condition(s), timeoutMs, ct);
|
||||
|
||||
async Task ICondition.Require(Func<ICondition, bool> condition, string errorMessage, int timeoutMs, CancellationToken ct)
|
||||
=> await Require(s => condition(s), errorMessage, timeoutMs, ct);
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────
|
||||
private static bool PosMatch(RobotState r, double tx, double ty)
|
||||
{
|
||||
double ax = r.X_Vda, ay = r.Y_Vda;
|
||||
if (double.IsNaN(ax) || double.IsNaN(ay)) return false;
|
||||
return Math.Abs(ax - tx) < POS_TOL && Math.Abs(ay - ty) < POS_TOL;
|
||||
}
|
||||
}
|
||||
58
Lab505/Application/Contexts/IDriverContext.cs
Normal file
58
Lab505/Application/Contexts/IDriverContext.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
using Lab505.Application.Services;
|
||||
using Lab505.Application.Condition;
|
||||
using Lab505.Application.Flow;
|
||||
using Lab505.Domain.Entities;
|
||||
using Lab505.Infrastructure.Drivers.Dobot;
|
||||
using Lab505.Infrastructure.Drivers.Amr;
|
||||
using Lab505.Infrastructure.Drivers.Asrs;
|
||||
using Lab505.Infrastructure.Drivers.Conveyor;
|
||||
using Lab505.Infrastructure.Drivers.Imr;
|
||||
using Lab505.Presentation.Api;
|
||||
using Lab505.Script;
|
||||
using Lab505.Script.Facades;
|
||||
|
||||
namespace Lab505.Application.Contexts;
|
||||
|
||||
/// <summary>
|
||||
/// Đại diện cho một hardware stack (Real hoặc Sim).
|
||||
/// Mỗi user được route đến đúng context qua UserContextResolver.
|
||||
/// 30+ user đồng thời: real users → RealDriverContext, sim users → SimDriverContext.
|
||||
/// </summary>
|
||||
public interface IDriverContext
|
||||
{
|
||||
bool IsReal { get; }
|
||||
|
||||
// ── Drivers ───────────────────────────────────────────────────────────
|
||||
ImrVdaDriver Imr { get; }
|
||||
AmrVdaDriver Amr { get; }
|
||||
IConveyorDriver Conveyor { get; }
|
||||
IAsrsDriver Asrs { get; }
|
||||
IDobotDriver Dobot { get; }
|
||||
|
||||
/// <summary>null đối với sim stack (không có OPC UA riêng cho sim IMR).</summary>
|
||||
ImrOpcUaDriver? ImrOpc { get; }
|
||||
|
||||
// ── State ─────────────────────────────────────────────────────────────
|
||||
RobotState ImrState { get; }
|
||||
RobotState AmrState { get; }
|
||||
ICondition SystemCondition { get; }
|
||||
|
||||
// ── Workflow ──────────────────────────────────────────────────────────
|
||||
FlowService Workflow { get; }
|
||||
IFlowFacade WorkflowFacade { get; }
|
||||
FlowWithAsrs AsrsFlow { get; }
|
||||
|
||||
// ── Per-stack infra ───────────────────────────────────────────────────
|
||||
/// <summary>Lock thiết bị — mỗi stack có lock riêng (real lock ≠ sim lock).</summary>
|
||||
DeviceGroupLock Locks { get; }
|
||||
DeviceCommandQueue ImrQueue { get; }
|
||||
DeviceCommandQueue AmrQueue { get; }
|
||||
DeviceCommandQueue DobotQueue { get; }
|
||||
|
||||
// ── Script interfaces ─────────────────────────────────────────────────
|
||||
IImrFacade ImrFacade { get; }
|
||||
IAmrFacade AmrFacade { get; }
|
||||
IConveyorFacade ScriptConveyor { get; }
|
||||
IAsrsFacade ScriptAsrs { get; }
|
||||
IDobotFacade DobotFacade { get; }
|
||||
}
|
||||
87
Lab505/Application/Contexts/RealDriverContext.cs
Normal file
87
Lab505/Application/Contexts/RealDriverContext.cs
Normal file
@@ -0,0 +1,87 @@
|
||||
using Lab505.Application.Services;
|
||||
using Lab505.Application.Condition;
|
||||
using Lab505.Application.Flow;
|
||||
using Lab505.Domain.Entities;
|
||||
using Lab505.Infrastructure.Drivers.Dobot;
|
||||
using Lab505.Infrastructure.Drivers.Amr;
|
||||
using Lab505.Infrastructure.Drivers.Asrs;
|
||||
using Lab505.Infrastructure.Drivers.Conveyor;
|
||||
using Lab505.Infrastructure.Drivers.Imr;
|
||||
using Lab505.Presentation.Api;
|
||||
using Lab505.Script;
|
||||
using Lab505.Script.Facades;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Lab505.Application.Contexts;
|
||||
|
||||
/// <summary>
|
||||
/// Wraps tất cả real-hardware singletons đã đăng ký trong DI.
|
||||
/// Real users → context này. Lock/Queue/Workflow là của real stack.
|
||||
/// </summary>
|
||||
public sealed class RealDriverContext : IDriverContext
|
||||
{
|
||||
public bool IsReal => true;
|
||||
|
||||
public ImrVdaDriver Imr { get; }
|
||||
public AmrVdaDriver Amr { get; }
|
||||
public IConveyorDriver Conveyor { get; }
|
||||
public IAsrsDriver Asrs { get; }
|
||||
public IDobotDriver Dobot { get; }
|
||||
public ImrOpcUaDriver? ImrOpc { get; }
|
||||
|
||||
public RobotState ImrState { get; }
|
||||
public RobotState AmrState { get; }
|
||||
public ICondition SystemCondition { get; }
|
||||
|
||||
public FlowService Workflow { get; }
|
||||
public IFlowFacade WorkflowFacade { get; }
|
||||
public FlowWithAsrs AsrsFlow { get; }
|
||||
|
||||
public DeviceGroupLock Locks { get; }
|
||||
public DeviceCommandQueue ImrQueue { get; }
|
||||
public DeviceCommandQueue AmrQueue { get; }
|
||||
public DeviceCommandQueue DobotQueue { get; }
|
||||
|
||||
public IImrFacade ImrFacade { get; }
|
||||
public IAmrFacade AmrFacade { get; }
|
||||
public IConveyorFacade ScriptConveyor { get; }
|
||||
public IAsrsFacade ScriptAsrs { get; }
|
||||
public IDobotFacade DobotFacade { get; }
|
||||
|
||||
public RealDriverContext(
|
||||
ImrVdaDriver imr, AmrVdaDriver amr, ImrOpcUaDriver imrOpc,
|
||||
IConveyorDriver conveyor, IAsrsDriver asrs, IDobotDriver dobot,
|
||||
IEnumerable<RobotState> states,
|
||||
FlowService workflow,
|
||||
FlowWithAsrs asrsFlow,
|
||||
SystemCondition systemState,
|
||||
DeviceGroupLock locks,
|
||||
[FromKeyedServices("imr")] DeviceCommandQueue imrQ,
|
||||
[FromKeyedServices("amr")] DeviceCommandQueue amrQ,
|
||||
[FromKeyedServices("dobot")] DeviceCommandQueue dobotQ,
|
||||
IImrFacade scriptImr, IAmrFacade scriptAmr,
|
||||
IConveyorFacade scriptConveyor, IAsrsFacade scriptAsrs, IDobotFacade scriptDobot)
|
||||
{
|
||||
var stateList = states.ToList();
|
||||
|
||||
Imr = imr; Amr = amr; ImrOpc = imrOpc;
|
||||
Conveyor = conveyor; Asrs = asrs; Dobot = dobot;
|
||||
ImrState = stateList[0]; AmrState = stateList[1];
|
||||
SystemCondition = systemState;
|
||||
|
||||
Workflow = workflow;
|
||||
WorkflowFacade = workflow;
|
||||
AsrsFlow = asrsFlow;
|
||||
|
||||
Locks = locks;
|
||||
ImrQueue = imrQ;
|
||||
AmrQueue = amrQ;
|
||||
DobotQueue = dobotQ;
|
||||
|
||||
ImrFacade = scriptImr;
|
||||
AmrFacade = scriptAmr;
|
||||
ScriptConveyor = scriptConveyor;
|
||||
ScriptAsrs = scriptAsrs;
|
||||
DobotFacade = scriptDobot;
|
||||
}
|
||||
}
|
||||
156
Lab505/Application/Contexts/SimDriverContext.cs
Normal file
156
Lab505/Application/Contexts/SimDriverContext.cs
Normal file
@@ -0,0 +1,156 @@
|
||||
using Lab505.Application.Services;
|
||||
using Lab505.Application.Condition;
|
||||
using Lab505.Application.Flow;
|
||||
using Lab505.Domain.Entities;
|
||||
using Lab505.Infrastructure.Drivers.Dobot;
|
||||
|
||||
using Lab505.Infrastructure.State;
|
||||
using Lab505.Infrastructure.Push;
|
||||
using Lab505.Infrastructure.Protocols.OpcUa;
|
||||
using Lab505.Infrastructure.Protocols.Vda5050;
|
||||
using Lab505.Infrastructure.Drivers.Amr;
|
||||
using Lab505.Infrastructure.Drivers.Asrs;
|
||||
using Lab505.Infrastructure.Drivers.Conveyor;
|
||||
using Lab505.Infrastructure.Drivers.Imr;
|
||||
using Lab505.Presentation.Api;
|
||||
using Lab505.Script;
|
||||
using Lab505.Script.Facades;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Lab505.Application.Contexts;
|
||||
|
||||
/// <summary>
|
||||
/// Sim hardware stack: kết nối đến localhost sim server.
|
||||
/// Chạy như IHostedService — tự quản lý background pollers của riêng mình.
|
||||
/// Sim users → context này. Lock/Queue/Workflow hoàn toàn tách biệt với Real stack.
|
||||
/// </summary>
|
||||
public sealed class SimDriverContext : IDriverContext, IHostedService
|
||||
{
|
||||
// ── IDriverContext ────────────────────────────────────────────────────
|
||||
public bool IsReal => false;
|
||||
|
||||
public ImrVdaDriver Imr { get; }
|
||||
public AmrVdaDriver Amr { get; }
|
||||
public IConveyorDriver Conveyor { get; }
|
||||
public IAsrsDriver Asrs { get; }
|
||||
public IDobotDriver Dobot { get; }
|
||||
public ImrOpcUaDriver? ImrOpc { get; }
|
||||
|
||||
public RobotState ImrState { get; }
|
||||
public RobotState AmrState { get; }
|
||||
|
||||
public FlowService Workflow { get; }
|
||||
public IFlowFacade WorkflowFacade { get; }
|
||||
public FlowWithAsrs AsrsFlow { get; }
|
||||
|
||||
public DeviceGroupLock Locks { get; }
|
||||
public DeviceCommandQueue ImrQueue { get; }
|
||||
public DeviceCommandQueue AmrQueue { get; }
|
||||
public DeviceCommandQueue DobotQueue { get; }
|
||||
|
||||
public IImrFacade ImrFacade { get; }
|
||||
public IAmrFacade AmrFacade { get; }
|
||||
public IConveyorFacade ScriptConveyor { get; }
|
||||
public IAsrsFacade ScriptAsrs { get; }
|
||||
public IDobotFacade DobotFacade { get; }
|
||||
public ICondition SystemCondition { get; }
|
||||
|
||||
// ── Public sim-only helpers (for SimStatePushService) ─────────────────
|
||||
public RobotCommandTracker Tracker { get; }
|
||||
public OpcUaClient UaClient { get; }
|
||||
|
||||
// ── Private background services ───────────────────────────────────────
|
||||
private readonly VdaStatePoller _vdaDual;
|
||||
private readonly OpcStatePoller _opcPoller;
|
||||
private readonly ConveyorState _conveyorState;
|
||||
private readonly AsrsState _asrsState;
|
||||
private readonly AmrCommandGuard _amrCommandGuard;
|
||||
private readonly ImrCommandGuard _imrCommandGuard;
|
||||
|
||||
public SimDriverContext(
|
||||
IConfiguration config,
|
||||
IOptions<FlowOptions> wfOpts,
|
||||
ILoggerFactory logFac,
|
||||
ILogger<VdaStatePoller> vdaLogger,
|
||||
INotificationService notif)
|
||||
{
|
||||
// ── Fixed-sim mode service (không bao giờ thay đổi) ───────────────
|
||||
var simMode = new OperationModeService();
|
||||
simMode.SetSimulation();
|
||||
|
||||
// ── OPC UA → sim server ───────────────────────────────────────────
|
||||
string simOpcUrl2 = config["Simulation:OpcUa:EndpointUrl"] ?? "opc.tcp://127.0.0.1:4840";
|
||||
string opcCfg2 = config["Infrastructure:OpcUa:Clients:0:ConfigSection"] ?? "";
|
||||
UaClient = new OpcUaClient(simOpcUrl2, opcCfg2, logFac.CreateLogger<OpcUaClient>(), notif)
|
||||
{
|
||||
KeepAliveInterval = config.GetValue("Infrastructure:OpcUa:Clients:0:KeepAliveIntervalMs", 1000)
|
||||
};
|
||||
|
||||
// ── Robot states ──────────────────────────────────────────────────
|
||||
ImrState = new RobotState();
|
||||
AmrState = new RobotState();
|
||||
|
||||
_conveyorState = new ConveyorState(config, simMode, notif);
|
||||
_asrsState = new AsrsState(config, simMode, notif);
|
||||
|
||||
// ── VDA API → sim server ──────────────────────────────────────────
|
||||
var api = new ApiService(config, simMode);
|
||||
|
||||
// ── State pollers ─────────────────────────────────────────────────
|
||||
int vdaMs = config.GetValue("Infrastructure:Polling:VdaIntervalMs", 300);
|
||||
int opcMs = config.GetValue("Infrastructure:Polling:OpcIntervalMs", 200);
|
||||
_vdaDual = new VdaStatePoller(api, ImrState, AmrState, vdaMs, notif);
|
||||
_opcPoller = new OpcStatePoller(UaClient, ImrState, opcMs);
|
||||
var sysState = new SystemCondition(ImrState, AmrState, _conveyorState, UaClient);
|
||||
SystemCondition = sysState;
|
||||
_amrCommandGuard = new AmrCommandGuard(sysState, AmrState);
|
||||
_imrCommandGuard = new ImrCommandGuard(sysState, ImrState);
|
||||
// ── Drivers ───────────────────────────────────────────────────────
|
||||
Imr = new ImrVdaDriver(api, ImrState, _vdaDual, notif, _imrCommandGuard);
|
||||
Amr = new AmrVdaDriver(api, AmrState, _vdaDual, notif, _amrCommandGuard);
|
||||
Conveyor = new ConveyorDriver(config, _conveyorState, simMode, notif);
|
||||
Asrs = new AsrsDriver(config, _asrsState, simMode,
|
||||
logFac.CreateLogger<AsrsDriver>(), notif);
|
||||
ImrOpc = new ImrOpcUaDriver(UaClient, ImrState);
|
||||
Dobot = new DobotOpcDriver(UaClient, notif);
|
||||
|
||||
// ── Per-stack infra ───────────────────────────────────────────────
|
||||
Locks = new DeviceGroupLock();
|
||||
ImrQueue = new DeviceCommandQueue(maxQueued: 1);
|
||||
AmrQueue = new DeviceCommandQueue(maxQueued: 1);
|
||||
DobotQueue = new DeviceCommandQueue(maxQueued: 1);
|
||||
|
||||
// ── Workflow ──────────────────────────────────────────────────────
|
||||
Tracker = new RobotCommandTracker();
|
||||
Workflow = new FlowService(Conveyor, Imr, Amr, Dobot, sysState, notif);
|
||||
WorkflowFacade = Workflow;
|
||||
AsrsFlow = new FlowWithAsrs(Workflow, Asrs, notif);
|
||||
|
||||
// ── Script interfaces ─────────────────────────────────────────────
|
||||
ImrFacade = new ImrFacade((IImrRaw)Imr);
|
||||
AmrFacade = new AmrFacade((IAmrRaw)Amr);
|
||||
ScriptConveyor = (IConveyorFacade)Conveyor;
|
||||
ScriptAsrs = (IAsrsFacade)Asrs;
|
||||
DobotFacade = new DobotFacade((IDobotRaw)Dobot, (IImrRaw)Imr);
|
||||
}
|
||||
|
||||
// ── IHostedService ────────────────────────────────────────────────────
|
||||
|
||||
public async Task StartAsync(CancellationToken ct)
|
||||
{
|
||||
await UaClient.Start();
|
||||
await _vdaDual.StartAsync(ct);
|
||||
await _opcPoller.StartAsync(ct);
|
||||
await _conveyorState.StartAsync(ct);
|
||||
await _asrsState.StartAsync(ct);
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken ct)
|
||||
{
|
||||
await _vdaDual.StopAsync(ct);
|
||||
await _opcPoller.StopAsync(ct);
|
||||
await _conveyorState.StopAsync(ct);
|
||||
await _asrsState.StopAsync(ct);
|
||||
await UaClient.Stop();
|
||||
}
|
||||
}
|
||||
377
Lab505/Application/Contexts/UserSimSession.cs
Normal file
377
Lab505/Application/Contexts/UserSimSession.cs
Normal file
@@ -0,0 +1,377 @@
|
||||
using Lab505.Application.Services;
|
||||
using Lab505.Application.Condition;
|
||||
using Lab505.Application.Flow;
|
||||
using Lab505.Domain.Entities;
|
||||
|
||||
using Lab505.Infrastructure.State;
|
||||
using Lab505.Infrastructure.Push;
|
||||
using Lab505.Infrastructure.Hubs;
|
||||
using Lab505.Infrastructure.Protocols.OpcUa;
|
||||
using Lab505.Infrastructure.Protocols.Vda5050;
|
||||
using Lab505.Infrastructure.Drivers.Amr;
|
||||
using Lab505.Infrastructure.Drivers.Asrs;
|
||||
using Lab505.Infrastructure.Drivers.Conveyor;
|
||||
using Lab505.Infrastructure.Drivers.Dobot;
|
||||
using Lab505.Infrastructure.Drivers.Imr;
|
||||
using Lab505.Presentation.Api;
|
||||
using Lab505.Script;
|
||||
using Lab505.Script.Facades;
|
||||
using Lab505.Shared;
|
||||
using Lab505.Sim;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Lab505.Application.Contexts;
|
||||
|
||||
/// <summary>
|
||||
/// Per-user isolated simulation session.
|
||||
/// Each sim user gets their own VDA mock server, Modbus sim servers,
|
||||
/// robot state, conveyor state, workflow — all fully independent.
|
||||
/// </summary>
|
||||
public sealed class UserSimSession : IDriverContext, IAsyncDisposable
|
||||
{
|
||||
// ── Identity ─────────────────────────────────────────────────
|
||||
public int UserId { get; }
|
||||
public int Index { get; }
|
||||
public string SimGroupName => $"sim-{UserId}";
|
||||
|
||||
// ── IDriverContext ────────────────────────────────────────────
|
||||
public bool IsReal => false;
|
||||
|
||||
public ImrVdaDriver Imr { get; }
|
||||
public AmrVdaDriver Amr { get; }
|
||||
public IConveyorDriver Conveyor { get; }
|
||||
public IAsrsDriver Asrs { get; }
|
||||
public IDobotDriver Dobot { get; }
|
||||
public ImrOpcUaDriver? ImrOpc => null; // no OPC UA per user
|
||||
|
||||
public RobotState ImrState { get; }
|
||||
public RobotState AmrState { get; }
|
||||
|
||||
public FlowService Workflow { get; }
|
||||
public IFlowFacade WorkflowFacade { get; }
|
||||
public FlowWithAsrs AsrsFlow { get; }
|
||||
|
||||
public DeviceGroupLock Locks { get; }
|
||||
public DeviceCommandQueue ImrQueue { get; }
|
||||
public DeviceCommandQueue AmrQueue { get; }
|
||||
public DeviceCommandQueue DobotQueue { get; }
|
||||
|
||||
public IImrFacade ImrFacade { get; }
|
||||
public IAmrFacade AmrFacade { get; }
|
||||
public IConveyorFacade ScriptConveyor { get; }
|
||||
public IAsrsFacade ScriptAsrs { get; }
|
||||
public IDobotFacade DobotFacade { get; }
|
||||
public ICondition SystemCondition { get; }
|
||||
|
||||
public RobotCommandTracker Tracker { get; }
|
||||
|
||||
// ── Sim servers ───────────────────────────────────────────────
|
||||
private readonly VdaSimulationHostedService _vdaSim;
|
||||
private readonly ModbusSimulationServer_ASRS _asrsSim;
|
||||
private readonly ConveyorModbusServer _conveyorSim;
|
||||
|
||||
// ── Background pollers ────────────────────────────────────────
|
||||
private readonly VdaStatePoller _vdaDual;
|
||||
private readonly ConveyorState _conveyorState;
|
||||
private readonly AsrsState _asrsState;
|
||||
|
||||
// ── State push ────────────────────────────────────────────────
|
||||
private readonly IHubContext<StateHub> _hub;
|
||||
private readonly INotificationService _notif;
|
||||
|
||||
// Transition tracking
|
||||
private bool? _lastImrNbr;
|
||||
private bool? _lastAmrNbr;
|
||||
private readonly Dictionary<string, (string Status, string Label)> _lastImrActions = new();
|
||||
private readonly Dictionary<string, (string Status, string Label)> _lastAmrActions = new();
|
||||
|
||||
public UserSimSession(
|
||||
int userId,
|
||||
int index,
|
||||
ILoggerFactory logFac,
|
||||
IOptions<FlowOptions> wfOpts,
|
||||
INotificationService notif,
|
||||
IHubContext<StateHub> hub,
|
||||
DeviceGroupLock sharedLock)
|
||||
{
|
||||
UserId = userId;
|
||||
Index = index;
|
||||
_hub = hub;
|
||||
_notif = notif;
|
||||
|
||||
int vdaPort = 7300 + index;
|
||||
int asrsPort = 6100 + index;
|
||||
int convPort = 6200 + index;
|
||||
|
||||
// ── Sim servers ───────────────────────────────────────────
|
||||
_vdaSim = new VdaSimulationHostedService(
|
||||
logFac.CreateLogger<VdaSimulationHostedService>(), vdaPort);
|
||||
_asrsSim = new ModbusSimulationServer_ASRS(asrsPort);
|
||||
_conveyorSim = new ConveyorModbusServer(convPort);
|
||||
|
||||
// ── State pollers ─────────────────────────────────────────
|
||||
_conveyorState = new ConveyorState("127.0.0.1", convPort, notif);
|
||||
_asrsState = new AsrsState("127.0.0.1", asrsPort, notif);
|
||||
|
||||
// ── VDA API → per-user sim server ─────────────────────────
|
||||
var api = new ApiService($"http://127.0.0.1:{vdaPort}/");
|
||||
|
||||
// ── Robot states ──────────────────────────────────────────
|
||||
ImrState = new RobotState();
|
||||
AmrState = new RobotState();
|
||||
|
||||
// ── VDA poller ────────────────────────────────────────────
|
||||
_vdaDual = new VdaStatePoller(
|
||||
api, ImrState, AmrState,
|
||||
periodMs: 300, notif: notif);
|
||||
|
||||
// ── Drivers ───────────────────────────────────────────────
|
||||
var simMode = new OperationModeService();
|
||||
simMode.SetSimulation();
|
||||
|
||||
// ConveyorDriver needs IConfiguration but we can pass empty config since
|
||||
// ConveyorState drives the actual IP/port; driver just writes coils.
|
||||
var emptyCfg = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?> {
|
||||
["Infrastructure:Modbus:Endpoints:0:IpAddress"] = "127.0.0.1",
|
||||
["Infrastructure:Modbus:Endpoints:1:IpAddress"] = "127.0.0.1",
|
||||
["Simulation:Modbus:IpAddress"] = "127.0.0.1",
|
||||
["Simulation:ModbusConveyor:Port"] = convPort.ToString(),
|
||||
}).Build();
|
||||
|
||||
Conveyor = new ConveyorDriver(emptyCfg, _conveyorState, simMode, notif);
|
||||
|
||||
var asrsCfg = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?> {
|
||||
["Infrastructure:Modbus:Endpoints:2:IpAddress"] = "127.0.0.1",
|
||||
["Simulation:Modbus:IpAddress"] = "127.0.0.1",
|
||||
["Infrastructure:Modbus:Endpoints:2:Port"] = asrsPort.ToString(),
|
||||
}).Build();
|
||||
|
||||
Asrs = new AsrsDriver(asrsCfg, _asrsState, simMode,
|
||||
logFac.CreateLogger<AsrsDriver>(), notif);
|
||||
Dobot = new NoOpDobotDriver();
|
||||
|
||||
// ── Per-stack infra ────────────────────────────────────────
|
||||
Locks = sharedLock;
|
||||
ImrQueue = new DeviceCommandQueue(maxQueued: 1);
|
||||
AmrQueue = new DeviceCommandQueue(maxQueued: 1);
|
||||
DobotQueue = new DeviceCommandQueue(maxQueued: 1);
|
||||
|
||||
// ── Workflow ───────────────────────────────────────────────
|
||||
// SystemCondition needs OpcUaClient for DobotOnline; use dummy (never started)
|
||||
var dummyUa = new OpcUaClient("opc.tcp://127.0.0.1:14840", "", logFac.CreateLogger<OpcUaClient>());
|
||||
var sysState = new SystemCondition(ImrState, AmrState, _conveyorState, dummyUa);
|
||||
SystemCondition = sysState;
|
||||
|
||||
var imrGuard = new ImrCommandGuard(sysState, ImrState);
|
||||
var amrGuard = new AmrCommandGuard(sysState, AmrState);
|
||||
Imr = new ImrVdaDriver(api, ImrState, _vdaDual, notif, imrGuard);
|
||||
Amr = new AmrVdaDriver(api, AmrState, _vdaDual, notif, amrGuard);
|
||||
|
||||
Tracker = new RobotCommandTracker();
|
||||
Workflow = new FlowService(Conveyor, Imr, Amr, Dobot, sysState, notif);
|
||||
WorkflowFacade = Workflow;
|
||||
AsrsFlow = new FlowWithAsrs(Workflow, Asrs, notif);
|
||||
|
||||
// ── Script interfaces ──────────────────────────────────────
|
||||
ImrFacade = new ImrFacade((IImrRaw)Imr);
|
||||
AmrFacade = new AmrFacade((IAmrRaw)Amr);
|
||||
ScriptConveyor = (IConveyorFacade)Conveyor;
|
||||
ScriptAsrs = (IAsrsFacade)Asrs;
|
||||
DobotFacade = new DobotFacade((IDobotRaw)Dobot, (IImrRaw)Imr);
|
||||
}
|
||||
|
||||
// ── Lifecycle ─────────────────────────────────────────────────
|
||||
|
||||
public async Task StartAsync(CancellationToken ct)
|
||||
{
|
||||
// Start sim servers first
|
||||
_vdaSim.Start();
|
||||
_asrsSim.Start();
|
||||
_conveyorSim.Start();
|
||||
|
||||
// Give servers a moment to bind their ports
|
||||
await Task.Delay(50, ct);
|
||||
|
||||
// Start background pollers
|
||||
await _vdaDual.StartAsync(ct);
|
||||
await _conveyorState.StartAsync(ct);
|
||||
await _asrsState.StartAsync(ct);
|
||||
|
||||
// Subscribe to state events for push
|
||||
SubscribeEvents();
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken ct)
|
||||
{
|
||||
UnsubscribeEvents();
|
||||
|
||||
await _vdaDual.StopAsync(ct);
|
||||
await _conveyorState.StopAsync(ct);
|
||||
await _asrsState.StopAsync(ct);
|
||||
|
||||
_vdaSim.Stop();
|
||||
_asrsSim.Stop();
|
||||
_conveyorSim.Stop();
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
(Conveyor as IDisposable)?.Dispose();
|
||||
_vdaSim.Dispose();
|
||||
_asrsSim.Dispose();
|
||||
_conveyorSim.Dispose();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
// ── State push ─────────────────────────────────────────────────
|
||||
|
||||
private void SubscribeEvents()
|
||||
{
|
||||
ImrState.OnUpdated += PushImrState;
|
||||
AmrState.OnUpdated += PushAmrState;
|
||||
Conveyor.ConveyorState!.OnStateChanged += PushConveyorState;
|
||||
Asrs.AsrsState.OnStatusChanged += PushAsrsState;
|
||||
Asrs.OnOperationStateChanged += PushAsrsState;
|
||||
Workflow.RunningStateChanged += PushWorkflowState;
|
||||
Tracker.OnChanged += PushWorkflowState;
|
||||
ImrQueue.OnChanged += PushWorkflowState;
|
||||
AmrQueue.OnChanged += PushWorkflowState;
|
||||
DobotQueue.OnChanged += PushWorkflowState;
|
||||
Locks.OnChanged += PushLockState;
|
||||
}
|
||||
|
||||
private void UnsubscribeEvents()
|
||||
{
|
||||
ImrState.OnUpdated -= PushImrState;
|
||||
AmrState.OnUpdated -= PushAmrState;
|
||||
Conveyor.ConveyorState!.OnStateChanged -= PushConveyorState;
|
||||
Asrs.AsrsState.OnStatusChanged -= PushAsrsState;
|
||||
Asrs.OnOperationStateChanged -= PushAsrsState;
|
||||
Workflow.RunningStateChanged -= PushWorkflowState;
|
||||
Tracker.OnChanged -= PushWorkflowState;
|
||||
ImrQueue.OnChanged -= PushWorkflowState;
|
||||
AmrQueue.OnChanged -= PushWorkflowState;
|
||||
DobotQueue.OnChanged -= PushWorkflowState;
|
||||
Locks.OnChanged -= PushLockState;
|
||||
}
|
||||
|
||||
public async Task PushAllToCallerAsync(IClientProxy caller)
|
||||
{
|
||||
await caller.SendAsync(HubContracts.ImrStateEvent, BuildRobotDto(ImrState, overrideDobot: true));
|
||||
await caller.SendAsync(HubContracts.AmrStateEvent, BuildRobotDto(AmrState));
|
||||
await caller.SendAsync(HubContracts.ConveyorStateEvent, BuildConveyorDto());
|
||||
await caller.SendAsync(HubContracts.AsrsStateEvent, BuildAsrsDto());
|
||||
await caller.SendAsync(HubContracts.WorkflowStateEvent, BuildWorkflowDto());
|
||||
await caller.SendAsync(HubContracts.LockStateEvent, BuildLockDto());
|
||||
await caller.SendAsync(HubContracts.SystemStateEvent, new SystemStateDto(true, false));
|
||||
}
|
||||
|
||||
private void PushImrState()
|
||||
{
|
||||
NotifyStateTransitions(ImrState, "IMR", ref _lastImrNbr, _lastImrActions);
|
||||
Fire(PushImrStateAsync);
|
||||
}
|
||||
|
||||
private void PushAmrState()
|
||||
{
|
||||
NotifyStateTransitions(AmrState, "AMR2WS", ref _lastAmrNbr, _lastAmrActions);
|
||||
Fire(PushAmrStateAsync);
|
||||
}
|
||||
|
||||
private void PushConveyorState() => Fire(PushConveyorStateAsync);
|
||||
private void PushAsrsState() => Fire(PushAsrsStateAsync);
|
||||
private void PushWorkflowState() => Fire(PushWorkflowStateAsync);
|
||||
private void PushLockState() => Fire(PushLockStateAsync);
|
||||
|
||||
private async void Fire(Func<Task> push)
|
||||
{
|
||||
try { await push(); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
private Task PushImrStateAsync()
|
||||
=> _hub.Clients.Group(SimGroupName).SendAsync(HubContracts.ImrStateEvent, BuildRobotDto(ImrState, overrideDobot: true));
|
||||
|
||||
private Task PushAmrStateAsync()
|
||||
=> _hub.Clients.Group(SimGroupName).SendAsync(HubContracts.AmrStateEvent, BuildRobotDto(AmrState));
|
||||
|
||||
private Task PushConveyorStateAsync()
|
||||
=> _hub.Clients.Group(SimGroupName).SendAsync(HubContracts.ConveyorStateEvent, BuildConveyorDto());
|
||||
|
||||
private Task PushAsrsStateAsync()
|
||||
=> _hub.Clients.Group(SimGroupName).SendAsync(HubContracts.AsrsStateEvent, BuildAsrsDto());
|
||||
|
||||
private Task PushWorkflowStateAsync()
|
||||
=> _hub.Clients.Group(SimGroupName).SendAsync(HubContracts.WorkflowStateEvent, BuildWorkflowDto());
|
||||
|
||||
private Task PushLockStateAsync()
|
||||
=> _hub.Clients.Group(SimGroupName).SendAsync(HubContracts.LockStateEvent, BuildLockDto());
|
||||
|
||||
// ── DTO builders ───────────────────────────────────────────────
|
||||
|
||||
// In sim there is no OPC UA → CodeDobotStatus_Opc stays at default 9999 (= "off").
|
||||
// overrideDobot=true → idle/0 so the Dobot panel shows as online.
|
||||
private static RobotStateDto BuildRobotDto(RobotState s, bool overrideDobot = false)
|
||||
=> StateDtoFactory.BuildRobotDto(s, overrideDobot);
|
||||
|
||||
private ConveyorPushDto BuildConveyorDto() => StateDtoFactory.BuildConveyorDto(Conveyor.ConveyorState);
|
||||
private AsrsPushDto BuildAsrsDto() => StateDtoFactory.BuildAsrsDto(Asrs.AsrsState, Asrs);
|
||||
private WorkflowStateDto BuildWorkflowDto() => StateDtoFactory.BuildWorkflowDto(Workflow, Tracker, ImrQueue, AmrQueue, DobotQueue);
|
||||
|
||||
private LockStateDto BuildLockDto() => StateDtoFactory.BuildLockDto(Locks);
|
||||
|
||||
// ── Transition helper ──────────────────────────────────────────
|
||||
|
||||
private void NotifyStateTransitions(
|
||||
RobotState state, string robot,
|
||||
ref bool? lastNbr,
|
||||
Dictionary<string, (string Status, string Label)> lastActions)
|
||||
{
|
||||
string NbrStr() => state.NewBaseRequest.HasValue
|
||||
? state.NewBaseRequest.Value.ToString().ToLower()
|
||||
: "không có";
|
||||
|
||||
// ── Action state changes ──────────────────────────────────
|
||||
var currentIds = new HashSet<string>();
|
||||
foreach (var a in state.ActionStates ?? [])
|
||||
{
|
||||
if (a is null || a.ActionID is not string id) continue;
|
||||
var status = a.ActionStatus ?? "không có";
|
||||
var label = a.ActionType ?? id;
|
||||
currentIds.Add(id);
|
||||
if (StateDtoFactory.SkipActions.Contains(label)) { lastActions[id] = (status, label); continue; }
|
||||
bool isNew = !lastActions.TryGetValue(id, out var prev);
|
||||
bool isChanged = !isNew && prev.Status != status;
|
||||
if (isNew || isChanged)
|
||||
{
|
||||
// WAITING/INITIALIZING là trạng thái chuyển tiếp rất nhanh — không cần thông báo
|
||||
if (status is not ("WAITING" or "INITIALIZING"))
|
||||
{
|
||||
string level = status switch
|
||||
{
|
||||
"FINISHED" => "success",
|
||||
"FAILED" or "ABORTED" => "error",
|
||||
_ => "info"
|
||||
};
|
||||
_notif.Notify($"[{robot}] {label}: {status} | NewBaseRequest={NbrStr()}", level);
|
||||
}
|
||||
}
|
||||
lastActions[id] = (status, label);
|
||||
}
|
||||
foreach (var key in lastActions.Keys.Where(k => !currentIds.Contains(k)).ToList())
|
||||
lastActions.Remove(key);
|
||||
|
||||
// ── NBR change (MoveTo navigation) ────────────────────────
|
||||
var nbr = state.NewBaseRequest;
|
||||
if (lastNbr.HasValue && nbr != lastNbr && state.MoveTarget != null)
|
||||
{
|
||||
string nbrVal = nbr.HasValue ? nbr.Value.ToString().ToLower() : "không có";
|
||||
string level = nbr == true ? "success" : "info";
|
||||
_notif.Notify($"[{robot}] MoveTo {state.MoveTarget}: NewBaseRequest={nbrVal}", level);
|
||||
}
|
||||
lastNbr = nbr;
|
||||
}
|
||||
}
|
||||
10
Lab505/Application/Flow/FlowOptions.cs
Normal file
10
Lab505/Application/Flow/FlowOptions.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace Lab505.Application.Flow;
|
||||
|
||||
public class FlowOptions
|
||||
{
|
||||
public int NbrTimeoutMs { get; set; } = 1_200_000;
|
||||
public int PositionTimeoutMs { get; set; } = 1_200_000;
|
||||
public int ActionTimeoutMs { get; set; } = 1_200_000;
|
||||
public int CoilTimeoutMs { get; set; } = 5_000;
|
||||
public int DobotHomeDelayMs { get; set; } = 8_000;
|
||||
}
|
||||
498
Lab505/Application/Flow/FlowService.cs
Normal file
498
Lab505/Application/Flow/FlowService.cs
Normal file
@@ -0,0 +1,498 @@
|
||||
using Lab505.Application.Condition;
|
||||
using Lab505.Application.Services;
|
||||
using Lab505.Domain.Entities;
|
||||
using Lab505.Infrastructure.Drivers.Amr;
|
||||
|
||||
using Lab505.Infrastructure.Drivers.Conveyor;
|
||||
using Lab505.Infrastructure.Drivers.Dobot;
|
||||
using Lab505.Infrastructure.Drivers.Imr;
|
||||
using Lab505.Script;
|
||||
using Lab505.Shared;
|
||||
|
||||
namespace Lab505.Application.Flow;
|
||||
|
||||
public class FlowService : IFlowFacade
|
||||
{
|
||||
// ── Drivers ───────────────────────────────────────────────────
|
||||
private readonly IConveyorDriver _conveyor;
|
||||
private readonly ImrVdaDriver _imr;
|
||||
private readonly AmrVdaDriver _amr;
|
||||
private readonly IDobotDriver _dobot;
|
||||
private readonly SystemCondition _sys;
|
||||
private readonly INotificationService _notif;
|
||||
|
||||
// ── State watchers ─────────────────────────────────────────────
|
||||
private readonly RobotConditionWaiter _imrW;
|
||||
private readonly RobotConditionWaiter _amrW;
|
||||
|
||||
// ── Timeouts ───────────────────────────────────────────────────
|
||||
private static readonly TimeSpan ACTION = TimeSpan.FromMinutes(20);
|
||||
private static readonly TimeSpan POS = TimeSpan.FromMinutes(30);
|
||||
private static readonly TimeSpan COIL = TimeSpan.FromMinutes(10);
|
||||
|
||||
// ── IFlowFacade state ─────────────────────────────────────────
|
||||
private bool _isRunning;
|
||||
private string? _lastError;
|
||||
private int _completedCycles;
|
||||
private CancellationTokenSource? _runCts;
|
||||
|
||||
public bool IsRunning => _isRunning;
|
||||
public string? LastError => _lastError;
|
||||
public int CompletedCycles => _completedCycles;
|
||||
public event Action? RunningStateChanged;
|
||||
|
||||
// ── Constructor ────────────────────────────────────────────────
|
||||
public FlowService(
|
||||
IConveyorDriver conveyor,
|
||||
ImrVdaDriver imr, AmrVdaDriver amr, IDobotDriver dobot,
|
||||
SystemCondition sys,
|
||||
INotificationService notif)
|
||||
{
|
||||
_conveyor = conveyor;
|
||||
_imr = imr; _amr = amr; _dobot = dobot;
|
||||
_sys = sys; _notif = notif;
|
||||
|
||||
_imrW = new RobotConditionWaiter(_imr.State);
|
||||
_amrW = new RobotConditionWaiter(_amr.State);
|
||||
}
|
||||
|
||||
// ── Dobot ──────────────────────────────────────────────────────
|
||||
|
||||
public async Task DobotGoHome(CancellationToken t = default)
|
||||
{
|
||||
await _dobot.Cancel(t);
|
||||
await _dobot.GoHome(t);
|
||||
await Task.Delay(8000, t);
|
||||
}
|
||||
|
||||
// ── Send helper — HTTP reject chỉ cảnh báo, không dừng flow ──
|
||||
|
||||
private static async Task TrySend(Func<Task> send)
|
||||
{
|
||||
try { await send(); }
|
||||
catch (InvalidOperationException) { }
|
||||
}
|
||||
|
||||
private static async Task WaitMoveAsync(
|
||||
RobotConditionWaiter waiter,
|
||||
Func<CancellationToken, Task> send,
|
||||
TimeSpan timeout,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var wait = waiter.WaitMoveTo(timeout, ct);
|
||||
await TrySend(() => send(ct));
|
||||
await wait;
|
||||
}
|
||||
|
||||
private static async Task WaitUndockAsync(
|
||||
RobotConditionWaiter waiter,
|
||||
Func<CancellationToken, Task<string>> send,
|
||||
TimeSpan timeout,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var nbrWait = waiter.WaitMoveTo(timeout, ct);
|
||||
string? actionId = null;
|
||||
|
||||
await TrySend(async () => actionId = await send(ct));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(actionId))
|
||||
{
|
||||
await nbrWait;
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.WhenAll(
|
||||
nbrWait,
|
||||
waiter.WaitActionIdCompleted(actionId, timeout, ct));
|
||||
}
|
||||
|
||||
private static async Task WaitActionAsync(
|
||||
RobotConditionWaiter waiter,
|
||||
string actionType,
|
||||
Func<Task> send,
|
||||
TimeSpan timeout,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var wait = waiter.ActionStates(actionType).WaitEitherCompleted(timeout, ct);
|
||||
await TrySend(send);
|
||||
await wait;
|
||||
}
|
||||
|
||||
// ── IMR primitives ─────────────────────────────────────────────
|
||||
|
||||
public async Task IMR_Undock_C1(CancellationToken t = default)
|
||||
{
|
||||
await WaitUndockAsync(
|
||||
_imrW,
|
||||
token => _imr.UndockFromStation_IMR(-RobotPositions.IMR_UNDOCK_C1, RobotPositions.IMR_UNDOCK_VEL, token),
|
||||
ACTION,
|
||||
t);
|
||||
}
|
||||
|
||||
public async Task IMR_Undock_ABB(CancellationToken t = default)
|
||||
{
|
||||
await WaitUndockAsync(
|
||||
_imrW,
|
||||
token => _imr.UndockFromStation_IMR(-RobotPositions.IMR_UNDOCK_ABB, RobotPositions.IMR_UNDOCK_VEL, token),
|
||||
ACTION,
|
||||
t);
|
||||
}
|
||||
|
||||
public async Task IMR_MoveToC1(CancellationToken t = default)
|
||||
{
|
||||
await WaitMoveAsync(_imrW, _imr.MoveToC1, POS, t);
|
||||
}
|
||||
|
||||
public async Task IMR_MoveToABB(CancellationToken t = default)
|
||||
{
|
||||
await WaitMoveAsync(_imrW, _imr.MoveToAbb, POS, t);
|
||||
}
|
||||
|
||||
public async Task IMR_Load(CancellationToken t = default)
|
||||
=> await WaitActionAsync(_imrW, "Load", () => _imr.Load_Vda(t), ACTION, t);
|
||||
|
||||
public async Task IMR_Unload(CancellationToken t = default)
|
||||
=> await WaitActionAsync(_imrW, "UnLoad", () => _imr.Unload_Vda(t), ACTION, t);
|
||||
|
||||
public async Task IMR_PickUp(int ok, int ng, CancellationToken t = default)
|
||||
=> await WaitActionAsync(_imrW, "PickUp", () => _imr.PickUp_Vda(ok, ng, t), ACTION, t);
|
||||
|
||||
// ── AMR primitives ─────────────────────────────────────────────
|
||||
|
||||
public async Task AMR_Undock(CancellationToken t = default)
|
||||
{
|
||||
await WaitUndockAsync(_amrW, _amr.UndockFromStation_AMR, ACTION, t);
|
||||
}
|
||||
|
||||
public async Task AMR_MoveToC1(CancellationToken t = default)
|
||||
{
|
||||
await WaitMoveAsync(_amrW, _amr.MoveToCap1, POS, t);
|
||||
}
|
||||
|
||||
public async Task AMR_MoveToC2(CancellationToken t = default)
|
||||
{
|
||||
await WaitMoveAsync(_amrW, _amr.MoveToCap2, POS, t);
|
||||
}
|
||||
|
||||
public async Task AMR_Load(CancellationToken t = default)
|
||||
=> await WaitActionAsync(_amrW, "UpLoad", () => _amr.Load_Vda(t), ACTION, t);
|
||||
|
||||
public async Task AMR_Unload(CancellationToken t = default)
|
||||
=> await WaitActionAsync(_amrW, "UnLoad", () => _amr.Unload_Vda(t), ACTION, t);
|
||||
|
||||
// ── Recovery helpers ───────────────────────────────────────────
|
||||
|
||||
public async Task EnsureImrAtC1(CancellationToken t = default)
|
||||
{
|
||||
await DobotGoHome(t);
|
||||
switch (_sys.DetectImr())
|
||||
{
|
||||
case ImrKnownPos.AtC1:
|
||||
return; // đã ở C1, không cần làm gì
|
||||
case ImrKnownPos.AtABB:
|
||||
await IMR_Undock_ABB(t);
|
||||
break;
|
||||
case ImrKnownPos.BackFromABB:
|
||||
case ImrKnownPos.BackFromC1:
|
||||
break; // đã lùi, sẵn sàng di chuyển
|
||||
default:
|
||||
throw new InvalidOperationException(
|
||||
$"IMR vị trí không xác định ({_sys.Imr.X_Vda:F2}, {_sys.Imr.Y_Vda:F2}) — không thể EnsureImrAtC1");
|
||||
}
|
||||
await IMR_MoveToC1(t);
|
||||
}
|
||||
|
||||
public async Task EnsureAmrAtC1(CancellationToken t = default)
|
||||
{
|
||||
switch (_sys.DetectAmr())
|
||||
{
|
||||
case AmrKnownPos.AtCap1:
|
||||
case AmrKnownPos.AtCap2:
|
||||
await AMR_Undock(t);
|
||||
break;
|
||||
case AmrKnownPos.BackFromCap1:
|
||||
case AmrKnownPos.BackFromCap2:
|
||||
case AmrKnownPos.AtHome:
|
||||
break; // đã lùi/undocked, sẵn sàng di chuyển
|
||||
default:
|
||||
throw new InvalidOperationException(
|
||||
$"AMR vị trí không xác định ({_sys.Amr.X_Vda:F2}, {_sys.Amr.Y_Vda:F2}) — không thể EnsureAmrAtC1");
|
||||
}
|
||||
await AMR_MoveToC1(t);
|
||||
}
|
||||
|
||||
public async Task EnsureAmrAtCap2(CancellationToken t = default)
|
||||
{
|
||||
switch (_sys.DetectAmr())
|
||||
{
|
||||
case AmrKnownPos.AtCap2:
|
||||
return; // đã ở Cap2, không cần làm gì
|
||||
case AmrKnownPos.AtCap1:
|
||||
await AMR_Undock(t);
|
||||
break;
|
||||
case AmrKnownPos.BackFromCap1:
|
||||
case AmrKnownPos.BackFromCap2:
|
||||
case AmrKnownPos.AtHome:
|
||||
break; // đã lùi/undocked, sẵn sàng di chuyển
|
||||
default:
|
||||
throw new InvalidOperationException(
|
||||
$"AMR vị trí không xác định ({_sys.Amr.X_Vda:F2}, {_sys.Amr.Y_Vda:F2}) — không thể EnsureAmrAtCap2");
|
||||
}
|
||||
await AMR_MoveToC2(t);
|
||||
}
|
||||
|
||||
// ── Step operations ────────────────────────────────────────────
|
||||
|
||||
/// <summary>① Đưa IMR về C1, AMR về Cap2 (song song)</summary>
|
||||
public async Task Op_Step1_Init(CancellationToken t = default)
|
||||
{
|
||||
_sys.Assert(s => s.ImrOnline && s.AmrOnline, "IMR hoặc AMR đang offline");
|
||||
var imrPos = _sys.DetectImr();
|
||||
var amrPos = _sys.DetectAmr();
|
||||
|
||||
List<Task> tasks = [];
|
||||
if (imrPos != ImrKnownPos.AtC1) tasks.Add(EnsureImrAtC1(t));
|
||||
if (amrPos != AmrKnownPos.AtCap2) tasks.Add(EnsureAmrAtCap2(t));
|
||||
if (tasks.Count > 0) await WhenAllThrow(tasks.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>② AMR nạp hàng từ C2 — C2Out bật khi Load RUNNING, kết thúc khi FINISHED</summary>
|
||||
public async Task Op_Step2_LoadFromC2(CancellationToken t = default)
|
||||
{
|
||||
_sys.Assert(s => s.AmrOnline && s.C2Online, "AMR offline hoặc C2 mất kết nối");
|
||||
// Gửi lệnh và đợi RUNNING song song — C2Out bật ngay khi robot RUNNING, không block vào HTTP
|
||||
var loadTask = TrySend(() => _amr.Load_Vda(t));
|
||||
await _amrW.ActionStates("UpLoad").Running.Wait(ACTION, t);
|
||||
_conveyor.C2Out(true);
|
||||
try
|
||||
{
|
||||
await loadTask;
|
||||
await _amrW.ActionStates("UpLoad").WaitEitherCompleted(ACTION, t);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Tắt C2Out + C2NotGoods dù thành công hay fail
|
||||
_conveyor.C2Out(false);
|
||||
_conveyor.C2NotGoods(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>③ AMR undock + di chuyển sang Cap1</summary>
|
||||
public async Task Op_Step3_ToCap1(CancellationToken t = default)
|
||||
{
|
||||
await AMR_Undock(t);
|
||||
await AMR_MoveToC1(t);
|
||||
}
|
||||
|
||||
/// <summary>④ Trao đổi AMR→IMR qua C1: AMR Unload + IMR Load với coil sequencing</summary>
|
||||
public async Task Op_C1_AmrToImr(CancellationToken t = default)
|
||||
{
|
||||
await _sys.Require(s => s.ImrReadyAtC1 && s.AmrReadyAtCap1,
|
||||
"IMR hoặc AMR chưa ở vị trí C1", (int)POS.TotalMilliseconds, t);
|
||||
|
||||
// Gửi IMR Load + bật C1Out song song — không block vào HTTP
|
||||
var imrLoadTask = TrySend(() => _imr.Load_Vda(t));
|
||||
_conveyor.C1Out(true);
|
||||
|
||||
// Gửi AMR Unload song song với WaitForCoil — không block vào HTTP response
|
||||
bool amrUnloadActive = _amr.State.ActionStates.Any(a =>
|
||||
a.ActionType == "UnLoad" &&
|
||||
(a.ActionStatus == "RUNNING" || a.ActionStatus == "INITIALIZING"));
|
||||
Task unloadTask;
|
||||
if (amrUnloadActive)
|
||||
{
|
||||
NotifyFlow("AMR UnLoad", "info", "đã có action đang chạy, bỏ qua gửi lệnh mới");
|
||||
unloadTask = Task.CompletedTask;
|
||||
}
|
||||
else
|
||||
unloadTask = TrySend(() => _amr.Unload_Vda(t));
|
||||
|
||||
// Chờ C1Out tắt (hàng qua sensor) → bật C1IMRout ngay, không chờ HTTP response
|
||||
// C1Out is not true = false hoặc null (mất kết nối Modbus cũng coi là "hàng đã qua")
|
||||
await _conveyor.WaitForCoil(() => _conveyor.ConveyorState?.C1Out is not true, (int)COIL.TotalMilliseconds, t);
|
||||
NotifyFlow("C1Out=False", "info", "bật C1IMRout ngay");
|
||||
_conveyor.C1IMRout(true);
|
||||
|
||||
// Chờ cả HTTP send + AMR Unload + IMR Load hoàn thành
|
||||
await WhenAllThrow(
|
||||
imrLoadTask,
|
||||
unloadTask,
|
||||
_amrW.ActionStates("UnLoad").WaitEitherCompleted(ACTION, t),
|
||||
_imrW.ActionStates("Load").WaitEitherCompleted(ACTION, t));
|
||||
|
||||
_conveyor.C1IMRout(false);
|
||||
_conveyor.C1NotGoods(false);
|
||||
}
|
||||
|
||||
/// <summary>⑤ IMR: undock C1 → ABB → PickUp → undock ABB → C1</summary>
|
||||
public async Task Op_Step5_Process(int ok, int ng, CancellationToken t = default)
|
||||
{
|
||||
_sys.Assert(s => s.ImrOnline && s.ImrReadyAtC1, "IMR chưa sẵn sàng tại C1");
|
||||
await IMR_Undock_C1(t);
|
||||
await Task.Delay(50, t);
|
||||
await IMR_MoveToABB(t);
|
||||
await Task.Delay(50, t);
|
||||
await IMR_PickUp(ok, ng, t);
|
||||
await DobotGoHome(t);
|
||||
await Task.Delay(50, t);
|
||||
await IMR_Undock_ABB(t);
|
||||
await Task.Delay(50, t);
|
||||
await IMR_MoveToC1(t);
|
||||
}
|
||||
|
||||
/// <summary>⑥ Trao đổi IMR→AMR qua C1: IMR Unload + AMR Load với coil sequencing</summary>
|
||||
public async Task Op_C1_ImrToAmr(CancellationToken t = default)
|
||||
{
|
||||
// Reset nếu C1IMRin còn đang bật từ lần trước
|
||||
if (_sys.C1IMRinOn) _conveyor.C1IMRin(false);
|
||||
|
||||
await _sys.Require(s => s.ImrReadyAtC1 && s.AmrReadyAtCap1,
|
||||
"IMR hoặc AMR chưa ở vị trí C1", (int)POS.TotalMilliseconds, t);
|
||||
|
||||
// Gửi IMR Unload + bật C1IMRin song song — không block vào HTTP
|
||||
var imrUnloadTask = TrySend(() => _imr.Unload_Vda(t));
|
||||
_conveyor.C1IMRin(true);
|
||||
|
||||
// Gửi AMR Load song song với WaitForCoil — không block vào HTTP response
|
||||
bool amrLoadActive = _amr.State.ActionStates.Any(a =>
|
||||
a.ActionType == "UpLoad" &&
|
||||
(a.ActionStatus == "RUNNING" || a.ActionStatus == "INITIALIZING"));
|
||||
Task amrLoadTask;
|
||||
if (amrLoadActive)
|
||||
{
|
||||
NotifyFlow("AMR UpLoad", "info", "đã có action đang chạy, bỏ qua gửi lệnh mới");
|
||||
amrLoadTask = Task.CompletedTask;
|
||||
}
|
||||
else
|
||||
amrLoadTask = TrySend(() => _amr.Load_Vda(t));
|
||||
|
||||
// Chờ C1IMRin tắt (hàng qua sensor) → bật C1In ngay, không chờ HTTP response
|
||||
await _conveyor.WaitForCoil(() => _conveyor.ConveyorState?.C1IMRin, false, (int)COIL.TotalMilliseconds, t);
|
||||
NotifyFlow("C1IMRin=False", "info", "bật C1In ngay");
|
||||
_conveyor.C1In(true);
|
||||
|
||||
// Chờ cả HTTP send + IMR Unload + AMR Load hoàn thành
|
||||
await WhenAllThrow(
|
||||
imrUnloadTask,
|
||||
amrLoadTask,
|
||||
_imrW.ActionStates("UnLoad").WaitEitherCompleted(ACTION, t),
|
||||
_amrW.ActionStates("UpLoad").WaitEitherCompleted(ACTION, t));
|
||||
|
||||
await _conveyor.WaitForCoil(() => _conveyor.ConveyorState?.C1In, false, (int)COIL.TotalMilliseconds, t);
|
||||
_conveyor.C1In(false);
|
||||
_conveyor.C1HasGoods(false);
|
||||
}
|
||||
|
||||
/// <summary>⑦ AMR undock + di chuyển sang Cap2</summary>
|
||||
public async Task Op_Step7_ToCap2(CancellationToken t = default)
|
||||
{
|
||||
await AMR_Undock(t);
|
||||
await AMR_MoveToC2(t);
|
||||
}
|
||||
|
||||
/// <summary>⑧ AMR trả hàng về C2</summary>
|
||||
public async Task Op_Step8_UnloadToC2(CancellationToken t = default)
|
||||
{
|
||||
_sys.Assert(s => s.AmrOnline && s.C2Online, "AMR offline hoặc C2 mất kết nối");
|
||||
await _sys.Require(s => s.AmrReadyAtCap2, "AMR chưa ở Cap2", (int)POS.TotalMilliseconds, t);
|
||||
_conveyor.C2In(true);
|
||||
try
|
||||
{
|
||||
await AMR_Unload(t);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_conveyor.C2In(false);
|
||||
_conveyor.C2HasGoods(false);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Home all ───────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Luồng 1: DobotGoHome → IMR lùi khỏi C1 → IMR về ABB (tuần tự)
|
||||
/// Luồng 2: AMR lùi khỏi trạm → AMR về Home (song song với luồng 1)
|
||||
/// </summary>
|
||||
public async Task HomeAll(CancellationToken t = default)
|
||||
{
|
||||
await WhenAllThrow(
|
||||
HomeImr(t),
|
||||
HomeAmr(t));
|
||||
}
|
||||
|
||||
internal async Task HomeImr(CancellationToken t)
|
||||
{
|
||||
switch (_sys.DetectImr())
|
||||
{
|
||||
case ImrKnownPos.AtC1: await IMR_Undock_C1(t); break;
|
||||
case ImrKnownPos.AtABB: await IMR_Undock_ABB(t); break;
|
||||
default: break; // đã lùi hoặc vị trí không xác định — thử di chuyển luôn
|
||||
}
|
||||
await IMR_MoveToABB(t);
|
||||
}
|
||||
|
||||
internal async Task HomeAmr(CancellationToken t)
|
||||
{
|
||||
await AMR_Undock(t);
|
||||
await WaitMoveAsync(_amrW, _amr.MoveToHome, POS, t);
|
||||
}
|
||||
|
||||
// ── Full cycle ─────────────────────────────────────────────────
|
||||
|
||||
public async Task RunCycle(int ok, int ng, CancellationToken token)
|
||||
{
|
||||
_lastError = null;
|
||||
_isRunning = true;
|
||||
RunningStateChanged?.Invoke();
|
||||
|
||||
using var runCts = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
_runCts = runCts;
|
||||
var ct = runCts.Token;
|
||||
|
||||
try
|
||||
{
|
||||
await Op_Step1_Init(ct);
|
||||
await Op_Step2_LoadFromC2(ct);
|
||||
await Op_Step3_ToCap1(ct);
|
||||
await Op_C1_AmrToImr(ct);
|
||||
await Op_Step5_Process(ok, ng, ct);
|
||||
await Op_C1_ImrToAmr(ct);
|
||||
await Op_Step7_ToCap2(ct);
|
||||
await Op_Step8_UnloadToC2(ct);
|
||||
_completedCycles++;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
NotifyFlow("Chu kỳ bị hủy", "warning", source: "Flow");
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_lastError = ex.Message;
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isRunning = false;
|
||||
_runCts = null;
|
||||
RunningStateChanged?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task EmergencyStop()
|
||||
{
|
||||
_runCts?.Cancel();
|
||||
_conveyor.StopAll();
|
||||
await WhenAllThrow(
|
||||
_dobot.Cancel(),
|
||||
_imr.Cancel_Vda(),
|
||||
_amr.Cancel_Vda());
|
||||
}
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────
|
||||
|
||||
private void NotifyFlow(string command, string level = "info", string? detail = null, string source = "WF")
|
||||
=> _notif.Notify(source, command, level, detail);
|
||||
|
||||
private static Task WhenAllThrow(params Task[] tasks) => Task.WhenAll(tasks);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user