commit 120923f9ccb7040618c7260a73bf3267779f21bc Author: trung09122002 Date: Fri Aug 28 11:12:28 2026 +0700 upload diff --git a/.claude/hooks/block-build.sh b/.claude/hooks/block-build.sh new file mode 100755 index 0000000..5ab246e --- /dev/null +++ b/.claude/hooks/block-build.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# PreToolUse hook for the manual-build-handoff skill. +# +# Blocks build / install / launch commands so Claude hands them to the user +# instead of running them. Exit code 2 = block the tool call and send stderr +# back to Claude as feedback. +# +# Bypass: append "# user-approved" to the command. Only do this when the user +# explicitly asked Claude to run that command. + +set -u + +payload=$(cat) + +extract_command() { + if command -v python3 >/dev/null 2>&1; then + printf '%s' "$payload" | python3 -c \ + 'import json,sys; print(json.load(sys.stdin).get("tool_input",{}).get("command",""))' 2>/dev/null + elif command -v jq >/dev/null 2>&1; then + printf '%s' "$payload" | jq -r '.tool_input.command // ""' 2>/dev/null + else + return 1 + fi +} + +# No JSON parser available: match against the raw payload. Slightly over-broad +# (the description field is included), which fails safe toward blocking. +cmd=$(extract_command) || cmd=$payload + +case "$cmd" in + *"# user-approved"*) exit 0 ;; +esac + +PATTERN='(colcon (build|test)|catkin_make|catkin build|cmake --build|(^|[;&|("] *)make( |$)|ninja|bazel build|cargo build|go build|docker build|docker run|docker compose up|pip[0-9.]* install|npm (install|run build)|yarn (install|build)|apt(-get)? install|rosdep install|roslaunch|ros2 (launch|run)|rosrun|rosbag |trtexec|dfu-util|openocd)' + +if printf '%s' "$cmd" | grep -qE "$PATTERN"; then + cat >&2 <<'EOF' +Blocked by the manual-build-handoff hook. + +Do not run build / install / launch commands yourself. Print a handoff block +instead and stop: + + - working directory + - environment prerequisites (source ...) + - the exact copy-pasteable command + - expected time and success signal + - what the user should report back + +Tip: suggest `2>&1 | tee /tmp/.log` so you can read the result back from +the log file instead of asking the user to paste it. + +If the user explicitly asked you to run this command, append "# user-approved" +to the end of the command to bypass this hook. +EOF + exit 2 +fi + +exit 0 diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..d19e97a --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-build.sh" + } + ] + } + ] + } +} diff --git a/.claude/skills/cavecrew/SKILL.md b/.claude/skills/cavecrew/SKILL.md new file mode 100644 index 0000000..d5574a3 --- /dev/null +++ b/.claude/skills/cavecrew/SKILL.md @@ -0,0 +1,83 @@ +--- +name: cavecrew +description: Framework giao việc cho 3 subagents chuyên biệt với output nén ~60% — investigator tìm code, builder sửa file, reviewer audit diffs. Dùng khi người dùng muốn 'tìm nơi function X được gọi', 'sửa nhỏ ở file này', 'review diff này', hoặc khi context budget đang cạn và cần delegate subtasks hiệu quả. +--- + +# Cavecrew + +## Mục tiêu + +Giao subtasks cho subagents chuyên biệt với output nhỏ hơn ~60% so với vanilla agents, phù hợp khi context budget hạn chế. + +## Ba Agents + +### cavecrew-investigator +Tìm code definitions, callers, usage patterns. + +**Output contract:** `path:line — symbol — note` + +**Dùng cho:** tìm function định nghĩa ở đâu, ai gọi nó, pattern xuất hiện ở đâu. + +### cavecrew-builder +Sửa chính xác tối đa 2 files. + +**Output contract:** `path:line-range — change` + verification status hoặc terminal codes (`too-big`, `ambiguous`, `done`) + +**Dùng cho:** targeted changes khi scope hẹp và rõ ràng. + +### cavecrew-reviewer +Audit diffs và branches để tìm defects. + +**Output contract:** emoji-flagged findings theo file và line, với severity totals + +**Dùng cho:** review diff sau khi thay đổi. + +## Pattern Chuẩn + +``` +1. Spawn investigator → tìm target locations +2. Đưa paths cụ thể cho builder → apply changes +3. Chạy reviewer trên diff → verify kết quả +``` + +## Khi nào dùng Cavecrew vs Vanilla + +| Cavecrew | Vanilla | +|---|---| +| Muốn findings ngắn gọn | Cần architectural commentary | +| Tối đa 2 files, scope hẹp | Xử lý 3+ files | +| Context budget hạn chế | Cần deep rationale | +| Pattern lặp lại nhiều lần | Phức tạp, nhiều unknowns | + +## Ví dụ minh hoạ + +**Ví dụ 1: Tìm và fix bug** + +User: "Tìm chỗ nào gọi `process_image()` rồi thêm null check" + +Hành động: +1. Spawn investigator: tìm tất cả callers của `process_image` + → `src/detection.py:45 — process_image — called without null guard` +2. Spawn builder: thêm null check tại line 45 + → `src/detection.py:44-46 — added: if img is None: return — done` +3. Spawn reviewer: check diff + → `L45: ✅ null guard added. No other callers affected.` + +**Ví dụ 2: Investigate trước khi refactor** + +User: "Tôi muốn rename topic `/camera/image` trước khi sửa" + +Spawn investigator: "tìm tất cả chỗ dùng `/camera/image` trong codebase" +→ 3 files với exact locations, sẵn sàng cho builder + +## Khắc phục sự cố + +**Vấn đề:** Builder báo `too-big` — thay đổi quá lớn +**Cách xử lý:** Chia nhỏ task, giao từng phần cho builder riêng biệt + +**Vấn đề:** Investigator trả về quá nhiều results +**Cách xử lý:** Làm hẹp query (thêm file path, function context) trước khi spawn lại + +## Tradeoff + +Output của cavecrew có thể "structured nhưng đôi khi terse đến mức cryptic". Dùng vanilla agents khi cần full explanation. diff --git a/.claude/skills/caveman-commit/SKILL.md b/.claude/skills/caveman-commit/SKILL.md new file mode 100644 index 0000000..39c79d4 --- /dev/null +++ b/.claude/skills/caveman-commit/SKILL.md @@ -0,0 +1,78 @@ +--- +name: caveman-commit +description: Tạo conventional commit messages ngắn gọn dưới 50 ký tự, tập trung vào intent không phải verbosity. Dùng khi người dùng yêu cầu 'viết commit message', 'tạo commit', 'git commit cho thay đổi này', '/caveman-commit', hoặc cần tóm tắt changes cho version control. +--- + +# Caveman Commit + +## Mục tiêu + +Tạo commit messages chính xác, conventional, và tối giản — không filler, không AI attribution, không self-reference. + +## Format + +``` +(): +``` + +- Subject line: ≤50 ký tự (hard limit 72) +- Imperative mood: "add" không phải "added", "fix" không phải "fixed" +- Không dấu chấm cuối +- Không đại từ ngôi thứ nhất (I, we) +- Không "Generated by Claude" hoặc tương tự (trừ khi project policy yêu cầu) +- Không emoji (trừ khi project convention dùng) + +## Khi nào thêm body + +Chỉ thêm body khi thực sự cần: +- Logic không rõ ràng từ subject +- Breaking changes (`BREAKING CHANGE:`) +- Migration steps cần thiết +- Issue references (`Closes #123`) + +Bỏ qua body hoàn toàn khi subject đã tự giải thích. + +## Luôn cần body + +- Breaking changes +- Security fixes +- Reversions (ghi rõ cái gì được revert và tại sao) + +## Ví dụ minh hoạ + +**Ví dụ 1: Bug fix đơn giản** + +User: "Tôi vừa fix null pointer exception trong user login" + +Kết quả: +``` +fix(auth): guard null user before email access +``` + +**Ví dụ 2: Feature mới với breaking change** + +User: "Thêm JWT auth, bỏ session-based auth cũ" + +Kết quả: +``` +feat(auth): replace session auth with JWT + +BREAKING CHANGE: session tokens no longer valid. +Clients must re-authenticate to obtain JWT. +``` + +## Khắc phục sự cố + +**Vấn đề:** Subject line dài hơn 50 ký tự +**Cách xử lý:** Rút gọn scope hoặc bỏ scope, ưu tiên từ mô tả action chính xác nhất + +**Vấn đề:** Không biết type phù hợp +**Cách xử lý:** feat/fix/chore/docs/refactor/test/perf — hỏi nếu cần context + +## Output + +Plain text commit message trong code block, sẵn sàng để paste. Không chạy git, không stage files, không amend commits. + +## Deactivation + +Nói "stop caveman-commit" hoặc "normal mode". diff --git a/.claude/skills/caveman-compress/SKILL.md b/.claude/skills/caveman-compress/SKILL.md new file mode 100644 index 0000000..5590067 --- /dev/null +++ b/.claude/skills/caveman-compress/SKILL.md @@ -0,0 +1,90 @@ +--- +name: caveman-compress +description: Nén prose trong các file markdown như CLAUDE.md, PROJECT_CONTEXT.md, todos thành caveman-speak ngắn gọn để giảm ~46% input tokens, giữ nguyên toàn bộ kỹ thuật và code. Dùng khi người dùng gõ '/caveman-compress ', yêu cầu 'nén file này', 'giảm size của CLAUDE.md', 'compress memory file', hoặc context files quá dài gây tốn tokens. +--- + +# Caveman Compress + +## Mục tiêu + +Rewrite prose sections của markdown files thành terse nhất có thể, giữ nguyên mọi technical fact, code block, và structural element. + +## Trigger + +`/caveman-compress ` hoặc user yêu cầu compress file cụ thể. + +## Quy trình + +### Bước 1: Đọc file + +Đọc file target, xác nhận là markdown/text (không phải code file). + +### Bước 2: Tạo backup + +Lưu bản gốc thành `.original.md` trước khi overwrite. + +### Bước 3: Compress prose + +Áp dụng rules bên dưới cho phần prose, giữ nguyên code blocks và technical content. + +### Bước 4: Validate + +Kiểm tra: không mất thông tin kỹ thuật, structure còn nguyên, không sửa code blocks. + +## Rules Compression + +**Xóa khỏi prose:** +- Articles (a, an, the) +- Filler words (really, basically, simply, just, very) +- Hedging (it seems, I think, có thể, có lẽ) +- Redundant phrases và connective fluff + +**Compress bằng cách:** +- Short synonyms +- Sentence fragments thay câu đầy đủ +- Action-focused language +- Merge redundant points (giữ một example đại diện) + +**Không bao giờ sửa:** +- Nội dung trong ` ``` ... ``` ` — copy EXACTLY +- Inline code trong backticks +- URLs, file paths, commands, technical terms +- Proper nouns, dates, version numbers, env variables +- Markdown headings, lists, tables, frontmatter + +## Ví dụ minh hoạ + +**Ví dụ 1: Compress PROJECT_CONTEXT.md** + +User: "/caveman-compress PROJECT_CONTEXT.md" + +Hành động: +1. Đọc file, tạo `PROJECT_CONTEXT.original.md` +2. Compress từng section prose +3. Giữ nguyên table structures và code examples +4. Output file nén với % reduction + +Trước: "The project uses ROS 2 Humble as the primary middleware framework for inter-process communication between nodes." +Sau: "ROS 2 Humble. IPC between nodes." + +**Ví dụ 2: Compress CLAUDE.md dài** + +User: "CLAUDE.md của tôi quá dài, giảm size đi" + +Kết quả: Compress ~46% prose, giữ nguyên commands, code examples, và technical constraints. + +## Khắc phục sự cố + +**Vấn đề:** Thông tin bị mất sau khi compress +**Cách xử lý:** Restore từ `.original.md` backup, tôi sẽ compress lại cẩn thận hơn + +**Vấn đề:** File là code file (Python, YAML config) +**Cách xử lý:** Skill chỉ xử lý .md, .txt, .tex và extensionless docs. Từ chối code/config files. + +## Note + +Đầy đủ nhất với Python script từ caveman repo (validation + retry tự động). Không có script, compress trực tiếp bằng model theo rules này. + +## Scope + +Chỉ xử lý: `.md`, `.txt`, `.typ`, `.tex`, extensionless documents. Không sửa code files, config files, env files. diff --git a/.claude/skills/caveman-help/SKILL.md b/.claude/skills/caveman-help/SKILL.md new file mode 100644 index 0000000..eb624d8 --- /dev/null +++ b/.claude/skills/caveman-help/SKILL.md @@ -0,0 +1,59 @@ +--- +name: caveman-help +description: Hiển thị bảng tham chiếu nhanh cho toàn bộ hệ thống caveman bao gồm modes, skills, lệnh, và cách tắt. Dùng khi người dùng gõ '/caveman-help', hỏi 'có những caveman mode nào', 'list lệnh caveman', 'quên cú pháp caveman', hoặc cần reminder về các tùy chọn compression. +--- + +# Caveman Help + +## Mục tiêu + +Hiển thị một lần (one-shot) bảng tham chiếu đầy đủ hệ thống caveman. Không thay đổi mode hay session state. + +## Bảng Tham Chiếu Nhanh + +### Modes + +| Mode | Style | Savings | +|---|---|---| +| `lite` | Bỏ filler, giữ câu đầy đủ | ~30% | +| `full` | Fragments, bỏ articles (default) | ~60% | +| `ultra` | Telegraphic, cực ngắn | ~75% | +| `wenyan-lite` | Semi-classical Chinese | ~70% | +| `wenyan-full` | Classical Chinese tối đa | ~85% | + +Bật: `/caveman [mode]` — default là `full` + +### Skills + +| Skill | Trigger | Chức năng | +|---|---|---| +| `caveman` | `/caveman [mode]` | Nén toàn bộ replies | +| `caveman-commit` | `/caveman-commit` | Commit messages ngắn | +| `caveman-review` | `/caveman-review` | Code review nén | +| `caveman-stats` | `/caveman-stats` | Token usage stats | +| `caveman-compress` | `/caveman-compress ` | Nén memory files | +| `cavecrew` | "dùng cavecrew" | Delegation subagents | +| `caveman-help` | `/caveman-help` | Card này | + +### Tắt + +Nói "stop caveman", "normal mode", hoặc "thôi caveman". +Resume bất cứ lúc nào với `/caveman`. + +### Quy tắc bất biến + +- Giữ nguyên ngôn ngữ của user +- Code, commands, error strings, technical terms: **không bao giờ** bị nén +- Security warnings và irreversible actions: tự động revert về normal + +## Ví dụ minh hoạ + +**Ví dụ: User quên cú pháp** + +User: "/caveman-help" + +Kết quả: Card này hiển thị một lần, session state không đổi. + +## Scope + +One-shot display. Không set hay thay đổi bất kỳ mode nào. diff --git a/.claude/skills/caveman-review/SKILL.md b/.claude/skills/caveman-review/SKILL.md new file mode 100644 index 0000000..52656e1 --- /dev/null +++ b/.claude/skills/caveman-review/SKILL.md @@ -0,0 +1,72 @@ +--- +name: caveman-review +description: Review code cực ngắn gọn với format L: severity problem. fix. — tối đa signal, zero filler. Dùng khi người dùng yêu cầu 'review code này', 'check PR', '/caveman-review', 'feedback ngắn gọn', hoặc muốn code review không có lời khen và hedging, chỉ có findings và fixes. +--- + +# Caveman Review + +## Mục tiêu + +Review code với maximum signal, zero filler. Mỗi finding đi kèm line number chính xác và fix cụ thể. + +## Output Format + +``` +L: [severity] . . +``` + +**Severity prefixes:** +- 🔴 bug — gây incorrect behavior +- 🟡 risk — tiềm ẩn vấn đề tùy context +- 🔵 nit — style hoặc minor improvement +- ❓ q — câu hỏi cần hỏi trước + +## Rules + +- Không hedging qualifiers ("I noticed", "you might want to consider", "có thể bạn nên") +- Không preamble ("Here's my review", "Tôi đã xem xét code của bạn") +- Không lời khen ("Great job on the overall structure") +- Luôn ghi: line number + symbol/variable + giải pháp cụ thể +- Code không bị sửa trong review output + +## Ví dụ minh hoạ + +**Ví dụ 1: Bug rõ ràng** + +Bad: "I noticed that on line 42 you're not checking if the user object is null, which could potentially cause issues down the line." + +Good: `L42: 🔴 bug: user null after .find(). Add guard before .email.` + +**Ví dụ 2: Review robotics code** + +``` +L15: 🔴 bug: no encoding check on image_msg. Assert rgb8 or convert. +L31: 🟡 risk: queue_size=1 drops messages at 30fps. Increase to 10. +L48: 🔵 nit: hardcoded threshold 0.5. Move to ROS param. +L67: ❓ q: why lookup TF every callback? Cache transform. +``` + +## Khi nào expand + +Viết đầy đủ hơn cho: +- CVE-level security vulnerabilities +- Architectural decisions cần rationale +- Onboarding context cho team member mới + +Resume terse mode sau đó. + +## Khắc phục sự cố + +**Vấn đề:** Line number không chính xác trong review +**Cách xử lý:** Cung cấp file với line numbers rõ ràng, hoặc paste đoạn code cụ thể + +**Vấn đề:** Muốn cả caveman-review VÀ robotics-code-review +**Cách xử lý:** Dùng `robotics-code-review` để tìm findings, format output theo `caveman-review` style + +## Scope + +Chỉ tạo review comments. Không viết fixes, không approve changes, không chạy linters. + +## Deactivation + +Nói "stop caveman-review" hoặc "normal mode". diff --git a/.claude/skills/caveman-stats/SKILL.md b/.claude/skills/caveman-stats/SKILL.md new file mode 100644 index 0000000..3f2dcea --- /dev/null +++ b/.claude/skills/caveman-stats/SKILL.md @@ -0,0 +1,66 @@ +--- +name: caveman-stats +description: Hiển thị thống kê token usage và estimated savings trong session hiện tại. Dùng khi người dùng gõ '/caveman-stats', hỏi 'tiết kiệm được bao nhiêu tokens', 'show token savings', 'token usage của session này', hoặc muốn đánh giá hiệu quả compression. +--- + +# Caveman Stats + +## Mục tiêu + +Hiển thị số liệu tokens thực tế đã dùng và ước tính savings trong session hiện tại. + +## Trigger + +`/caveman-stats` hoặc user hỏi về token usage stats. + +## Behavior + +Khi không có hook system (standalone skill), estimate session stats: + +1. Đếm số exchanges có caveman mode active +2. Ước tính baseline tokens (không có compression) vs actual +3. Báo cáo savings percentage + +## Output Format + +``` +Session stats: +- Caveman active: N exchanges +- Est. tokens used: ~X +- Est. baseline (no compression): ~Y +- Est. savings: ~Z% (~W tokens) +- Current mode: [lite/full/ultra/off] +``` + +## Ví dụ minh hoạ + +**Ví dụ 1: Check sau session dài** + +User: "/caveman-stats" + +Kết quả: +``` +Session stats: +- Caveman active: 12/15 exchanges +- Est. tokens used: ~4,200 +- Est. baseline (no compression): ~12,000 +- Est. savings: ~65% (~7,800 tokens) +- Current mode: full +``` + +## Khắc phục sự cố + +**Vấn đề:** Số liệu không chính xác +**Nguyên nhân:** Standalone skill chỉ estimate, không đọc session log trực tiếp +**Cách xử lý:** Để có số liệu chính xác 100%, cần cài `hooks/caveman-stats.js` từ repo caveman gốc (juliusbrussee/caveman) + +**Vấn đề:** Skill không biết caveman đã active bao lâu +**Cách xử lý:** Mention khi nào bật caveman để context rõ hơn + +## Note + +Đầy đủ nhất khi cài `hooks/caveman-stats.js` — đọc trực tiếp từ Claude Code session log, không cần estimate. Không có hook, con số là heuristic. + +## Scope + +Read-only display. Không thay đổi session state hay bật/tắt modes. diff --git a/.claude/skills/caveman/SKILL.md b/.claude/skills/caveman/SKILL.md new file mode 100644 index 0000000..ca76988 --- /dev/null +++ b/.claude/skills/caveman/SKILL.md @@ -0,0 +1,65 @@ +--- +name: caveman +description: Giảm ~75% output tokens bằng cách nói ngắn gọn, bỏ từ thừa nhưng giữ nguyên kỹ thuật, code, error strings. Dùng khi người dùng yêu cầu 'ít tokens hơn', 'ngắn gọn thôi', 'caveman mode', '/caveman', 'less verbose', 'talk like caveman', hoặc muốn tiết kiệm tokens trong session dài. +--- + +# Caveman Mode + +## Mục tiêu + +Nén toàn bộ responses để tối thiểu hóa tokens, giữ nguyên mọi thông tin kỹ thuật, code block, và error strings. + +## Rules + +- **Bỏ:** articles (a/an/the), filler words (just, really, basically, simply), lời khen (great question, certainly), hedging (I think, it seems, có lẽ, tôi nghĩ) +- **Giữ:** tất cả kỹ thuật, code blocks, error strings chính xác, API names, acronyms, command flags +- **Pattern:** `[thing] [action] [reason]. [next step].` +- **Ngôn ngữ:** match theo ngôn ngữ user, chỉ nén style +- **Không** thông báo mode hoặc tự reference ("me caveman think") + +## 5 Mức độ + +| Mức | Style | Savings | +|---|---|---| +| `lite` | Bỏ filler, giữ câu đầy đủ | ~30% | +| `full` | Cho phép fragments, bỏ articles (default) | ~60% | +| `ultra` | Cực ngắn, telegraphic | ~75% | +| `wenyan-lite` | Semi-classical Chinese | ~70% | +| `wenyan-full` | Classical Chinese tối đa | ~85% | + +Đổi mức: `/caveman [level]` + +## Ngoại lệ tự động + +Tạm thời revert về normal cho: +- Cảnh báo bảo mật +- Xác nhận hành động không thể undo +- Multi-step sequence phức tạp cần rõ ràng + +Resume caveman ngay sau đó. + +## Ví dụ minh hoạ + +**Ví dụ 1: Giải thích lỗi** + +Normal: "I noticed that the error you're encountering is likely due to a missing null check on line 42. You might want to consider adding a guard clause before accessing the email property." + +Caveman full: "L42: null check missing. Add guard before .email." + +**Ví dụ 2: Hướng dẫn cài đặt** + +Normal: "First, you'll need to install the dependencies by running npm install. After that's complete, you can start the development server using npm run dev." + +Caveman full: "npm install → npm run dev." + +## Khắc phục sự cố + +**Vấn đề:** Claude vẫn dùng ngôn ngữ dài dòng sau khi bật caveman +**Cách xử lý:** Nhắc lại "caveman mode on" hoặc gõ `/caveman full` để reinforce + +**Vấn đề:** Code bị nén/viết tắt không mong muốn +**Cách xử lý:** Code blocks luôn được giữ nguyên theo rule. Nếu bị ảnh hưởng, báo lỗi và tôi sẽ fix ngay. + +## Deactivation + +Nói "stop caveman", "normal mode", hoặc "thôi caveman". diff --git a/.claude/skills/cv-pipeline-analysis/SKILL.md b/.claude/skills/cv-pipeline-analysis/SKILL.md new file mode 100644 index 0000000..8fd278f --- /dev/null +++ b/.claude/skills/cv-pipeline-analysis/SKILL.md @@ -0,0 +1,102 @@ +--- +name: cv-pipeline-analysis +description: Phân tích pipeline computer vision cho robot từ đầu vào camera đến đầu ra, bao gồm calibration, preprocessing, inference và postprocessing. Dùng khi người dùng yêu cầu 'phân tích camera pipeline', 'debug perception node', 'kiểm tra image encoding', 'trace CV pipeline', hoặc gặp vấn đề với object detection, segmentation, depth estimation, synchronization. +--- + +# CV Pipeline Analysis + +## Mục tiêu + +Trace và đánh giá toàn bộ computer vision pipeline trong repository từ sensor input đến outputs, sử dụng configuration và code đã được xác minh. + +## Khi nào dùng + +Dùng cho các vấn đề về camera ingestion, image processing, object detection, segmentation, tracking, depth, calibration, perception topics, inference nodes, hoặc visualization. + +## Quy trình + +### Bước 1: Đọc context + +Đọc `PROJECT_CONTEXT.md` và `MODEL_DEPLOYMENT_CONTEXT.md` nếu có. + +### Bước 2: Khám phá pipeline từ repo + +Từ repo, discover: +- Camera topics, drivers, calibration files (camera_info, yaml, json) +- Image encodings (rgb8, bgr8, mono8, 16UC1) +- Frame IDs và synchronization policy + +### Bước 3: Trace preprocessing + +Kiểm tra từng bước: resize, crop, pad, color conversion, normalization, undistortion, rectification, batching. + +### Bước 4: Trace inference stage + +Xác minh: model/runtime, input/output shapes, thresholds, postprocessing, coordinate transforms. + +### Bước 5: Trace outputs + +Kiểm tra: topics, message types, frames, units, visualization markers, diagnostics, logs, saved artifacts. + +### Bước 6: So sánh patterns + +- ROS 1: image_transport, message_filters, CameraInfo +- ROS 2: image_transport, QoS, message_filters, composition + +## Checklist + +- [ ] Input image encoding và calibration đã xác minh +- [ ] Camera frame và optical frame usage đã kiểm tra +- [ ] Synchronization và timestamp policy đã kiểm tra +- [ ] Preprocessing khớp với model/algorithm contract +- [ ] Postprocessing units, frames, thresholds đã kiểm tra +- [ ] Unknowns ghi `Unknown / needs confirmation` + +## Ví dụ minh hoạ + +**Ví dụ 1: Debug detection node không ra kết quả** + +Người dùng nói: "Object detection node chạy nhưng không publish gì" + +Hành động: +1. Tìm node entry point, trace subscriber của `/image_raw` hoặc topic tương đương +2. Kiểm tra encoding: node expect `rgb8` nhưng camera publish `bgr8`? +3. Kiểm tra CameraInfo subscription và calibration loading +4. Trace inference call và threshold filter + +Kết quả: Xác định mismatch encoding hoặc threshold quá cao, đề xuất fix cụ thể. + +**Ví dụ 2: Phân tích độ trễ pipeline** + +Người dùng nói: "Pipeline detection chạy chậm, cần biết bottleneck ở đâu" + +Hành động: +1. Map toàn bộ pipeline: camera → preprocessing → inference → postprocessing → publish +2. Kiểm tra có image copy không cần thiết không +3. Kiểm tra preprocessing có resize trước inference không +4. Kiểm tra có GPU transfer overhead không + +Kết quả: Pipeline map với estimated latency từng bước và top-3 optimization candidates. + +## Khắc phục sự cố + +**Lỗi:** Calibration không load được +**Nguyên nhân:** Path hardcode hoặc file không tồn tại ở runtime +**Cách xử lý:** Tìm calibration file path trong launch/config, xác minh file tồn tại, kiểm tra parameter load + +**Lỗi:** Image encoding mismatch (CV_8UC3 vs bgr8) +**Nguyên nhân:** cv_bridge convert sai hoặc node giả định encoding khác với camera publish +**Cách xử lý:** Trace cv_bridge call, kiểm tra `encoding` parameter, so sánh với camera driver publish format + +**Lỗi:** Synchronization drift giữa camera và LiDAR +**Nguyên nhân:** message_filters ApproximateTime slop quá nhỏ hoặc clock source khác nhau +**Cách xử lý:** Kiểm tra slop value trong code, xác minh cả hai sensor dùng cùng clock source + +## Output Format + +- Pipeline map: từng stage với input/output contracts +- Verified configuration: calibration, encoding, thresholds +- Contract checks: preprocessing ↔ model alignment +- Failure points: evidence từ file/line cụ thể +- Performance considerations: copy, resize, transfer overhead +- Next verification: commands hoặc tests cần chạy diff --git a/.claude/skills/edge-ai-deployment/SKILL.md b/.claude/skills/edge-ai-deployment/SKILL.md new file mode 100644 index 0000000..ad33f09 --- /dev/null +++ b/.claude/skills/edge-ai-deployment/SKILL.md @@ -0,0 +1,99 @@ +--- +name: edge-ai-deployment +description: Đánh giá và review quy trình triển khai AI model cho robot và thiết bị edge, bao gồm model format, runtime, accelerator, latency và memory constraints. Dùng khi người dùng yêu cầu 'deploy model lên edge', 'review TensorRT/ONNX deployment', 'kiểm tra GPU memory', 'optimize inference', hoặc gặp vấn đề với latency, packaging, power, hoặc compatibility. +--- + +# Edge AI Deployment + +## Mục tiêu + +Đánh giá xem AI model deployment path có coherent cho robot/edge system mục tiêu hay không, dựa trên facts đã xác minh từ repo và user. + +## Khi nào dùng + +Dùng cho TensorRT, ONNX Runtime, TFLite, OpenVINO, Core ML, CUDA, NPU, TPU, VPU, embedded Linux, container, cross-compile, hoặc robotics inference deployment. + +## Quy trình + +### Bước 1: Đọc context + +Đọc `PROJECT_CONTEXT.md` và `MODEL_DEPLOYMENT_CONTEXT.md` nếu có. + +### Bước 2: Khám phá artifacts + +Discover từ repo: model files, conversion scripts, runtime wrappers, Dockerfiles, launch/config files, hardware references. + +### Bước 3: Xác minh model contract + +Kiểm tra: source format, deployment format, opset/version, precision, batch size, input/output shapes, preprocessing contract. + +### Bước 4: Kiểm tra runtime và hardware + +Chỉ xác nhận khi có evidence từ repo hoặc user: target runtime, accelerator, driver version. + +### Bước 5: Kiểm tra ROS integration + +- ROS 1: node/nodelet, topics, queue sizes, timestamps, frames, diagnostics +- ROS 2: node/component, QoS, lifecycle, timestamps, frames, diagnostics + +### Bước 6: Đánh giá constraints + +Latency, memory footprint, startup time, thermal/power, fallback behavior, model artifact versioning. + +## Checklist + +- [ ] Model path và version đã xác minh +- [ ] Runtime và hardware target đã xác minh hoặc ghi unknown +- [ ] Input/output tensor contract đã kiểm tra +- [ ] Pre/postprocessing consistency đã kiểm tra +- [ ] Deployment packaging và environment đã kiểm tra +- [ ] Unknowns ghi `Unknown / needs confirmation` + +## Ví dụ minh hoạ + +**Ví dụ 1: Review TensorRT deployment trên Jetson** + +Người dùng nói: "Tôi có model ONNX muốn deploy lên Jetson Orin, cần review path deployment" + +Hành động: +1. Tìm conversion script (thường là `convert.py` hoặc `build_engine.py`) +2. Xác minh: opset version, FP16/INT8, dynamic batch hay không, workspace size +3. Kiểm tra preprocessing trong ROS node có khớp với training preprocessing không +4. Kiểm tra memory budget: activation memory + weight size vs available GPU memory + +Kết quả: Report deployment risks, recommended TRT flags, memory estimates. + +**Ví dụ 2: Debug inference latency quá cao** + +Người dùng nói: "Model inference mất 150ms nhưng cần dưới 50ms" + +Hành động: +1. Xác minh precision: đang chạy FP32 thay vì FP16? +2. Kiểm tra batch size và dynamic shape overhead +3. Kiểm tra có CPU↔GPU memory copy không cần thiết không +4. Kiểm tra preprocessing có chạy trên CPU thay vì GPU không + +Kết quả: Top bottlenecks với estimated speedup cho từng fix. + +## Khắc phục sự cố + +**Lỗi:** TensorRT engine build thất bại với "No implementation for layer" +**Nguyên nhân:** Custom op hoặc ONNX node không được TRT hỗ trợ +**Cách xử lý:** Tìm op trong ONNX graph, xem có TRT plugin không, hoặc fallback về ONNX Runtime + +**Lỗi:** Accuracy giảm sau FP16 conversion +**Nguyên nhân:** Precision loss ở softmax, normalization, hoặc small activations +**Cách xử lý:** Thêm `precision_constraints` cho sensitive layers, giữ FP32 cho output head + +**Lỗi:** OOM (Out of Memory) khi load engine +**Nguyên nhân:** Activation memory + weight vượt quá GPU memory +**Cách xử lý:** Giảm batch size, bật memory pool, hoặc dùng model nhỏ hơn + +## Output Format + +- Deployment summary: source → target format path +- Verified artifacts và runtime +- Contract risks: preprocessing mismatch, shape issues +- Integration risks: ROS topic, timing, frame +- Performance/resource risks: latency, memory, thermal +- Next checks: commands hoặc files cần xem xét diff --git a/.claude/skills/manual-build-handoff/SKILL.md b/.claude/skills/manual-build-handoff/SKILL.md new file mode 100644 index 0000000..fd45802 --- /dev/null +++ b/.claude/skills/manual-build-handoff/SKILL.md @@ -0,0 +1,223 @@ +--- +name: manual-build-handoff +description: Cấm Claude tự chạy build, compile, install, launch, train, flash hoặc bất kỳ lệnh chạy ngầm nào. Thay vào đó Claude in ra lệnh chính xác để người dùng tự chạy trong terminal, dừng lại chờ, rồi phân tích kết quả người dùng báo về. Kích hoạt khi cần colcon build, catkin_make, cmake, make, npm/cargo/pip install, docker build, roslaunch, ros2 launch/run, rosbag play, trtexec, train script, flash firmware, hoặc khi người dùng nói 'đừng tự chạy', 'đưa lệnh tôi chạy', 'don't run it yourself', 'give me the command'. +--- + +# Manual Build Handoff + +## Mục tiêu + +Claude **không bao giờ** tự thực thi lệnh build/run. Claude chỉ soạn lệnh chính xác, bàn giao cho người dùng chạy trong terminal thật, dừng lại chờ, rồi đọc kết quả người dùng báo về để phân tích tiếp. + +Lý do: build robotics/CV tốn nhiều phút, chiếm CPU/GPU, đụng phần cứng thật, ghi đè `install/`, `build/`, `devel/`, hoặc khởi động node điều khiển robot. Người dùng phải là người bấm nút. + +## Khi nào dùng + +Luôn luôn, trong mọi session của repo này. Không cần người dùng gọi tên. + +## Rules + +### Lệnh BỊ CẤM tự chạy + +Claude **không** chạy, kể cả ở foreground lẫn background (`run_in_background`, `&`, `nohup`, `tmux`, `screen`): + +| Nhóm | Ví dụ | +|---|---| +| Build ROS | `colcon build`, `catkin_make`, `catkin build`, `. install/setup.bash` kèm build | +| Build chung | `make`, `ninja`, `cmake --build`, `bazel build`, `cargo build`, `go build` | +| Package manager | `pip install`, `npm install`, `npm run build`, `apt install`, `rosdep install` | +| Container | `docker build`, `docker run`, `docker compose up` | +| Chạy robot | `roslaunch`, `ros2 launch`, `ros2 run`, `rosrun`, `rosbag play/record` | +| AI/Model | `train.py`, `trtexec`, `onnx export`, `tflite convert`, quantization script | +| Phần cứng | flash firmware, `dfu-util`, `openocd`, ghi SD card, `dd` | +| Test nặng | `colcon test`, `pytest` toàn repo, integration test cần hardware | +| Bất kỳ lệnh nào | chạy > ~10s, cần sudo, cần GPU, hoặc sửa file ngoài repo | + +### Lệnh VẪN được tự chạy + +Read-only inspection, chạy nhanh, không sửa state: + +`ls`, `cat`, `head`, `tail`, `grep`, `rg`, `find`, `tree`, `wc` +`git status`, `git log`, `git diff`, `git show`, `git branch` +`ros2 pkg list`, `ros2 topic list`, `ros2 param list` (chỉ liệt kê, không echo lâu) +`python -c "import x; print(x.__version__)"`, `nvidia-smi`, `uname -a`, `pkg-config --modversion` + +Nghi ngờ → coi như bị cấm, bàn giao cho người dùng. + +### Quy tắc bàn giao + +- Một lần bàn giao = **một lệnh** (hoặc một chuỗi lệnh liền mạch chạy một lượt). Không nhồi 5 lệnh rời rạc. +- Luôn nêu **thư mục làm việc** và **điều kiện trước** (`source` môi trường nào). +- Luôn nói rõ **cần báo lại gì** — full log, 30 dòng cuối, hay chỉ exit code. +- Sau khi in block bàn giao, **dừng hẳn**. Không đoán trước kết quả, không viết tiếp code dựa trên giả định build pass. +- Không hỏi "bạn có muốn tôi chạy không?" — mặc định là không chạy. + +## Quy trình + +### Bước 1: Xác định lệnh cần chạy + +Discover lệnh build thật từ repo (`package.xml`, `CMakeLists.txt`, `Makefile`, `pyproject.toml`, `docker-compose.yml`, CI config), không bịa. + +### Bước 2: Thu hẹp phạm vi lệnh + +Ưu tiên lệnh nhỏ nhất đủ để kiểm chứng. Ví dụ `colcon build --packages-select my_pkg` thay vì build cả workspace. + +### Bước 3: In block bàn giao + +Theo đúng Handoff Format bên dưới. + +### Bước 4: Dừng và chờ + +Kết thúc lượt trả lời. Không gọi thêm tool chạy lệnh. + +### Bước 5: Nhận kết quả + +Người dùng dán output, hoặc chỉ nói `pass` / `fail`, hoặc trỏ tới file log. + +### Bước 6: Phân tích + +Đọc log, xác định lỗi thật (dòng error đầu tiên, không phải dòng cuối), đề xuất fix. Nếu cần chạy lại → quay lại Bước 3. + +## Handoff Format + +````text +## Lệnh cần chạy + +Thư mục: <đường dẫn tuyệt đối> +Chuẩn bị: + +```bash + +``` + +Mục đích: +Thời gian dự kiến: <~2 phút / vài giây / lâu> +Kỳ vọng: + +Báo lại cho tôi: + +Đang chờ kết quả — tôi không tự chạy lệnh này. +```` + +## Mẹo: ghi log để Claude tự đọc + +Thay vì dán output dài, cho lệnh ghi ra file rồi bảo Claude đọc file (đọc file là read-only, được phép): + +```bash +colcon build --packages-select my_pkg 2>&1 | tee /tmp/build.log +``` + +Rồi chỉ cần nói: *"xong rồi, đọc /tmp/build.log"*. + +Với lệnh dài, thêm exit code vào log: + +```bash +{ colcon build --packages-select my_pkg; echo "EXIT=$?"; } 2>&1 | tee /tmp/build.log +``` + +## Ví dụ minh hoạ + +**Ví dụ 1: Sửa xong code, cần build lại** + +Người dùng nói: *"Sửa lỗi type mismatch trong `image_proc_node.cpp` rồi build lại"* + +Hành động: Claude sửa file (theo `patch-preview-before-edit`), rồi **không** chạy `colcon build`, mà in: + +````text +## Lệnh cần chạy + +Thư mục: /home/user/ros2_ws +Chuẩn bị: source /opt/ros/humble/setup.bash + +```bash +{ colcon build --packages-select image_proc --symlink-install; echo "EXIT=$?"; } 2>&1 | tee /tmp/build.log +``` + +Mục đích: xác nhận fix type mismatch compile được +Thời gian dự kiến: ~40 giây +Kỳ vọng: `Summary: 1 package finished`, `EXIT=0` + +Báo lại cho tôi: nói "xong" và tôi đọc /tmp/build.log + +Đang chờ kết quả — tôi không tự chạy lệnh này. +```` + +Kết quả: Người dùng chạy, báo `xong`, Claude đọc log và phân tích. + +**Ví dụ 2: Cần chạy node để xem topic** + +Người dùng nói: *"Chạy thử node xem có publish `/camera/image_raw` không"* + +Hành động: Bàn giao **hai** lệnh cho **hai** terminal, đánh số rõ ràng: + +````text +## Lệnh cần chạy + +Terminal 1 — Thư mục: /home/user/ros2_ws · Chuẩn bị: source install/setup.bash + +```bash +ros2 launch camera_driver camera.launch.py +``` + +Terminal 2 — Chuẩn bị: source install/setup.bash + +```bash +ros2 topic hz /camera/image_raw +``` + +Mục đích: xác nhận node publish đúng topic và rate +Kỳ vọng: `average rate: ~30.0` + +Báo lại cho tôi: 5 dòng đầu của Terminal 2, và bất kỳ error nào ở Terminal 1 + +Đang chờ kết quả — tôi không tự chạy lệnh này. +```` + +**Ví dụ 3: Người dùng chủ động yêu cầu Claude chạy** + +Người dùng nói: *"Chạy `colcon build` giùm tôi đi"* + +Hành động: Người dùng override rõ ràng → được phép chạy, nhưng chạy **foreground**, không `run_in_background`, và báo trước thời gian dự kiến. Skill này chỉ cấm chạy **tự động, ngầm, không ai yêu cầu**. + +## Enforcement cứng + +Skill là chỉ dẫn mềm — vẫn có xác suất Claude quên. Nên `install.sh` cài kèm một `PreToolUse` hook chặn ở tầng harness, không phụ thuộc model có nhớ hay không: + +- `.claude/hooks/block-build.sh` — khớp regex danh sách lệnh cấm, exit code 2 = huỷ tool call và trả stderr về cho Claude đọc +- `.claude/settings.json` — đăng ký hook với `matcher: "Bash"` + +Hook đọc `tool_input.command` từ JSON payload (dùng `python3`, fallback `jq`), nên chỉ khớp **lệnh thật**, không khớp nhầm phần `description`. Ví dụ `cat /tmp/build.log` với mô tả *"read log after colcon build"* vẫn được phép chạy. + +Hook có hiệu lực sau khi **restart Claude Code**. + +**Escape hatch:** thêm `# user-approved` vào cuối lệnh để bỏ qua hook. Chỉ dùng khi người dùng chủ động yêu cầu chạy (Ví dụ 3 ở trên): + +```bash +colcon build --packages-select my_pkg # user-approved +``` + +Marker hiện rõ trong lệnh nên người dùng luôn thấy được khi nào hook bị bypass. + +**Tắt hook:** xoá entry `matcher: "Bash"` trỏ tới `block-build.sh` trong `.claude/settings.json`. + +## Khắc phục sự cố + +**Lỗi:** Claude vẫn tự chạy build +**Nguyên nhân:** Chưa restart Claude Code sau khi cài, hoặc lệnh nằm trong `permissions.allow` của `settings.json` +**Cách xử lý:** Restart Claude Code; kiểm tra `permissions.allow` không chứa `Bash(colcon build:*)`; xác nhận hook chạy được bằng `printf '{"tool_input":{"command":"colcon build"}}' | .claude/hooks/block-build.sh; echo $?` (phải in `2`) + +**Lỗi:** Hook chặn nhầm lệnh vô hại +**Nguyên nhân:** Regex trong `block-build.sh` quá rộng so với repo cụ thể +**Cách xử lý:** Sửa `PATTERN` trong `.claude/hooks/block-build.sh`, hoặc thêm `# user-approved` cho lệnh đó + +**Lỗi:** Lệnh bàn giao chạy lỗi "command not found" +**Nguyên nhân:** Thiếu bước `source` môi trường ROS/venv +**Cách xử lý:** Claude phải luôn ghi dòng `Chuẩn bị:` — nếu thiếu, yêu cầu bổ sung + +**Lỗi:** Output build quá dài không dán được +**Nguyên nhân:** Build cả workspace +**Cách xử lý:** Dùng `tee /tmp/build.log` rồi bảo Claude đọc file; hoặc thu hẹp bằng `--packages-select` + +**Lỗi:** Claude phân tích log cũ +**Nguyên nhân:** File log không bị ghi đè, hoặc người dùng chạy lệnh khác +**Cách xử lý:** Đặt tên log theo lần chạy (`/tmp/build-2.log`), hoặc `rm` log trước khi chạy lại diff --git a/.claude/skills/model-conversion-debugging/SKILL.md b/.claude/skills/model-conversion-debugging/SKILL.md new file mode 100644 index 0000000..e240705 --- /dev/null +++ b/.claude/skills/model-conversion-debugging/SKILL.md @@ -0,0 +1,98 @@ +--- +name: model-conversion-debugging +description: Debug lỗi chuyển đổi AI model giữa các format như ONNX, TensorRT, TFLite, OpenVINO, quantization trong khi bảo toàn input/output contracts. Dùng khi người dùng báo 'ONNX export thất bại', 'TensorRT build lỗi', 'accuracy giảm sau conversion', 'unsupported op', 'shape mismatch', 'quantization error', hoặc 'output drift'. +--- + +# Model Conversion Debugging + +## Mục tiêu + +Chẩn đoán conversion failures hoặc accuracy regressions giữa training/source models và deployment formats, không phỏng đoán target runtime details. + +## Khi nào dùng + +Dùng cho ONNX export, TensorRT engine build, TFLite conversion, OpenVINO IR, quantization, precision changes, unsupported ops, shape mismatches, hoặc output drift. + +## Quy trình + +### Bước 1: Đọc context + +Đọc project và model deployment context nếu có. + +### Bước 2: Khám phá artifacts + +Discover từ repo: source model, conversion scripts, config files, sample inputs, validation scripts, deployment runtime. + +### Bước 3: Xác minh input/output contract + +Kiểm tra: input names, shapes, dtypes, color order, normalization, dynamic axes, batch size, output names. + +### Bước 4: Kiểm tra compatibility + +Opset/runtime compatibility, unsupported operators, plugins/custom ops, calibration data, quantization settings, precision changes. + +### Bước 5: Kiểm tra ROS integration + +Xác minh converted model assumptions khớp với node's preprocessing và postprocessing. + +### Bước 6: So sánh outputs + +So sánh source và converted outputs trên representative inputs khi commands và data đã được xác minh. + +## Checklist + +- [ ] Source và target formats đã xác minh +- [ ] Conversion command đã xác minh trước khi dùng +- [ ] Input/output contracts đã bảo toàn +- [ ] Pre/postprocessing alignment đã kiểm tra +- [ ] Numeric tolerance và representative data đã xem xét +- [ ] Unknowns ghi `Unknown / needs confirmation` + +## Ví dụ minh hoạ + +**Ví dụ 1: ONNX export thất bại với custom op** + +Người dùng nói: "torch.onnx.export() báo lỗi: Unsupported op: Deformable Convolution" + +Hành động: +1. Tìm op trong model code, xác minh đây là custom op hay standard op +2. Kiểm tra ONNX opset version (thường cần >= 17 cho deformable conv) +3. Xem có onnx-simplifier hoặc onnxruntime-extensions hỗ trợ không +4. Xem xét fallback: export partial model hoặc fuse op trước khi export + +Kết quả: Nguyên nhân cụ thể và 2-3 giải pháp với tradeoffs. + +**Ví dụ 2: Accuracy giảm sau INT8 quantization** + +Người dùng nói: "mAP giảm từ 0.85 xuống 0.62 sau khi quantize INT8" + +Hành động: +1. Kiểm tra calibration dataset có representative không (đủ ảnh diverse?) +2. Xác định layers nhạy cảm với quantization (thường là detection head, softmax) +3. Thử mixed precision: giữ FP16 cho output layers +4. So sánh per-layer activations giữa FP32 và INT8 + +Kết quả: Xác định layers cần giữ FP16, calibration recommendations. + +## Khắc phục sự cố + +**Lỗi:** "RuntimeError: Exporting the operator... is not supported" +**Nguyên nhân:** Torch op chưa có ONNX mapping +**Cách xử lý:** Upgrade opset version, dùng symbolic override, hoặc rewrite op bằng primitive ops + +**Lỗi:** Output shape mismatch giữa PyTorch và ONNX Runtime +**Nguyên nhân:** Dynamic shape không được export đúng (batch dim, spatial dim) +**Cách xử lý:** Thêm `dynamic_axes` đúng trong export call, verify với `onnxruntime.InferenceSession` + +**Lỗi:** TRT engine chạy đúng nhưng output khác PyTorch +**Nguyên nhân:** FP16 precision loss hoặc layer fusion thay đổi computation order +**Cách xử lý:** Disable FP16 cho specific layers, so sánh intermediate activations + +## Output Format + +- Conversion path: source → intermediate → target format +- Failure/regression symptom: error message hoặc metric drop +- Verified contracts: input/output spec +- Likely causes: ordered by evidence strength +- Validation plan: commands và test inputs +- Next fix: specific change với expected result diff --git a/.claude/skills/patch-preview-before-edit/SKILL.md b/.claude/skills/patch-preview-before-edit/SKILL.md new file mode 100644 index 0000000..1dd85fb --- /dev/null +++ b/.claude/skills/patch-preview-before-edit/SKILL.md @@ -0,0 +1,132 @@ +--- +name: patch-preview-before-edit +description: Hiển thị diff thay đổi được đề xuất dạng unified diff và chờ xác nhận rõ ràng từ người dùng trước khi sửa đổi bất kỳ file nào trong repository. Dùng trước khi sửa source code, config, launch files, scripts, build files, docs. Kích hoạt khi người dùng muốn 'xem trước thay đổi', 'preview diff', 'show me what will change', hoặc khi làm việc với code nhạy cảm. +--- + +# Patch Preview Before Edit + +## Mục tiêu + +Trước khi thay đổi nội dung repository, hiển thị additions và deletions được đề xuất dạng diff, giải thích impact và risks, và chờ xác nhận rõ ràng trước khi apply bất kỳ thay đổi nào. + +## Khi nào dùng + +Dùng trước khi sửa source code, configuration, launch files, scripts, build files, documentation, generated templates, hoặc bất kỳ file nào trong repository. + +## Rules + +- **Không** edit, create, delete, rename, overwrite files trước khi user xác nhận +- **Không** chạy commands sửa đổi files, dependencies, caches, lockfiles trước khi xác nhận +- Read-only inspection commands được phép trước khi xác nhận +- Các lệnh formatting, code generation, dependency install, migration, autofix đều là modifying commands +- Preview phải đủ cụ thể để user hiểu change trước khi approve +- Nếu change quá rộng, chia thành patches nhỏ hơn hoặc hỏi clarification + +**Từ xác nhận hợp lệ:** `confirm`, `apply`, `ok`, `yes`, `dong y`, `đồng ý`, `tiep tuc`, `tiếp tục`, `sửa đi` + +## Quy trình + +### Bước 1: Inspect + +Dùng read-only commands và file reads để hiểu repository. + +### Bước 2: Xác định files sẽ thay đổi + +List từng file và lý do cần thay đổi. + +### Bước 3: Chuẩn bị preview + +Tạo diff preview mà không apply. + +### Bước 4: Hiển thị preview theo format + +Xem Preview Format bên dưới. + +### Bước 5: Giải thích impact và risks + +Nêu rõ expected impact, risks, assumptions, unverified details. + +### Bước 6: Dừng và chờ + +Stop và chờ explicit user confirmation. + +### Bước 7: Apply sau khi xác nhận + +Apply chỉ những changes đã được approve. + +### Bước 8: Tóm tắt sau khi apply + +Report changes đã thực hiện và validation results. + +## Preview Format + +````text +Proposed changes: +- : +- : + +Preview: +```diff +diff --git a/ b/ +--- a/ ++++ b/ +@@ +- ++ +``` + +Impact: +- + +Risks: +- + +Assumptions: +- + +Waiting for confirmation before editing. Confirm with: confirm, apply, ok, yes, đồng ý, tiếp tục, or sửa đi. +```` + +## Ví dụ minh hoạ + +**Ví dụ 1: Sửa launch file parameter** + +Người dùng nói: "Đổi camera_fps từ 30 thành 60 trong launch file" + +Hành động: +1. Đọc launch file, tìm parameter `camera_fps` +2. Hiển thị diff preview +3. Chờ xác nhận + +Kết quả: Chỉ apply sau khi user nói "ok" hoặc "đồng ý". + +**Ví dụ 2: Refactor nhiều files** + +Người dùng nói: "Rename topic /camera/image thành /camera/image_raw trong toàn bộ codebase" + +Hành động: +1. Grep tất cả files có string `/camera/image` +2. Chia thành 3 groups: source code, launch files, config files +3. Hiển thị từng group diff, giải thích risk (runtime mismatch nếu thiếu file nào) +4. Chờ xác nhận cho từng group hoặc tất cả + +Kết quả: Có thể apply tuần tự từng group sau khi xác nhận. + +## Khắc phục sự cố + +**Lỗi:** User xác nhận nhưng thay đổi thực tế khác preview +**Nguyên nhân:** File đã bị thay đổi giữa lúc preview và apply +**Cách xử lý:** Dừng lại, hiển thị updated preview, chờ xác nhận lại + +**Lỗi:** Diff quá lớn, user không đọc được +**Nguyên nhân:** Change scope quá rộng +**Cách xử lý:** Chia nhỏ thành từng file riêng biệt, hiển thị tuần tự + +## After-Apply Summary + +Sau khi apply, report: +- Files đã thay đổi +- Những gì đã add, remove, hoặc update +- Deviations so với approved preview (nếu có) +- Validation checks đã chạy và kết quả +- Checks chưa chạy và lý do diff --git a/.claude/skills/project-onboarding/SKILL.md b/.claude/skills/project-onboarding/SKILL.md new file mode 100644 index 0000000..c4913c1 --- /dev/null +++ b/.claude/skills/project-onboarding/SKILL.md @@ -0,0 +1,92 @@ +--- +name: project-onboarding +description: Khám phá và lập bản đồ cấu trúc repository robotics/ROS chưa biết, xác định stack, commands, interfaces và tạo PROJECT_CONTEXT.md với facts đã xác minh. Dùng khi người dùng mới bắt đầu với repo, yêu cầu 'onboard repo mới', 'tìm hiểu project này', 'map cấu trúc codebase', 'PROJECT_CONTEXT.md chưa có', hoặc bắt đầu làm việc sau khi clone repo. +--- + +# Project Onboarding + +## Mục tiêu + +Xây dựng bản đồ ban đầu đáng tin cậy của một repository robotics mà không giả định package names, topics, frames, hardware, models, hoặc commands. + +## Khi nào dùng + +Dùng khi bắt đầu làm việc trong một repository robotics, ROS, ROS 2, CV, simulation, embedded, hoặc edge AI mới. + +## Quy trình + +### Bước 1: Đọc context có sẵn + +Đọc `CLAUDE.md` và `PROJECT_CONTEXT.md` nếu có. + +### Bước 2: Khám phá top-level structure + +List top-level files, detect: manifests, docs, launch/config folders, packages, tests, CI. + +### Bước 3: Xác định ROS version + +ROS 1 indicators: `package.xml`, `CMakeLists.txt`, `.launch`, `catkin`, `rosbag`, `nodelet`, `dynamic_reconfigure` + +ROS 2 indicators: `package.xml`, `setup.py`, `setup.cfg`, `ament`, `colcon`, launch Python, components, lifecycle nodes, QoS config + +### Bước 4: Locate CV/AI assets + +Camera calibration, model files, conversion scripts, preprocessing code, deployment configs. + +### Bước 5: Ghi vào PROJECT_CONTEXT.md + +Chỉ ghi verified facts. Để `Unknown / needs confirmation` cho bất kỳ field nào chưa xác minh được. + +## Checklist + +- [ ] Repository role đã xác định từ docs hoặc manifests +- [ ] Build, test, lint, launch commands đã xác minh trước khi ghi +- [ ] Packages, nodes, topics, services, actions, frames, parameters, models đã discover từ files +- [ ] Hardware và sensor assumptions không được phỏng đoán +- [ ] Open questions đã liệt kê rõ ràng + +## Ví dụ minh hoạ + +**Ví dụ 1: Onboard repo ROS 2 mới** + +Người dùng nói: "Tôi vừa clone repo này, bạn có thể giúp tôi hiểu cấu trúc không?" + +Hành động: +1. `ls` top-level, tìm `package.xml`, `colcon.meta`, `setup.py` +2. Detect ROS 2 từ `ament_cmake` trong CMakeLists.txt +3. List tất cả packages, trace main nodes +4. Tìm launch files, extract topic remaps và parameters +5. Tạo/cập nhật PROJECT_CONTEXT.md + +Kết quả: PROJECT_CONTEXT.md với stack, packages, main interfaces, build command, open questions. + +**Ví dụ 2: Onboard repo CV/AI không có ROS** + +Người dùng nói: "Project này có camera và detection, giúp tôi hiểu pipeline" + +Hành động: +1. Tìm entry points (main.py, inference.py, pipeline.py) +2. Trace: camera source → preprocessing → model → postprocessing → output +3. Tìm model files (.pt, .onnx, .trt) và config files +4. Ghi vào PROJECT_CONTEXT.md phần CV And AI + +Kết quả: CV pipeline map với verified paths, model format, open questions về hardware. + +## Khắc phục sự cố + +**Lỗi:** Không tìm được build command +**Nguyên nhân:** Project dùng custom build system hoặc Makefile không standard +**Cách xử lý:** Tìm `Makefile`, `justfile`, `taskfile.yml`, CI scripts (`.github/workflows/`), ghi `Unknown / needs confirmation` nếu vẫn không tìm được + +**Lỗi:** Quá nhiều packages, không biết bắt đầu từ đâu +**Nguyên nhân:** Monorepo với nhiều components +**Cách xử lý:** Tìm top-level README hoặc workspace launch file, identify "main" package từ dependency graph + +## Output Format + +- Snapshot: repository purpose và tech stack +- Verified layout: key directories và manifests +- Runtime map: known nodes/interfaces/frames/models +- Commands: verified hoặc `Unknown / needs confirmation` +- Updated files: ghi rõ PROJECT_CONTEXT.md đã được update +- Open questions: danh sách ngắn gọn diff --git a/.claude/skills/read-source-code/SKILL.md b/.claude/skills/read-source-code/SKILL.md new file mode 100644 index 0000000..ea870b9 --- /dev/null +++ b/.claude/skills/read-source-code/SKILL.md @@ -0,0 +1,90 @@ +--- +name: read-source-code +description: Trace và giải thích hành vi của source code robotics, ROS, CV, edge AI dựa trên bằng chứng từ repository, không phỏng đoán chi tiết project. Dùng khi người dùng yêu cầu 'giải thích code này', 'trace logic của node X', 'tìm bug trong pipeline', 'làm thế nào X hoạt động', hoặc cần hiểu callback flow, executor, topic pub/sub, model inference path. +--- + +# Read Source Code + +## Mục tiêu + +Giải thích code hoạt động như thế nào, dependencies là gì, và behavior được configure ở đâu, trong khi giữ unknown project details là explicit. + +## Khi nào dùng + +Dùng khi cần hiểu một node, package, launch path, perception pipeline, controller, driver wrapper, model runtime, hoặc bug path. + +## Quy trình + +### Bước 1: Đọc context + +Đọc project context files nếu có. + +### Bước 2: Bắt đầu từ entry point + +Bắt đầu từ file/symbol/log/topic/node/model mà user cung cấp. + +### Bước 3: Trace theo hướng phù hợp + +Dùng source search để trace: definitions, call sites, launch/config references, parameters, tests. + +**ROS 1:** publishers/subscribers, services, actionlib, node handles, private parameters, callbacks, timers, spin model + +**ROS 2:** nodes/components, executors, callback groups, lifecycle, QoS, parameters, services/actions, timers, composition + +**CV/AI:** image encoding, calibration, preprocessing, inference, postprocessing, synchronization, output contracts + +### Bước 4: Ghi nhận unknowns + +Mark bất kỳ details nào chưa xác minh được là `Unknown / needs confirmation`. + +## Checklist + +- [ ] Entry points và runtime configuration đã xác định +- [ ] Message types, units, frames, timestamps, rates đã kiểm tra +- [ ] Threading, callback order, queues/QoS, shared state đã kiểm tra +- [ ] Error handling, timeouts, watchdogs, degraded sensor input đã kiểm tra +- [ ] Unknown details đã mark rõ + +## Ví dụ minh hoạ + +**Ví dụ 1: Trace tại sao node không publish** + +Người dùng nói: "detection_node chạy nhưng /detections topic luôn trống" + +Hành động: +1. Tìm node entry point, locate publisher cho `/detections` +2. Trace callback: subscriber nhận gì → xử lý → điều kiện publish +3. Tìm guard conditions: threshold filter, confidence check, state machine +4. Kiểm tra có publisher được tạo đúng không (wrong namespace?) + +Kết quả: Xác định chính xác line code gây ra issue, không publish, explain logic. + +**Ví dụ 2: Hiểu executor và callback groups** + +Người dùng nói: "Tại sao timer callback của tôi bị block bởi subscriber callback?" + +Hành động: +1. Tìm executor type: SingleThreadedExecutor hay MultiThreadedExecutor? +2. Kiểm tra callback group assignment: MutuallyExclusive hay Reentrant? +3. Trace timer và subscriber được assign group nào +4. Giải thích scheduling behavior với executor đó + +Kết quả: Explanation cụ thể + fix với đúng callback group type. + +## Khắc phục sự cố + +**Lỗi:** Không tìm được node entry point +**Nguyên nhân:** Node được launch qua `ros2 run` với package/executable khác tên folder +**Cách xử lý:** Tìm trong `CMakeLists.txt` (ament_target_dependencies), `setup.py` (entry_points), hoặc launch file + +**Lỗi:** Callback trace dừng lại tại virtual function +**Nguyên nhân:** Polymorphism, plugin architecture (pluginlib, class_loader) +**Cách xử lý:** Tìm plugin manifest (`plugins.xml`), grep registered class name, trace concrete implementation + +## Output Format + +- What it does: concise behavior summary (1-3 sentences) +- Evidence: file:line references +- Runtime dependencies: topics, params, frames, models, hardware nếu verified +- Risks hoặc ambiguities: practical issues +- Next verification: tests, commands, logs, hoặc questions diff --git a/.claude/skills/real-time-performance-profiling/SKILL.md b/.claude/skills/real-time-performance-profiling/SKILL.md new file mode 100644 index 0000000..10f160c --- /dev/null +++ b/.claude/skills/real-time-performance-profiling/SKILL.md @@ -0,0 +1,100 @@ +--- +name: real-time-performance-profiling +description: Phân tích bottleneck hiệu suất và rủi ro real-time trong pipeline robotics, CV, edge AI bao gồm latency, jitter, CPU/GPU load, callback contention, throughput. Dùng khi người dùng báo 'bỏ lỡ deadline', 'frame rate thấp', 'callback backlog', 'dropped messages', 'CPU/GPU quá tải', 'memory leak', 'startup chậm', hoặc cần optimize throughput. +--- + +# Real-Time Performance Profiling + +## Mục tiêu + +Xác định performance bottlenecks và determinism risks trong robotics, CV, edge AI pipelines sử dụng verified repo facts và measured evidence. + +## Khi nào dùng + +Dùng cho missed deadlines, low frame rate, control latency, callback backlog, dropped messages, high CPU/GPU load, memory growth, startup delays, hoặc thermal throttling. + +## Quy trình + +### Bước 1: Đọc context + +Đọc project context files nếu có. + +### Bước 2: Discover runtime structure + +Từ repo: entry points, nodes, launch/config, topic rates, timers, callback structure, model runtime, target hardware. + +### Bước 3: Xác định critical path + +Define critical path và timing budget. Mark unknown budgets là `Unknown / needs confirmation`. + +### Bước 4: Kiểm tra ROS-specific issues + +**ROS 1:** callback queues, spinner type, queue sizes, nodelets, rosconsole timing, rosbag replay effects + +**ROS 2:** executors, callback groups, QoS history depth, intra-process communication, lifecycle state, tracing, composition + +### Bước 5: Inspect CV/AI hotspots + +Image copies, encoding conversion, resize, synchronization, inference, postprocessing, GPU/accelerator transfer, memory allocation. + +### Bước 6: Đề xuất measurement plan + +Measurement commands phù hợp với repo hoặc clearly generic examples. + +## Checklist + +- [ ] Critical path đã xác định +- [ ] Rates, latencies, queue/QoS settings, resource use đã kiểm tra +- [ ] Blocking calls, locks, allocations, copies, thread contention đã xem xét +- [ ] Hardware, OS, accelerator assumptions đã xác minh hoặc mark unknown +- [ ] Measurement commands phù hợp với repo + +## Ví dụ minh hoạ + +**Ví dụ 1: Detection pipeline chỉ đạt 5 FPS thay vì 30 FPS** + +Người dùng nói: "Detection chạy chậm hơn expected 6x, không biết bottleneck ở đâu" + +Hành động: +1. Trace critical path: camera callback → preprocess → inference → postprocess → publish +2. Kiểm tra preprocessing: có resize từ 4K xuống 640 trên CPU không? +3. Kiểm tra inference: batch size, dynamic shape overhead +4. Kiểm tra có memory allocation trong hot path không (np.zeros() trong callback) +5. Đề xuất profiling: `ros2 topic hz`, `nvidia-smi dmon`, `perf stat` + +Kết quả: Top 3 bottlenecks với estimated contribution và fix recommendations. + +**Ví dụ 2: Control loop có jitter, robot behavior không smooth** + +Người dùng nói: "Control command publish rate không ổn định, đôi khi skip cycles" + +Hành động: +1. Kiểm tra executor type: SingleThreaded sẽ bị block bởi slow callbacks +2. Tìm shared callback group với heavy callbacks (sensor processing) +3. Kiểm tra timer period vs actual execution time +4. Kiểm tra có system-level jitter không (CPU governor, IRQ affinity) + +Kết quả: Executor/callback group restructuring plan + OS-level recommendations. + +## Khắc phục sự cố + +**Lỗi:** Callback queue backup liên tục tăng +**Nguyên nhân:** Publisher rate nhanh hơn subscriber processing rate +**Cách xử lý:** Giảm queue size (drop old messages), tăng processing speed, hoặc giảm publisher rate + +**Lỗi:** GPU utilization thấp mặc dù inference chậm +**Nguyên nhân:** CPU preprocessing là bottleneck hoặc CPU-GPU transfer quá nhiều +**Cách xử lý:** Move preprocessing lên GPU (CUDA/OpenCV CUDA), batch nhiều frames + +**Lỗi:** Memory tăng dần theo thời gian (leak) +**Nguyên nhân:** Python objects không được free (circular references, cache không giới hạn) +**Cách xử lý:** Dùng `tracemalloc`, giới hạn cache size, kiểm tra callback capture + +## Output Format + +- Performance symptom +- Critical path map: từng stage với estimated time +- Evidence và unknowns +- Likely bottlenecks: ordered by impact +- Measurement plan: specific commands hoặc tools +- Optimization candidates với tradeoffs diff --git a/.claude/skills/repo-context-maintainer/SKILL.md b/.claude/skills/repo-context-maintainer/SKILL.md new file mode 100644 index 0000000..316a282 --- /dev/null +++ b/.claude/skills/repo-context-maintainer/SKILL.md @@ -0,0 +1,90 @@ +--- +name: repo-context-maintainer +description: Cập nhật và duy trì PROJECT_CONTEXT.md, ROS_TOPIC_MAP.md, TF_FRAME_MAP.md, MODEL_DEPLOYMENT_CONTEXT.md với facts đã được xác minh từ repository. Dùng khi context files bị stale, sau code changes lớn, trước tasks phức tạp, hoặc khi người dùng yêu cầu 'cập nhật context', 'refresh project map', 'update topic map', 'sync PROJECT_CONTEXT'. +--- + +# Repo Context Maintainer + +## Mục tiêu + +Giữ project context files chính xác, cập nhật và hữu ích mà không thêm unverified robotics assumptions. + +## Khi nào dùng + +Dùng sau onboarding, sau major code changes, trước large tasks, hoặc khi context files bị missing, stale, hoặc incomplete. + +## Quy trình + +### Bước 1: Đọc context files hiện có + +Đọc `PROJECT_CONTEXT.md`, `ROS_TOPIC_MAP.md`, `TF_FRAME_MAP.md`, `MODEL_DEPLOYMENT_CONTEXT.md` nếu có. + +### Bước 2: Inspect repository + +Inspect: manifests, docs, launch/config, source, tests, CI, model assets, deployment files. + +### Bước 3: Update chỉ những gì xác minh được + +Chỉ update fields có thể verify từ repository evidence hoặc explicit user input. + +### Bước 4: Preserve unknowns + +Giữ `Unknown / needs confirmation` cho package names, topics, frames, commands, hardware, model paths, build details chưa xác minh. + +### Bước 5: Ghi nguồn xác minh + +Ghi rõ source files dùng để verify và open questions. + +## Checklist + +- [ ] Context changes có evidence từ repo +- [ ] Commands đã verify trước khi document +- [ ] Topics, services, actions, frames, models, hardware không được phỏng đoán +- [ ] CV/AI deployment contracts đã document nếu có +- [ ] Stale hoặc contradictory facts đã được flag + +## Ví dụ minh hoạ + +**Ví dụ 1: Update sau khi thêm camera mới** + +Người dùng nói: "Tôi vừa thêm depth camera vào hệ thống, cần cập nhật context" + +Hành động: +1. Tìm camera driver node mới trong source/launch +2. Xác minh topics: `/depth/image_raw`, `/depth/camera_info`, `/depth/points` +3. Tìm frame ID trong URDF hoặc launch +4. Update PROJECT_CONTEXT.md phần Sensors và Runtime Interfaces +5. Update ROS_TOPIC_MAP.md với camera topics mới + +Kết quả: Updated files với verified entries, chỉ rõ files đã check. + +**Ví dụ 2: Sync sau refactor lớn** + +Người dùng nói: "Tôi vừa refactor detection module, context files cũ rồi" + +Hành động: +1. Compare context hiện tại với code thực tế +2. Tìm topics/nodes đã đổi tên hoặc xóa +3. Tìm topics/nodes mới chưa có trong context +4. Update MODEL_DEPLOYMENT_CONTEXT.md nếu model path/format đổi +5. Flag những changes có thể ảnh hưởng integration + +Kết quả: Updated context với diff summary và stale entries đã xóa. + +## Khắc phục sự cố + +**Lỗi:** Không biết topic có còn active không +**Nguyên nhân:** Code có thể conditional publish hoặc topic được rename +**Cách xử lý:** Grep cả codebase cho topic string, kiểm tra conditional blocks, ghi `Needs runtime verification` trong context + +**Lỗi:** Build command trong context không còn chạy được +**Nguyên nhân:** Build system đã thay đổi (catkin → colcon, pip → uv) +**Cách xử lý:** Tìm CI scripts (`.github/workflows/`), Makefile, hoặc README mới nhất để lấy command đúng + +## Output Format + +- Files đã update +- Facts đã add hoặc correct +- Evidence files đã inspect +- Remaining unknowns +- Suggested next context improvements diff --git a/.claude/skills/robotics-code-review/SKILL.md b/.claude/skills/robotics-code-review/SKILL.md new file mode 100644 index 0000000..f8f5fb2 --- /dev/null +++ b/.claude/skills/robotics-code-review/SKILL.md @@ -0,0 +1,91 @@ +--- +name: robotics-code-review +description: Review code robotics, ROS, CV, edge AI để tìm behavioral bugs, integration risks, timing issues, safety concerns và gaps trong verification. Dùng khi người dùng yêu cầu 'review code', 'check PR này', 'kiểm tra launch file', 'review perception changes', 'audit safety', hoặc trước khi merge code ảnh hưởng đến runtime behavior, safety, timing, resource management. +--- + +# Robotics Code Review + +## Mục tiêu + +Tìm defects và risks cụ thể trong robotics code, ưu tiên runtime behavior, safety, integration contracts, timing, và missing tests. + +## Khi nào dùng + +Dùng cho pull requests, diffs, package changes, launch/config updates, perception changes, model deployment changes, drivers, controllers, hoặc performance-sensitive code. + +## Quy trình + +### Bước 1: Đọc context + +Đọc project context files nếu có. + +### Bước 2: Review target files + +Phân biệt changed behavior từ existing behavior. + +### Bước 3: Kiểm tra theo ROS version + +**ROS 1:** callback queues, node handles, params, remaps, launch XML, message filters, catkin/package dependencies + +**ROS 2:** QoS, executors, callback groups, lifecycle, parameters, composition, launch files, ament dependencies + +### Bước 4: Kiểm tra common issues + +Timestamps, frame IDs, units, synchronization, calibration, resource lifetime, error handling, diagnostics, degraded input behavior. + +### Bước 5: Kiểm tra CV/AI specifics + +Tensor contracts, encodings, precision, thresholds, model artifact paths, runtime compatibility. + +## Checklist + +- [ ] Findings tied to file/line evidence +- [ ] Không phỏng đoán project-specific facts +- [ ] Safety, timing, hardware interaction, recovery paths đã xem xét +- [ ] Tests hoặc runtime verification gaps đã xác định +- [ ] Unknowns mark `Unknown / needs confirmation` + +## Ví dụ minh hoạ + +**Ví dụ 1: Review perception node mới** + +Người dùng nói: "Review PR thêm YOLOv8 detection node này trước khi merge" + +Hành động: +1. Kiểm tra callback: subscriber nhận image, có check encoding không? +2. Kiểm tra preprocessing: có tương thích với model training preprocessing không? +3. Kiểm tra postprocessing: NMS threshold, coordinate transform đúng frame chưa? +4. Kiểm tra error handling: model load thất bại xử lý thế nào? +5. Kiểm tra diagnostics: có publish `/diagnostics` khi model không ready không? + +Kết quả: Findings ordered by severity, mỗi finding có file:line, issue, impact, fix. + +**Ví dụ 2: Review launch/config changes** + +Người dùng nói: "Review file launch này, tôi sửa một số parameters" + +Hành động: +1. Kiểm tra parameter names: đúng namespace? Có typo? +2. Kiểm tra remaps: topic names khớp với subscribers/publishers không? +3. Kiểm tra node startup order: dependencies đúng thứ tự chưa? +4. Kiểm tra có hardcoded paths/IP addresses không + +Kết quả: List issues với severity, deployment risks. + +## Khắc phục sự cố + +**Lỗi:** Không xác định được severity của finding +**Nguyên nhân:** Thiếu context về robot behavior và safety requirements +**Cách xử lý:** Mark `Unknown / needs confirmation` cho safety impact, hỏi user về use case và safety constraints + +**Lỗi:** Code quá phức tạp để trace hết +**Nguyên nhân:** Large codebase, nhiều abstraction layers +**Cách xử lý:** Focus vào changed files trong diff, trace outward từ changed lines, không review toàn bộ codebase + +## Output Format + +- Findings: ordered by severity (Critical > High > Medium > Low) +- Mỗi finding: `file:line | issue | impact | suggested fix` +- Open questions +- Verification gaps: tests cần viết +- Brief change summary nếu relevant diff --git a/.claude/skills/ros-package-analysis/SKILL.md b/.claude/skills/ros-package-analysis/SKILL.md new file mode 100644 index 0000000..25eb622 --- /dev/null +++ b/.claude/skills/ros-package-analysis/SKILL.md @@ -0,0 +1,94 @@ +--- +name: ros-package-analysis +description: Phân tích cấu trúc ROS 1/ROS 2 package, manifests, dependencies, launch files, interfaces và integration points chỉ từ repository evidence. Dùng khi người dùng yêu cầu 'phân tích package', 'kiểm tra dependencies', 'map launch files', 'tìm publishers/subscribers của node X', hoặc gặp vấn đề build, dependency conflict, hoặc package boundary. +--- + +# ROS Package Analysis + +## Mục tiêu + +Lập bản đồ cấu trúc, dependencies, runtime interfaces, và integration risks của một ROS package chỉ sử dụng repository evidence. + +## Khi nào dùng + +Dùng khi inspect một package, dependency issue, launch path, migration risk, build problem, hoặc package boundary. + +## Quy trình + +### Bước 1: Đọc context + +Đọc project context files nếu có. + +### Bước 2: Locate package manifests + +Tìm package manifests và build files. + +### Bước 3: Inspect theo ROS version + +**ROS 1:** `package.xml`, `CMakeLists.txt`, launch XML, `cfg`, `msg`, `srv`, `action`, nodelets, catkin conventions + +**ROS 2:** `package.xml`, `CMakeLists.txt` hoặc Python packaging, launch files, `msg/srv/action`, ament exports, components, lifecycle, colcon conventions + +### Bước 4: Trace entry points + +Trace executables → publishers, subscribers, services, actions, parameters, TF, model/config assets. + +### Bước 5: Verify dependencies + +So sánh declared dependencies với code imports/includes và launch usage. + +## Checklist + +- [ ] Package role đã verify +- [ ] Build type và dependencies đã kiểm tra +- [ ] Runtime interfaces và parameters đã map +- [ ] Launch/config files đã link với executables +- [ ] Tests và CI coverage đã locate +- [ ] Unknowns mark `Unknown / needs confirmation` + +## Ví dụ minh hoạ + +**Ví dụ 1: Hiểu package trước khi sửa** + +Người dùng nói: "Tôi cần sửa package `detection_ros2`, cho tôi biết structure của nó" + +Hành động: +1. Đọc `package.xml`: build_type, dependencies +2. Xem `CMakeLists.txt`: executables và libraries được build +3. List launch files và nodes chúng launch +4. Trace main node: subscriptions, publications, services, parameters +5. Tìm test files + +Kết quả: Package map với entry points, interfaces, parameter list, dependencies. + +**Ví dụ 2: Debug build failure** + +Người dùng nói: "colcon build báo 'package X not found'" + +Hành động: +1. Đọc `package.xml` phần `` và `` +2. Kiểm tra package X có trong workspace không +3. Kiểm tra `CMakeLists.txt` có `find_package(X REQUIRED)` không +4. Kiểm tra `package.xml` có declare dependency không +5. Xem `colcon.meta` hoặc workspace setup + +Kết quả: Missing dependency root cause, fix commands. + +## Khắc phục sự cố + +**Lỗi:** Node launch nhưng không tìm được parameter +**Nguyên nhân:** Parameter namespace sai hoặc node name remapped +**Cách xử lý:** Trace launch file remaps, kiểm tra `~param` (private) vs `param` (global) namespace, verify `use_sim_time` nếu cần + +**Lỗi:** `ament_target_dependencies` báo không tìm thấy package +**Nguyên nhân:** Package không trong `package.xml` hoặc chưa source workspace +**Cách xử lý:** Add vào `package.xml` ``, rebuild với `--packages-select` để isolate + +## Output Format + +- Package summary: role, build type, main executables +- Manifest/build findings: declared vs actual +- Runtime interfaces: publishers, subscribers, services, actions, params +- Launch/config map: launch files → nodes → remaps +- Dependency gaps hoặc risks +- Suggested next checks diff --git a/.claude/skills/ros-topic-debugging/SKILL.md b/.claude/skills/ros-topic-debugging/SKILL.md new file mode 100644 index 0000000..eacbb6b --- /dev/null +++ b/.claude/skills/ros-topic-debugging/SKILL.md @@ -0,0 +1,97 @@ +--- +name: ros-topic-debugging +description: Debug vấn đề ROS 1/ROS 2 topic như thiếu messages, wrong types, rate bất thường, stale timestamps, queue drops, QoS mismatch, encoding errors. Dùng khi người dùng báo 'topic không có data', 'subscriber không nhận messages', 'rate quá thấp', 'QoS incompatible', 'message type mismatch', 'latching không hoạt động', hoặc 'timestamp cũ'. +--- + +# ROS Topic Debugging + +## Mục tiêu + +Chẩn đoán topic-related failures như missing messages, wrong types, bad rates, stale timestamps, queue drops, QoS mismatches, hoặc encoding/contract errors. + +## Khi nào dùng + +Dùng cho publisher/subscriber issues, perception input failures, control command gaps, synchronization problems, bag replay differences, hoặc bridge problems. + +## Quy trình + +### Bước 1: Đọc context + +Đọc `PROJECT_CONTEXT.md` và `ROS_TOPIC_MAP.md` nếu có. + +### Bước 2: Discover topics + +Tìm topic names và message types từ source, launch, config, docs, hoặc user logs. + +### Bước 3: Kiểm tra theo ROS version + +**ROS 1:** remaps, namespaces, queue sizes, latching, `message_filters`, transport hints, `rostopic` evidence + +**ROS 2:** remaps, namespaces, QoS profiles, durability, reliability, history depth, lifecycle state, `ros2 topic` evidence + +### Bước 4: Verify message contract + +Message fields, timestamps, frame IDs, units, rates, image encodings. + +### Bước 5: Phân biệt evidence + +Phân biệt verified runtime evidence từ expected behavior. + +## Checklist + +- [ ] Publisher và subscriber code paths đã xác định +- [ ] Message type và schema đã verify +- [ ] Topic names, namespaces, remaps đã trace +- [ ] QoS hoặc queue settings đã kiểm tra +- [ ] Time synchronization và frame IDs đã kiểm tra +- [ ] Unknowns mark `Unknown / needs confirmation` + +## Ví dụ minh hoạ + +**Ví dụ 1: Subscriber không nhận messages** + +Người dùng nói: "Node của tôi subscribe `/lidar/points` nhưng callback không bao giờ được gọi" + +Hành động: +1. Trace publisher của `/lidar/points` trong codebase +2. Kiểm tra topic name exact match (case, namespace, leading slash) +3. ROS 2: Kiểm tra QoS mismatch (publisher dùng BEST_EFFORT, subscriber dùng RELIABLE?) +4. Kiểm tra lifecycle: publisher node đã trong ACTIVE state chưa? +5. Kiểm tra có remap ẩn trong launch file không + +Kết quả: Root cause với specific file:line, fix commands. + +**Ví dụ 2: Image topic có rate thấp bất thường** + +Người dùng nói: "Camera publish 30fps nhưng `/detections` chỉ ra 5Hz" + +Hành động: +1. Kiểm tra subscriber queue size: đang drop messages? +2. Kiểm tra callback processing time: quá lâu so với message interval? +3. Kiểm tra SingleThreadedExecutor: bị block bởi slow callback khác? +4. Kiểm tra image_transport: compressed transport có được decode đúng không? + +Kết quả: Bottleneck identification với executor/callback fix hoặc queue adjustment. + +## Khắc phục sự cố + +**Lỗi:** QoS incompatible warning trong ROS 2 +**Nguyên nhân:** Publisher và subscriber có QoS profile không match (Reliability, Durability, History) +**Cách xử lý:** Kiểm tra cả hai phía, set subscriber Reliability = BEST_EFFORT nếu publisher là BEST_EFFORT + +**Lỗi:** Topic tồn tại nhưng timestamp luôn cũ (stale) +**Nguyên nhân:** Publisher dùng `ros::Time(0)` hoặc `rclpy.time.Time()` thay vì current time +**Cách xử lý:** Trace timestamp assignment trong publisher code, thay bằng `node.get_clock().now()` + +**Lỗi:** `message_filters` ApproximateTimeSynchronizer không trigger +**Nguyên nhân:** Slop quá nhỏ hoặc messages không arrive trong cùng time window +**Cách xử lý:** Tăng slop value, kiểm tra header.stamp của từng topic, verify clock source match + +## Output Format + +- Symptom: mô tả cụ thể vấn đề +- Verified topic map: publishers, subscribers, types, namespaces +- Likely causes: ordered by evidence strength +- ROS 1/ROS 2 checks applicable +- Commands: chỉ dùng nếu verified hoặc clearly generic +- Next action: cụ thể nhất có thể diff --git a/.claude/skills/rosbag-analysis/SKILL.md b/.claude/skills/rosbag-analysis/SKILL.md new file mode 100644 index 0000000..59103da --- /dev/null +++ b/.claude/skills/rosbag-analysis/SKILL.md @@ -0,0 +1,97 @@ +--- +name: rosbag-analysis +description: Phân tích ROS 1 bag và ROS 2 bag2 để kiểm tra topics, timing, frame consistency, sensor quality và debug perception/model inputs. Dùng khi người dùng có file .bag hoặc bag2 directory, yêu cầu 'phân tích bag', 'debug từ recording', 'kiểm tra sensor data', 'replay bag', 'xem topic rate', hoặc debug recorded failures. +--- + +# Rosbag Analysis + +## Mục tiêu + +Dùng bag data để verify runtime behavior, topic contracts, timing, frame consistency, và perception/model inputs, tránh phỏng đoán về robot. + +## Khi nào dùng + +Dùng khi debug recorded failures, replay differences, sensor timing, dropped data, perception outputs, model inputs, hoặc control behavior. + +## Quy trình + +### Bước 1: Đọc context + +Đọc project context và topic/frame maps nếu có. + +### Bước 2: Xác định bag format + +Xác định ROS 1 rosbag hay ROS 2 rosbag2 từ files hoặc user input. + +### Bước 3: Inventory bag contents + +Topics, message types, start/end time, rates, frame IDs, sizes. + +### Bước 4: Kiểm tra format-specific details + +**ROS 1:** `rosbag info`, `rostopic hz`, playback clock, latching, connection metadata + +**ROS 2:** `ros2 bag info`, storage backend, serialization format, QoS override, simulated time + +### Bước 5: Kiểm tra data quality + +Synchronization, timestamp monotonicity, dropped frames, image encodings, calibration topics/files, TF coverage, model input/output topics. + +## Checklist + +- [ ] Bag format và metadata đã xác minh +- [ ] Topic types và rates đã ghi nhận +- [ ] TF availability và timestamp range đã kiểm tra +- [ ] Sensor payload quality và encodings đã kiểm tra +- [ ] Replay assumptions đã document +- [ ] Unknowns mark `Unknown / needs confirmation` + +## Ví dụ minh hoạ + +**Ví dụ 1: Debug tại sao detection thất bại ở một thời điểm trong bag** + +Người dùng nói: "Trong bag này, detection bị miss object từ giây 45-60, cần hiểu tại sao" + +Hành động: +1. `ros2 bag info` để xem topics và time range +2. Kiểm tra `/camera/image_raw` rate trong khoảng 45-60s: có drop không? +3. Kiểm tra `/camera/camera_info` có publish parallel không +4. Kiểm tra TF: frame `camera_link` → `base_link` có available không +5. Đề xuất replay với specific time range để observe + +Kết quả: Timeline của events, likely cause (camera drop? TF gap?), reproduce steps. + +**Ví dụ 2: Validate sensor data quality** + +Người dùng nói: "Kiểm tra bag này xem LiDAR và camera có sync không" + +Hành động: +1. List camera topics và LiDAR topics với rates +2. So sánh timestamps: camera header.stamp vs LiDAR header.stamp +3. Kiểm tra delta: difference trong 100ms là ok, 500ms+ là vấn đề +4. Kiểm tra TF tree có cover cả LiDAR frame và camera frame không + +Kết quả: Sync quality report với max/avg/min delta, TF coverage status. + +## Khắc phục sự cố + +**Lỗi:** `ros2 bag play` báo lỗi QoS incompatible +**Nguyên nhân:** Bag được record với QoS settings khác node đang subscribe +**Cách xử lý:** Dùng `--qos-profile-overrides-path` hoặc override reliability thành BEST_EFFORT + +**Lỗi:** Timestamp không monotonic trong bag +**Nguyên nhân:** Clock jump, simulated time bị reset, hoặc sensor internal clock drift +**Cách xử lý:** Kiểm tra có dùng `/clock` topic không, verify sensor driver timestamp source + +**Lỗi:** Bag thiếu TF data ở một thời điểm +**Nguyên nhân:** TF broadcaster bị crash hoặc không record `/tf_static` +**Cách xử lý:** Kiểm tra `/tf_static` có trong bag không, replay với `--clock` flag + +## Output Format + +- Bag identity và format (ROS 1/2, storage backend) +- Topic summary: names, types, rates, count +- Timing và TF findings +- Sensor/CV/model observations +- Likely causes hoặc risks +- Reproducible next commands hoặc checks diff --git a/.claude/skills/technical-document-reader/SKILL.md b/.claude/skills/technical-document-reader/SKILL.md new file mode 100644 index 0000000..2690c3a --- /dev/null +++ b/.claude/skills/technical-document-reader/SKILL.md @@ -0,0 +1,98 @@ +--- +name: technical-document-reader +description: Đọc tài liệu kỹ thuật robotics, ROS, CV, AI, hardware, vendor và trích xuất engineering facts đã xác minh mà không thêm thông tin project chưa biết. Dùng khi người dùng upload datasheet, API docs, paper, calibration note, model card, hardware manual, hoặc yêu cầu 'đọc tài liệu này', 'extract specs từ PDF', 'tóm tắt technical doc', 'tìm thông số kỹ thuật'. +--- + +# Technical Document Reader + +## Mục tiêu + +Trích xuất facts có thể hành động, có nguồn gốc rõ ràng từ technical documents và chỉ connect với target project khi repository confirm relationship. + +## Khi nào dùng + +Dùng cho datasheets, API docs, papers, READMEs, design notes, calibration notes, ROS package docs, model cards, hardware manuals, vendor deployment guides. + +## Quy trình + +### Bước 1: Xác định document + +Document source, version, date, và scope. + +### Bước 2: Đọc project context + +Đọc `PROJECT_CONTEXT.md` nếu có. Nếu không, mark project context là `Unknown / needs confirmation`. + +### Bước 3: Extract facts với citations + +Extract facts với citations đến sections, files, hoặc page numbers khi available. + +### Bước 4: Phân tách document facts và repo facts + +Tách biệt rõ facts từ document với facts từ target repo. + +### Bước 5: Kiểm tra theo domain + +**ROS 1:** topics, nodelets, parameters, launch XML, catkin, rosbag, dynamic reconfigure + +**ROS 2:** nodes, components, lifecycle, parameters, launch Python/XML/YAML, QoS, rosbag2, colcon + +**CV/AI:** camera model, calibration, encoding, preprocessing, model runtime, precision, memory + +### Bước 6: Flag risks + +Unsupported assumptions, missing versions, ambiguous units, timing constraints, calibration requirements, hardware dependencies. + +## Checklist + +- [ ] Source identity và version đã capture +- [ ] Units, coordinate frames, timestamp expectations, message/schema contracts đã kiểm tra +- [ ] Camera model, calibration, image encoding, preprocessing đã kiểm tra khi relevant +- [ ] Model runtime, precision, accelerator, memory, latency constraints đã kiểm tra khi relevant +- [ ] Unknown target-specific fields là `Unknown / needs confirmation` + +## Ví dụ minh hoạ + +**Ví dụ 1: Đọc camera datasheet để cấu hình driver** + +Người dùng nói: "Đây là datasheet của Intel RealSense D435i, tôi cần biết thông số để configure ROS driver" + +Hành động: +1. Extract: resolution options, frame rate, depth range, color/IR specs +2. Extract: interface (USB 3.0), SDK version required +3. Map sang ROS parameters: `color_width`, `color_height`, `color_fps`, `depth_fps` +4. Flag: calibration files cần thiết, `depth_scale` parameter +5. Note: ROS 1 dùng `realsense2_camera`, ROS 2 dùng `realsense2_camera_node` + +Kết quả: Parameter list với values và source citations, missing info list. + +**Ví dụ 2: Đọc model card để verify deployment** + +Người dùng nói: "Model card của YOLOv8n, tôi cần biết preprocessing requirements" + +Hành động: +1. Extract input spec: `[1, 3, 640, 640]`, RGB, normalized `[0, 1]`, letterbox resize +2. Extract output spec: `[1, 84, 8400]`, XYXY format, confidence scores +3. Compare với node preprocessing trong repo nếu có +4. Flag: letterbox vs simple resize difference, normalization order (mean/std vs /255) + +Kết quả: Verified preprocessing contract, mismatch warnings nếu có. + +## Khắc phục sự cố + +**Lỗi:** Document dùng đơn vị ambiguous (mm hay m? rad hay deg?) +**Nguyên nhân:** Vendor docs không nhất quán +**Cách xử lý:** Flag ambiguity rõ ràng, không assume, đề xuất user verify với hardware test + +**Lỗi:** Document version cũ không match với SDK hiện tại +**Nguyên nhân:** API thay đổi giữa versions +**Cách xử lý:** Note version mismatch, recommend kiểm tra changelog hoặc latest docs + +## Output Format + +- Document: name/version/source +- Verified facts: concise bullets với source references (section/page) +- Repository matches: facts đã confirm trong target repo +- Unknowns: `Unknown / needs confirmation` +- Risks: integration, safety, timing, compatibility, deployment concerns +- Next checks: specific files, commands, hoặc questions diff --git a/.claude/skills/tf-frame-debugging/SKILL.md b/.claude/skills/tf-frame-debugging/SKILL.md new file mode 100644 index 0000000..ff48c31 --- /dev/null +++ b/.claude/skills/tf-frame-debugging/SKILL.md @@ -0,0 +1,97 @@ +--- +name: tf-frame-debugging +description: Debug vấn đề TF/TF2 frame trong ROS bao gồm transforms, timestamps, naming, static/dynamic broadcasters và frame conventions. Dùng khi người dùng báo 'missing transform', 'extrapolation error', 'TF tree broken', 'sensor không align', 'navigation thất bại do frame', 'URDF frame không đúng', hoặc 'visualization lệch'. +--- + +# TF Frame Debugging + +## Mục tiêu + +Tìm TF tree, transform timing, frame naming, và coordinate convention issues mà không phỏng đoán robot frames. + +## Khi nào dùng + +Dùng cho missing transforms, extrapolation errors, incorrect visualization, sensor alignment, navigation failures, perception frame mismatches, hoặc calibration suspicion. + +## Quy trình + +### Bước 1: Đọc context + +Đọc `PROJECT_CONTEXT.md` và `TF_FRAME_MAP.md` nếu có. + +### Bước 2: Discover frames + +Tìm frame IDs từ source, URDF/Xacro, launch, config, bags, logs, message headers. + +### Bước 3: Kiểm tra theo ROS version + +**ROS 1:** `tf`/`tf2_ros`, static transform publishers, URDF robot state publisher, launch XML + +**ROS 2:** `tf2_ros`, static transform publishers, robot state publisher, lifecycle/composition, launch Python/YAML + +### Bước 4: Verify transforms + +Parent-child direction, timestamp source, broadcast rate, static vs dynamic intent, optical frame conventions, map/odom/base relationships. + +### Bước 5: Mark unknowns + +Absent hoặc ambiguous frames là `Unknown / needs confirmation`. + +## Checklist + +- [ ] Frame names đã verify từ repo hoặc runtime evidence +- [ ] Static và dynamic transforms đã tách biệt +- [ ] Timestamp và clock source đã kiểm tra +- [ ] Camera optical frame và REP-103/REP-105 conventions đã xem xét +- [ ] Calibration files và URDF/Xacro consistency đã kiểm tra +- [ ] Unknowns đã mark rõ + +## Ví dụ minh hoạ + +**Ví dụ 1: "Cannot transform from camera_frame to base_link"** + +Người dùng nói: "Tôi bị lỗi: 'Could not transform camera_link to base_link at time X'" + +Hành động: +1. Tìm `camera_link` broadcaster: static transform publisher hay robot state publisher? +2. Kiểm tra URDF: `camera_link` có được define không? Parent frame là gì? +3. Kiểm tra timestamp: broadcaster có dùng đúng clock không (sim time vs real time)? +4. Kiểm tra tree connectivity: `base_link` → ... → `camera_link` có path không? +5. Đề xuất debug: `ros2 run tf2_tools view_frames` hoặc `tf2_echo` + +Kết quả: Missing link trong TF tree, specific broadcaster file/line cần fix. + +**Ví dụ 2: Camera point cloud lệch so với LiDAR** + +Người dùng nói: "Khi overlay camera và LiDAR trong RViz, chúng bị lệch ~10cm" + +Hành động: +1. Kiểm tra `camera_optical_frame` vs `camera_link` - có missing REP-103 rotation không? +2. Kiểm tra extrinsic calibration: giá trị trong URDF có đúng không? +3. Kiểm tra timestamp của camera và LiDAR có sync không +4. Kiểm tra có `base_link` → `camera_link` → `camera_optical_frame` chain đúng không + +Kết quả: Identify xem là calibration error, frame convention error, hay timestamp issue. + +## Khắc phục sự cố + +**Lỗi:** "ExtrapolationException: Lookup would require extrapolation into the future" +**Nguyên nhân:** TF lookup time mới hơn latest available transform (clock skew hoặc lookup too early) +**Cách xử lý:** Dùng `rclpy.time.Time()` (latest) thay vì specific timestamp, hoặc tăng timeout trong `lookup_transform` + +**Lỗi:** Static transform bị override liên tục +**Nguyên nhân:** Hai nodes publish cùng static transform với values khác nhau +**Cách xử lý:** Grep tất cả nodes publish transform đó, xác định node nào "win", tắt node redundant + +**Lỗi:** TF tree bị broken sau khi node restart +**Nguyên nhân:** Dynamic transform broadcaster restart, TF buffer chưa populated lại +**Cách xử lý:** Thêm delay hoặc wait-for-transform trước lookup, publish `/tf_static` cho static transforms + +## Output Format + +- Symptom: error message cụ thể +- Verified frame facts: broadcasters, rates, parent-child +- Suspected issue và evidence +- ROS 1 hoặc ROS 2 verification steps +- Risk to perception/navigation/control +- Next action: commands hoặc code changes cụ thể diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8dc5320 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +# catkin +build/ +devel/ +logs/ +install/ +.catkin_tools/ + + # Du lieu lon + bags/ + *.bag + *.bag.active +*.db # RTAB-Map database +# RTAB-Map database +*.db +*.db-shm +*.db-wal +maps/*.pgm +maps/*.yaml +maps/*.pcd +maps/*.ply + + +# Third-party source (quan ly bang .rosinstall + vcstool) +src/third_party/* +!src/third_party/.rosinstall +!src/third_party/README.md +!src/third_party/CATKIN_IGNORE + +# Python +__pycache__/ +*.pyc + +# Ket qua danh gia +results/ +*.csv +*.tum + +# IDE / OS +.vscode/ +.idea/ +*.swp +.DS_Store diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..0b8a040 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,90 @@ +# Robotics / CV / ROS Repository Guidance + +This repository may contain robotics, ROS, ROS 2, computer vision, edge AI, embedded, simulation, or deployment code. Treat every project-specific detail as unknown until verified from this repository or from user-provided context. + +## Project Context + +- Read `PROJECT_CONTEXT.md` if present before making assumptions. +- Prefer verified repository facts over generic robotics assumptions. +- If `ROS_TOPIC_MAP.md`, `TF_FRAME_MAP.md`, or `MODEL_DEPLOYMENT_CONTEXT.md` exists, read the relevant file before analyzing related behavior. +- If a context file is missing or incomplete, use `Unknown / needs confirmation` for unverified facts. + +## Discovery Rules + +- Discover package names, node names, launch files, parameters, topics, services, actions, TF frames, model paths, robot names, hardware, and build/test commands from the target repo at usage time. +- Do not invent commands, topics, frames, model paths, hardware, calibration files, accelerators, middleware, operating systems, or deployment targets. +- Generic examples are allowed only when clearly marked as examples. +- Consider both ROS 1 and ROS 2 conventions where relevant. + +## Robotics Engineering Checks + +- Check message contracts, timestamps, coordinate frames, units, calibration, synchronization, QoS or queue settings, lifecycle behavior, launch parameters, and runtime configuration. +- Consider safety, watchdogs, failure modes, degraded sensor input, timing, resource limits, and hardware interaction boundaries. +- For CV and AI code, check image encodings, camera models, preprocessing, postprocessing, model input/output contracts, conversion precision, accelerator support, and runtime memory pressure. + +## Change Discipline + +- Keep edits scoped to the requested task. +- Do not rewrite unrelated launch, configuration, model, or hardware files. +- Preserve user changes and repository conventions. +- At the end, summarize changed files and verification performed. + +## Edit Approval Workflow + +- Before modifying source code, configs, launch files, scripts, build files, docs, templates, or other repository files, present the proposed additions and deletions in diff-style format. +- Explain the expected impact, risks, assumptions, and files that would change. +- Do not edit, create, delete, rename, overwrite, reformat, regenerate, or run modifying commands before explicit user confirmation. +- Read-only inspection commands are allowed before confirmation. +- Treat formatting, code generation, dependency installation, migration, autofix, cleanup, and build-system update commands as modifying commands when they can change files or state. +- Accepted confirmation words include `confirm`, `apply`, `ok`, `yes`, `dong y`, `đồng ý`, `tiep tuc`, `tiếp tục`, and `sửa đi`. +- After applying approved changes, summarize files changed, what changed, validation checks run, and checks not run. + +## Build & Run Handoff Workflow + +- Never execute build, compile, install, launch, train, flash, or long-running commands automatically — foreground or background (`run_in_background`, `&`, `nohup`, `tmux`, `screen`). +- This covers `colcon build`, `catkin_make`, `cmake --build`, `make`, `ninja`, `cargo build`, `pip install`, `npm install`, `docker build`, `docker run`, `roslaunch`, `ros2 launch`, `ros2 run`, `rosbag play/record`, `trtexec`, training scripts, firmware flashing, and any command that needs sudo, GPU, hardware, or more than ~10 seconds. +- Instead, print the exact command for the user to run in their own terminal: working directory, environment prerequisites, the copy-pasteable command, expected success signal, and what to report back. Then stop and wait. +- Read-only inspection commands (`ls`, `cat`, `grep`, `git status`, `git diff`, `ros2 pkg list`, `nvidia-smi`) may still be run directly. +- Suggest `2>&1 | tee /tmp/.log` so the result can be read back from the log file instead of pasted. +- Do not continue writing code that assumes a build passed. Wait for the actual result. +- If the user explicitly asks Claude to run a build command, that override is allowed — run it in the foreground, never backgrounded. +- Full details in the `manual-build-handoff` skill. + +## Output Style — Caveman Mode (Always On) + +Caveman mode is **always active** in this project. Apply `full` level by default to every response. + +**Drop:** articles (a/an/the), filler words (just, really, basically, simply), pleasantries (certainly, great question), hedging (I think, it seems, có lẽ) +**Keep:** all technical substance, code blocks, exact error strings, API names, acronyms, command flags +**Pattern:** `[thing] [action] [reason]. [next step].` +**Language:** match user's language, compress style only. Never announce mode. + +Auto-revert to normal for: security warnings, irreversible action confirmations, multi-step sequences where brevity risks misunderstanding. Resume caveman after. + +Override anytime: `/caveman lite` (softer) · `/caveman ultra` (harder) · `normal mode` (off) + +## Available Slash Commands + +Use these slash commands for structured robotics engineering tasks: + +- `/project-onboarding` — onboard into this repository and populate PROJECT_CONTEXT.md +- `/read-source-code` — trace source code behavior using repo evidence +- `/robotics-code-review` — review code for behavioral bugs, timing, and integration risks +- `/patch-preview-before-edit` — preview diffs before any file is modified +- `/manual-build-handoff` — hand build/run commands to the user instead of executing them +- `/ros-package-analysis` — analyze ROS package structure and interfaces +- `/ros-topic-debugging` — debug topic issues (publishers, subscribers, QoS, rates) +- `/tf-frame-debugging` — debug TF frame naming, transforms, and timing +- `/rosbag-analysis` — analyze ROS bag data for topics, timing, and sensor quality +- `/cv-pipeline-analysis` — trace CV pipelines from camera input to outputs +- `/edge-ai-deployment` — review model deployment path for edge devices +- `/model-conversion-debugging` — debug ONNX/TRT/TFLite/OpenVINO conversion issues +- `/real-time-performance-profiling` — profile latency, jitter, and resource usage +- `/repo-context-maintainer` — update PROJECT_CONTEXT.md with verified facts +- `/technical-document-reader` — extract engineering facts from technical documents +- `/caveman [mode]` — adjust compression level (lite/full/ultra/wenyan) +- `/caveman-commit` — generate terse conventional commit message +- `/caveman-review` — ultra-compressed code review (L: problem. fix.) +- `/caveman-stats` — show estimated token savings this session +- `/caveman-compress ` — compress a markdown memory file +- `/caveman-help` — show all caveman modes and commands diff --git a/PROJECT_CONTEXT.md b/PROJECT_CONTEXT.md new file mode 100644 index 0000000..25973dc --- /dev/null +++ b/PROJECT_CONTEXT.md @@ -0,0 +1,112 @@ +# Project Context + +Use this file for verified target-repository facts only. Keep unknown values as `Unknown / needs confirmation`. + +## Project Identity + +- Project name: `vSLAM_ws` — catkin workspace at `~/projects/vSLAM_ws` +- Robot or system: `service_robot` (URDF ``), differential-drive indoor service robot, 2 driven wheels + front/rear casters +- Primary use case: 2.5D SLAM + navigation for a food-serving robot in multi-floor restaurants/hotels. Pose is SE(2); roll/pitch are **measured** from IMU, never estimated; z assumed 0. 2D ToF LiDAR is the SLAM backbone, RealSense D410 is perception-only. Back-end intended to be GTSAM. +- Repository role: single ROS 1 workspace holding 8 first-party packages + a `third_party/` vcstool manifest. Development is currently simulation-first; no real sensors are attached yet. + +## Stack + +- ROS distribution: Noetic (`/opt/ros/noetic` present) +- ROS variant: ROS 1 — `package format="2"`, catkin, XML `.launch`, nodelets, `dynamic` params via param server +- Operating system: Linux, kernel 5.15. Distro version not verified (Noetic implies Ubuntu 20.04 but this was not checked) +- Build system: `catkin_tools` (`.catkin_tools/` + `build/` + `devel/`), i.e. `catkin build`, not `catkin_make` +- Main languages: C++ (roscpp nodes and nodelets), Python 3 (rospy scripts), xacro/URDF, YAML, one bash script +- Simulation stack: Gazebo via `gazebo_ros` + `gazebo_plugins`. Worlds: `restaurant`, `hotel_corridor` (`src/robot_sim/worlds/`) + +## Repository Layout + +- ROS packages (all under `src/`, all first-party): + - `robot_bringup` — URDF/TF, central config, the layered launch files. No code. + - `robot_sim` — Gazebo plugins, worlds, ground truth, barometer/elevator/degradation simulators + - `robot_drivers` — `wheel_odom_node` (C++, shared sim+real), `imu_bridge_node.py`, RICHBEAM LiDAR wrapper + - `robot_safety` — independent safety process: bumper, ultrasonic, speed limits, e-stop + - `perception_3d` — zero-copy nodelets: `DepthFilterNodelet`, `GravityAlignNodelet` + - `slam_core` — 2.5D factor-graph node, **currently passthrough** (GTSAM not installed) + - `localization_ops` — dock init, barometer/AprilTag floor detection, multi-map manager + - `slam_eval` — ATE/RPE, repeatability, resource profiling, rosbag recording + - `experimental/` — carries `CATKIN_IGNORE`, GPL quarantine area (empty of code) + - `third_party/` — carries `CATKIN_IGNORE`, `.rosinstall` only; nothing imported yet +- Launch/config locations: `src//launch/*.launch`, `src//config/*.yaml`. Central robot geometry in `src/robot_bringup/config/robot.yaml` +- Source locations: `src//src/*.cpp`, `src//scripts/*.py`, headers in `src/slam_core/include/slam_core/` +- Test locations: **none** — no rostest, gtest, or unittest anywhere in the repo, and no CI config. Verification is manual per-layer acceptance (L0–L6 in `README.md`) plus the `slam_eval` scripts +- Documentation locations: `README.md` (run instructions, layer table, status), `docs/ARCHITECTURE.md` (design rationale — read before changing architecture), `docs/HARDWARE.md`, `docs/ROADMAP.md` (phases GĐ0–GĐ8), `docs/SIM_VS_REAL.md`, `docs/SLAM-vSLAM-3DSLAM-ban-thao.md`. All docs are in Vietnamese. + +## Runtime Interfaces + +- Main nodes: + - `robot_state_publisher`, `joint_state_publisher` (fake joints only at L0) + - `wheel_odom` (`robot_drivers/wheel_odom_node`) — same binary in sim and on real hardware + - `ekf_odom` (`robot_localization/ekf_localization_node`) — owns TF `odom → base_footprint` + - `perception_manager` nodelet manager hosting `depth_to_cloud` (`depth_image_proc/point_cloud_xyz`), `depth_filter`, `gravity_align` + - `octomap_server` + - `slam_core` — owns TF `map → odom` + - `move_base`, `amcl`, `map_server` (localization mode) + - `safety_monitor` — always a separate process, `respawn="true"` + - `dock_init`, `floor_detector`, `multi_map_manager` + - Sim-only: `spawn_robot`, `baro_sim`, `elevator_sim`, `sim_degradation` +- Topics (see `ROS_TOPIC_MAP.md` for the full table): + - Raw sensors: `/scan`, `/imu/data_raw`, `/joint_states`, `/camera/depth/image_rect_raw`, `/camera/depth/camera_info`, `/camera/infra1|infra2/image_rect_raw`, `/baro/pressure`, `/baro/temperature` + - Odometry: `/odom`, `/odometry/filtered`, `/wheel_odom/slip_metric` + - Perception: `/perception/cloud_raw` → `/perception/cloud_filtered` → `/perception/cloud_aligned`, `/gravity_align/roll_pitch`, `/octomap_full`, `/map` (octomap `projected_map` is remapped to `/map`) + - SLAM/localization: `/slam/pose`, `/initialpose`, `/map_metadata`, `/map_name`, `/floor/current`, `/floor/status`, `/floor/tag_hint` + - Control/safety: `/cmd_vel` → `safety_monitor` → `/cmd_vel_safe` → motors/Gazebo, `/bumper`, `/safety/status`, `/ultrasonic/*` (list is currently empty) + - Sim-only: `/ground_truth/odom` (evaluation only — no estimator may subscribe), `/elevator/status`, `/elevator/goto_floor` +- Services: `safety/reset`, `safety/estop` (`robot_safety`), `dock_init/set_dock_pose` (`std_srvs/Trigger`) +- Actions: no custom actions defined in-repo. `move_base` contributes its standard `/move_base` action interface +- Parameters: loaded from `robot_bringup/config/{robot,ekf_odom,move_base,costmap_common,costmap_local,costmap_global}.yaml`, `slam_core/config/slam_core.yaml`, `perception_3d/config/depth_filter.yaml` (namespaces `depth_filter` and `gravity_align`), `robot_safety/config/safety.yaml`, `localization_ops/config/floors.yaml`, `robot_sim/config/sim_sensors.yaml` +- TF frames (see `TF_FRAME_MAP.md`): `map → odom → base_footprint → base_link → {left/right_wheel_link, front/rear_caster_link, laser_link, camera_link, imu_link}`; `camera_link → camera_depth_optical_frame → camera_infra1_optical_frame`, `camera_infra2_optical_frame`. TF ownership is strictly split: `ekf_odom` publishes `odom → base_footprint`, `slam_core` publishes `map → odom`. At L3 a static identity `map → odom` stands in and is disabled at L4. + +## Sensors And Hardware + +- Cameras: Intel RealSense **D410**, Product Id `0AD2`, FW `5.17.0.10`, USB 3.2 — verified via `rs-enumerate-devices` (2026-08). **No RGB** (Stereo Module only), **no built-in IMU**, no alternating-emitter mode, rolling shutter, 69° FOV. Configured 640×480 @ 30 Hz for depth + infra1 + infra2; emitter fixed at `1` (Laser), never `2` (Laser Auto). Min-Z **estimated** ~22 cm at this resolution — not yet measured. +- LiDAR: RICHBEAM 2D ToF. **Driver not yet obtained** — `richbeam.launch` launches nothing; the real node is commented out pending the vendor package. Four properties still unverified: interface (Ethernet vs USB), whether the device supplies its own timestamp, true FOV (270° vs 360°), scan rate/angular resolution. Gazebo stands in with `gpu_ray`: 960 samples, FOV ±120° (deliberately 240°, not 270°, so rays do not hit the robot body), 15 Hz, range 0.05–30 m. +- IMU: **not purchased**. Planned ICM-42688-P or BMI088 read by an MCU (STM32F4/Teensy 4.0/RP2040) over serial at 921600 baud, timestamped at sample time. Barometer BMP390/BMP581 planned in the same module. Gazebo stands in with `libgazebo_ros_imu_sensor` @ 200 Hz using datasheet-derived noise. +- Compute target: development on i5-14500 + RTX 4060. Deployment target is an industrial PC (IPC) — model not chosen (`docs/ROADMAP.md` GĐ8). +- Accelerators: RTX 4060, used only for Gazebo `gpu_ray`. No inference accelerator in the pipeline. +- Actuators or robot base: differential drive. `wheel_radius` 0.075 m, `wheel_separation` 0.36 m, body 0.40 × 0.34 × 0.85 m, `ground_clearance` 0.04 m, `body_offset_x` −0.06 m. These values exist in **two** places that must stay in sync: `robot_bringup/urdf/robot.urdf.xacro` and `robot_bringup/config/robot.yaml`. Gazebo's `diff_drive_controller` subscribes to `cmd_vel_safe`, so the safety layer is exercised in simulation too. Bumper and ultrasonic sensors are **not yet purchased**; `ultrasonic_topics` is an empty list, meaning glass and mirrors are currently undetectable. + +## CV And AI + +- Models: **none**. No model or weight files exist in the repo (`.pt`, `.onnx`, `.trt`, `.engine`, `.pth`, `.tflite` — all absent), and no package depends on an inference runtime. This is not an edge-AI deployment repo at present. +- Model formats: not applicable +- Inference runtimes: not applicable +- Preprocessing: depth image → point cloud (`depth_image_proc/point_cloud_xyz`) → `DepthFilterNodelet` (range gate 0.22–4.0 m, 3 cm voxel, temporal confirmation with `min_hits: 3`, optional statistical outlier removal currently off) → `GravityAlignNodelet` (complementary filter α 0.98, accel low-pass α 0.05, accel gate 1.0 m/s²; outputs in `base_footprint`) +- Postprocessing: `octomap_server` at 0.05 m resolution, `occupancy_min_z` 0.05, `occupancy_max_z` 1.10, producing `/octomap_full` and `/map` +- Calibration files: **none exist yet**. Three calibrations are outstanding and every covariance currently in config is a datasheet guess: `allan_variance_ros` for IMU noise (≥3 h run), UMBmark for wheel geometry (targets ~5% → ~1% odometry error), and camera/LiDAR extrinsics. + +## Commands + +- Build command: `cd ~/projects/vSLAM_ws && catkin build && source devel/setup.bash` +- Test command: `Unknown / needs confirmation` — no automated test suite exists. The de-facto verification is the L0–L6 acceptance table in `README.md` +- Lint command: `Unknown / needs confirmation` — no linter is configured +- Launch examples (layered; each layer is accepted before the next is run): + - `roslaunch robot_bringup description.launch` — L0, URDF + TF only + - `roslaunch robot_bringup sim.launch world:=restaurant|hotel_corridor` — L1, Gazebo + - `roslaunch robot_bringup odom.launch` — L2, wheel odom + EKF + - `roslaunch robot_bringup perception.launch` — L3, cloud pipeline + OctoMap + - `roslaunch robot_bringup slam.launch` — L4, adds `slam_core` + - `roslaunch robot_bringup nav.launch` — L5, adds `move_base` (robot will not move: no safety layer to bridge `/cmd_vel` → `/cmd_vel_safe`) + - `roslaunch robot_bringup robot.launch [use_sim:=false]` — L6, full system + - `roslaunch robot_bringup mapping.launch` / `localization.launch` — the two operating modes +- Bag playback examples: `rosrun slam_eval record_bag.sh ` writes to `bags/` (raw topics only — outputs are deliberately excluded so algorithms can be re-run on identical input). Playback command not scripted: `Unknown / needs confirmation`. `bags/`, `maps/`, and `results/` are all currently empty. +- Evaluation: `rosrun slam_eval eval_ate.py --out results/`, `repeatability.py --samples 20`, `resource_profile.py --duration 60` + +## Verification Notes + +- Last inspected by Claude Code: 2026-08-26 +- Verified files: `README.md`; `docs/ARCHITECTURE.md`; `docs/HARDWARE.md`; all 8 `package.xml`; all launch files in `robot_bringup`, `robot_drivers`, `robot_sim`, `perception_3d`, `slam_core`, `robot_safety`, `localization_ops`; `robot.urdf.xacro`; `sensors.xacro`; `gazebo_sensors.xacro`; `robot.yaml`; `ekf_odom.yaml`; `slam_core.yaml`; `safety.yaml`; `depth_filter.yaml`; `floors.yaml`; `topics_to_record.yaml`; `record_bag.sh`; `src/third_party/{README.md,.rosinstall}`; publisher/subscriber declarations in every `.cpp` and `.py` node +- Open questions: + 1. `slam_core` is passthrough — GTSAM is not installed, so there is no optimization, no scan matching, no loop closure, and pose **will drift**. This is expected until GĐ5. + 2. RICHBEAM driver absent; the four LiDAR properties in `docs/HARDWARE.md` §2 are unverified, so `/scan` on real hardware is not yet characterized. + 3. IMU, barometer, bumper, and ultrasonic sensors are unpurchased. With `ultrasonic_topics: []`, glass and mirrors cannot be detected at all. + 4. Every covariance in `slam_core.yaml`, `ekf_odom.yaml`, `robot.yaml`, and `imu_bridge.launch` is a datasheet guess pending calibration. + 5. librealsense version conflict (Intel 2.58.3 vs ROS 2.50.0 with wrapper 2.3.2) blocks running the real camera. Does not affect simulation. + 6. D410 Min-Z ~22 cm is an estimate; the measured value determines the bumper specification and `depth_filter/min_range`. + 7. No maps exist yet, so `localization.launch` and the multi-floor path cannot run; `floors.yaml` paths point at files that have not been created. + 8. L5 and L6 have never been run (`README.md` status table). + 9. Ubuntu release not confirmed. diff --git a/README.md b/README.md new file mode 100644 index 0000000..78cb43e --- /dev/null +++ b/README.md @@ -0,0 +1,190 @@ +# vSLAM_ws — SLAM cho robot dịch vụ indoor + +Workspace ROS1 Noetic cho robot phục vụ chạy trong nhà hàng / khách sạn nhiều tầng. + +**Kiến trúc:** 2.5D SLAM — pose SE(2), roll/pitch **đo** từ IMU. LiDAR 2D ToF là +trụ cột SLAM, RealSense D410 là cảm biến perception 3D. Back-end GTSAM. + +> Lý do đằng sau từng quyết định nằm ở [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md). +> Đọc file đó trước khi sửa kiến trúc. + +--- + +## Cài đặt + +### 1. Dependencies + +```bash +sudo apt install -y \ + ros-noetic-navigation \ + ros-noetic-pcl-ros ros-noetic-pcl-conversions ros-noetic-tf2-sensor-msgs \ + ros-noetic-robot-localization \ + ros-noetic-octomap-server ros-noetic-octomap-ros \ + ros-noetic-depth-image-proc \ + python3-serial python3-numpy +``` + +Để sau (giai đoạn baseline / phần cứng thật): + +```bash +sudo apt install -y ros-noetic-rtabmap-ros ros-noetic-cartographer-ros ros-noetic-apriltag-ros +pip3 install evo pyrealsense2 +``` + +**GTSAM không cài bằng apt** — là thư viện CMake thuần, không phải catkin package. +Xem [`src/third_party/README.md`](src/third_party/README.md). Workspace build xanh +khi chưa có GTSAM (`slam_core` chạy chế độ passthrough). + +### 2. Build + +```bash +cd ~/projects/vSLAM_ws +catkin build +source setup_env.sh # KHÔNG phải devel/setup.bash — xem bên dưới +``` + +### ⚠️ Dùng `setup_env.sh`, không dùng `devel/setup.bash` + +SDK camera Hikvision **MVS** (`/opt/MVS`) tự prepend một bản `libusb` **cũ** vào +`LD_LIBRARY_PATH` trong cả `~/.bashrc` lẫn `~/.profile`. Bản đó thiếu +`libusb_set_option`, nên mọi binary dùng `libpcl_io` **chết ngay khi khởi động**: + +``` +rtabmap: symbol lookup error: libpcl_io.so.1.10: undefined symbol: libusb_set_option +[rtabmap/rtabmap-16] process has died [exit code 127] +``` + +`setup_env.sh` gỡ `/opt/MVS` khỏi `LD_LIBRARY_PATH` (chỉ trong shell đó), rồi +mới source workspace. MVS vẫn dùng bình thường ở các shell khác. + +> Đổi `prepend` thành `append` **không cứu được**: `LD_LIBRARY_PATH` luôn được +> tìm trước cache `ldconfig`, nên chỉ cần `/opt/MVS` còn trong biến đó là nó vẫn +> thắng thư viện hệ thống. + +--- + +## Chạy — 7 lớp tăng dần + +**Không sang lớp sau khi lớp trước chưa xanh.** Mỗi lớp nghiệm thu độc lập. + +| Lớp | Lệnh | Nghiệm thu | Trạng thái | +|---|---|---|---| +| **L0** | `roslaunch robot_bringup description.launch` | `rqt_tf_tree` liền mạch | ✅ đã kiểm chứng | +| **L1** | `roslaunch robot_bringup sim.launch` | 7 luồng cảm biến đúng tần số | ✅ đã kiểm chứng | +| **L2** | `roslaunch robot_bringup odom.launch` | `/odometry/filtered` lệch < 2% so `/ground_truth/odom` | ✅ **1.04%** | +| **L3** | `roslaunch robot_bringup perception.launch` | Cloud khớp vật thể, **thấy mặt bàn nhô ra** | ✅ đã kiểm chứng | +| **L4** | `roslaunch robot_bringup slam.launch` | `rosrun slam_eval eval_ate.py` ra được số | ✅ đã kiểm chứng | +| **L5** | `roslaunch robot_bringup nav.launch` | Đặt 2D Nav Goal → có global + local plan | ✅ plan 616 điểm | +| **L6** | `roslaunch robot_bringup robot.launch` | Robot tới được đích | ✅ `SUCCEEDED` | + +⚠️ **L6 đạt về chức năng nhưng odometry sai 18%**: khi `move_base` báo tới đích, +odometry nói 2.05 m còn thực tế 1.74 m. Nguyên nhân là bánh trượt lúc tăng tốc +(`slip_metric` = 0.170 > ngưỡng 0.15). Đã giảm `max_vel_x` 0.5 → 0.35 và +`acc_lim_x` 0.5 → 0.3 để giảm triệu chứng, nhưng **nguyên nhân gốc phải xử lý +bằng hiệu chuẩn UMBmark ở GĐ2** trên robot thật. + +Chuyển sang phần cứng thật: thêm `use_sim:=false`. **Mọi thứ từ L2 trở lên không +đổi một dòng nào** — đó là kết quả của nguyên tắc parity sim↔real. + +### World mô phỏng + +```bash +roslaunch robot_bringup sim.launch world:=restaurant # nhà hàng, bàn ghế +roslaunch robot_bringup sim.launch world:=hotel_corridor # hành lang, cửa giống hệt nhau +``` + +⚠️ **Chạy `hotel_corridor` trước khi tin vào kết quả ở `restaurant`.** Nó tái +tạo hai kịch bản xấu nhất: perceptual aliasing (cửa giống hệt nhau → false loop +closure phá map) và thoái hoá hình học (hai tường song song → scan matching +trượt tự do dọc trục). + +### Lái robot + +```bash +# L1–L5 (chưa có lớp an toàn): publish thẳng vào cmd_vel_safe +rosrun teleop_twist_keyboard teleop_twist_keyboard.py cmd_vel:=/cmd_vel_safe + +# L6 (có lớp an toàn): publish vào cmd_vel, đi qua safety_monitor +rosrun teleop_twist_keyboard teleop_twist_keyboard.py +``` + +### Hai chế độ vận hành + +```bash +roslaunch robot_bringup mapping.launch # build map, VẮNG KHÁCH +rosrun map_server map_saver -f maps/map_floor_1 + +roslaunch robot_bringup localization.launch # vận hành, map tĩnh đã duyệt +``` + +Tách hai chế độ loại bỏ phần lớn độ phức tạp: không cần lifelong SLAM, không sợ +false loop closure phá map giữa ca phục vụ. Xem `mapping.launch` để biết lý do. + +--- + +## Đánh giá + +```bash +rosrun slam_eval eval_ate.py --out results/run1 # ATE/RPE bằng ground truth Gazebo +rosrun slam_eval repeatability.py --samples 20 # độ phân tán khi tới cùng waypoint +rosrun slam_eval resource_profile.py --duration 60 # CPU/RAM từng node +rosrun slam_eval record_bag.sh nha_hang_vang_khach # ghi raw topic +``` + +**Repeatability quan trọng hơn ATE** với robot phục vụ: khách không quan tâm +robot nghĩ mình ở toạ độ nào, chỉ cần nó dừng đúng cạnh bàn mỗi lần. + +Mọi so sánh thuật toán phải chạy trên **cùng một rosbag**. So giữa các lần chạy +khác nhau là vô nghĩa — mỗi lần robot đi một đường khác. + +--- + +## Cấu trúc + +``` +src/ +├── robot_bringup/ URDF/TF, launch 7 lớp, config tập trung +├── robot_sim/ Gazebo: plugin cảm biến, world, ground truth +├── robot_drivers/ wheel_odom (chung sim+thật), imu_bridge, richbeam +├── robot_safety/ ⚠️ process ĐỘC LẬP: bumper, siêu âm, e-stop +├── perception_3d/ nodelet zero-copy: lọc cloud + bù nghiêng +├── slam_core/ factor graph 2.5D (đang passthrough, GTSAM ở GĐ5) +├── localization_ops/ dock init, phát hiện tầng, đa bản đồ +├── slam_eval/ ATE/RPE, repeatability, profile tài nguyên +├── experimental/ ⚠️ CATKIN_IGNORE — vùng cách ly GPL +└── third_party/ .rosinstall + vcstool +``` + +### Ba quy tắc không được phá + +1. **`robot_safety` luôn là process riêng.** Nếu `slam_core` segfault, khả năng + dừng của robot phải còn. Nghiệm thu: `rosnode kill /slam_core` → `/safety/status` + vẫn chạy. +2. **Mỗi cảm biến vào factor graph đúng một lần.** IMU không bao giờ xuất hiện ở + hai nơi — đó là lỗi khiến estimator overconfident và covariance vô nghĩa. +3. **`/ground_truth/odom` chỉ dùng cho `slam_eval`.** Không node ước lượng nào + được subscribe. Trên robot thật topic này không tồn tại. + +### Đồng bộ thông số + +Hình học robot có ở **hai nơi** và phải khớp nhau: +- `src/robot_bringup/urdf/robot.urdf.xacro` — cho TF và mô phỏng +- `src/robot_bringup/config/robot.yaml` — cho node đọc từ param server + +--- + +## Trạng thái + +| Đã có | Chưa có | +|---|---| +| ✅ Mô phỏng Gazebo + ground truth | ❌ Factor graph GTSAM (GĐ5) | +| ✅ Odometry + slip detection | ❌ Scan matching, loop closure | +| ✅ Perception 3D (nodelet, bù nghiêng) | ❌ Baseline Cartographer / RTAB-Map | +| ✅ Lớp an toàn | ❌ Phần cứng thật (IMU, barometer, bumper, siêu âm chưa mua) | +| ✅ Bộ đo ATE/repeatability | ❌ Hiệu chuẩn (allan_variance, UMBmark, extrinsic) | +| ✅ Khung đa tầng | ❌ Xử lý xung đột librealsense | + +Lộ trình đầy đủ: [`docs/ROADMAP.md`](docs/ROADMAP.md) + +⚠️ **Mọi giá trị covariance trong config hiện là số phỏng đoán từ datasheet.** +Chúng phải được thay bằng kết quả hiệu chuẩn thật trước khi tin vào kết quả SLAM. diff --git a/ROS_TOPIC_MAP.md b/ROS_TOPIC_MAP.md new file mode 100644 index 0000000..d390f05 --- /dev/null +++ b/ROS_TOPIC_MAP.md @@ -0,0 +1,93 @@ +# ROS Topic Map + +Use verified target-repository facts only. Keep unknown values as `Unknown / needs confirmation`. + +All interfaces are ROS 1 (Noetic). "Queue" columns are ROS 1 publisher/subscriber queue sizes — ROS 1 has no QoS profiles. Rates marked *(sim)* come from Gazebo plugin `update_rate`/`updateRate` values; real-hardware rates are unverified because no sensor is connected yet. + +Parity rule (`docs/ARCHITECTURE.md` §6): simulation and real hardware publish the **same topic name, frame_id, and message type**. Only the publisher differs. + +## Raw Sensors + +| Topic | ROS 1/ROS 2 | Message Type | Publishers | Subscribers | Rate | QoS/Queue | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `/scan` | ROS 1 | `sensor_msgs/LaserScan` | sim: `richbeam_lidar` gpu_ray plugin (`libgazebo_ros_gpu_laser.so`); real: RICHBEAM driver — **absent** | `safety_monitor` (1), `slam_core` (10), `move_base` obstacle_layer | 15 Hz *(sim)* | sub 1 / 10 | frame `laser_link`. Sim FOV is ±120° / 960 samples — deliberately narrower than 270° so rays do not hit the robot body (at 270°, 71.7% of rays returned <0.35 m). Real FOV, scan rate and timestamp source all unverified. | +| `/imu/data_raw` | ROS 1 | `sensor_msgs/Imu` | sim: `libgazebo_ros_imu_sensor`; real: `imu_bridge_node.py` (MCU over serial) | `wheel_odom` (100), `gravity_align` (200), `slam_core` (200), `ekf_odom` (20) | 200 Hz *(sim)* | pub 100 (real) | frame `imu_link`. `ekf_odom` fuses **only** angular velocity Z — linear acceleration is deliberately excluded. Roll/pitch are consumed by `gravity_align`, never estimated. | +| `/joint_states` | ROS 1 | `sensor_msgs/JointState` | sim: `diff_drive_controller` (`publishWheelJointState`); L0: `joint_state_publisher` (fake); real: MCU firmware | `wheel_odom` (50), `robot_state_publisher` | ~50 Hz *(sim)* | sub 50 | Joints `left_wheel_joint` / `right_wheel_joint` are **the encoder interface** — identical name in all three sources so `wheel_odom_node` cannot tell where it is running. | +| `/camera/depth/image_rect_raw` | ROS 1 | `sensor_msgs/Image` | sim: `libgazebo_ros_openni_kinect`; real: `realsense2_camera` | `depth_to_cloud` nodelet | 30 Hz | — | 640×480. Resolution chosen for Min-Z ~22 cm over 848×480's ~30 cm. | +| `/camera/depth/camera_info` | ROS 1 | `sensor_msgs/CameraInfo` | same as above | `depth_to_cloud` nodelet | 30 Hz | — | | +| `/camera/infra1/image_rect_raw` | ROS 1 | `sensor_msgs/Image` | sim: openni_kinect `imageTopicName`; real: `realsense2_camera` | none in-repo | 30 Hz | — | Recorded to bag for a possible ORB-SLAM3 branch (GĐ6). D410 has no RGB, so IR is the only image stream. | +| `/camera/infra1/camera_info` | ROS 1 | `sensor_msgs/CameraInfo` | same as above | none in-repo | 30 Hz | — | | +| `/camera/infra2/image_rect_raw` | ROS 1 | `sensor_msgs/Image` | **real only** (`enable_infra2:=true`) | none in-repo | 30 Hz | — | ⚠️ Sim/real asymmetry: the Gazebo plugin publishes only infra1. Do not expect a stereo IR pair in simulation. | +| `/camera/infra2/camera_info` | ROS 1 | `sensor_msgs/CameraInfo` | **real only** | none in-repo | 30 Hz | — | | +| `/camera/depth/points` | ROS 1 | `sensor_msgs/PointCloud2` | sim: openni_kinect `pointCloudTopicName` | **none — intentionally unused** | 30 Hz | — | The pipeline rebuilds the cloud with `depth_image_proc` instead, because both sources publish identical depth image + camera_info. Real driver sets `enable_pointcloud:=false`. | +| `/baro/pressure` | ROS 1 | `sensor_msgs/FluidPressure` | sim: `baro_sim`; real: `imu_bridge` (BMP390) | `floor_detector` (10) | 25 Hz *(sim)* | pub 10 | Only short-term *differences* are usable — absolute pressure drifts hundreds of Pa/hour with weather while one floor is ~40–45 Pa. | +| `/baro/temperature` | ROS 1 | `sensor_msgs/Temperature` | `imu_bridge` — **real only** | none in-repo | Unknown / needs confirmation | pub 10 | `baro_sim` does not publish this. | +| `/bumper` | ROS 1 | `std_msgs/Bool` | **no publisher** — hardware not purchased | `safety_monitor` (1) | — | sub 1 | Covers the depth camera's Min-Z blind zone. Ideally cuts motor power in hardware, not through ROS. | +| `/ultrasonic/*` | ROS 1 | `sensor_msgs/Range` | **no publisher** — hardware not purchased | `safety_monitor`, one sub per entry in `ultrasonic_topics` | — | sub 1 each | ⚠️ `ultrasonic_topics` is currently `[]`. Ultrasound is the **only** sensor in this set that detects glass and mirrors (905 nm LiDAR and IR depth both pass through). Empty list = glass is invisible to the robot. | + +## Odometry And State Estimation + +| Topic | ROS 1/ROS 2 | Message Type | Publishers | Subscribers | Rate | QoS/Queue | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `/odom` | ROS 1 | `nav_msgs/Odometry` | `wheel_odom` | `ekf_odom` (`odom0`, 10) | tied to `/joint_states` | pub 50 | `header.frame_id=odom`, `child_frame_id=base_footprint`. This node does **not** broadcast TF. EKF fuses velocities only (`vx`, `vyaw`), never absolute pose. | +| `/odometry/filtered` | ROS 1 | `nav_msgs/Odometry` | `ekf_odom` (`robot_localization`) | `slam_core` (50, remapped from `odom`) | 50 Hz | — | The smooth, never-blind odometry source. Owner of TF `odom → base_footprint`. | +| `/wheel_odom/slip_metric` | ROS 1 | `std_msgs/Float64` | `wheel_odom` | none — diagnostic | tied to `/joint_states` | pub 10 | Compares gyro Z against encoder-derived yaw rate. ≈0 means good traction. Restaurant floors carry water and grease; on slip the covariance is multiplied by 100 rather than the data being discarded. | +| `/slam/pose` | ROS 1 | `geometry_msgs/PoseWithCovarianceStamped` | `slam_core` | `eval_ate.py` (200), `repeatability.py` | keyframe-driven (0.25 m / 0.20 rad) | pub 10 | frame `map`. ⚠️ Back-end is **passthrough** — GTSAM is not installed, so this is integrated odometry and it will drift. | + +## Perception + +| Topic | ROS 1/ROS 2 | Message Type | Publishers | Subscribers | Rate | QoS/Queue | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `/perception/cloud_raw` | ROS 1 | `sensor_msgs/PointCloud2` | `depth_to_cloud` (`depth_image_proc/point_cloud_xyz`) | `depth_filter` (5) | 30 Hz | 5 | Camera optical frame. All three cloud topics live inside one nodelet manager — ~4.9 MB/frame at 30 Hz would cost ~147 MB/s per process hop. | +| `/perception/cloud_filtered` | ROS 1 | `sensor_msgs/PointCloud2` | `depth_filter` (`perception_3d/DepthFilterNodelet`) | `gravity_align` (5) | 30 Hz | 5 | Range gate 0.22–4.0 m, 3 cm voxel, temporal confirmation (`min_hits: 3`). Still in the camera optical frame. | +| `/perception/cloud_aligned` | ROS 1 | `sensor_msgs/PointCloud2` | `gravity_align` (`perception_3d/GravityAlignNodelet`) | `octomap_server`, `move_base` obstacle_layer (`camera_cloud`) | 30 Hz | 5 | frame `base_footprint`, tilt-compensated using roll/pitch measured from IMU. This is the layer that sees what 2D LiDAR cannot: overhanging table tops, low objects, hanging objects, steps. | +| `/gravity_align/roll_pitch` | ROS 1 | `std_msgs/Float64MultiArray` | `gravity_align` | none — diagnostic | 200 Hz (per IMU sample) | pub 10 | Payload is `[roll, pitch, accel_ok]`. Near zero when the robot is still on level floor. | +| `/octomap_full` | ROS 1 | `octomap_msgs/Octomap` | `octomap_server` | none in-repo | on cloud input | — | 0.05 m resolution, occupancy band z ∈ [0.05, 1.10]. | + +## Map, Localization And Multi-Floor + +| Topic | ROS 1/ROS 2 | Message Type | Publishers | Subscribers | Rate | QoS/Queue | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `/map` | ROS 1 | `nav_msgs/OccupancyGrid` | **three mutually exclusive sources**: `octomap_server` (`projected_map` remapped, mapping/L3+), `map_server` (localization mode), `multi_map_manager` (multi-floor, latched) | `amcl`, `move_base` global_costmap `static_layer` | on update / latched | latched for `map_server` and `multi_map_manager` | The remap exists so `move_base` and the costmaps never need to know which mode is running. Exactly one publisher must be active. | +| `/map_metadata` | ROS 1 | `nav_msgs/MapMetaData` | `map_server`, `multi_map_manager` | standard consumers | latched | 1 | | +| `/map_name` | ROS 1 | `std_msgs/String` | `multi_map_manager` | none in-repo | latched | 1 | Which floor map is currently loaded. | +| `/initialpose` | ROS 1 | `geometry_msgs/PoseWithCovarianceStamped` | `dock_init`, RViz "2D Pose Estimate" | `amcl` | on demand (`delay: 3.0` after start) | — | frame `map`. Startup pose comes from the charging dock — a *known* pose — so global relocalization is not needed for ~95% of real starts. ⚠️ Dock pose in `floors.yaml` is still `0,0,0` and must be measured after a real map exists. | +| `/floor/current` | ROS 1 | `std_msgs/Int32` | `floor_detector` | `multi_map_manager` (1) | on change | 1, latched | | +| `/floor/status` | ROS 1 | `std_msgs/String` | `floor_detector` | none in-repo | on change | 1, latched | | +| `/floor/tag_hint` | ROS 1 | `std_msgs/Int32` | `apriltag_ros` — **not installed** | `floor_detector` (5) | — | sub 5 | Barometer says *that* the floor changed; AprilTag says *which* floor. Hotel floors look identical, so geometric and visual recognition both fail — this is the absolute identity source. `tag_to_floor` mapping is in `floors.yaml`. | + +## Control And Safety + +| Topic | ROS 1/ROS 2 | Message Type | Publishers | Subscribers | Rate | QoS/Queue | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `/cmd_vel` | ROS 1 | `geometry_msgs/Twist` | `move_base`, teleop (L6) | `safety_monitor` (1) | 10 Hz (`controller_frequency`) | 1 | Never wired straight to motors. | +| `/cmd_vel_safe` | ROS 1 | `geometry_msgs/Twist` | `safety_monitor` | sim: `diff_drive_controller` (`commandTopic`); real: motor driver | 10 Hz | pub 1 | Gazebo plays the motor and therefore sits **behind** the safety layer, exactly as on real hardware. ⚠️ At L5 there is no `safety_monitor`, so nothing bridges `/cmd_vel` → `/cmd_vel_safe` and the robot will not move — this is intentional. For L1–L5 teleop, publish here directly. | +| `/safety/status` | ROS 1 | `std_msgs/String` | `safety_monitor` | none — operator inspection | on change | 1, latched | The isolation test: `rosnode kill /slam_core`, then confirm this topic is still alive. | + +## Evaluation And Simulation-Only + +| Topic | ROS 1/ROS 2 | Message Type | Publishers | Subscribers | Rate | QoS/Queue | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `/ground_truth/odom` | ROS 1 | `nav_msgs/Odometry` | `libgazebo_ros_p3d` (`ground_truth_odom`) | `baro_sim` (1), `eval_ate.py` (200), `repeatability.py` (10) | 50 Hz | — | ⚠️ **Evaluation only.** No estimator may subscribe — this is one of the three hard rules in `README.md`. The topic does not exist on real hardware. `header.frame_id` is `world`, which is *not* in the TF tree. | +| `/gazebo/odom_unused` | ROS 1 | `nav_msgs/Odometry` | `diff_drive_controller` (`odometryTopic`) | **none — intentionally** | 50 Hz | — | Gazebo's perfect odometry is parked on a deliberately useless name so it cannot be consumed by accident; `wheel_odom_node` must be tested instead, slip detection included. | +| `/repeatability/mark` | ROS 1 | `std_msgs/Empty` | manual (`rostopic pub`) | `repeatability.py` (10) | on demand | 10 | Marks arrival at a waypoint. Repeatability matters more than ATE for a serving robot. | +| `/elevator/status` | ROS 1 | `std_msgs/String` | `elevator_sim` | none in-repo | on change | 1, latched | Sim only. | +| `/elevator/goto_floor` | ROS 1 | `std_msgs/Int32` | manual / external | `elevator_sim` (1) | on demand | 1 | Sim only. | +| `/gazebo/set_model_state` | ROS 1 | `gazebo_msgs/ModelState` | `elevator_sim` | Gazebo | on demand | 1 | Teleports the robot model between floor heights to fake an elevator ride. | +| `/tf`, `/tf_static` | ROS 1 | `tf2_msgs/TFMessage` | see `TF_FRAME_MAP.md` | all TF consumers | — | — | Bag recording captures `/tf_static` only; `/tf` is regenerated on replay. | + +## Services + +| Service | Type | Server | Clients | Notes | +| --- | --- | --- | --- | --- | +| `/safety/reset` | `std_srvs/Trigger` | `safety_monitor` | operator | Clears a latched safety stop. | +| `/safety/estop` | `std_srvs/Trigger` | `safety_monitor` | operator | Software e-stop. A mechanical bumper that cuts motor power in hardware is still the preferred path. | +| `/dock_init/set_dock_pose` | `std_srvs/Trigger` | `dock_init` | operator | Re-publishes the configured dock pose to `/initialpose`. | + +Standard services from third-party nodes (`move_base/make_plan`, `move_base/clear_costmaps`, `amcl/global_localization`, `map_server/static_map`, Gazebo services) are available when those nodes run but are not defined in this repo. + +## Actions + +| Action | Type | Server | Clients | Notes | +| --- | --- | --- | --- | --- | +| `/move_base` | `move_base_msgs/MoveBaseAction` | `move_base` | RViz "2D Nav Goal", any external task scheduler | The only action interface in the system. **No custom actions are defined in this repository.** | diff --git a/TF_FRAME_MAP.md b/TF_FRAME_MAP.md new file mode 100644 index 0000000..c946d6f --- /dev/null +++ b/TF_FRAME_MAP.md @@ -0,0 +1,39 @@ +# TF Frame Map + +Use verified target-repository facts only. Keep unknown values as `Unknown / needs confirmation`. + +Static edges come from URDF fixed joints, published once on `/tf_static` by `robot_state_publisher`. Offsets below are resolved from the xacro properties in `robot.urdf.xacro` (`wheel_radius` 0.075, `wheel_separation` 0.36). + +| Parent Frame | Child Frame | Static/Dynamic | Broadcaster | Rate | Source File | Notes | +| --- | --- | --- | --- | --- | --- | --- | +| `map` | `odom` | Dynamic | **one of three, never more**: `slam_core` (L4+), `amcl` (localization mode), `static_transform_publisher` identity (L3 only) | keyframe-driven / amcl update / latched | `slam_core/src/slam_core_node.cpp:191-204`, `robot_bringup/launch/perception.launch`, `robot_bringup/launch/localization.launch` | The drift-correction edge — allowed to jump. `slam.launch` passes `publish_static_map_tf:=false` precisely to retire L3's identity publisher before `slam_core` takes over. ⚠️ `slam_core` is passthrough (no GTSAM), so this correction is currently a no-op and pose drifts. | +| `odom` | `base_footprint` | Dynamic | `ekf_odom` (`robot_localization/ekf_localization_node`) | 50 Hz | `robot_bringup/config/ekf_odom.yaml` | The smooth, continuous, never-blind edge — drifts but never jumps. `slam_core` is configured never to publish it (`publish_tf` there means `map → odom` only). | +| `base_footprint` | `base_link` | Static | `robot_state_publisher` (joint `base_joint`) | `/tf_static` | `robot_bringup/urdf/robot.urdf.xacro` | xyz `0 0 0.075` — exactly `wheel_radius`. `base_footprint` is the ground projection and is the frame the whole nav stack uses. | +| `base_link` | `left_wheel_link` | Dynamic | `robot_state_publisher` from `/joint_states` | ~50 Hz *(sim)* | `robot_bringup/urdf/robot.urdf.xacro` | Continuous joint `left_wheel_joint`, xyz `0 0.18 0`. The joint **name** is the encoder interface shared by Gazebo, the L0 fake publisher, and real MCU firmware. | +| `base_link` | `right_wheel_link` | Dynamic | `robot_state_publisher` from `/joint_states` | ~50 Hz *(sim)* | `robot_bringup/urdf/robot.urdf.xacro` | Continuous joint `right_wheel_joint`, xyz `0 -0.18 0`. | +| `base_link` | `front_caster_link` | Static | `robot_state_publisher` | `/tf_static` | `robot_bringup/urdf/robot.urdf.xacro` | xyz `0.08 0 -0.0375`. Contact stiffness `kp` is 100× softer than the wheels — with a rigid body on four contact points, load distribution is indeterminate and ODE resolves it by stiffness. Getting this wrong once made the encoders report 4.4 m while ground truth showed 0.66 m. | +| `base_link` | `rear_caster_link` | Static | `robot_state_publisher` | `/tf_static` | `robot_bringup/urdf/robot.urdf.xacro` | xyz `-0.20 0 -0.0375`. | +| `base_link` | `laser_link` | Static | `robot_state_publisher` (joint `laser_joint`) | `/tf_static` | `robot_bringup/urdf/sensors.xacro` | xyz `0.24 0 0.125`, no rotation. Mounted ahead of the body front face (x=0.14) so rays are not blocked; height 0.20 m above ground sees chair and table *legs*, not table tops. | +| `base_link` | `camera_link` | Static | `robot_state_publisher` (joint `camera_joint`) | `/tf_static` | `robot_bringup/urdf/sensors.xacro` | xyz `0.19 0 0.725`, rpy `0 0.2618 0` — pitched 15° **down** to see the floor near the robot plus steps and drops. | +| `base_link` | `imu_link` | Static | `robot_state_publisher` (joint `imu_joint`) | `/tf_static` | `robot_bringup/urdf/sensors.xacro` | xyz `0 0 0.025`. Mount rigidly, close to `base_link`, far from motors, with mechanical damping — tile floors and hard wheels produce heavy vibration. | +| `camera_link` | `camera_depth_optical_frame` | Static | `robot_state_publisher` | `/tf_static` | `robot_bringup/urdf/sensors.xacro` | rpy `-π/2 0 -π/2` → z-forward, x-right, y-down (REP-103 optical convention). Depth images and the raw cloud are stamped with this frame. | +| `camera_depth_optical_frame` | `camera_infra1_optical_frame` | Static | `robot_state_publisher` | `/tf_static` | `robot_bringup/urdf/sensors.xacro` | Identity — the D410 computes depth in the left IR frame, so they share an origin. | +| `camera_depth_optical_frame` | `camera_infra2_optical_frame` | Static | `robot_state_publisher` | `/tf_static` | `robot_bringup/urdf/sensors.xacro` | xyz `0.055 0 0` — the 55 mm stereo baseline. | + +## Frame Conventions + +- Fixed/world frame: `map` +- Robot base frame: `base_footprint` — used by the EKF (`base_link_frame`), `slam_core`, both costmaps (`robot_base_frame`), `octomap_server` (`base_frame_id`), `gravity_align` (`output_frame`), and the Gazebo diff-drive plugin (`robotBaseFrame`). Note `gravity_align` reads `base_frame: base_link` for the tilt lookup but emits clouds in `base_footprint`. +- Sensor frames: `laser_link`, `camera_link`, `imu_link` — all x-forward, y-left, z-up (REP-103) +- Camera optical frames: `camera_depth_optical_frame`, `camera_infra1_optical_frame`, `camera_infra2_optical_frame` — z-forward, x-right, y-down +- Map/odom relationship: strict single-owner split. `ekf_odom` owns `odom → base_footprint` (smooth, continuous, accumulates drift); the SLAM layer owns `map → odom` (corrects drift, permitted to jump). Two nodes publishing one edge produces no error message — only erratic transforms — so this split is enforced by configuration in `ekf_odom.yaml` and `slam_core.yaml` and by the `publish_static_map_tf` argument. + +## Known Risks + +- **Three candidate publishers for `map → odom`.** L3 uses a static identity, L4+ uses `slam_core`, localization mode uses `amcl`. If `perception.launch` is included without `publish_static_map_tf:=false` while `slam_core` runs, both publish the same edge and TF output jitters silently. `slam.launch` already handles this; any new launch file must too. +- **`slam_core` is passthrough.** GTSAM is not installed, so there is no optimization, scan matching, or loop closure. `map → odom` does not actually correct anything yet and pose drifts without bound. Expected until GĐ5. +- **`world` is not in the TF tree.** It appears only as `header.frame_id` on `/ground_truth/odom`, stamped by `libgazebo_ros_p3d`. Nothing broadcasts a transform to it, so `lookupTransform` against `world` will always fail. Evaluation scripts must compare message poses directly. +- **`/joint_states` can get two publishers.** `description.launch` defaults `publish_fake_joints:=true` for standalone L0. `sim.launch` and the real-hardware path both pass `false`. Leaving it true alongside Gazebo or MCU firmware yields two sources on one topic and unstable wheel TF. +- **Camera extrinsics are nominal, not calibrated.** The 15° downward pitch and all sensor offsets exist only as URDF numbers. `drivers.launch` sets `publish_tf:=false` on `realsense2_camera`, so on real hardware *every* camera frame comes from this URDF — a mount that does not match these values silently misplaces the point cloud. Extrinsic calibration is outstanding (GĐ2). +- **Robot geometry is duplicated.** `wheel_radius` and `wheel_separation` live in `robot.urdf.xacro`, `robot.yaml`, and `depth_filter.yaml` (`gravity_align/wheel_radius`). All three must be edited together. UMBmark calibration will change them. +- **`transform_tolerance: 0.5` in all three costmap configs** is generous enough to mask moderate TF latency rather than surface it. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..95c18a0 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,280 @@ +# Kiến trúc — quyết định và lý do + +Tài liệu này ghi **vì sao** hệ thống được thiết kế như hiện tại. Đọc trước khi +thay đổi kiến trúc — nhiều quyết định trông có vẻ tuỳ tiện nhưng thực ra bắt +nguồn từ ràng buộc phần cứng đã kiểm chứng. + +--- + +## 1. Vì sao bỏ đề xuất ban đầu (ORB-SLAM3 + DM-VIO + GTSAM) + +### 1.1. Fuse ORB-SLAM3 với DM-VIO là sai về mặt toán học + +Cả hai **ăn chung một nguồn dữ liệu**: cùng camera, cùng IMU. Sai số của chúng +**tương quan mạnh**, không độc lập. + +Mọi bộ fusion đều giả định các phép đo **độc lập có điều kiện**: + +$$p(z_A, z_B \mid X) \neq p(z_A \mid X) \cdot p(z_B \mid X)$$ + +Hệ quả khi vi phạm: + +- **Đếm hai lần thông tin IMU** → ma trận thông tin bị thổi phồng → estimator + **overconfident**. Nó rất tự tin vào một kết quả sai. +- **Covariance đầu ra vô nghĩa** → tầng navigation không biết khi nào nên nghi ngờ pose. +- Khi cả hai cùng sai (đi qua hành lang trắng không texture), chúng **sai cùng + một hướng**. Không có "bù trừ" nào — chỉ có sai số được nhân đôi độ tự tin. + +> **Nguyên tắc:** Bù trừ chỉ xảy ra khi các nhánh dùng **cảm biến khác nhau, có +> chế độ hỏng khác nhau**. LiDAR ↔ Camera bù trừ nhau. Encoder ↔ IMU bù trừ nhau. +> ORB-SLAM3 ↔ DM-VIO thì không — cả hai đều mù khi camera mù. + +### 1.2. GTSAM không cùng hạng mục với hai cái kia + +GTSAM là **thư viện tối ưu back-end** (như g2o/Ceres). ORB-SLAM3 và DM-VIO là +**hệ thống hoàn chỉnh, mỗi cái đã có back-end riêng**. + +"Kết hợp ORB-SLAM3 + DM-VIO + GTSAM" giống như "kết hợp Photoshop + GIMP + libpng". +GTSAM là **chỗ ráp mọi thứ lại**, không phải nhánh thứ ba. + +### 1.3. DM-VIO sai công cụ cho bài toán này + +| Vấn đề | Chi tiết | +|---|---| +| Monocular only | Vứt bỏ toàn bộ kênh depth — thứ đắt tiền nhất đã mua | +| Cần photometric calibration | Gồm **exposure time từng frame**. RealSense chạy auto-exposure, không export tin cậy qua ROS | +| Không loop closure, không map, không relocalization | Là *odometry* thuần. Mà robot dịch vụ cần nhất map bền vững + relocalization | +| Ánh sáng nhà hàng phá direct method | Đèn chỉnh theo giờ, nến, nắng cửa sổ → giả định *brightness constancy* vỡ liên tục | +| Delayed Marginalization giải bài toán ta không có | Nó giải **khởi tạo scale cho monocular**. Depth camera đã cho scale tuyệt đối từ frame đầu | + +--- + +## 2. Vì sao 2.5D, không phải 6-DoF + +### 2.1. Phần cứng gần như không ràng buộc được chiều thứ ba + +| Cảm biến | Đóng góp cho z / roll / pitch | +|---|---| +| Encoder | ❌ Không gì — chỉ đo chuyển động phẳng | +| LiDAR 2D | ❌ **Không gì** — chỉ quét MỘT mặt phẳng | +| IMU | ✅ roll/pitch (từ trọng lực). ❌ z trôi tự do (tích phân accel hai lần) | +| D410 | ⚠️ Có, nhưng yếu: rolling shutter + FOV 69° + emitter làm nhiễu feature | + +→ Có **~1.5 nguồn cho 3 chiều tự do bổ sung**. Ước lượng tự do sẽ cho ra z trôi +và pitch trôi — sai số **không có cơ sở vật lý nào**, vì robot vẫn đang ở trên +sàn phẳng. + +### 2.2. Tệ hơn: LiDAR 2D *giả định* chuyển động phẳng + +LiDAR 2D quét một mặt phẳng cố định so với thân robot. Robot nghiêng 5° thì mặt +phẳng quét lệch lên trần / xuống sàn và scan matching nhận **dữ liệu rác**. + +Nghĩa là: thêm 6-DoF không giúp LiDAR 2D, mà LiDAR 2D **còn hỏng khi thực sự có +6-DoF**. Ràng buộc mạnh nhất trong hệ lại là ràng buộc đòi hỏi mặt phẳng. + +> **Nguyên tắc:** Đừng ước lượng biến mà cảm biến không quan sát được. Mỗi chiều +> tự do thừa là một kênh cho drift chui vào, không phải một tính năng. + +### 2.3. Giải pháp: đo, không ước lượng + +``` +POSE SE(2) — (x, y, θ) ← tối ưu trong factor graph +ROLL/PITCH ĐO TRỰC TIẾP từ IMU ← KHÔNG ước lượng +Z giả định 0 +MAP grid 2D + OctoMap 3D +``` + +Roll/pitch dùng ở [`perception_3d/gravity_align_nodelet`](../src/perception_3d/src/gravity_align_nodelet.cpp) +để bù nghiêng cho point cloud. Robot qua gờ cửa chúi 3° thì cloud vẫn ghép đúng +chỗ thay vì bắn lên trần. + +**Mất gì so với 6-DoF thật?** Gần như không gì. Bản đồ 3D vẫn đầy đủ, tránh vật +cản 3D vẫn đầy đủ. Chỉ mất khả năng đi trên địa hình nghiêng > ~5° — mà robot +bưng đồ ăn cũng không nên đi. + +**Khi nào cần 6-DoF thật?** Dốc > 5°, nhiều cốt nền, sàn gồ ghề. Lúc đó điểm yếu +không nằm ở thuật toán mà ở **LiDAR 2D** — cần nâng cấp lên LiDAR 3D. Đừng cố ép +6-DoF trên LiDAR 2D: đó là nghịch lý tự thân. + +--- + +## 3. Vì sao D410 không tham gia SLAM + +Đã xác minh qua `rs-enumerate-devices`: + +``` +Name : RealSense D410 Product Id : 0AD2 +Imu Type : IMU_Unknown <- KHÔNG có IMU +Stream Profiles supported by Stereo Module <- chỉ 1 sensor, KHÔNG có RGB +Emitter Enabled : 0 ... 2 (Off / Laser / Laser Auto) <- KHÔNG có nhấp nháy xen kẽ +``` + +**Bốn điểm yếu cộng dồn cho visual odometry:** + +1. **Không RGB** → phải dùng ảnh IR +2. **Emitter chiếu mẫu chấm** cố định theo camera, không cố định theo thế giới → + ORB bám vào chấm thay vì cảnh → VO sai hoàn toàn. Và **không có chế độ nhấp + nháy xen kẽ** để né +3. **Rolling shutter** → méo ảnh khi robot xoay tại chỗ, việc robot phục vụ làm liên tục +4. **Không IMU tích hợp** → không hardware time sync → không VIO tight-coupled được + +### Quyết định: emitter BẬT cố định, camera = perception thuần + +Đây là bất đối xứng rủi ro, không phải đánh đổi tính năng: + +| | Nếu chọn sai | Hậu quả | +|---|---|---| +| Emitter **ON** | Mất ORB-SLAM3 | Mất một tính năng **tuỳ chọn** | +| Emitter **OFF** | Depth thủng lỗ trên một vật cản trơn | **Robot đâm vào khách hàng** | + +Chỉ cần **một loại vật** (thùng carton trắng, chậu nhựa bóng, vali trơn) mất +depth là có lỗ hổng an toàn. Đánh đổi cái đó lấy một module SLAM vốn đã yếu sẵn +thì không đáng. + +**Không dùng "Laser Auto"** — công suất laser thay đổi ngầm theo cảnh → mất tính +tất định. Với một hệ phải tune covariance và debug lâu dài, tính tất định quan +trọng hơn tối ưu cục bộ. + +### D410 đóng góp gì + +Thứ **chỉ camera 3D làm được** trong hệ này: + +``` + ┌─────────────┐ ← mặt bàn NHÔ RA — LiDAR không thấy → robot đâm cạnh bàn + │ │ + ═══╪═════════════╪═══ ← mặt phẳng quét LiDAR (chỉ thấy chân bàn) + │ │ + └──┬───────┬──┘ + │ │ ← túi xách dưới sàn — LiDAR không thấy +``` + +Mặt bàn nhô ra, vật thấp, vật treo, bậc/hố. + +--- + +## 4. Vì sao encoder là bắt buộc + +Đề xuất ban đầu không có encoder. Đây là lỗ hổng nghiêm trọng. + +**Observability của VIO trên robot mặt đất:** scale và IMU bias chỉ quan sát được +khi có **gia tốc thay đổi** trên đủ các trục. Nhưng robot phục vụ đi thẳng, vận +tốc gần hằng số, trên mặt phẳng — chính xác là **degenerate motion**: + +- Gia tốc ≈ 0 → accelerometer chỉ đo trọng lực → **bias accel không quan sát được** +- Chuyển động phẳng → **không kích thích trục z** +- Quay tại chỗ (robot dịch vụ làm suốt) → **không tịnh tiến** → scale mất quan sát + +Đây là lý do các hệ VIO benchmark tốt trên drone (EuRoC) lại kém trên AGV. + +Encoder giải quyết gần như miễn phí: ràng buộc tịnh tiến metric trực tiếp, tần số +cao, **không bao giờ mù**. + +--- + +## 5. Vì sao tách process + +### 5.1. `robot_safety` — lý do an toàn + +``` +slam_core segfault + └─ nếu monolith → bumper + siêu âm + e-stop CHẾT THEO + → robot đang chạy giữa khách hàng, mất hết khả năng dừng +``` + +`robot_safety` **chỉ** subscribe `/cmd_vel`, `/scan`, `/bumper`, `/ultrasonic/*`. +Không TF, không point cloud, không map, không SLAM. Càng ít phụ thuộc, càng ít +thứ kéo nó chết theo. + +Nghiệm thu: `rosnode kill /slam_core` → `/safety/status` vẫn chạy. + +### 5.2. `experimental/` — lý do license + +Mục tiêu là *nghiên cứu trước, thương mại hoá sau*. ORB-SLAM3 là **GPLv3** — link +vào chung binary thì binary đó thành GPLv3, phải mở mã nguồn khi bán. + +Gộp monolith là **đóng cửa vĩnh viễn** hướng thương mại hoá. + +### 5.3. Nodelet cho đường point cloud — lý do hiệu năng + +Cloud 640×480 ≈ **4.9 MB/frame**, ở 30 Hz là **~147 MB/s** mỗi hop. Chuỗi có 3 +chặng → ~440 MB/s chỉ để **copy**. Nodelet trong cùng manager chia sẻ `shared_ptr` +→ zero-copy. + +Điểm này sẽ quan trọng hơn nữa khi chuyển từ i5-14500 sang IPC. + +--- + +## 6. Vì sao parity sim ↔ real + +Mô phỏng và phần cứng thật publish **cùng tên topic, cùng frame_id, cùng message +type**. Chuyển đổi bằng đúng một argument `use_sim:=true|false`. + +Ví dụ cụ thể — **encoder**: + +``` +Gazebo : gazebo_ros_diff_drive, publishWheelJointState=true ─┐ + ├→ /joint_states +Robot thật: firmware MCU đọc encoder, đổi tick → radian ─┘ + ↓ + wheel_odom_node (CÙNG MỘT BINARY) +``` + +`publishOdomTF=false` trong plugin Gazebo là **cố ý**: nếu để Gazebo publish odom, +ta sẽ test nhầm odometry hoàn hảo của mô phỏng thay vì logic thật của mình — kể +cả slip detection. + +Nhờ vậy mọi thứ từ L2 trở lên được kiểm chứng trong sim là **đúng nguyên xi** cái +sẽ chạy ngoài đời. + +--- + +## 7. Vì sao tách Mapping mode và Operating mode + +| Mapping (vắng khách) | Operating (đang phục vụ) | +|---|---| +| Môi trường **tĩnh** | Môi trường **động** (30 khách đi lại) | +| Ghi vào bản đồ | **Không** ghi vào bản đồ | +| Cho phép loop closure | Không có rủi ro false loop phá map | +| Người vận hành duyệt map | Chạy trên map đã duyệt | + +Đây là cách các robot dịch vụ thương mại thực sự làm, và nó loại bỏ ~70% độ phức +tạp: không cần lifelong SLAM, không cần dynamic object removal tinh vi, không sợ +false loop closure phá map giữa ca phục vụ. + +Vật thể động chỉ vào **costmap** để tránh va chạm, **không bao giờ vào map**. + +--- + +## 8. Đa tầng không phải 6-DoF SLAM + +Robot khách sạn đi thang máy cần **quản lý đa bản đồ**, không phải pose 6-DoF: + +``` +Tầng 1 → map_floor_1 Mỗi tầng vẫn là bài toán 2.5D phẳng bình thường. +Tầng 2 → map_floor_2 Thứ duy nhất cần thêm: biết đang ở tầng nào. +Tầng 3 → map_floor_3 +``` + +**Hai nguồn, hai vai trò khác nhau:** + +| Nguồn | Vai trò | Giới hạn | +|---|---|---| +| **Barometer** | Phát hiện **CÓ** đổi tầng | ⚠️ Áp suất tuyệt đối trôi theo thời tiết hàng trăm Pa/giờ, trong khi một tầng chỉ ~40–45 Pa. **Chỉ dùng chênh lệch ngắn hạn** | +| **AprilTag** | Xác nhận tầng **NÀO** | Cần dán tag, nhưng chi phí ~0 | + +Không giao việc xác định tầng cho SLAM: các tầng khách sạn trông giống hệt nhau, +cả nhận dạng hình học lẫn nhận dạng ảnh đều sẽ nhầm. + +--- + +## 9. Những gì thuật toán không giải được + +| Vấn đề | Vì sao SLAM bó tay | Giải pháp thật | +|---|---|---| +| **Cửa kính** | LiDAR ToF 905nm **xuyên qua** kính; depth IR cũng vậy | **Siêu âm** (sóng âm phản xạ tốt trên kính) + virtual wall vẽ tay vào map | +| **Gương** | Tạo hình học ảo và feature ảo → map bị bơm thêm "căn phòng không tồn tại" | Virtual wall | +| **Vùng mù Min-Z ~22cm** | Depth stereo không có dữ liệu gần hơn ngưỡng | **Bumper cơ khí** | +| **Bề mặt đen** (ghế da, thảm sẫm) | ToF dựa vào photon phản xạ; vật đen hấp thụ gần hết | Test tại chỗ; nếu nặng thì đổi model LiDAR | + +Đây là lý do `robot_safety` tồn tại như một lớp độc lập, không phải một tính năng +của SLAM. diff --git a/docs/HARDWARE.md b/docs/HARDWARE.md new file mode 100644 index 0000000..e7394b3 --- /dev/null +++ b/docs/HARDWARE.md @@ -0,0 +1,209 @@ +# Phần cứng + +## 1. RealSense D410 — đã xác minh + +Output thật từ `rs-enumerate-devices` (2026-08): + +``` +Name : RealSense D410 Product Id : 0AD2 +Firmware Version : 5.17.0.10 Advanced Mode : YES +Usb Type Descriptor : 3.2 Connection Type : USB +Imu Type : IMU_Unknown ← KHÔNG có IMU + +Stream Profiles supported by Stereo Module ← chỉ MỘT sensor, KHÔNG có RGB + +Laser Power : 0 ... 360 default 150 +Emitter Enabled : 0 ... 2 default 1 → Off / Laser / Laser Auto +Global Time Enabled : 0 ... 1 default 1 ← đã bật sẵn +``` + +### Kết luận + +| | | +|---|---| +| ❌ Không có RGB | Chỉ có `Stereo Module`. ORB-SLAM3 phải dùng ảnh IR | +| ❌ Không có IMU | → phải mua IMU rời → **không có hardware time sync** | +| ❌ Không có nhấp nháy xen kẽ emitter | `Emitter On Off` không xuất hiện trong danh sách option | +| ⚠️ Rolling shutter | Méo ảnh khi robot xoay tại chỗ | +| ⚠️ FOV 69° (hẹp) | Mất feature nhanh khi xoay | +| ✅ `Y8` grayscale, `Infrared 1` + `Infrared 2` | Stereo IR khả dụng về mặt kỹ thuật | +| ✅ Global Time đã bật | Timestamp device↔host đã đồng bộ | +| ✅ Advanced Mode | Nạp được depth preset JSON | + +### Cấu hình chốt: 640×480 @ 30Hz cho cả 3 luồng + +Depth và IR **bắt buộc cùng độ phân giải** — depth do ASIC tính từ chính cặp IR đó. + +**Min-Z tỉ lệ thuận với độ phân giải:** + +| Độ phân giải | Min-Z ước tính | Đánh giá | +|---|---|---| +| 1280×720 | ~45 cm ❌ | Vùng mù quá lớn | +| 848×480 | ~30 cm | Nếu ưu tiên chất lượng SLAM | +| **640×480** | **~22 cm** ⭐ | **Đã chọn** — vùng mù gần nguy hiểm hơn tầm xa | +| 424×240 | ~15 cm | Quá thô | + +> ⚠️ **22 cm là ƯỚC TÍNH, chưa đo.** Phải đo thật: đẩy một hộp lại gần dần đến +> khi depth biến mất. Con số thật quyết định đặc tả bumper. + +**Nghịch lý cần nhớ:** độ phân giải cao hơn = nhìn xa tốt hơn **nhưng vùng mù gần +lớn hơn**. Với robot chạy giữa bàn ghế, vùng mù gần nguy hiểm hơn. + +### Emitter: BẬT cố định (giá trị 1) + +**Không dùng "Laser Auto" (giá trị 2)** — công suất laser thay đổi ngầm theo cảnh +→ mất tính tất định, khó tune và khó debug. + +Lý do bật thay vì tắt: xem [`ARCHITECTURE.md`](ARCHITECTURE.md) mục 3 (bất đối +xứng rủi ro). + +--- + +## 2. RICHBEAM 2D ToF LiDAR + +ToF hơn hẳn LiDAR tam giác (RPLidar A1/A2, YDLidar): tầm xa hơn, độ chính xác ổn +định theo khoảng cách, ít bị nhiễu bởi ánh sáng môi trường. + +### ⚠️ 4 điều phải xác minh khi có driver + +| # | Câu hỏi | Ảnh hưởng | +|---|---|---| +| 1 | **Interface: Ethernet hay USB?** | Ethernet → jitter thấp, có thể timestamp trên thiết bị. USB → timestamp gán ở driver, jitter 10–50 ms | +| 2 | **LiDAR có tự cấp timestamp không?** | Nếu có → dùng nó. **Tuyệt đối không dùng `ros::Time::now()` trong driver** | +| 3 | **FOV 270° hay 360°?** | 270° thì phía sau mù → ảnh hưởng scan matching khi lùi và ảnh hưởng an toàn | +| 4 | **Scan rate & angular resolution?** | Tối thiểu 10Hz / 0.25° để scan matching hoạt động tốt | + +Kiểm tra #2: `rostopic echo /scan/header` so với `date +%s.%N`. + +Sau khi có số thật, cập nhật `robot_sim/urdf/gazebo_sensors.xacro` cho khớp. + +### ⚠️ Hai điểm yếu của ToF + +1. **Bề mặt đen, nhám** — ghế da đen, thảm sẫm, bàn gỗ đen **rất phổ biến trong + nhà hàng/khách sạn cao cấp**. ToF dựa vào photon phản xạ; bề mặt đen hấp thụ + gần hết → **dropout, không thấy vật**. +2. **Kính** — bước sóng 905nm **xuyên qua kính**. Không thuật toán nào cứu được; + phải giải bằng siêu âm + virtual wall. + +--- + +## 3. BOM — cần mua + +| Hạng mục | Đề xuất | Ghi chú | +|---|---|---| +| **IMU** | **ICM-42688-P** hoặc BMI088 | ~$10–20. ❌ **Tuyệt đối tránh MPU6050/9250** — bias instability kém, trôi nhiệt mạnh | +| **Barometer** | **BMP390** / BMP581 | ~$3. **Bắt buộc** vì chạy khách sạn nhiều tầng. Mua ngay từ đầu — gắn thêm sau đắt hơn nhiều | +| **MCU đọc IMU** | STM32F4 / Teensy 4.0 / RP2040 | Đọc SPI @200–400Hz, **timestamp ngay lúc lấy mẫu** | +| **Bumper cơ khí** | — | Bắt buộc: bịt vùng mù Min-Z. Lý tưởng nhất là cắt nguồn motor **bằng phần cứng**, không qua ROS | +| **Siêu âm** | 2–3 cảm biến phía trước | **Cách duy nhất phát hiện kính** | +| **AprilTag** | In giấy | Dán mỗi tầng + trong thang máy | + +**Phương án thay thế cho khối IMU+baro+MCU:** một flight controller F4/F7 giá rẻ +đã tích hợp sẵn ICM42688 + BMP390 + firmware timestamping đã kiểm thử. + +### Nguyên tắc quan trọng hơn cả việc chọn chip + +> **Cách gắn timestamp cho IMU quan trọng hơn chất lượng IMU.** +> Một ICM-42688 đọc bởi MCU, timestamp ngay lúc lấy mẫu, gửi qua link đã đồng bộ +> → tốt hơn nhiều một ADIS16470 cắm USB rồi để driver gán `ros::Time::now()` với +> jitter 20 ms. + +Giao thức serial đã định nghĩa trong `robot_drivers/scripts/imu_bridge_node.py`. + +### Lắp đặt + +- **Gắn cứng**, gần `base_link`, **xa motor** (nhiễu từ + rung) +- **Giảm chấn cơ khí** — sàn gạch + bánh cứng = rung mạnh, accel nhiễu nặng +- ❌ **Bỏ magnetometer** — trong nhà gần thép/motor/bếp thì từ trường loạn hoàn + toàn, hại nhiều hơn lợi + +--- + +## 4. Encoder — đã có + +Hai việc cần làm: + +1. **Hiệu chuẩn UMBmark**: chạy hình vuông 4×4 m theo cả hai chiều, đo lệch, chỉnh + bán kính bánh trái/phải + wheelbase. Giảm sai số **từ ~5% xuống ~1%** — rẻ nhất + trong mọi cải tiến có thể làm. +2. **Slip detection**: đã cài trong `wheel_odom_node` — so `gyro_z` với `yaw_rate` + suy từ encoder. + +--- + +## 5. ⭐ Checklist khảo sát địa điểm thật + +Mang laptop + D410 + LiDAR tới **đúng nhà hàng/khách sạn mục tiêu**. +Kết quả có thể **thay đổi kiến trúc**. + +### 5.1. Đo độ dốc + +Dùng app đo nghiêng điện thoại, kiểm tra **mọi lối robot sẽ đi**. + +| Kết quả | Hệ quả | +|---|---| +| Tất cả < 3° | ✅ 2.5D dư sức | +| 3–5° | ⚠️ Cần bù nghiêng cẩn thận (`gravity_align` đã có) | +| > 5° | ❌ LiDAR 2D là điểm yếu → cần xét LiDAR 3D | + +### 5.2. Đo Min-Z thật + +Đẩy một hộp lại gần camera dần đến khi depth biến mất. Ghi lại khoảng cách. +→ Nạp vào `perception_3d/config/depth_filter.yaml` và `robot_safety/config/safety.yaml`. + +### 5.3. Bảng "vật cản × cảm biến nào thấy" — **tài liệu an toàn nền tảng** + +Emitter **BẬT**, đặt từng vật ở 0.3 / 0.5 / 1 / 2 / 4 m: + +| Vật cản | LiDAR thấy? | Depth thấy? | Ghi chú | +|---|---|---|---| +| Ghế của quán | | | | +| Bàn (mặt nhô ra) | | | LiDAR chỉ thấy chân | +| Người đứng | | | | +| Thùng carton **trắng trơn** | | | | +| Chậu cây / vali **nhựa bóng** | | | | +| **Cửa kính** | | | Dự đoán: cả hai đều xuyên qua | +| **Gương** | | | Dự đoán: tạo hình học ảo | +| Ghế da **đen** | | | ToF có dropout? | +| Thảm **sẫm màu** | | | | +| Vật thấp < 15cm | | | | + +→ Mọi ô trống ở cả hai cột = **vật cản phải giao cho siêu âm/bumper**. +Đây là đặc tả cho `robot_safety`. + +### 5.4. Test ảnh IR (tham khảo cho GĐ6) + +```bash +realsense-viewer +# Stereo Module → Emitter Enabled = 0 +# Bật Infrared 1, 640×480 +``` + +Có thấy rõ cạnh bàn, khung cửa, tranh treo tường không? Hay tối om + nhiễu hạt? + +⚠️ **Đèn LED gần như không phát IR.** Nhà hàng/khách sạn hiện đại dùng LED → +ảnh IR có thể rất tối khi tắt emitter. Đèn sợi đốt/halogen thì ngược lại. + +Kết quả quyết định ORB-SLAM3 có nằm trong kiến trúc hay không. + +### 5.5. Test rolling shutter (làm ngay tại bàn, 5 phút) + +```bash +realsense-viewer # tắt Emitter, bật Infrared 1 +``` +Cầm camera xoay ngang qua lại với tốc độ tương đương robot xoay (~30–60°/s). +Nhìn kỹ các cạnh thẳng đứng (khung cửa, chân bàn) — nếu chúng **nghiêng/cong** +khi xoay → rolling shutter đang méo ảnh → ORB-SLAM3 sẽ drift khi xoay. + +--- + +## 6. Nếu cần visual relocalization thật sự + +Đừng ép D410 làm hai việc xung đột nhau. Thêm **một camera mono global-shutter +rời** (~$40–80): + +- Chọn được **global shutter** (hết méo khi xoay) và **FOV rộng** (hết mất track) +- Không cần depth → rẻ, nhẹ, dễ gá +- Không đụng gì đến D410 → **cảm biến an toàn không bị thoả hiệp** + +Rẻ hơn và sạch hơn so với vật lộn với ràng buộc của D410. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..471fb9a --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,218 @@ +# Lộ trình + +Ước tính **≈5–6 tháng**. Giai đoạn 0–4 đã cho một robot chạy được (dùng baseline). +GĐ5 trở đi là nâng cấp và mở rộng. + +**Trạng thái hiện tại:** khung workspace + mô phỏng đã dựng xong. `slam_core` +đang ở chế độ passthrough. Chưa mua phần cứng, chưa hiệu chuẩn. + +--- + +## GĐ0 — Môi trường, mua sắm, khảo sát (≈1 tuần) + +### 0.1. ⚠️ Xung đột librealsense — *chặn mọi việc trên phần cứng thật* + +Máy hiện có **hai bản librealsense cùng lúc**: + +``` +librealsense2 2.58.3 (Intel repo) +ros-noetic-librealsense2 2.50.0 (ROS repo) +ros-noetic-realsense2-camera 2.3.2 ← build theo 2.50.0 → lỗi ABI +``` + +**Hướng chính:** gỡ `ros-noetic-realsense2-camera` + `ros-noetic-librealsense2`, +giữ Intel `2.58.3`, build `realsense2_camera` từ source vào `src/third_party/`. + +**Dự phòng** (nếu wrapper 2.3.2 không compile với LRS 2.58 do API đổi): pin về cặp +đã kiểm thử — Intel LRS `2.50.x` + apt wrapper `2.3.2`. + +**Không cản mô phỏng** — chỉ cần xử lý trước khi cắm camera thật. + +### 0.2. Xác minh hardware timestamp + +`librealsense2-dkms 1.3.27` đã cài → có thể có UVC metadata. Kiểm tra trong +`realsense-viewer` (panel metadata trên frame): `Frame Timestamp` có giá trị thật +hay `N/A`. Không có → dựa vào `Global Time Enabled=1` (đã bật mặc định) và **ghi +nhận đây là nguồn sai số cần bù**. + +### 0.3. Mua sắm + +Xem [`HARDWARE.md`](HARDWARE.md) — BOM đầy đủ. + +### 0.4. ⭐ Khảo sát địa điểm thật — *quan trọng nhất giai đoạn này* + +Xem checklist trong [`HARDWARE.md`](HARDWARE.md). Đầu ra: bảng +**"vật cản × cảm biến nào thấy"** — tài liệu an toàn nền tảng cho toàn dự án. + +Kết quả có thể **thay đổi kiến trúc**: nếu độ dốc > 5° hoặc LiDAR ToF dropout +nặng trên nội thất đen, cần xét lại lựa chọn LiDAR. + +--- + +## GĐ1 — Driver, TF, đồng bộ thời gian (≈2 tuần) + +| Việc | Trạng thái | +|---|---| +| Cấu hình camera 640×480, emitter=1 cố định | ✅ `robot_drivers/launch/drivers.launch` | +| URDF & TF tree | ✅ `robot_bringup/urdf/` | +| Wheel odometry + slip detection | ✅ `robot_drivers/src/wheel_odom_node.cpp` | +| Recipe ghi rosbag | ✅ `slam_eval/scripts/record_bag.sh` | +| **Driver RICHBEAM** | ❌ Chờ hãng — xem 4 điều phải xác minh trong `richbeam.launch` | +| **Firmware MCU cho IMU** | ❌ Chờ phần cứng — giao thức đã định nghĩa trong `imu_bridge_node.py` | + +**Nghiệm thu:** tất cả topic publish ổn định, `rqt_tf_tree` không đứt gãy, ghi +được bag 10 phút không drop frame. + +--- + +## GĐ2 — Hiệu chuẩn (≈1.5 tuần) + +> Bước quyết định 80% chất lượng cuối cùng. Không được rút gọn. + +| Loại | Công cụ | Đầu ra nạp vào | +|---|---|---| +| **IMU noise** | `allan_variance_ros`, để yên **≥3 giờ** | `slam_core/config/slam_core.yaml`, `robot_sim/urdf/gazebo_sensors.xacro` | +| **Encoder** | **UMBmark**: hình vuông 4×4m cả hai chiều | `robot_bringup/config/robot.yaml` + `robot.urdf.xacro` | +| **Camera intrinsic** | Đọc factory calibration từ librealsense | — (RealSense hiệu chuẩn sẵn) | +| **Extrinsic LiDAR↔base** | Đo cơ khí + khớp scan với tường đã biết | `robot.urdf.xacro` | +| **Extrinsic camera↔base** | Đo cơ khí + fit mặt phẳng sàn từ depth | `robot.urdf.xacro` | +| **Time offset** | Ước lượng chéo trên bag tĩnh/động | Driver | + +UMBmark giảm sai số odometry từ ~5% xuống ~1% — **rẻ nhất trong mọi cải tiến có +thể làm**. + +**Nghiệm thu:** hình vuông 4×4m, sai số khép kín odometry < 2% chu vi. + +--- + +## GĐ3 — Baseline (≈2–3 tuần) + +Mục tiêu: có **số liệu tham chiếu** trước khi tự xây, để biết GTSAM có thực sự +tốt hơn không. + +Chạy trên **cùng bộ rosbag**: +- **Cartographer** (hoặc `slam_toolbox`) — LiDAR 2D thuần +- **RTAB-Map** — RGB-D(IR) + LiDAR + odom, `Reg/Force3DoF=true` + +RTAB-Map đáng chạy nghiêm túc: BSD license, quản lý bộ nhớ STM/WM/LTM cho vận +hành cả ngày, có sẵn loop closure + relocalization + localization mode, hỗ trợ +đa phiên (hữu ích cho đa tầng ở GĐ7). + +Bộ đo đã có: `slam_eval/`. + +**Nghiệm thu:** bảng so sánh Cartographer vs RTAB-Map. Đây là mốc GĐ5 phải vượt. + +--- + +## GĐ4 — Perception 3D (≈2 tuần) — ✅ khung đã xong + +| Việc | Trạng thái | +|---|---| +| Depth filter chain (nodelet) | ✅ `perception_3d/src/depth_filter_nodelet.cpp` | +| Bù nghiêng bằng roll/pitch từ IMU | ✅ `perception_3d/src/gravity_align_nodelet.cpp` | +| OctoMap → costmap 3D | ✅ `perception_nodelets.launch` | +| **Phát hiện người → mask khi mapping** | ❌ Chưa làm | +| **Profile CPU-only** | ❌ Chưa đo — GPU RTX 4060 hiện có sẽ không có trên IPC | + +**Nghiệm thu:** robot dừng trước mặt bàn nhô ra và túi xách dưới sàn — hai trường +hợp LiDAR 2D không thấy. World `restaurant` đã dựng sẵn cả hai. + +--- + +## GĐ5 — ★ Lõi GTSAM (≈6–8 tuần) — phần chính + +Cài GTSAM (xem `src/third_party/README.md`), rồi cài đặt phần thật thay cho stub +trong `slam_core/src/graph_builder.cpp`. + +| Factor | Nguồn | Ghi chú | +|---|---|---| +| `ImuFactor` (preintegration) | ICM-42688 @200Hz | **IMU chỉ xuất hiện ở đây** | +| `BetweenFactor` | Wheel odometry | Covariance động theo slip detection | +| `BetweenFactor` | LiDAR scan-to-map | ★ Ràng buộc chính | +| Loop closure factor | VPR / scan descriptor | **Bắt buộc switchable constraint** | + +Tối ưu tăng dần bằng **iSAM2**. + +**Điểm kỹ thuật:** +- Scan matching: cân nhắc **correlative scan matching** (vét cạn → không kẹt cực + trị địa phương) thay vì ICP thuần +- **Degeneracy-aware weighting**: hành lang dài → LiDAR không ràng buộc được vị + trí dọc trục. Phát hiện qua eigenvalue nhỏ nhất của Hessian scan-match, rồi + giảm trọng số LiDAR / tăng trọng số nguồn khác. Đây là chỗ đáng đầu tư nhất + nếu muốn `slam_core` thực sự hơn RTAB-Map + +**Nghiệm thu:** chạy trên **cùng bộ rosbag** của GĐ3, bảng so sánh với baseline. +Nếu không vượt được RTAB-Map → dùng RTAB-Map cho sản phẩm, `slam_core` là đóng +góp nghiên cứu. **Cả hai đều là kết quả hợp lệ.** + +--- + +## GĐ6 — Relocalization & vận hành 2 chế độ (≈3 tuần) + +| Việc | Trạng thái | +|---|---| +| Tách mapping / localization mode | ✅ `mapping.launch`, `localization.launch` | +| Khởi động từ dock | ✅ `localization_ops/scripts/dock_init.py` | +| **Công cụ curation map** (virtual wall, keepout) | ❌ Chưa làm | +| **Global relocalization** | ❌ Chưa làm | + +### Global relocalization — coarse-to-fine, mỗi tầng có cổng kiểm tra + +``` +VPR / scan descriptor → top-K + → SEQUENCE MATCHING (N frame liên tiếp) ← giết perceptual aliasing + → GEOMETRIC VERIFICATION, ngưỡng inlier CHẶT + → GICP / correlative scan matching refinement + → ACCEPTANCE TEST: fitness + covariance + nhất quán với odometry + → nếu không chắc: TRẢ VỀ "KHÔNG BIẾT" +``` + +Robot đứng yên hỏi lại tốt hơn robot tự tin chạy sai tầng. + +⚠️ **Geometric verification phải nằm TRƯỚC GICP**, không phải sau: GICP là bước +đắt, và quan trọng hơn — nó **luôn hội tụ về một cái gì đó**, fitness score thấp +không có nghĩa là đúng chỗ. + +### Nhánh thí nghiệm ORB-SLAM3 (tuỳ chọn, GPLv3, cách ly) + +Chỉ làm nếu test ảnh IR ở GĐ0.4 đạt. Chạy **Stereo IR, tắt IMU**, chỉ dùng cho +nhận diện nơi chốn — không lấy pose. Xem `src/experimental/README.md`. + +--- + +## GĐ7 — Đa tầng (≈3 tuần) — khung đã xong + +| Việc | Trạng thái | +|---|---| +| Phát hiện đổi tầng (barometer) | ✅ `localization_ops/scripts/floor_detector.py` | +| Quản lý đa bản đồ | ✅ `localization_ops/scripts/multi_map_manager.py` | +| Mô phỏng thang máy | ✅ `robot_sim/scripts/elevator_sim.py` | +| **AprilTag → tầng tuyệt đối** | ❌ Cần `apriltag_ros` + dán tag | +| **Tương tác thang máy thật** | ❌ Tuỳ hạ tầng khách sạn | + +--- + +## GĐ8 — An toàn, đánh giá, chuyển IPC (≈2–3 tuần) + +| Việc | Trạng thái | +|---|---| +| Lớp an toàn (bumper, siêu âm, e-stop) | ✅ `robot_safety/` — chưa có phần cứng | +| Profile tài nguyên | ✅ `slam_eval/scripts/resource_profile.py` | +| **Chốt cấu hình IPC** | ❌ Cần số đo CPU-only | +| **Test dài hạn 8 giờ** | ❌ Cần robot thật | + +**Nghiệm thu cuối:** chạy liên tục 8 giờ trong giờ phục vụ thật. Theo dõi rò rỉ +bộ nhớ, phình map, tần suất mất track, số lần cần can thiệp. + +--- + +## Rủi ro + +| Rủi ro | Ảnh hưởng | Giảm thiểu | +|---|---|---| +| **Kính & gương** | LiDAR ToF và depth IR đều xuyên qua → robot đâm cửa kính | Siêu âm + virtual wall. **Không thuật toán nào giải được** | +| **LiDAR ToF trên bề mặt đen** | Ghế da đen / thảm sẫm hấp thụ IR → dropout | Test GĐ0.4. Nếu nặng → xét lại model LiDAR | +| **Perceptual aliasing hành lang** | 1 false loop phá nát map | Switchable constraints + sequence matching + tách mapping/operating. Test bằng `hotel_corridor.world` | +| **ROS Noetic + Ubuntu 20.04 đã EOL** | Không còn security patch | Chấp nhận cho nghiên cứu. Cần lộ trình ROS2 nếu vòng đời sản phẩm > 2 năm | +| **GPLv3 của ORB-SLAM3** | Cản trở thương mại hoá | Cách ly trong `experimental/`. Cần tư vấn pháp lý trước khi bán | +| **IPC yếu hơn máy dev** | Chạy được lúc dev nhưng không nổi trên robot | Profile CPU-only từ GĐ4, chốt IPC sớm | diff --git a/docs/SIM_VS_REAL.md b/docs/SIM_VS_REAL.md new file mode 100644 index 0000000..a183270 --- /dev/null +++ b/docs/SIM_VS_REAL.md @@ -0,0 +1,242 @@ +# Mô phỏng vs Thực tế + +Mô phỏng là quyết định đúng cho giai đoạn này. Nhưng nó **sẽ trông đẹp hơn thực +tế rất nhiều**, và biết trước chỗ nào nó nói dối là điều kiện để không bị bất ngờ. + +--- + +## Mô phỏng cho gì + +| Lợi ích | Chi tiết | +|---|---| +| ⭐ **Ground truth thật** | Plugin `p3d` cho pose chính xác tuyệt đối → chạy `evo` tính ATE/RPE **đúng nghĩa**. Trong nhà hàng thật bạn sẽ không bao giờ có motion capture | +| Không cần chờ phần cứng | IMU/barometer chưa mua vẫn phát triển được `slam_core`, `localization_ops` | +| Lặp lại được | Cùng kịch bản chạy 100 lần giống hệt → so sánh thuật toán công bằng | +| Kịch bản khó theo yêu cầu | `hotel_corridor.world` tái tạo perceptual aliasing và degeneracy | +| An toàn | Test lỗi mà không đâm vào khách hàng | + +--- + +## Mô phỏng đã bắt được 3 lỗi thật (2026-08) + +Ghi lại vì cả ba đều **không thể phát hiện bằng đọc code**, và cả ba đều sẽ gây +ra hành vi khó hiểu nếu chỉ gặp lần đầu trên phần cứng thật. + +### 1. Thân robot chạm đất → robot không di chuyển được + +Hộp `base_link` trải z từ **0.00** đến 0.85 — đáy nằm đúng mặt sàn. Robot tì +thân xuống đất, bánh quay trượt tại chỗ. + +**Triệu chứng:** encoder báo đi 5.1 m, ground truth cho thấy robot dịch chuyển +**0.002 m**. + +**Sửa:** thêm `ground_clearance = 0.04` vào `robot.urdf.xacro`. + +### 2. LiDAR nằm bên trong thân robot + +LiDAR gá ở x=0.18 trong khi thân trải x = −0.225…+0.225. + +**Triệu chứng:** **71.7%** tia báo khoảng cách < 0.35 m, `range` nhỏ nhất chạm +đúng `range_min` = 0.050 m. Toàn bộ là thân robot, không phải môi trường. + +**Sửa:** lùi thân (`body_offset_x = -0.06`), đẩy LiDAR ra trước (x=0.24), và +giảm FOV 270° → 240° cho khớp cung không bị che. + +→ Trên robot thật, dùng `laser_filters` (angular bounds / footprint filter) để +cắt cung bị thân che, thay vì để scan matching ăn dữ liệu rác. + +### 3. Độ cứng tiếp xúc đặt ngược → bánh mất lực kéo + +2 bánh + 2 caster cùng chạm sàn phẳng là **tiếp xúc siêu tĩnh**: với vật rắn, +chia tải giữa 4 điểm là bất định và ODE quyết định theo `kp` — điểm nào **cứng +hơn** thì gánh nhiều lực pháp tuyến hơn. + +Bánh đặt `kp=1e6`, caster **không khai báo `kp`** → Gazebo dùng mặc định ~`1e12`, +tức caster cứng hơn bánh **một triệu lần**. Caster (mu=0) gánh gần hết tải, bánh +chủ động gần như không tì xuống sàn. + +**Triệu chứng:** encoder 4.4 m vs ground truth 0.66 m. + +**Sửa:** caster `kp=1e4` (mềm hơn bánh 100 lần) + đặt trọng tâm thấp ngay trên +trục bánh (`cz=0.15`). + +**Kết quả sau khi sửa:** sai số odometry khi đi thẳng còn **1.04%** (đạt tiêu +chí < 2%). + +### 4. Trọng tâm ngay trên trục bánh → robot chúi mũi 16.8° + +Sửa lỗi 3 xong, tôi đặt trọng tâm **đúng ngay trục bánh** (`cx=0`) để dồn tải lên +bánh chủ động. Đó là **cân bằng không bền**: robot chúi tới cho tới khi caster +trước lún đủ sâu để đỡ. Với `kp=1e4` cần lún 24 mm ⇒ nghiêng **16.8°**. + +Hậu quả dây chuyền — mất nhiều vòng mới lần ra: + +``` +robot chúi 16.8° + → mặt phẳng quét LiDAR cắt vào SÀN ở 0.42 m + → safety_monitor thấy "vật cản" → bóp tốc độ còn 35% + → move_base tưởng thất bại → ABORTED + → camera (vốn đã chúc 15°) thành chúc ~32° → thấy sàn rất gần + → octomap ghi sàn thành vật cản → costmap đầy ô lethal +``` + +**Cách nhận ra:** profile quét theo góc khớp đúng `r(θ) = 0.41/cos(θ)` và nhảy +vọt tại ±90° — chữ ký của mặt phẳng cắt sàn, không phải vật cản. + +**Sửa:** `cx = -0.05` (tựa ổn định trên bánh + caster sau, 3 điểm tĩnh định) và +caster `kp` 1e4 → 5e4. Kết quả: pitch **+16.80° → −1.95°**, scan phía trước +**0.41 m → 3.26 m**. + +### 5. `octomap` không phải nguồn bản đồ 2D cho điều hướng + +Dùng `projected_map` của octomap làm `static_layer` cho global costmap: 18% ô +lethal, và **mẫu ô chiếm dụng không ổn định giữa hai lần chạy cùng một cảnh +tĩnh** — nhiễu chứ không phải hình học. Global planner sinh plan rỗng. + +`octomap` là để biểu diễn vật cản 3D. Bản đồ 2D điều hướng phải đến từ **2D SLAM +chạy bằng LiDAR** (GĐ3 baseline hoặc GĐ5 `slam_core`). Khi chưa có SLAM, cấu +hình đúng là **cửa sổ trượt trên dữ liệu cảm biến trực tiếp**. + +Sau khi đổi: 90% ô trống, 1% lethal, global plan **616 điểm**. + +> Điểm này đúng cả với phần cứng thật, không riêng mô phỏng. + +### 6. Trượt bánh khi tăng tốc → odometry sai 18% + +`move_base` báo `SUCCEEDED` với odometry 2.05 m trong khi ground truth 1.74 m. +`slip_metric` vọt lên 0.170 lúc tăng tốc từ đứng yên lên 0.5 m/s. + +Bộ phát hiện trượt hoạt động đúng — nó **bắt được** sự cố. Đã hạ `max_vel_x` +0.5 → 0.35 và `acc_lim_x` 0.5 → 0.3, nhưng đó chỉ là giảm triệu chứng: nguyên +nhân gốc cần **UMBmark ở GĐ2**. + +--- + +> Sáu lỗi trên đều thuộc nhóm "sim mô phỏng được". Danh sách bên dưới là nhóm +> **sim không mô phỏng được** — nguy hiểm hơn vì không có gì báo cho bạn biết. + +--- + +## ⚠️ Mô phỏng KHÔNG kiểm chứng được gì + +### 1. ⚠️⚠️ Đồng bộ thời gian — nguy hiểm nhất + +Gazebo dùng `/clock` **đồng bộ hoàn hảo**: mọi message có timestamp chính xác +tuyệt đối, không bao giờ drop, không bao giờ lệch. + +Trên robot thật: +- Camera cắm USB, LiDAR cắm Ethernet, IMU qua UART → **ba đồng hồ khác nhau** +- D410 **không có IMU tích hợp** → không có hardware sync +- Jitter timestamp 10–50 ms là bình thường +- Drop frame khi CPU bận + +> **Kinh nghiệm ngành: ~80% lỗi SLAM thực tế đến từ hiệu chuẩn sai hoặc đồng bộ +> sai, không phải từ thuật toán.** + +Sim che giấu **toàn bộ** nhóm lỗi này. + +**Giảm thiểu:** `robot_sim/scripts/sim_degradation.py` bơm jitter/drop có kiểm +soát. Bật dần từng mức sau khi qua được L4: + +```yaml +# robot_sim/config/sim_sensors.yaml +sim_degradation: + topics: + - {in: /scan, out: /scan_degraded, type: LaserScan, + offset_ms: 20.0, jitter_ms: 30.0, drop: 0.01} +``` + +Giá trị tham khảo cho phần cứng thật: + +| Nguồn | offset | jitter | +|---|---|---| +| D410 qua USB, Global Time bật | ~0 | 5–15 ms | +| LiDAR qua USB, driver gán stamp | 10–30 ms | 10–50 ms | +| LiDAR qua Ethernet có timestamp | ~0 | 1–5 ms | +| IMU qua UART, MCU gán stamp | ~0 | 1–3 ms | + +### 2. Mẫu chấm IR của emitter + +Gazebo render depth "hoàn hảo", không có mẫu chấm. Trên D410 thật, emitter bật +thì mẫu chấm **cố định theo camera** xuất hiện trong ảnh IR và phá hỏng feature +matching hoàn toàn. + +→ **Không thể đánh giá ORB-SLAM3 trong sim.** + +### 3. Rolling shutter + +Sim là global shutter lý tưởng. D410 thật là rolling shutter → méo ảnh khi robot +xoay tại chỗ. + +### 4. Depth dropout trên bề mặt đen / bóng + +Sim thấy mọi vật như nhau. Thực tế: +- Ghế da đen, thảm sẫm → **ToF LiDAR có thể dropout** +- Thùng trắng trơn, nhựa bóng → **depth stereo có thể thủng lỗ** + +Đây là rủi ro **an toàn**, không chỉ là chất lượng SLAM. + +### 5. ⚠️ Kính và gương + +Gazebo coi kính là **vật cản đặc** hoặc **vô hình** — cả hai đều sai. + +Thực tế: LiDAR ToF 905nm **xuyên qua** kính, depth IR cũng vậy. Gương tạo **hình +học ảo** trong LiDAR và **feature ảo** trong camera → map bị bơm thêm "căn phòng +không tồn tại". + +→ Sảnh khách sạn và mặt tiền nhà hàng gần như luôn có kính. **Không thể test +trong sim.** + +### 6. Nhiễu IMU thật + +`gazebo_sensors.xacro` dùng số từ datasheet ICM-42688-P. Datasheet **luôn lạc +quan hơn thực tế**. Phải chạy `allan_variance_ros` ≥3 giờ trên chính con chip mua +về rồi cập nhật lại — cả trong sim lẫn trong `slam_core.yaml`. + +### 7. Trượt bánh + +Mô phỏng được một phần qua tham số `mu1`/`mu2` trong `gazebo_sensors.xacro` (hạ +xuống ~0.3 để mô phỏng sàn dầu mỡ), nhưng động lực học trượt thật phức tạp hơn. + +### 8. Môi trường động + +World hiện tại **hoàn toàn tĩnh**. Nhà hàng thật có 30 khách đi lại, ghế bị kéo +ra, bàn được xếp lại. + +--- + +## Checklist: phải test lại trên phần cứng thật + +Đánh dấu khi đã kiểm chứng ngoài đời — **không được tin kết quả sim cho các mục này**: + +- [ ] Đồng bộ thời gian giữa camera / LiDAR / IMU (đo offset và jitter thật) +- [ ] Min-Z thật của D410 (đẩy hộp lại gần đến khi depth mất) +- [ ] Depth trên thùng trắng trơn, chậu nhựa bóng, vali +- [ ] LiDAR ToF trên ghế da đen, thảm sẫm, bàn gỗ đen +- [ ] **Cửa kính và gương** — cả LiDAR lẫn depth +- [ ] Ảnh IR khi tắt emitter, dưới đèn thật của quán +- [ ] Rolling shutter khi robot xoay tại chỗ +- [ ] Nhiễu IMU thật (`allan_variance_ros` ≥3 giờ) +- [ ] Hiệu chuẩn encoder (UMBmark hình vuông 4×4m) +- [ ] Trượt bánh trên sàn ướt/dầu +- [ ] Vận hành trong giờ đông khách (môi trường động) +- [ ] Chạy liên tục 8 giờ (rò rỉ bộ nhớ, phình map) + +--- + +## Nguyên tắc + +> **Sim dùng để kiểm chứng LOGIC, không phải để kiểm chứng ĐỘ TIN CẬY.** + +Cụ thể: + +| Sim trả lời tốt | Sim không trả lời được | +|---|---| +| Factor graph có hội tụ không? | Hệ có chạy nổi khi timestamp lệch không? | +| Loop closure có sửa được drift không? | Có phát hiện được cửa kính không? | +| Logic chuyển map đa tầng có đúng không? | Barometer thật có đủ nhạy không? | +| Costmap có thấy mặt bàn nhô ra không? | Depth có thấy vali trắng không? | +| Bù nghiêng có đúng toán học không? | IMU thật nhiễu đến mức nào? | + +Khi chuyển sang phần cứng, **kỳ vọng kết quả tệ đi đáng kể**. Đó không phải dấu +hiệu làm sai — đó là những thứ sim không mô phỏng được đang xuất hiện. diff --git a/docs/SLAM-vSLAM-3DSLAM-ban-thao.md b/docs/SLAM-vSLAM-3DSLAM-ban-thao.md new file mode 100644 index 0000000..b82f057 --- /dev/null +++ b/docs/SLAM-vSLAM-3DSLAM-ban-thao.md @@ -0,0 +1,779 @@ +# SLAM – vSLAM – 3D SLAM +### Bản thảo tài liệu kỹ thuật: Định nghĩa, vai trò, nhiệm vụ và phương thức triển khai + +--- + +## MỤC LỤC + +1. [Tổng quan bài toán SLAM](#1-tổng-quan-bài-toán-slam) +2. [Mối quan hệ giữa SLAM – vSLAM – 3D SLAM](#2-mối-quan-hệ-giữa-slam--vslam--3d-slam) +3. [Kiến trúc chung của một hệ thống SLAM](#3-kiến-trúc-chung-của-một-hệ-thống-slam) +4. [SLAM cổ điển (2D / LiDAR-based)](#4-slam-cổ-điển-2d--lidar-based) +5. [vSLAM – Visual SLAM](#5-vslam--visual-slam) +6. [3D SLAM](#6-3d-slam) +7. [Bảng so sánh tổng hợp](#7-bảng-so-sánh-tổng-hợp) +8. [Quy trình triển khai thực tế](#8-quy-trình-triển-khai-thực-tế) +9. [Thư viện, công cụ và bộ dữ liệu](#9-thư-viện-công-cụ-và-bộ-dữ-liệu) +10. [Thách thức và xu hướng phát triển](#10-thách-thức-và-xu-hướng-phát-triển) +11. [Lộ trình học và tài liệu tham khảo](#11-lộ-trình-học-và-tài-liệu-tham-khảo) + +--- + +## 1. TỔNG QUAN BÀI TOÁN SLAM + +### 1.1. Định nghĩa + +**SLAM** (*Simultaneous Localization and Mapping* – Định vị và Dựng bản đồ đồng thời) là bài toán trong đó một tác nhân di động (robot, drone, xe tự hành, kính AR/VR…) đặt vào một môi trường **hoàn toàn chưa biết**, phải đồng thời thực hiện hai việc: + +- **Localization (Định vị):** ước lượng vị trí và hướng (pose) của chính nó trong môi trường. +- **Mapping (Dựng bản đồ):** xây dựng mô hình biểu diễn môi trường xung quanh. + +### 1.2. Nghịch lý "con gà – quả trứng" + +Đây là điểm khiến SLAM khó: + +> Muốn **định vị chính xác** thì cần có **bản đồ chính xác**. +> Muốn **dựng bản đồ chính xác** thì cần biết **vị trí chính xác**. + +Cả hai đại lượng đều chưa biết và phụ thuộc lẫn nhau → phải giải **đồng thời** (simultaneous), không thể tách rời. + +### 1.3. Phát biểu toán học + +Ký hiệu: + +| Ký hiệu | Ý nghĩa | +|---|---| +| $x_{1:t}$ | Chuỗi trạng thái (pose) của robot từ thời điểm 1 → t | +| $m$ | Bản đồ môi trường | +| $z_{1:t}$ | Chuỗi quan sát từ cảm biến (camera, LiDAR…) | +| $u_{1:t}$ | Chuỗi lệnh điều khiển / dữ liệu odometry | + +SLAM là bài toán ước lượng **phân phối hậu nghiệm** (posterior): + +$$p(x_{1:t},\ m \mid z_{1:t},\ u_{1:t})$$ + +Hai biến thể: + +| Dạng | Công thức | Đặc điểm | Nhóm thuật toán | +|---|---|---|---| +| **Online SLAM** | $p(x_t, m \mid z_{1:t}, u_{1:t})$ | Chỉ ước lượng pose **hiện tại**, loại bỏ (marginalize) pose quá khứ | Filtering: EKF, UKF, Particle Filter | +| **Full SLAM** | $p(x_{1:t}, m \mid z_{1:t}, u_{1:t})$ | Ước lượng **toàn bộ quỹ đạo** | Smoothing: Graph-based, Bundle Adjustment | + +Trên thực tế hiện nay, **Full SLAM (graph-based / optimization-based)** chiếm ưu thế nhờ độ chính xác cao và khả năng sửa sai hồi tố khi phát hiện loop closure. + +### 1.4. Vai trò của SLAM trong hệ thống robot + +SLAM là **lớp nhận thức không gian (spatial perception layer)** — nền tảng bắt buộc cho các lớp phía trên: + +``` +┌─────────────────────────────────────────┐ +│ Ứng dụng (AR, dọn nhà, giao hàng…) │ +├─────────────────────────────────────────┤ +│ Task Planning / Behavior │ +├─────────────────────────────────────────┤ +│ Path Planning & Navigation │ ← cần BẢN ĐỒ +├─────────────────────────────────────────┤ +│ Control / Obstacle Avoidance │ ← cần POSE +├─────────────────────────────────────────┤ +│ ★ SLAM (Localization + Mapping) ★ │ +├─────────────────────────────────────────┤ +│ Cảm biến: Camera / LiDAR / IMU / Encoder │ +└─────────────────────────────────────────┘ +``` + +**Nhiệm vụ cụ thể SLAM đảm nhận:** + +1. Cung cấp pose 6-DoF (hoặc 3-DoF với 2D) theo thời gian thực cho vòng điều khiển. +2. Xây dựng bản đồ để lập kế hoạch đường đi và tránh vật cản. +3. Khử tích lũy sai số (drift) của odometry bánh xe / IMU. +4. Cho phép **re-localization**: robot khởi động lại vẫn biết mình ở đâu trong bản đồ cũ. +5. Cung cấp hệ quy chiếu chung để gắn thông tin ngữ nghĩa (semantic), vật thể, người dùng. +6. Thay thế GPS trong môi trường không có tín hiệu (indoor, hầm mỏ, dưới nước, trong nhà máy). + +--- + +## 2. MỐI QUAN HỆ GIỮA SLAM – vSLAM – 3D SLAM + +Đây là điểm nhiều người nhầm lẫn. **Ba khái niệm này không nằm cùng một trục phân loại.** + +- **SLAM** = tên bài toán tổng quát (khái niệm mẹ). +- **vSLAM** = phân loại theo **cảm biến chính** (camera). +- **3D SLAM** = phân loại theo **chiều không gian** của pose và bản đồ đầu ra. + +``` + SLAM (bài toán tổng quát) + │ + ┌────────────────────────┼────────────────────────┐ + │ Trục 1: THEO CẢM BIẾN │ + │ • vSLAM (camera) │ + │ • LiDAR SLAM │ + │ • Radar SLAM / Sonar SLAM │ + │ • VI-SLAM (camera + IMU), LIO (LiDAR + IMU) │ + └─────────────────────────────────────────────────┘ + ┌─────────────────────────────────────────────────┐ + │ Trục 2: THEO CHIỀU KHÔNG GIAN │ + │ • 2D SLAM: pose 3-DoF (x, y, θ), bản đồ lưới 2D│ + │ • 3D SLAM: pose 6-DoF (x,y,z,roll,pitch,yaw) │ + └─────────────────────────────────────────────────┘ + ┌─────────────────────────────────────────────────┐ + │ Trục 3: THEO PHƯƠNG PHÁP TOÁN │ + │ • Filter-based (EKF, PF) │ + │ • Optimization/Graph-based (BA, Factor Graph) │ + │ • Learning-based (NeRF-SLAM, 3DGS-SLAM) │ + └─────────────────────────────────────────────────┘ +``` + +**Kết luận quan trọng:** Một hệ thống có thể đồng thời là cả ba. Ví dụ ORB-SLAM3 chạy stereo camera vừa là **vSLAM**, vừa là **3D SLAM**, vừa là **SLAM optimization-based**. + +--- + +## 3. KIẾN TRÚC CHUNG CỦA MỘT HỆ THỐNG SLAM + +Hầu như mọi hệ SLAM hiện đại đều theo kiến trúc **Front-end / Back-end**: + +```mermaid +flowchart LR + A[Cảm biến
Camera/LiDAR/IMU] --> B[FRONT-END] + B --> B1[Tiền xử lý
khử méo, lọc nhiễu] + B1 --> B2[Trích xuất đặc trưng
hoặc dùng trực tiếp] + B2 --> B3[Data Association
ghép cặp quan sát] + B3 --> B4[Odometry
ước lượng chuyển động tương đối] + B4 --> C[BACK-END] + C --> C1[Tối ưu phi tuyến
Factor Graph / BA] + C1 --> D[Loop Closure
phát hiện + đóng vòng] + D --> C1 + C1 --> E[MAPPING
sinh bản đồ đầu ra] + E --> F[Pose 6-DoF + Bản đồ] +``` + +### 3.1. Front-end – "Bộ phận cảm nhận" + +**Nhiệm vụ:** Biến dữ liệu cảm biến thô thành các **ràng buộc hình học** (constraints). + +| Bước | Nội dung | Kỹ thuật điển hình | +|---|---|---| +| Tiền xử lý | Khử méo ảnh, lọc nhiễu point cloud, cân bằng sáng, khử motion distortion của LiDAR | Undistortion, Voxel Grid Filter, CLAHE | +| Trích xuất đặc trưng | Tìm điểm/đường/mặt phẳng đặc trưng | ORB, SIFT, SuperPoint, LOAM edge/planar | +| Data Association | Ghép đặc trưng khung hiện tại với khung trước / bản đồ | Brute-force + ratio test, KNN, ICP, NDT, LightGlue | +| Odometry | Tính pose tương đối giữa 2 khung | Epipolar geometry, PnP, ICP, direct photometric | +| Khử ngoại lai | Loại bỏ ghép sai | RANSAC, chi-square test, robust kernel (Huber, Cauchy) | + +### 3.2. Back-end – "Bộ phận suy luận" + +**Nhiệm vụ:** Từ tập ràng buộc do front-end sinh ra, tìm cấu hình pose + bản đồ **phù hợp nhất về mặt xác suất**. + +Bài toán quy về **bình phương tối thiểu phi tuyến (Nonlinear Least Squares)**: + +$$X^* = \arg\min_X \sum_{i} \rho\left( \left\| f_i(X) - z_i \right\|^2_{\Sigma_i} \right)$$ + +Trong đó: +- $X$: tập biến cần tối ưu (pose, điểm bản đồ, bias IMU…) +- $f_i(X)$: hàm đo dự đoán (measurement model) +- $z_i$: giá trị đo thực tế +- $\Sigma_i$: ma trận hiệp phương sai (độ tin cậy) +- $\rho$: hàm robust kernel để chống outlier + +**Cách giải:** Gauss-Newton hoặc Levenberg-Marquardt, khai thác **tính thưa (sparsity)** của ma trận Hessian bằng phân rã Cholesky thưa / Schur complement. + +### 3.3. Loop Closure – "Bộ phận trí nhớ" + +**Vai trò then chốt:** Nếu không có loop closure, mọi hệ SLAM đều **drift** (trôi sai số) vô hạn theo thời gian. + +Ba bước: + +1. **Phát hiện (Detection):** Nhận ra "tôi đã từng ở đây" — dùng Bag-of-Words (DBoW2/DBoW3), NetVLAD, Scan Context (cho LiDAR). +2. **Xác thực (Verification):** Kiểm tra hình học để loại false positive — RANSAC + PnP, ICP với ngưỡng inlier. +3. **Hiệu chỉnh (Correction):** Thêm cạnh ràng buộc mới vào đồ thị → tối ưu lại toàn cục (Pose Graph Optimization), phân phối sai số đều lên toàn quỹ đạo. + +--- + +## 4. SLAM CỔ ĐIỂN (2D / LiDAR-BASED) + +### 4.1. Vai trò và nhiệm vụ + +- Dùng cho robot di chuyển trên **mặt phẳng**: AGV/AMR trong kho, robot hút bụi, robot phục vụ nhà hàng, xe nâng tự động. +- Đầu ra: pose 3-DoF $(x, y, \theta)$ + **Occupancy Grid Map** (bản đồ lưới chiếm dụng). +- Ưu tiên: **độ ổn định, chi phí tính toán thấp, chạy được trên CPU nhúng**. + +### 4.2. Các họ thuật toán và cách thức thực hiện + +#### a) EKF-SLAM (Extended Kalman Filter SLAM) + +**Cách làm:** +1. Gộp pose robot và toạ độ tất cả landmark vào **một vector trạng thái duy nhất**: + $X = [x_r, y_r, \theta_r, x_{l1}, y_{l1}, \dots, x_{ln}, y_{ln}]^T$ +2. **Bước dự đoán (Prediction):** dùng mô hình chuyển động + odometry để đẩy trạng thái tiến 1 bước, hiệp phương sai $P$ tăng lên. +3. **Bước cập nhật (Update):** khi quan sát landmark, tính Kalman Gain, hiệu chỉnh trạng thái, $P$ giảm xuống. +4. Tuyến tính hoá mô hình phi tuyến bằng ma trận Jacobian. + +**Hạn chế:** Độ phức tạp $O(n^2)$ theo số landmark → không mở rộng được cho bản đồ lớn. Sai số tuyến tính hoá tích luỹ gây bất nhất (inconsistency). Ngày nay chủ yếu mang giá trị **học thuật, giáo dục**. + +#### b) FastSLAM (Rao-Blackwellized Particle Filter) + +**Ý tưởng cốt lõi:** Nếu **biết chính xác quỹ đạo**, các landmark trở nên **độc lập có điều kiện** với nhau. Vậy: + +$$p(x_{1:t}, m \mid z, u) = \underbrace{p(x_{1:t} \mid z, u)}_{\text{Particle Filter}} \cdot \prod_{k=1}^{n} \underbrace{p(m_k \mid x_{1:t}, z)}_{\text{EKF nhỏ độc lập}}$$ + +**Cách làm:** +1. Mỗi particle mang **một giả thuyết quỹ đạo riêng** + tập EKF 2×2 nhỏ cho từng landmark. +2. Sampling: sinh pose mới cho từng particle từ mô hình chuyển động. +3. Weighting: chấm điểm particle theo mức khớp giữa quan sát dự đoán và quan sát thực. +4. Resampling: loại particle điểm thấp, nhân bản particle điểm cao. + +**Ứng dụng thực tế:** `gmapping` trong ROS chính là biến thể **Grid-based FastSLAM 2.0**. + +#### c) Graph-based SLAM (Pose Graph Optimization) + +Đây là phương pháp **chủ đạo hiện nay**. + +**Cách làm:** +1. **Xây đồ thị:** + - **Node (đỉnh)** = một pose của robot tại thời điểm $t$ (hoặc keyframe). + - **Edge (cạnh)** = ràng buộc chuyển động tương đối giữa 2 node, kèm ma trận thông tin $\Omega$. + - *Odometry edge:* nối 2 node liên tiếp. + - *Loop closure edge:* nối 2 node cách xa nhau về thời gian nhưng gần nhau về không gian. +2. **Tối ưu:** Tìm cấu hình các node sao cho tổng sai số ràng buộc nhỏ nhất: + $$X^* = \arg\min_X \sum_{ij} e_{ij}(X)^T \Omega_{ij} e_{ij}(X)$$ +3. **Mapping:** Sau khi pose đã tối ưu, "dán" (render) dữ liệu quét vào bản đồ lưới. + +**Triển khai tiêu biểu:** Google **Cartographer** — submap local + scan matching + branch-and-bound loop closure; **Karto SLAM**; **SLAM Toolbox** (mặc định trong ROS 2 Nav2). + +### 4.3. Kỹ thuật Scan Matching (khớp quét) + +| Phương pháp | Nguyên lý | Ưu / Nhược | +|---|---|---| +| **ICP** (Iterative Closest Point) | Lặp: tìm điểm gần nhất → tính transform tối ưu (SVD) → áp dụng → lặp lại | Đơn giản, phổ biến / Cần khởi tạo tốt, dễ kẹt cực trị địa phương | +| **Point-to-Plane ICP** | Giảm khoảng cách theo pháp tuyến mặt phẳng | Hội tụ nhanh hơn ICP thường | +| **NDT** (Normal Distributions Transform) | Chia không gian thành ô, mô hình mỗi ô bằng phân phối Gauss, tối ưu likelihood | Mượt, không cần tìm điểm tương ứng / Nhạy với kích thước ô | +| **Correlative Scan Matching** | Vét cạn trên lưới thô → tinh | Rất robust, dùng trong Cartographer | + +--- + +## 5. vSLAM – VISUAL SLAM + +### 5.1. Vai trò và nhiệm vụ + +**vSLAM** dùng **camera** làm cảm biến chính. Vai trò đặc thù: + +- **Chi phí thấp – thông tin giàu:** camera rẻ hơn LiDAR hàng chục lần nhưng cung cấp texture, màu sắc, ngữ nghĩa. +- **Nền tảng của AR/VR:** mọi kính AR (HoloLens, Apple Vision Pro, Quest) và tính năng AR trên smartphone (ARKit/ARCore) đều chạy vSLAM (chính xác hơn là VI-SLAM). +- **Nhẹ và nhỏ:** phù hợp drone, robot mini, thiết bị đeo — nơi LiDAR quá nặng/tốn điện. +- **Cầu nối tới thị giác cấp cao:** cùng một luồng ảnh vừa dùng cho SLAM, vừa dùng cho nhận dạng vật thể, phân đoạn ngữ nghĩa. + +**Nhiệm vụ cụ thể:** +1. Ước lượng pose 6-DoF camera theo từng khung hình (thường 20–60 FPS). +2. Dựng bản đồ điểm 3D thưa (sparse point cloud) hoặc dày (dense/semi-dense). +3. Duy trì cơ sở dữ liệu keyframe cho re-localization. +4. Phát hiện loop closure bằng nhận dạng ảnh. + +### 5.2. Phân loại theo cấu hình camera + +| Loại | Đặc điểm | Vấn đề đặc thù | +|---|---|---| +| **Monocular** | 1 camera, rẻ nhất | **Bất định tỉ lệ (scale ambiguity)** – không biết bản đồ lớn thật bao nhiêu mét; cần chuyển động tịnh tiến để khởi tạo | +| **Stereo** | 2 camera, baseline cố định | Có scale tuyệt đối; giới hạn tầm đo theo baseline; cần hiệu chuẩn chính xác | +| **RGB-D** | Camera + cảm biến độ sâu (structured light / ToF) | Có depth trực tiếp, dựng bản đồ dày dễ; **chỉ dùng tốt trong nhà**, bị nhiễu bởi ánh sáng mặt trời, tầm 0.5–5 m | +| **Fisheye / Omni** | Góc nhìn siêu rộng | Nhiều đặc trưng hơn, robust hơn khi quay nhanh; mô hình méo phức tạp | +| **Event Camera** | Chỉ ghi thay đổi độ sáng, độ trễ µs | Cực tốt khi chuyển động nhanh / HDR; cần thuật toán hoàn toàn khác | +| **VI-SLAM** | Camera + IMU (**cấu hình thực dụng nhất**) | Giải quyết scale cho mono, robust khi mất đặc trưng, cần đồng bộ thời gian chính xác | + +### 5.3. Phân loại theo phương pháp + +#### a) Feature-based / Indirect Method + +**Nguyên lý:** Trích xuất đặc trưng → khớp cặp → tối thiểu hoá **sai số tái chiếu (reprojection error)**. + +$$E = \sum_{i,j} \rho\left( \left\| u_{ij} - \pi(T_i, P_j) \right\|^2 \right)$$ + +với $u_{ij}$ là toạ độ pixel quan sát, $\pi(\cdot)$ là hàm chiếu điểm 3D $P_j$ qua pose $T_i$. + +**Đại diện:** PTAM (2007, mở đường cho tách luồng tracking/mapping), **ORB-SLAM2/ORB-SLAM3** (chuẩn mực hiện nay). + +**Ưu:** Rất robust với thay đổi ánh sáng, chuyển động lớn; dễ làm loop closure bằng BoW. +**Nhược:** Thất bại ở vùng ít texture (tường trắng, hành lang trống); vứt bỏ ~90% thông tin ảnh. + +#### b) Direct Method + +**Nguyên lý:** Không trích xuất đặc trưng. Tối thiểu hoá trực tiếp **sai số quang trắc (photometric error)** trên cường độ pixel: + +$$E = \sum_{p} \left\| I_2\left(\pi(T \cdot \pi^{-1}(p, d_p))\right) - I_1(p) \right\|_\gamma$$ + +**Đại diện:** LSD-SLAM (semi-dense), **DSO** (Direct Sparse Odometry). + +**Ưu:** Dùng được vùng ít texture, tạo bản đồ dày hơn, không tốn thời gian tính descriptor. +**Nhược:** Giả định độ sáng bất biến (brightness constancy) — hỏng khi tự động phơi sáng thay đổi; yêu cầu hiệu chuẩn quang trắc (photometric calibration); baseline nhỏ. + +#### c) Semi-direct + +**Đại diện:** SVO (Semi-direct Visual Odometry) — dùng direct alignment để tracking nhanh, feature-based để mapping. Rất nhanh, phù hợp drone. + +### 5.4. Pipeline chi tiết của một hệ vSLAM (mẫu ORB-SLAM) + +Hệ thống chạy **3 luồng song song**: + +```mermaid +flowchart TD + IN[Khung hình mới] --> T + subgraph T[LUỒNG 1: TRACKING - mỗi frame] + T1[Trích xuất ORB features] --> T2[Ước lượng pose ban đầu
từ frame trước / relocalization] + T2 --> T3[Track Local Map
chiếu điểm bản đồ, tìm thêm match] + T3 --> T4[Motion-only BA
tối ưu riêng pose] + T4 --> T5{Có phải
Keyframe?} + end + T5 -->|Có| M + subgraph M[LUỒNG 2: LOCAL MAPPING - mỗi keyframe] + M1[Chèn Keyframe vào Covisibility Graph] --> M2[Loại điểm bản đồ kém chất lượng] + M2 --> M3[Tam giác hoá điểm 3D mới] + M3 --> M4[Local Bundle Adjustment] + M4 --> M5[Loại keyframe dư thừa] + end + M --> L + subgraph L[LUỒNG 3: LOOP CLOSING] + L1[Truy vấn DBoW2
tìm keyframe tương tự] --> L2[Tính Sim3 / SE3
+ RANSAC xác thực] + L2 --> L3[Fuse điểm trùng lặp] + L3 --> L4[Essential Graph Optimization] + L4 --> L5[Full Bundle Adjustment] + end +``` + +#### Bước 1 – Khởi tạo (Initialization) + +Với **monocular**, cần khởi tạo bản đồ ban đầu: +1. Tính song song **Homography H** (giả thiết mặt phẳng) và **Fundamental/Essential matrix F/E** (giả thiết cảnh 3D). +2. Chọn mô hình theo điểm số heuristic. +3. Phân rã ma trận → thu được $[R|t]$ (t chỉ biết đến sai khác một hệ số tỉ lệ). +4. **Tam giác hoá (triangulation)** tạo tập điểm 3D ban đầu. +5. Ấn định scale tuỳ ý (ví dụ độ sâu trung vị = 1). + +Với **stereo/RGB-D**: khởi tạo ngay từ khung đầu tiên vì đã có depth. + +#### Bước 2 – Tracking (mỗi khung hình) + +1. Trích xuất ~1000–2000 đặc trưng ORB (FAST corner + BRIEF descriptor có định hướng), phân bố đều qua **image pyramid** để bất biến tỉ lệ. +2. Dự đoán pose bằng mô hình vận tốc không đổi (constant velocity model). +3. Khớp đặc trưng với keyframe tham chiếu; nếu mất dấu → **Relocalization** qua BoW. +4. Giải bài toán **PnP** (Perspective-n-Point) + RANSAC. +5. **Motion-only BA:** giữ cố định điểm bản đồ, chỉ tối ưu pose hiện tại. +6. Quyết định có tạo keyframe mới không (dựa trên số frame trôi qua, tỉ lệ điểm được track, chất lượng tracking). + +#### Bước 3 – Local Mapping + +1. Cập nhật **Covisibility Graph** (đồ thị đồng quan sát: 2 keyframe nối nhau nếu cùng thấy ≥ 15 điểm). +2. Tam giác hoá điểm mới từ các keyframe lân cận chưa khớp. +3. **Local BA:** tối ưu đồng thời keyframe lân cận + điểm bản đồ mà chúng nhìn thấy (các keyframe xa giữ cố định làm neo). +4. Culling: loại điểm bản đồ bị quan sát ít hơn 25% số lần dự kiến, loại keyframe có > 90% điểm trùng với keyframe khác. + +#### Bước 4 – Loop Closing + +1. Chuyển ảnh thành **vector BoW** → truy vấn cơ sở dữ liệu keyframe. +2. Lọc ứng viên bằng ràng buộc thời gian và điểm tương đồng. +3. Tính phép biến đổi: + - **Monocular:** dùng **Sim(3)** – 7 DoF (3 tịnh tiến + 3 quay + **1 scale**) để sửa cả drift tỉ lệ. + - **Stereo/RGB-D:** dùng **SE(3)** – 6 DoF. +4. Hợp nhất điểm bản đồ trùng lặp. +5. **Essential Graph Optimization** rồi **Full BA** (chạy nền, không chặn tracking). + +### 5.5. Visual-Inertial SLAM (VI-SLAM / VIO) + +Đây là dạng **thực dụng nhất** trong sản phẩm thương mại. + +**Vì sao cần IMU?** +- Cung cấp **scale tuyệt đối** cho monocular. +- Ước lượng được **hướng trọng lực** → pitch/roll quan sát được tuyệt đối, không drift. +- Duy trì pose khi camera bị che, mờ do chuyển động (motion blur), hoặc quay nhanh. +- Tần số cao (200–1000 Hz) lấp khoảng trống giữa các khung hình. + +**Kỹ thuật cốt lõi – IMU Pre-integration:** +Thay vì tích phân lại IMU mỗi lần pose thay đổi trong quá trình tối ưu, ta **tiền tích phân** các phép đo IMU giữa 2 keyframe thành một ràng buộc tương đối độc lập với pose tuyệt đối. Điều này giúp nhúng IMU vào factor graph mà không phải tính lại — chìa khoá cho tối ưu thời gian thực. + +**Ghép nối:** +- *Loosely coupled:* chạy VO và IMU riêng, hợp nhất kết quả bằng EKF. Đơn giản, kém chính xác. +- *Tightly coupled:* đưa cả phép đo ảnh và IMU vào **cùng một bài toán tối ưu**. Chính xác hơn nhiều. (VINS-Mono, OKVIS, ORB-SLAM3) + +**Đại diện:** VINS-Mono / VINS-Fusion, OKVIS, MSCKF (dùng trong nhiều thiết bị AR do nhẹ), ORB-SLAM3, Kimera. + +--- + +## 6. 3D SLAM + +### 6.1. Vai trò và nhiệm vụ + +**3D SLAM** ước lượng pose **6-DoF** đầy đủ $(x, y, z, \text{roll}, \text{pitch}, \text{yaw})$ và dựng bản đồ **3 chiều**. + +**Khi nào bắt buộc phải dùng 3D SLAM:** +- Thiết bị bay (drone/UAV), thiết bị ngầm (AUV) — chuyển động tự do trong không gian. +- Xe tự hành ngoài trời: dốc, cầu, đường nhiều tầng, hầm chui. +- Robot chân (legged robot) — thân robot lắc lư theo mọi trục. +- Khảo sát – đo đạc: quét công trình, mỏ, đường hầm, tạo bản sao số (digital twin). +- AR/VR: cần biết hình học 3D để đặt vật ảo lên bề mặt thực, xử lý che khuất (occlusion). + +**Nhiệm vụ mở rộng so với 2D SLAM:** +1. Ước lượng pose 6-DoF liên tục. +2. Dựng biểu diễn 3D môi trường ở mức phù hợp ứng dụng (thưa/dày/lưới tam giác). +3. Quản lý bộ nhớ cho bản đồ lớn (bản đồ 3D dày tăng dung lượng cực nhanh). +4. Xử lý **motion distortion** của LiDAR quay (điểm trong một vòng quét được thu ở các thời điểm khác nhau). +5. Cung cấp bản đồ phục vụ lập kế hoạch 3D và tránh vật cản trên không. + +### 6.2. Các cách biểu diễn bản đồ 3D + +| Biểu diễn | Mô tả | Ưu điểm | Nhược điểm | Dùng ở đâu | +|---|---|---|---|---| +| **Sparse Point Cloud** | Vài nghìn điểm đặc trưng 3D | Cực nhẹ, đủ để định vị | Không dùng để tránh vật cản | ORB-SLAM | +| **Dense Point Cloud** | Hàng triệu điểm | Trực quan, chi tiết | Nặng, không có thông tin "không gian trống" | LiDAR mapping | +| **Occupancy Voxel / OctoMap** | Chia không gian thành voxel, mỗi voxel có xác suất chiếm dụng, lưu bằng octree | Phân biệt rõ *chiếm / trống / chưa biết*; nén tốt | Độ phân giải cố định | Lập kế hoạch đường bay 3D | +| **TSDF** (Truncated Signed Distance Function) | Mỗi voxel lưu khoảng cách có dấu tới bề mặt gần nhất | Bề mặt mượt, dễ trích lưới bằng Marching Cubes | Tốn bộ nhớ, cần GPU | KinectFusion, Voxblox | +| **Surfel** | Tập đĩa nhỏ có tâm, pháp tuyến, bán kính | Biến dạng linh hoạt khi loop closure | Khó dùng cho planning trực tiếp | ElasticFusion, SuMa | +| **Mesh** | Lưới tam giác | Chuẩn cho đồ hoạ/AR, nhẹ khi render | Khó cập nhật động | Kimera, BundleFusion | +| **Neural Implicit (NeRF)** | MLP mã hoá trường mật độ + màu | Bản đồ liên tục, "lấp" được vùng chưa quét | Chậm, khó mở rộng quy mô | iMAP, NICE-SLAM | +| **3D Gaussian Splatting** | Tập Gaussian 3D có màu, độ mờ, hiệp phương sai | Render thời gian thực, chất lượng ảnh cao | Tốn VRAM, mới ở giai đoạn nghiên cứu | SplaTAM, MonoGS | + +### 6.3. 3D LiDAR SLAM – cách thức thực hiện + +#### a) LOAM (LiDAR Odometry and Mapping) – nền tảng kinh điển + +Ý tưởng đột phá: **tách bài toán thành 2 nhánh chạy ở 2 tần số khác nhau**. + +1. **Trích xuất đặc trưng theo độ cong (curvature):** + Với mỗi điểm, tính độ "trơn" $c$ dựa trên khoảng cách tới các điểm lân cận cùng scan line. + - $c$ lớn → **Edge point** (điểm cạnh, ví dụ góc tường, cột) + - $c$ nhỏ → **Planar point** (điểm mặt phẳng, ví dụ mặt đất, tường) + +2. **LiDAR Odometry (10 Hz, thô nhưng nhanh):** + Khớp scan-to-scan. Hàm chi phí: + - Edge point → tối thiểu **khoảng cách điểm-tới-đường thẳng** + - Planar point → tối thiểu **khoảng cách điểm-tới-mặt phẳng** + Giải bằng Levenberg-Marquardt. + +3. **LiDAR Mapping (1 Hz, chậm nhưng chính xác):** + Khớp scan-to-map với bản đồ tích luỹ, số điểm nhiều hơn 10 lần → tinh chỉnh pose. + +4. **Transform Integration:** hợp nhất hai đầu ra để có pose tần số cao, độ chính xác cao. + +**Biến thể quan trọng:** +- **LeGO-LOAM:** phân đoạn mặt đất riêng, tối ưu 2 giai đoạn, chạy được trên nền tảng nhúng. +- **LIO-SAM:** đưa vào **factor graph** (dùng GTSAM) với 4 loại factor: IMU pre-integration, LiDAR odometry, GPS, loop closure. Rất chính xác cho ngoài trời. +- **FAST-LIO2:** bỏ hẳn bước trích xuất đặc trưng, khớp **trực tiếp điểm thô** vào bản đồ bằng **iterated Extended Kalman Filter**, dùng cấu trúc dữ liệu **ikd-Tree** (kd-tree cập nhật tăng dần) → cực nhanh, chạy tốt trên CPU nhúng của drone. + +#### b) Xử lý motion distortion + +LiDAR quay 10 Hz nghĩa là một "khung" quét mất 100 ms. Nếu robot di chuyển 5 m/s, điểm đầu và điểm cuối lệch nhau 0.5 m. **Bắt buộc phải khử méo:** +- Dùng IMU tần số cao nội suy pose tại thời điểm thu từng điểm. +- Chiếu (de-skew) tất cả điểm về cùng một mốc thời gian (thường là đầu hoặc cuối scan). + +#### c) Loop closure cho LiDAR + +- **Scan Context:** mã hoá một scan 3D thành ma trận 2D (bin theo phương vị × bán kính, giá trị = độ cao lớn nhất) → so khớp bất biến quay. Rất phổ biến. +- **ICP/GICP verification** để xác thực và tính transform chính xác. + +### 6.4. 3D SLAM từ camera RGB-D + +| Hệ thống | Kỹ thuật cốt lõi | +|---|---| +| **KinectFusion** (2011) | Tích hợp depth vào **volume TSDF** trên GPU, tracking bằng point-to-plane ICP với raycast từ model. Mở ra kỷ nguyên dense SLAM thời gian thực. | +| **ElasticFusion** | Bản đồ **surfel** có thể biến dạng đàn hồi (deformation graph) khi loop closure — không cần pose graph riêng. | +| **BundleFusion** | Tối ưu toàn cục theo thứ bậc (local chunk → global), tái tích hợp (de-integrate/re-integrate) khi pose thay đổi. | +| **RTAB-Map** | Quản lý bộ nhớ theo cơ chế "trí nhớ ngắn hạn / dài hạn", rất thực dụng, tích hợp sẵn ROS, hỗ trợ nhiều loại cảm biến. | + +### 6.5. Xu hướng mới: Neural & Gaussian SLAM + +- **iMAP / NICE-SLAM / Co-SLAM / Point-SLAM:** dùng mạng nơ-ron ngầm định (implicit) làm bản đồ; tối ưu đồng thời trọng số mạng và pose camera bằng sai số render. +- **SplaTAM / MonoGS / Gaussian-SLAM (2024–2025):** thay NeRF bằng **3D Gaussian Splatting** — render nhanh hơn nhiều bậc, cho phép SLAM dense thời gian thực với chất lượng dựng hình gần ảnh thật. +- **Foundation model trong SLAM:** dùng mô hình ước lượng độ sâu đơn ảnh (Depth Anything, Metric3D), matcher học sâu (SuperPoint + LightGlue), hoặc mô hình dựng hình 3D feed-forward (DUSt3R/MASt3R) làm front-end thay thế đặc trưng thủ công. +- **Semantic / Object-level SLAM:** Kimera, Hydra — xây **3D Scene Graph** (đồ thị cảnh: phòng → vật thể → quan hệ), phục vụ robot hiểu ngữ cảnh và nhận lệnh ngôn ngữ tự nhiên. + +--- + +## 7. BẢNG SO SÁNH TỔNG HỢP + +| Tiêu chí | SLAM 2D (LiDAR) | vSLAM | 3D SLAM (LiDAR) | VI-SLAM | +|---|---|---|---|---| +| **Cảm biến chính** | LiDAR 2D | Camera | LiDAR 3D | Camera + IMU | +| **Chi phí phần cứng** | Trung bình | **Thấp nhất** | Cao | Thấp | +| **DoF của pose** | 3 | 6 | 6 | 6 | +| **Bản đồ đầu ra** | Lưới 2D | Điểm 3D thưa/dày | Point cloud / voxel 3D | Điểm 3D thưa | +| **Độ chính xác** | Cao (trong mặt phẳng) | Trung bình–Cao | **Rất cao** | Cao | +| **Tầm hoạt động** | 10–30 m | 5–50 m | 100–200 m | 5–50 m | +| **Chịu thiếu sáng** | **Rất tốt** | **Kém** | **Rất tốt** | Kém–Trung bình | +| **Chịu môi trường ít texture** | Tốt | **Kém** | Tốt | Trung bình | +| **Chịu môi trường ít cấu trúc hình học** (hành lang dài, đồng trống) | Kém | **Tốt** | Kém | Tốt | +| **Tải tính toán** | Thấp | Trung bình–Cao | Cao | Trung bình | +| **Ngoài trời ánh nắng gắt** | Trung bình | Trung bình | Tốt | Trung bình | +| **Ứng dụng điển hình** | AMR kho hàng, robot hút bụi | AR/VR, drone nhỏ, robot giá rẻ | Xe tự hành, khảo sát, mỏ | Điện thoại AR, drone FPV | + +**Nguyên tắc chọn lựa:** LiDAR mạnh về *hình học*, camera mạnh về *ngoại quan (appearance)*. Hai loại **bù trừ nhau**, nên các hệ thống cao cấp hiện nay đều là **multi-sensor fusion (LiDAR + Camera + IMU + GNSS)**. + +--- + +## 8. QUY TRÌNH TRIỂN KHAI THỰC TẾ + +### Bước 1 – Phân tích yêu cầu bài toán + +Cần trả lời rõ 8 câu hỏi trước khi chọn công nghệ: + +| # | Câu hỏi | Ảnh hưởng đến | +|---|---|---| +| 1 | Trong nhà hay ngoài trời? | Chọn RGB-D vs LiDAR/Stereo | +| 2 | Diện tích bản đồ bao nhiêu? | Cần loop closure & quản lý bộ nhớ ở mức nào | +| 3 | Robot di chuyển 2D hay 3D? | 2D SLAM vs 3D SLAM | +| 4 | Sai số cho phép bao nhiêu cm? | Thuật toán và loại cảm biến | +| 5 | Yêu cầu tần số đầu ra (Hz)? | Kiến trúc luồng, filter vs optimization | +| 6 | Ngân sách phần cứng? | Camera vs LiDAR | +| 7 | Nền tảng tính toán (Jetson? x86? MCU?) | Mức tối ưu hoá cần thiết | +| 8 | Môi trường tĩnh hay động (nhiều người qua lại)? | Cần module lọc vật thể động | + +### Bước 2 – Lựa chọn cấu hình cảm biến + +**Gợi ý cấu hình theo ứng dụng:** + +| Ứng dụng | Cấu hình đề xuất | Thuật toán đề xuất | +|---|---|---| +| AMR trong kho | LiDAR 2D + encoder + IMU | SLAM Toolbox / Cartographer | +| Robot dịch vụ trong nhà | RGB-D + IMU + encoder | RTAB-Map | +| Drone trong nhà | Stereo/mono + IMU | VINS-Fusion, ORB-SLAM3 | +| Drone khảo sát ngoài trời | LiDAR 3D nhẹ (Livox/Ouster) + IMU + GNSS | FAST-LIO2, LIO-SAM | +| Xe tự hành | LiDAR 3D + nhiều camera + IMU + RTK-GNSS | LIO-SAM + fusion tuỳ chỉnh | +| AR/thiết bị đeo | Camera (mono/fisheye) + IMU | MSCKF, ORB-SLAM3 | + +### Bước 3 – Hiệu chuẩn (Calibration) — **bước quan trọng nhất và hay bị bỏ qua nhất** + +> Kinh nghiệm thực tế: **80% lỗi SLAM trong dự án thực tế bắt nguồn từ hiệu chuẩn sai hoặc đồng bộ thời gian sai**, không phải do thuật toán. + +| Loại hiệu chuẩn | Nội dung | Công cụ | +|---|---|---| +| **Camera Intrinsic** | Tiêu cự $f_x, f_y$, tâm ảnh $c_x, c_y$, hệ số méo | `camera_calibration` (ROS), Kalibr, MATLAB Camera Calibrator | +| **Stereo Extrinsic** | Ma trận $R, t$ giữa 2 camera | Kalibr, OpenCV `stereoCalibrate` | +| **Camera–IMU Extrinsic** | Phép biến đổi $T_{cam}^{imu}$ + **time offset** | **Kalibr** (bắt buộc) | +| **IMU Noise** | Noise density, random walk của gyro/accel | `allan_variance_ros` | +| **LiDAR–IMU Extrinsic** | $T_{lidar}^{imu}$ | LI-Init, `lidar_align`, FAST-LIO tự hiệu chuẩn | +| **LiDAR–Camera Extrinsic** | $T_{cam}^{lidar}$ | `direct_visual_lidar_calibration`, target-based với bảng cờ vua | +| **Đồng bộ thời gian** | Hardware trigger hoặc PTP; nếu không có thì ước lượng time offset online | PTP, GPS PPS, ước lượng $t_d$ trong tối ưu | + +### Bước 4 – Xây dựng / lựa chọn hệ thống + +**Lộ trình thực dụng:** + +``` +Giai đoạn 1: Chạy thử thuật toán mã nguồn mở trên DATASET CHUẨN + → xác nhận môi trường biên dịch, hiểu tham số +Giai đoạn 2: Chạy trên dữ liệu ROSbag của CHÍNH robot mình + → phát hiện vấn đề hiệu chuẩn, đồng bộ +Giai đoạn 3: Tinh chỉnh tham số cho môi trường thực tế +Giai đoạn 4: Chạy online trên robot thật +Giai đoạn 5: Tích hợp vào navigation stack +Giai đoạn 6: Tuỳ biến / thay thế module nếu cần +``` + +### Bước 5 – Thu thập dữ liệu + +**Nguyên tắc quay dữ liệu tốt:** +- Di chuyển **chậm và mượt** ở giai đoạn khởi tạo (đặc biệt monocular cần chuyển động **tịnh tiến**, không chỉ xoay). +- Đảm bảo có ít nhất **một vòng lặp kín** (quay lại điểm xuất phát) để kiểm chứng loop closure. +- Với VIO: cần **kích thích đủ mọi trục** (excitation) để IMU bias và scale quan sát được. +- Ghi lại toàn bộ raw topic vào rosbag để tái lập (reproduce) khi debug. + +### Bước 6 – Tinh chỉnh tham số (Tuning) + +| Nhóm tham số | Ví dụ | Ảnh hưởng | +|---|---|---| +| Đặc trưng | Số ORB features, ngưỡng FAST, số tầng pyramid | Nhiều hơn = robust hơn nhưng chậm hơn | +| Keyframe | Ngưỡng tạo keyframe mới | Thưa quá → mất track; dày quá → tốn tài nguyên | +| Loop closure | Ngưỡng điểm BoW, số inlier tối thiểu | Lỏng quá → false loop **phá hỏng toàn bộ bản đồ** | +| Voxel/lọc | Kích thước voxel downsample | Đánh đổi giữa tốc độ và chi tiết | +| Robust kernel | Ngưỡng Huber | Chống outlier | +| Trọng số hiệp phương sai | Tin IMU hay tin camera hơn | Rất quan trọng trong fusion | + +> **Cảnh báo:** Một **false loop closure** duy nhất có thể phá huỷ toàn bộ bản đồ. Luôn đặt ngưỡng xác thực hình học chặt chẽ. + +### Bước 7 – Đánh giá định lượng + +**Hai chỉ số chuẩn:** + +1. **ATE (Absolute Trajectory Error)** – Sai số quỹ đạo tuyệt đối + - Căn chỉnh (align) quỹ đạo ước lượng với ground truth (Umeyama, có/không scale) rồi tính RMSE khoảng cách từng điểm. + - **Đánh giá tính nhất quán toàn cục** của bản đồ. + +2. **RPE (Relative Pose Error)** – Sai số pose tương đối + - Đo sai lệch pose trên các đoạn ngắn (ví dụ mỗi 1 m, 10 m, 100 m). + - **Đánh giá drift cục bộ** — phù hợp để so sánh chất lượng odometry. + +**Công cụ:** [`evo`](https://github.com/MichaelGrupp/evo) — chuẩn công nghiệp. +```bash +evo_ape tum groundtruth.txt result.txt -va --plot --align --correct_scale +evo_rpe tum groundtruth.txt result.txt -r trans_part --delta 10 --delta_unit m +``` + +**Chỉ số bổ sung cần theo dõi:** +- Thời gian xử lý trung bình / khung (ms) và độ trễ đuôi (p99). +- Tỉ lệ tracking thành công (%), số lần mất dấu (tracking loss). +- Mức tiêu thụ RAM/VRAM theo thời gian (kiểm tra rò rỉ bộ nhớ và tăng trưởng bản đồ). +- Độ chính xác dựng bản đồ: so sánh với mô hình quét reference (cloud-to-cloud distance). + +### Bước 8 – Tích hợp vào hệ thống điều hướng + +``` +SLAM → publish TF (map → odom → base_link) + /map hoặc /point_cloud + ↓ +Costmap 2D/3D (inflation, obstacle layer) + ↓ +Global Planner (A*, Dijkstra, RRT*) → Local Planner (DWA, TEB, MPPI) + ↓ +Controller → Motor +``` + +Trong ROS 2, chuỗi này được chuẩn hoá bởi **Nav2**. Lưu ý quy ước TF: `map → odom` do SLAM/localization cung cấp (sửa drift, có thể nhảy), `odom → base_link` do odometry cung cấp (mượt, liên tục, có drift). + +--- + +## 9. THƯ VIỆN, CÔNG CỤ VÀ BỘ DỮ LIỆU + +### 9.1. Thư viện tối ưu (Back-end) + +| Thư viện | Đặc điểm | +|---|---| +| **g2o** | General Graph Optimization; nhẹ, dùng trong ORB-SLAM2 | +| **GTSAM** | Factor graph, iSAM2 (tối ưu tăng dần rất hiệu quả); dùng trong LIO-SAM, Kimera | +| **Ceres Solver** | Google; auto-differentiation mạnh, tài liệu tốt; dùng trong VINS-Mono, Cartographer | +| **SymForce** | Sinh mã tối ưu tự động, hiệu năng cao | + +### 9.2. Thư viện hỗ trợ + +| Thư viện | Vai trò | +|---|---| +| **Eigen** | Đại số tuyến tính (nền tảng của mọi thứ) | +| **Sophus** | Lie group SO(3), SE(3), Sim(3) — biểu diễn phép quay/biến đổi đúng chuẩn | +| **OpenCV** | Xử lý ảnh, đặc trưng, hình học đa góc nhìn | +| **PCL** | Point Cloud Library — lọc, phân đoạn, ICP, kd-tree | +| **Open3D** | Xử lý & trực quan hoá point cloud hiện đại, API Python thân thiện | +| **DBoW2 / DBoW3** | Bag of Words cho loop closure | +| **nanoflann / ikd-Tree** | Tìm kiếm lân cận nhanh | + +### 9.3. Framework SLAM mã nguồn mở đáng dùng + +| Tên | Loại | Ghi chú | +|---|---|---| +| **ORB-SLAM3** | vSLAM/VI-SLAM | Chuẩn mực học thuật; mono/stereo/RGB-D, pinhole/fisheye, multi-map Atlas | +| **VINS-Fusion** | VI-SLAM | Rất robust, hỗ trợ GPS fusion | +| **OpenVINS** | VIO (MSCKF) | Mã sạch, tài liệu tốt, hợp để học | +| **DSO / DM-VIO** | Direct VO/VIO | Chính xác cao trong điều kiện tốt | +| **RTAB-Map** | RGB-D/Stereo/LiDAR | Thực dụng nhất cho sản phẩm, tích hợp ROS sẵn | +| **Cartographer** | 2D/3D LiDAR | Google, rất ổn định | +| **SLAM Toolbox** | 2D LiDAR | Mặc định trong ROS 2 Nav2, hỗ trợ lifelong mapping | +| **FAST-LIO2 / Faster-LIO** | LiDAR-Inertial | Nhanh nhất hiện nay cho nền tảng nhúng | +| **LIO-SAM** | LiDAR-Inertial | Chính xác cao, factor graph đầy đủ | +| **KISS-ICP** | LiDAR Odometry | Cực đơn giản, ít tham số, hiệu quả bất ngờ | +| **Kimera** | Metric-Semantic | Dựng mesh + ngữ nghĩa + scene graph | + +### 9.4. Bộ dữ liệu chuẩn (Benchmark) + +| Dataset | Cảm biến | Môi trường | Dùng để | +|---|---|---|---| +| **KITTI** | Stereo + LiDAR 3D + GPS/INS | Đường phố, ngoài trời | Benchmark odometry kinh điển | +| **EuRoC MAV** | Stereo + IMU | Drone trong nhà | Chuẩn vàng cho VIO | +| **TUM RGB-D** | RGB-D | Văn phòng trong nhà | Chuẩn cho RGB-D SLAM | +| **TUM VI** | Fisheye stereo + IMU | Trong/ngoài nhà | VIO khó | +| **Newer College** | LiDAR + Stereo + IMU | Khuôn viên trường | LiDAR SLAM có ground truth chính xác | +| **NCLT** | Đa cảm biến, dài hạn | Khuôn viên, nhiều mùa | SLAM dài hạn, thay đổi môi trường | +| **M2DGR** | Đa cảm biến mặt đất | Đa dạng, có kịch bản khó | Đánh giá robustness | +| **Hilti SLAM Challenge** | LiDAR + camera + IMU | Công trường xây dựng | Ứng dụng công nghiệp | + +--- + +## 10. THÁCH THỨC VÀ XU HƯỚNG PHÁT TRIỂN + +### 10.1. Các thách thức chưa được giải quyết trọn vẹn + +| Thách thức | Mô tả | Hướng tiếp cận | +|---|---|---| +| **Môi trường động** | Người, xe di chuyển làm hỏng giả định "thế giới tĩnh" | Phát hiện & loại bỏ vật động (DynaSLAM), theo dõi đối tượng động riêng (DATMO) | +| **Thoái hoá hình học** (degeneracy) | Hành lang dài, đường hầm, đồng trống → thiếu ràng buộc theo một trục | Phát hiện degeneracy, fusion đa cảm biến, thêm ràng buộc từ IMU/bánh xe | +| **Thay đổi ngoại quan** | Cùng một nơi nhưng khác mùa/thời điểm trong ngày | Đặc trưng học sâu bất biến, semantic localization | +| **SLAM dài hạn (Lifelong)** | Bản đồ phải cập nhật khi môi trường đổi, nhưng không được phình vô hạn | Quản lý bộ nhớ theo tầng, map maintenance, "quên có chọn lọc" | +| **Mở rộng quy mô lớn** | Bản đồ hàng km² | Submap, hierarchical mapping, bản đồ phân tán | +| **Multi-agent SLAM** | Nhiều robot dựng chung bản đồ | Map merging, distributed optimization, băng thông giới hạn | +| **Bất định & an toàn** | Cần biết "mức tin cậy" của pose để ra quyết định an toàn | Ước lượng hiệp phương sai đáng tin, phát hiện thất bại (failure detection) | +| **Chống bắt cóc (Kidnapped robot)** | Robot bị nhấc và đặt sang chỗ khác | Global relocalization mạnh | + +### 10.2. Xu hướng 2024–2026 + +1. **Học sâu thấm sâu vào front-end:** đặc trưng học (SuperPoint, DISK, ALIKED), matcher học (LightGlue, LoFTR) đang thay dần ORB/SIFT trong các hệ thống mới. +2. **Bản đồ khả vi (differentiable map):** NeRF và đặc biệt **3D Gaussian Splatting** trở thành biểu diễn bản đồ chính, cho phép tối ưu pose bằng gradient của sai số render. +3. **Mô hình nền tảng 3D:** DUSt3R/MASt3R, VGGT, Depth Anything… tạo ra khả năng "dựng 3D chỉ từ vài ảnh không cần hiệu chuẩn", đang được ghép vào pipeline SLAM. +4. **SLAM ngữ nghĩa & Scene Graph:** bản đồ không chỉ là hình học mà là **đồ thị cảnh có ngữ nghĩa** (phòng, vật thể, quan hệ), phục vụ robot nhận lệnh ngôn ngữ tự nhiên kết hợp LLM/VLM. +5. **Fusion đa cảm biến chặt chẽ (tightly-coupled):** LiDAR + Camera + IMU + GNSS + radar trong một factor graph duy nhất. +6. **SLAM trên thiết bị biên (edge):** tối ưu cho NPU/DSP, chạy trên kính AR và drone siêu nhỏ với ngân sách điện năng vài watt. +7. **Event-camera SLAM:** khai thác độ trễ micro-giây cho chuyển động cực nhanh và điều kiện HDR. + +--- + +## 11. LỘ TRÌNH HỌC VÀ TÀI LIỆU THAM KHẢO + +### 11.1. Kiến thức nền bắt buộc + +| Lĩnh vực | Nội dung cụ thể | +|---|---| +| **Đại số tuyến tính** | SVD, phân rã Cholesky/QR, hệ thưa, bình phương tối thiểu | +| **Xác suất thống kê** | Bayes, phân phối Gauss đa biến, ước lượng hợp lý cực đại (MLE/MAP) | +| **Tối ưu phi tuyến** | Gauss-Newton, Levenberg-Marquardt, robust cost function, marginalization | +| **Hình học 3D & Lie Group** | SO(3), SE(3), Sim(3), exponential/log map, phép quay (quaternion, trục-góc), Jacobian trên manifold | +| **Thị giác máy tính** | Mô hình camera pinhole, epipolar geometry, homography, triangulation, PnP, RANSAC, Bundle Adjustment | +| **Lập trình** | C++ (hiện đại, hiệu năng cao), Python (prototype/đánh giá), ROS/ROS 2, CMake, đa luồng | + +### 11.2. Lộ trình đề xuất (khoảng 6 tháng) + +| Tháng | Mục tiêu | Sản phẩm đầu ra | +|---|---|---| +| 1 | Nền toán + Eigen + Sophus | Tự viết hàm chuyển đổi SO(3)/SE(3) | +| 2 | Thị giác 3D + OpenCV | Tự viết Visual Odometry 2 khung hình (2D-2D và 3D-2D) | +| 3 | Tối ưu phi tuyến + g2o/Ceres | Tự viết Bundle Adjustment quy mô nhỏ | +| 4 | Chạy & đọc mã ORB-SLAM3 hoặc VINS-Mono | Chạy trên EuRoC, vẽ ATE/RPE bằng `evo` | +| 5 | LiDAR SLAM (FAST-LIO2 / LIO-SAM) | Chạy trên KITTI/Newer College, so sánh kết quả | +| 6 | Dự án riêng | Triển khai SLAM trên phần cứng thật (Jetson + camera/LiDAR) | + +### 11.3. Tài liệu tham khảo cốt lõi + +**Sách:** +- *Probabilistic Robotics* — Thrun, Burgard, Fox (nền tảng lý thuyết xác suất của SLAM) +- *Multiple View Geometry in Computer Vision* — Hartley & Zisserman (kinh thánh hình học đa góc nhìn) +- *State Estimation for Robotics* — Timothy Barfoot (ước lượng trạng thái trên manifold, rất chặt chẽ) +- *视觉SLAM十四讲 / Introduction to Visual SLAM* — Gao Xiang (thực hành tốt nhất cho người mới, có bản tiếng Anh) + +**Bài báo tổng quan (survey):** +- Cadena et al., *"Past, Present, and Future of SLAM: Towards the Robust-Perception Age"* (IEEE T-RO, 2016) — bài survey quan trọng nhất, nên đọc đầu tiên. +- Macario Barros et al., *"A Comprehensive Survey of Visual SLAM Algorithms"* (2022). +- Các survey mới về NeRF/3DGS-based SLAM (2024–2025). + +**Bài báo nền tảng theo dòng thời gian:** +- MonoSLAM (2007) → PTAM (2007) → KinectFusion (2011) → LSD-SLAM (2014) → ORB-SLAM (2015) → LOAM (2014) → DSO (2016) → VINS-Mono (2018) → ORB-SLAM3 (2021) → FAST-LIO2 (2022) → iMAP/NICE-SLAM (2021–2022) → SplaTAM/MonoGS (2024) + +**Khoá học trực tuyến:** +- Cyrill Stachniss — *Mobile Sensing and Robotics* (YouTube, Đại học Bonn) — chất lượng rất cao, miễn phí. +- Michael Kaess — *Robot Localization and Mapping* (CMU 16-833). + +--- + +## PHỤ LỤC: THUẬT NGỮ ĐỐI CHIẾU + +| Tiếng Anh | Tiếng Việt | +|---|---| +| Pose | Tư thế (vị trí + hướng) | +| Keyframe | Khung hình chủ chốt | +| Loop Closure | Đóng vòng lặp / phát hiện quay lại nơi cũ | +| Drift | Trôi sai số / tích luỹ sai số | +| Bundle Adjustment | Hiệu chỉnh chùm tia | +| Reprojection Error | Sai số tái chiếu | +| Photometric Error | Sai số quang trắc | +| Data Association | Ghép cặp dữ liệu | +| Occupancy Grid Map | Bản đồ lưới chiếm dụng | +| Point Cloud | Đám mây điểm | +| Triangulation | Tam giác hoá | +| Marginalization | Biên hoá / loại biến | +| Outlier | Điểm ngoại lai | +| Degeneracy | Thoái hoá (thiếu ràng buộc) | +| Relocalization | Tái định vị | +| Ground Truth | Giá trị chuẩn tham chiếu | +| Tightly-coupled | Ghép nối chặt | +| Front-end / Back-end | Tầng trước / Tầng sau | + +--- + +*Bản thảo — có thể mở rộng thêm phần mã nguồn minh hoạ, sơ đồ chi tiết cho từng thuật toán, hoặc thu gọn theo hướng ứng dụng cụ thể tuỳ mục đích sử dụng.* diff --git a/setup_env.sh b/setup_env.sh new file mode 100644 index 0000000..45ca43b --- /dev/null +++ b/setup_env.sh @@ -0,0 +1,85 @@ +# Source file nay THAY CHO devel/setup.bash: +# +# cd ~/projects/vSLAM_ws && source setup_env.sh +# +# ============================================================ +# VI SAO CAN FILE NAY +# ============================================================ +# SDK camera Hikvision MVS (/opt/MVS) ship kem mot ban libusb CU va tu prepend +# vao LD_LIBRARY_PATH trong ca ~/.bashrc lan ~/.profile: +# +# export LD_LIBRARY_PATH=/opt/MVS/lib/64:/opt/MVS/lib/32:$LD_LIBRARY_PATH +# +# Ban libusb do THIEU ham libusb_set_option (co tu libusb 1.0.22). +# Ubuntu 20.04 ship 1.0.23 va CO ham nay - nhung LD_LIBRARY_PATH luon duoc tim +# TRUOC cache cua ldconfig, nen ban cu cua MVS thang. +# +# Hau qua: bat ky binary nao dung libpcl_io deu chet ngay khi khoi dong: +# +# /opt/ros/noetic/lib/rtabmap_slam/rtabmap: symbol lookup error: +# /lib/x86_64-linux-gnu/libpcl_io.so.1.10: undefined symbol: libusb_set_option +# [rtabmap/rtabmap-16] process has died [exit code 127] +# +# ⚠️ Doi prepend thanh append KHONG cuu duoc: chi can /opt/MVS con trong +# LD_LIBRARY_PATH la no van duoc tim truoc thu vien he thong. +# Cach duy nhat la BO HAN no ra khoi bien - do la viec file nay lam. +# +# MVS van dung duoc binh thuong o cac shell khac (bashrc van set nhu cu). +# ============================================================ + +_ws_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +# 1. Bo /opt/MVS khoi LD_LIBRARY_PATH (chi trong shell nay) +if [[ ":$LD_LIBRARY_PATH:" == *"/opt/MVS"* ]]; then + LD_LIBRARY_PATH="$(echo "$LD_LIBRARY_PATH" | tr ':' '\n' \ + | grep -v '^/opt/MVS' | grep -v '^$' | paste -sd: -)" + export LD_LIBRARY_PATH + echo " [setup_env] da bo /opt/MVS khoi LD_LIBRARY_PATH (xung dot libusb)" +fi + +# 2. Nap workspace +if [ -f "$_ws_dir/devel/setup.bash" ]; then + source "$_ws_dir/devel/setup.bash" +else + echo " [setup_env] ⚠️ chua co devel/setup.bash - chay 'catkin build' truoc" + source /opt/ros/noetic/setup.bash +fi + +# 3. Chan Gazebo goi ra mang tim model (lam treo luc khoi dong) +export GAZEBO_MODEL_DATABASE_URI="" + +# 3b. Model cua AWS RoboMaker hospital world (dung boi hospital*.world). +# De NGOAI repo vi 132 MB - qua nang de commit. +# Nguon: https://github.com/nomeera/nomeer_robot (Apache 2.0) +# models/ -> ~/gazebo_models/aws_hospital 76 MB, 37 model +# fuel_models/ -> ~/gazebo_models/aws_hospital_fuel 56 MB, 44 model +# +# ⚠️ Thieu dong nay thi Gazebo KHONG BAO LOI - no dung im o +# "Waiting for model" mai mai, vi GAZEBO_MODEL_DATABASE_URI="" da +# chan duong tai online. Rat kho doan neu khong biet truoc. +for _gm in "$HOME/gazebo_models/aws_hospital" "$HOME/gazebo_models/aws_hospital_fuel" \ + "/opt/ros/noetic/share/turtlebot3_gazebo/models"; do + if [ -d "$_gm" ]; then + case ":$GAZEBO_MODEL_PATH:" in + *":$_gm:"*) : ;; + *) export GAZEBO_MODEL_PATH="$_gm${GAZEBO_MODEL_PATH:+:$GAZEBO_MODEL_PATH}" ;; + esac + else + echo " [setup_env] ⚠️ thieu $_gm - world hospital* se treo luc load" + fi +done +unset _gm + +# 4. Kiem tra nhanh +if command -v ldd >/dev/null 2>&1 && [ -f /opt/ros/noetic/lib/rtabmap_slam/rtabmap ]; then + _usb="$(ldd /opt/ros/noetic/lib/rtabmap_slam/rtabmap 2>/dev/null \ + | awk '/libusb-1.0/{print $3}')" + case "$_usb" in + /opt/MVS/*) echo " [setup_env] ❌ VAN dang dung libusb cua MVS: $_usb" ;; + "") : ;; + *) echo " [setup_env] libusb: $_usb" ;; + esac + unset _usb +fi + +unset _ws_dir diff --git a/src/experimental/CATKIN_IGNORE b/src/experimental/CATKIN_IGNORE new file mode 100644 index 0000000..e69de29 diff --git a/src/experimental/README.md b/src/experimental/README.md new file mode 100644 index 0000000..1e0a19f --- /dev/null +++ b/src/experimental/README.md @@ -0,0 +1,52 @@ +# experimental/ — Vùng cách ly GPL + +**Thư mục này có `CATKIN_IGNORE` — catkin bỏ qua, không build.** + +## Vì sao tồn tại + +Mục tiêu dự án là *nghiên cứu trước, thương mại hoá sau*. Điều đó đặt ra một +ràng buộc cứng về license: + +> **ORB-SLAM3 là GPLv3.** Nếu link nó vào chung binary với code của bạn, binary +> đó trở thành GPLv3 — nghĩa là phải mở mã nguồn khi bán sản phẩm. + +Gộp monolith là **đóng cửa vĩnh viễn** hướng thương mại hoá. + +## Quy tắc + +| | | +|---|---| +| Lõi (`slam_core`, `perception_3d`, `robot_*`) | Chỉ BSD / Apache / MPL | +| `experimental/` | Được phép GPL | +| Giao tiếp giữa hai bên | **Chỉ qua ROS topic/service** — không bao giờ link trực tiếp | +| Phụ thuộc | Lõi **không được** phụ thuộc bất cứ thứ gì trong đây. Gỡ `experimental/` đi, hệ thống vẫn chạy | + +Tách process là biện pháp cách ly phổ biến trong ngành, nhưng vẫn là **vùng xám +pháp lý**. Cần luật sư xác nhận trước khi bán sản phẩm. + +## Nội dung dự kiến + +### `orbslam3_vpr/` — chưa có code + +Chỉ làm nếu **test ảnh IR tại địa điểm thật đạt** (xem `docs/HARDWARE.md`). + +Vai trò **rất hạn chế**: chỉ nhận diện nơi chốn cho relocalization. +**Không lấy pose từ nó.** + +Lý do hạn chế vai trò — D410 có 4 điểm yếu cộng dồn cho visual odometry: + +1. **Không có RGB** → phải dùng ảnh IR +2. **Emitter chiếu mẫu chấm** cố định theo camera → ORB bám vào chấm thay vì cảnh + → VO sai hoàn toàn. Mà D410 **không có chế độ nhấp nháy xen kẽ** + (`Emitter Enabled` chỉ có `Off/Laser/Laser Auto`), nên không tránh được +3. **Rolling shutter** → méo ảnh khi robot xoay tại chỗ, việc robot phục vụ làm liên tục +4. **Không có IMU tích hợp** (`Imu Type: IMU_Unknown`) → không có hardware time + sync → không làm VIO tight-coupled được + +Nếu về sau cần visual relocalization thật sự, **thêm một camera global-shutter +rời (~$40–80) rẻ hơn và sạch hơn** so với vật lộn với ràng buộc của D410 — +và không làm thoả hiệp cảm biến an toàn. + +Nếu chạy ở chế độ stereo IR (`infra1` + `infra2`, emitter tắt), phải **tắt IMU** +trong ORB-SLAM3: IMU đã thuộc về `slam_core`, đưa vào hai nơi là đếm trùng +thông tin. diff --git a/src/localization_ops/CMakeLists.txt b/src/localization_ops/CMakeLists.txt new file mode 100644 index 0000000..a1a76b0 --- /dev/null +++ b/src/localization_ops/CMakeLists.txt @@ -0,0 +1,17 @@ +cmake_minimum_required(VERSION 3.0.2) +project(localization_ops) + +find_package(catkin REQUIRED) + +catkin_package() + +catkin_install_python(PROGRAMS + scripts/dock_init.py + scripts/floor_detector.py + scripts/multi_map_manager.py + DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +) + +install(DIRECTORY launch config + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} +) diff --git a/src/localization_ops/config/floors.yaml b/src/localization_ops/config/floors.yaml new file mode 100644 index 0000000..8cb291e --- /dev/null +++ b/src/localization_ops/config/floors.yaml @@ -0,0 +1,64 @@ +# ============================================================= +# Cau hinh da tang (khach san) +# +# Ban do CHUA TON TAI - se sinh ra o che do mapping. Duong dan o day la +# noi chung SE duoc luu. +# ============================================================= + +floor_detector: + # 3.0 m = khoang cach tang cua world hospital_two_floors / three_floors. + # Da do tu chinh file world: model tap trung o z = 0, 3, 6. + # ⚠️ DO LAI tai khach san that - 3.0 la so cua MO PHONG, khong phai cua doi. + floor_height: 3.0 + start_floor: 1 + + smooth_window: 25 # so mau trung binh truot (25 @25Hz = 1s) + + # Nguong phat hien: 0.6 lan chenh lech mot tang. + # De qua -> bao dong gia khi thoi tiet doi. + # Chat qua -> khong phat hien duoc khi di 1 tang. + change_ratio: 0.6 + + settle_time: 3.0 # s cho on dinh truoc khi chot tang moi + +multi_map_manager: + # ⚠️ Duong dan tuyet doi. Cap nhat sau khi build map that. + # + # ⚠️ KEY PHAI LA CHUOI (co dau nhay), khong duoc de so nguyen. + # roslaunch de quy vao dict de tao ten param va goi ns_join(prefix, key); + # key kieu int lam no chet voi: + # TypeError: 'int' object is not subscriptable + # va TOAN BO launch file khong khoi dong duoc. Da mac loi nay - robot.launch + # exit 1 trong khi nav.launch van chay (vi nav.launch khong nap file nay). + # multi_map_manager.py da tu doi sang int khi doc, nen chuoi la an toan. + floors: + "1": /home/quangtrung/projects/vSLAM_ws/maps/map_floor_1.yaml + "2": /home/quangtrung/projects/vSLAM_ws/maps/map_floor_2.yaml + "3": /home/quangtrung/projects/vSLAM_ws/maps/map_floor_3.yaml + +dock_init: + map_frame: map + # ⚠️ Pose dock - PHAI do lai sau khi build map that. + dock_x: 0.0 + dock_y: 0.0 + dock_yaw: 0.0 + # Do bat dinh nho: dock la co khi dinh vi cung, robot ve dung mot cho. + sigma_xy: 0.03 + sigma_yaw: 0.02 + auto_publish: true + delay: 3.0 + +# ============================================================= +# AprilTag - nguon xac dinh tang TUYET DOI +# +# Barometer chi noi "da doi tang". Tang NAO thi phai co AprilTag, +# vi cac tang khach san trong giong het nhau. +# +# Dan tag trong thang may va o moi sanh tang. Node apriltag_ros doc tag id +# roi map sang so tang, publish len /floor/tag_hint (std_msgs/Int32). +# ============================================================= +# Key la chuoi vi cung ly do nhu tren (roslaunch khong xu ly duoc key int). +tag_to_floor: + "0": 1 + "1": 2 + "2": 3 diff --git a/src/localization_ops/launch/localization_ops.launch b/src/localization_ops/launch/localization_ops.launch new file mode 100644 index 0000000..781da27 --- /dev/null +++ b/src/localization_ops/launch/localization_ops.launch @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + diff --git a/src/localization_ops/package.xml b/src/localization_ops/package.xml new file mode 100644 index 0000000..7de439c --- /dev/null +++ b/src/localization_ops/package.xml @@ -0,0 +1,22 @@ + + + localization_ops + 0.1.0 + + Van hanh dinh vi: khoi tao pose tu dock, phat hien tang bang barometer + + AprilTag, quan ly da ban do cho khach san nhieu tang. + + quangtrung + BSD + + catkin + + rospy + sensor_msgs + nav_msgs + geometry_msgs + std_msgs + std_srvs + python3-numpy + python3-yaml + diff --git a/src/localization_ops/scripts/dock_init.py b/src/localization_ops/scripts/dock_init.py new file mode 100644 index 0000000..1231761 --- /dev/null +++ b/src/localization_ops/scripts/dock_init.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +""" +dock_init - Khoi tao pose tu dock sac. + +============ VI SAO VIEC NAY LAM BAI TOAN NHO DI RAT NHIEU ============ +Robot dich vu LUON quay ve dock sac. Dock la mot pose DA BIET CHINH XAC. + +=> Khoi dong tu dock thi KHONG CAN global relocalization, chi can xac nhan. + +Global relocalization (bai toan "kidnapped robot") chi can cho truong hop hiem: +bi nguoi be di, hoac mat track giua ca. Dung dau tu 3 thang vao mot tinh nang +chay 1 lan/tuan truoc khi luong chinh chay tot. + +Thu tu uu tien dung: + 1. Khoi dong tu dock <- lam truoc, de, bao phu 95% truong hop + 2. Khoi dong tu waypoint biet <- de + 3. Global relocalization <- lam sau cung, kho nhat +""" + +import math + +import rospy +from geometry_msgs.msg import PoseWithCovarianceStamped +from std_srvs.srv import Trigger, TriggerResponse + + +class DockInit(object): + def __init__(self): + self.map_frame = rospy.get_param('~map_frame', 'map') + + # Pose cua dock trong ban do. PHAI do lai sau khi build map that. + self.dock_x = rospy.get_param('~dock_x', 0.0) + self.dock_y = rospy.get_param('~dock_y', 0.0) + self.dock_yaw = rospy.get_param('~dock_yaw', 0.0) + + # Do bat dinh khi o dock: nho, vi dock la co khi dinh vi cung. + self.sigma_xy = rospy.get_param('~sigma_xy', 0.03) + self.sigma_yaw = rospy.get_param('~sigma_yaw', 0.02) + + self.auto_publish = rospy.get_param('~auto_publish', True) + self.delay = rospy.get_param('~delay', 3.0) + + self.pub = rospy.Publisher('/initialpose', PoseWithCovarianceStamped, + queue_size=1, latch=True) + self.srv = rospy.Service('~set_dock_pose', Trigger, self.on_trigger) + + rospy.loginfo('dock_init: dock tai (%.3f, %.3f, %.3f rad)', + self.dock_x, self.dock_y, self.dock_yaw) + + if self.auto_publish: + rospy.Timer(rospy.Duration(self.delay), self.on_timer, oneshot=True) + + def build_msg(self): + msg = PoseWithCovarianceStamped() + msg.header.stamp = rospy.Time.now() + msg.header.frame_id = self.map_frame + msg.pose.pose.position.x = self.dock_x + msg.pose.pose.position.y = self.dock_y + msg.pose.pose.orientation.z = math.sin(self.dock_yaw / 2.0) + msg.pose.pose.orientation.w = math.cos(self.dock_yaw / 2.0) + + msg.pose.covariance[0] = self.sigma_xy ** 2 + msg.pose.covariance[7] = self.sigma_xy ** 2 + msg.pose.covariance[35] = self.sigma_yaw ** 2 + return msg + + def on_timer(self, _evt): + self.pub.publish(self.build_msg()) + rospy.loginfo('dock_init: da publish /initialpose tai dock.') + + def on_trigger(self, _req): + self.pub.publish(self.build_msg()) + return TriggerResponse(success=True, message='Da dat pose ve dock.') + + +if __name__ == '__main__': + rospy.init_node('dock_init') + try: + DockInit() + rospy.spin() + except rospy.ROSInterruptException: + pass diff --git a/src/localization_ops/scripts/floor_detector.py b/src/localization_ops/scripts/floor_detector.py new file mode 100644 index 0000000..2d15b56 --- /dev/null +++ b/src/localization_ops/scripts/floor_detector.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +""" +floor_detector - Xac dinh robot dang o tang nao. + +============ TAI SAO KHONG DUNG SLAM DE BIET TANG ============ +Cac tang khach san TRONG GIONG HET NHAU: cung bo tri hanh lang, cung loai cua, +cung tham, cung den. Ca nhan dang hinh hoc (LiDAR) lan nhan dang anh (VPR) deu +se nham tang nay voi tang khac. Day la perceptual aliasing o muc te nhat. + +Nen viec xac dinh tang KHONG duoc giao cho SLAM. + +============ HAI NGUON, HAI VAI TRO KHAC NHAU ============ +1. BAROMETER -> phat hien CO doi tang (chenh lech ngan han) + ⚠️ KHONG duoc suy tang tu ap suat TUYET DOI: ap suat troi theo thoi tiet va + nhiet do hang tram Pa moi gio, trong khi mot tang chi ~40-45 Pa. + Sang chay dung, chieu chay sai. Chi dung CHENH LECH. + +2. APRILTAG -> xac nhan tang NAO (tuyet doi, khong troi) + Dan trong thang may va o moi sanh tang. Chi phi gan bang 0. + +Baro noi "vua di len 2 tang", AprilTag noi "day la tang 3". Ket hop hai cai +moi du tin cay. Thieu mot trong hai, he thong se sai vao luc ban khong ngo. +""" + +import collections + +import rospy +from sensor_msgs.msg import FluidPressure +from std_msgs.msg import Int32, String + +# Gradient ap suat gan mat dat: ~ -12 Pa moi met +PA_PER_METER = 12.0 + + +class FloorDetector(object): + def __init__(self): + self.floor_height = rospy.get_param('~floor_height', 3.5) + self.current_floor = rospy.get_param('~start_floor', 1) + + # Cua so trung binh truot de khu nhieu ngau nhien + self.window = int(rospy.get_param('~smooth_window', 25)) + + # Nguong phat hien doi tang: mot phan cua chenh lech mot tang + self.change_ratio = rospy.get_param('~change_ratio', 0.6) + + # Sau khi phat hien doi tang, cho on dinh bao lau moi chot + self.settle_time = rospy.get_param('~settle_time', 3.0) + + self.buf = collections.deque(maxlen=self.window) + self.reference_pressure = None + self.last_change_time = None + self.pending_floor = None + self.tag_floor = None + + self.floor_pub = rospy.Publisher('/floor/current', Int32, queue_size=1, latch=True) + self.status_pub = rospy.Publisher('/floor/status', String, queue_size=1, latch=True) + + rospy.Subscriber('/baro/pressure', FluidPressure, self.on_baro, queue_size=10) + rospy.Subscriber('/floor/tag_hint', Int32, self.on_tag, queue_size=5) + + self.pa_per_floor = PA_PER_METER * self.floor_height + + rospy.loginfo('floor_detector: %.1f m/tang -> ~%.1f Pa moi tang', + self.floor_height, self.pa_per_floor) + rospy.logwarn('floor_detector: barometer chi phat hien CO doi tang. ' + 'Xac nhan tang NAO can AprilTag (/floor/tag_hint).') + + self.publish(self.current_floor, 'khoi tao') + + def publish(self, floor, reason): + self.current_floor = floor + self.floor_pub.publish(Int32(data=floor)) + self.status_pub.publish(String(data='floor=%d (%s)' % (floor, reason))) + rospy.loginfo('floor_detector: TANG %d (%s)', floor, reason) + + def on_tag(self, msg): + """AprilTag: nguon tuyet doi, luon thang barometer.""" + self.tag_floor = msg.data + if msg.data != self.current_floor: + rospy.loginfo('floor_detector: AprilTag bao tang %d (dang nghi %d) ' + '-> tin AprilTag.', msg.data, self.current_floor) + self.publish(msg.data, 'AprilTag') + # Neo lai ap suat tham chieu theo tang da xac nhan + if self.buf: + self.reference_pressure = sum(self.buf) / len(self.buf) + self.pending_floor = None + + def on_baro(self, msg): + self.buf.append(msg.fluid_pressure) + if len(self.buf) < self.buf.maxlen: + return + + smooth = sum(self.buf) / len(self.buf) + + if self.reference_pressure is None: + self.reference_pressure = smooth + rospy.loginfo('floor_detector: neo ap suat tham chieu %.1f Pa', smooth) + return + + # Ap suat GIAM khi len cao + delta_pa = self.reference_pressure - smooth + floors_moved = delta_pa / self.pa_per_floor + + now = rospy.Time.now() + + if abs(floors_moved) >= self.change_ratio: + candidate = self.current_floor + int(round(floors_moved)) + + if self.pending_floor != candidate: + self.pending_floor = candidate + self.last_change_time = now + rospy.loginfo('floor_detector: nghi dang doi tang -> %d ' + '(chenh %.1f Pa). Cho on dinh %.1fs ...', + candidate, delta_pa, self.settle_time) + return + + if (now - self.last_change_time).to_sec() >= self.settle_time: + self.publish(candidate, 'barometer (chenh %.1f Pa)' % delta_pa) + self.reference_pressure = smooth + self.pending_floor = None + + if self.tag_floor is not None and self.tag_floor != candidate: + rospy.logwarn('floor_detector: barometer noi tang %d nhung ' + 'AprilTag gan nhat noi tang %d. Can AprilTag xac nhan.', + candidate, self.tag_floor) + else: + self.pending_floor = None + + +if __name__ == '__main__': + rospy.init_node('floor_detector') + try: + FloorDetector() + rospy.spin() + except rospy.ROSInterruptException: + pass diff --git a/src/localization_ops/scripts/multi_map_manager.py b/src/localization_ops/scripts/multi_map_manager.py new file mode 100644 index 0000000..3e23497 --- /dev/null +++ b/src/localization_ops/scripts/multi_map_manager.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +""" +multi_map_manager - Chuyen ban do khi robot doi tang. + +============ DA TANG KHONG PHAI 6-DoF SLAM ============ +Day la diem hay bi hieu nham. Robot khach san di thang may KHONG can uoc luong +pose 6-DoF. No can QUAN LY DA BAN DO: + + Tang 1 -> map_floor_1 (2D grid + octomap 3D) + Tang 2 -> map_floor_2 + Tang 3 -> map_floor_3 + ^ neo boi vi tri thang may + +Moi tang van la mot bai toan 2.5D phang binh thuong. Thu duy nhat can them la +biet dang o tang nao (floor_detector) va nap dung ban do. + +============ VI SAO TU NAP MAP THAY VI DUNG map_server ============ +map_server cua ROS1 Noetic khong co service doi map luc dang chay. Cac cach +khac (kill/restart node) lam mat lien tuc TF va lam AMCL/costmap hoang mang. +Nap va publish OccupancyGrid truc tiep thi chuyen map muot va kiem soat duoc. +""" + +import os + +import rospy +import yaml +from nav_msgs.msg import OccupancyGrid, MapMetaData +from std_msgs.msg import Int32, String + +try: + import numpy as np +except ImportError: + np = None + + +def read_pgm(path): + """Doc PGM nhi phan (P5). Tra ve numpy array uint8, khong can PIL.""" + with open(path, 'rb') as f: + data = f.read() + + # Header: P5 , co the xen ke comment '#' + tokens = [] + idx = 0 + while len(tokens) < 4 and idx < len(data): + # bo qua khoang trang + while idx < len(data) and data[idx:idx + 1].isspace(): + idx += 1 + # bo qua comment + if data[idx:idx + 1] == b'#': + while idx < len(data) and data[idx:idx + 1] not in (b'\n', b'\r'): + idx += 1 + continue + start = idx + while idx < len(data) and not data[idx:idx + 1].isspace(): + idx += 1 + tokens.append(data[start:idx]) + + if len(tokens) < 4 or tokens[0] != b'P5': + raise ValueError('%s khong phai PGM nhi phan (P5)' % path) + + width = int(tokens[1]) + height = int(tokens[2]) + idx += 1 # mot ky tu trang sau maxval + + pixels = np.frombuffer(data[idx:idx + width * height], dtype=np.uint8) + return pixels.reshape((height, width)) + + +class MultiMapManager(object): + def __init__(self): + if np is None: + rospy.logerr('multi_map_manager: thieu numpy. ' + 'sudo apt install python3-numpy') + return + + # floors: {1: '/duong/dan/map_floor_1.yaml', ...} + floors_param = rospy.get_param('~floors', {}) + self.floors = {int(k): v for k, v in floors_param.items()} + + self.current_floor = None + + self.map_pub = rospy.Publisher('/map', OccupancyGrid, queue_size=1, latch=True) + self.meta_pub = rospy.Publisher('/map_metadata', MapMetaData, + queue_size=1, latch=True) + self.name_pub = rospy.Publisher('/map_name', String, queue_size=1, latch=True) + + rospy.Subscriber('/floor/current', Int32, self.on_floor, queue_size=1) + + if not self.floors: + rospy.logwarn('multi_map_manager: chua cau hinh ~floors.') + rospy.logwarn('multi_map_manager: chay khong tai. ' + 'Xem localization_ops/config/floors.yaml') + else: + rospy.loginfo('multi_map_manager: da dang ky %d tang: %s', + len(self.floors), sorted(self.floors.keys())) + + def on_floor(self, msg): + if msg.data == self.current_floor: + return + + path = self.floors.get(msg.data) + if path is None: + rospy.logerr('multi_map_manager: KHONG co ban do cho tang %d. ' + 'Robot se dung tren ban do cu -> se dinh vi SAI.', msg.data) + return + + if self.load_map(path, msg.data): + self.current_floor = msg.data + + def load_map(self, yaml_path, floor): + if not os.path.isfile(yaml_path): + rospy.logerr('multi_map_manager: khong thay %s', yaml_path) + return False + + try: + with open(yaml_path, 'r') as f: + meta = yaml.safe_load(f) + except (IOError, yaml.YAMLError) as e: + rospy.logerr('multi_map_manager: loi doc %s: %s', yaml_path, e) + return False + + image = meta.get('image') + if not image: + rospy.logerr('multi_map_manager: %s thieu truong "image"', yaml_path) + return False + if not os.path.isabs(image): + image = os.path.join(os.path.dirname(yaml_path), image) + + try: + pix = read_pgm(image) + except (IOError, ValueError) as e: + rospy.logerr('multi_map_manager: loi doc %s: %s', image, e) + return False + + resolution = float(meta.get('resolution', 0.05)) + origin = meta.get('origin', [0.0, 0.0, 0.0]) + negate = int(meta.get('negate', 0)) + occ_th = float(meta.get('occupied_thresh', 0.65)) + free_th = float(meta.get('free_thresh', 0.196)) + + # PGM: 0 = den = chiem dung, 255 = trang = trong + p = pix.astype(np.float32) / 255.0 + if negate: + occupancy = p + else: + occupancy = 1.0 - p + + grid = np.full(occupancy.shape, -1, dtype=np.int8) # -1 = chua biet + grid[occupancy > occ_th] = 100 + grid[occupancy < free_th] = 0 + + # ROS OccupancyGrid tinh tu goc DUOI-TRAI; PGM luu tu tren xuong + grid = np.flipud(grid) + + msg = OccupancyGrid() + msg.header.stamp = rospy.Time.now() + msg.header.frame_id = 'map' + msg.info.resolution = resolution + msg.info.width = grid.shape[1] + msg.info.height = grid.shape[0] + msg.info.origin.position.x = float(origin[0]) + msg.info.origin.position.y = float(origin[1]) + msg.info.origin.orientation.w = 1.0 + msg.data = grid.reshape(-1).tolist() + + self.map_pub.publish(msg) + self.meta_pub.publish(msg.info) + self.name_pub.publish(String(data='map_floor_%d' % floor)) + + rospy.loginfo('multi_map_manager: da nap TANG %d - %s (%dx%d @ %.3f m/o)', + floor, os.path.basename(yaml_path), + msg.info.width, msg.info.height, resolution) + return True + + +if __name__ == '__main__': + rospy.init_node('multi_map_manager') + try: + MultiMapManager() + rospy.spin() + except rospy.ROSInterruptException: + pass diff --git a/src/perception_3d/CMakeLists.txt b/src/perception_3d/CMakeLists.txt new file mode 100644 index 0000000..e962780 --- /dev/null +++ b/src/perception_3d/CMakeLists.txt @@ -0,0 +1,61 @@ +cmake_minimum_required(VERSION 3.0.2) +project(perception_3d) + +add_compile_options(-std=c++14) + +find_package(catkin REQUIRED COMPONENTS + roscpp + nodelet + pluginlib + sensor_msgs + std_msgs + geometry_msgs + tf2 + tf2_ros + pcl_ros + pcl_conversions +) + +find_package(PCL REQUIRED COMPONENTS common filters) +find_package(Eigen3 REQUIRED) + +catkin_package( + CATKIN_DEPENDS roscpp nodelet pluginlib sensor_msgs std_msgs geometry_msgs + tf2 tf2_ros pcl_ros pcl_conversions +) + +include_directories( + include + ${catkin_INCLUDE_DIRS} + ${PCL_INCLUDE_DIRS} + ${EIGEN3_INCLUDE_DIRS} +) + +link_directories(${PCL_LIBRARY_DIRS}) +add_definitions(${PCL_DEFINITIONS}) + +# Ca hai nodelet trong MOT thu vien -> nap chung mot manager, chia se shared_ptr. +add_library(${PROJECT_NAME}_nodelets + src/depth_filter_nodelet.cpp + src/gravity_align_nodelet.cpp + src/scan_to_cloud_nodelet.cpp +) +target_link_libraries(${PROJECT_NAME}_nodelets + ${catkin_LIBRARIES} + ${PCL_LIBRARIES} +) +add_dependencies(${PROJECT_NAME}_nodelets + ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + +install(TARGETS ${PROJECT_NAME}_nodelets + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} +) + +install(FILES nodelet_plugins.xml + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} +) + +install(DIRECTORY launch config + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} +) diff --git a/src/perception_3d/config/depth_filter.yaml b/src/perception_3d/config/depth_filter.yaml new file mode 100644 index 0000000..15b855e --- /dev/null +++ b/src/perception_3d/config/depth_filter.yaml @@ -0,0 +1,67 @@ +# ============================================================= +# Tham so chuoi loc point cloud (D410) +# ============================================================= + +depth_filter: + # min_range PHAI >= Min-Z that cua D410. + # ⚠️ 0.22 la gia tri UOC TINH cho 640x480 (Min-Z ty le thuan voi do phan giai: + # 1280x720 ~ 45cm, 848x480 ~ 30cm, 640x480 ~ 22cm). + # PHAI DO LAI tren camera that: day mot hop lai gan dan den khi depth bien mat. + # Gan hon nguong nay camera KHONG THAY GI -> viec cua bumper + sieu am. + min_range: 0.22 + max_range: 4.0 # xa hon ~4m depth stereo baseline 55mm nhieu manh + + voxel_size: 0.03 # 3cm - du chi tiet cho vat can, du nhe cho IPC + + # ⚠️ TAT. Node nay chay o frame quang hoc camera, ma frame do di chuyen cung + # robot -> cung mot diem the gioi roi vao voxel key khac nhau sau moi lan + # robot nhuch nhich -> bo dem hit khong cong don duoc -> loc VUT BO vat can + # that khi dang di. Nguoc han y do ban dau. + # octomap_server da tich phan xac suat chiem dung trong frame `map` co dinh, + # tuc lam dung viec nay roi. Chi bat khi robot DUNG YEN. + enable_temporal: false + min_hits: 3 + temporal_window: 0.5 + + # Loc ngoai lai thong ke - hieu qua nhung TON CPU (kd-tree). + # Do bang slam_eval/resource_profile.py truoc khi bat tren IPC. + enable_sor: false + sor_mean_k: 20 + sor_stddev: 1.0 + +gravity_align: + base_frame: base_link + output_frame: base_footprint + wheel_radius: 0.075 # PHAI khop robot.urdf.xacro + + # Complementary filter. 0.98 @200Hz -> hang so thoi gian ~0.25s. + alpha: 0.98 + + # ⚠️ Loc thong thap accel - BAT BUOC, khong phai tinh chinh. + # Do thuc te trong sim: robot DUNG YEN ma a_z dao dong 8.3 ... 11.3 m/s^2 + # (rung do tiep xuc banh-san). Neu gate len mau THO thi gan nhu moi mau bi + # tu choi -> mat hieu chinh accel -> pitch tich phan gyro va troi 5.2 do/10s. + # Robot that con rung manh hon (san gach + banh cung). + # 0.05 @200Hz -> hang so thoi gian ~0.1s. + accel_lpf_alpha: 0.05 + + # Bo qua hieu chinh khi |a_DA_LOC| lech xa g qua nguong nay (m/s^2): + # luc do robot dang tang/giam toc that su, accel khong do duoc trong luc. + accel_gate: 1.0 + + imu_timeout: 0.5 + + # ⚠️ CAT DAI CHIEU CAO (trong base_footprint, sau khi da bu nghieng). + # + # Camera chuc xuong 15 do o z=0.80 nen NHIN THAY SAN tu ~1.1m tro ra. + # Diem san nam o z~0, nhung octomap resolution 0.05 co tam voxel tai + # 0.025 / 0.075 / 0.125..., va nhieu depth day mot phan diem san len voxel + # z=0.075 -> lot qua occupancy_min_z=0.05 -> SAN bi chieu thanh vat can. + # + # Hau qua da do: tham o LETHAL trai truoc mui robot (cost 99-100 tu 0.4m), + # global planner khong sinh duoc duong, move_base ABORTED. + # + # 0.06: tren nhieu san (3 sigma ~0.02) nhung duoi vat can thap that + # (hop 12cm trong restaurant.world van duoc giu lai). + min_height: 0.06 + max_height: 1.20 diff --git a/src/perception_3d/launch/perception_nodelets.launch b/src/perception_3d/launch/perception_nodelets.launch new file mode 100644 index 0000000..904348c --- /dev/null +++ b/src/perception_3d/launch/perception_nodelets.launch @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/perception_3d/nodelet_plugins.xml b/src/perception_3d/nodelet_plugins.xml new file mode 100644 index 0000000..88a3ce1 --- /dev/null +++ b/src/perception_3d/nodelet_plugins.xml @@ -0,0 +1,32 @@ + + + + + Chuoi loc cloud: cat theo tam -> voxel grid -> (tuy chon) loc ngoai lai + -> xac nhan theo thoi gian. Chay trong nodelet manager de zero-copy. + + + + + + Chieu LaserScan 2D thanh PointCloud2 trong base_footprint, de LiDAR + dong gop vao ban do 3D/2D chu khong chi camera. LiDAR co FOV 240 do va + tam 30m; camera chi 69 do va 4m - thieu LiDAR thi ban do qua nho de + dieu huong. + + + + + + Bu nghieng cloud bang roll/pitch DO tu IMU (complementary filter). + Mau chot cua kien truc 2.5D: khong uoc luong 6-DoF, chi do huong trong luc. + + + + diff --git a/src/perception_3d/package.xml b/src/perception_3d/package.xml new file mode 100644 index 0000000..31c0c22 --- /dev/null +++ b/src/perception_3d/package.xml @@ -0,0 +1,34 @@ + + + perception_3d + 0.1.0 + + Xu ly point cloud 3D tu D410 duoi dang nodelet (zero-copy): + loc chuoi + bu nghieng bang roll/pitch do tu IMU. + Day la lop cho robot "nhin thay" nhung thu LiDAR 2D mu hoan toan: + mat ban nho ra, vat thap duoi san, vat treo, bac/ho. + + quangtrung + BSD + + catkin + + roscpp + nodelet + pluginlib + sensor_msgs + std_msgs + geometry_msgs + tf2 + tf2_ros + pcl_ros + pcl_conversions + eigen + + depth_image_proc + octomap_server + + + + + diff --git a/src/perception_3d/src/depth_filter_nodelet.cpp b/src/perception_3d/src/depth_filter_nodelet.cpp new file mode 100644 index 0000000..681e1e5 --- /dev/null +++ b/src/perception_3d/src/depth_filter_nodelet.cpp @@ -0,0 +1,218 @@ +/** + * depth_filter_nodelet - Chuoi loc point cloud tu D410. + * + * ================== VI SAO LA NODELET, KHONG PHAI NODE ================== + * Cloud 640x480 ~ 4.9 MB moi frame. O 30 Hz la ~147 MB/s. Moi lan di qua ranh + * gioi process la mot lan serialize + copy. Chay 2-3 hop bang node rieng se + * dot hang tram MB/s chi de CHUYEN du lieu. + * + * Nodelet trong cung mot manager chia se shared_ptr -> ZERO COPY. + * Diem nay se con quan trong hon khi chuyen tu may ban i5-14500 sang IPC. + * + * ================== VI SAO HighDensity, KHONG PHAI HighAccuracy ================== + * Voi robot chay giua khach hang, hai loai loi KHONG can xung nhau: + * - BO SOT vat can -> robot dam vao nguoi. Khong chap nhan duoc. + * - Diem nhieu gia -> robot dung khong can thiet. Phien, nhung an toan. + * + * Nen: lay preset HighDensity (nguong confidence thap, nhieu diem hon), roi bu + * lai nhieu bang XAC NHAN THEO THOI GIAN - vat can phai xuat hien o cung mot + * voxel it nhat min_hits lan trong cua so gan day moi duoc coi la that. + * Nhieu ngau nhien khong lap lai duoc o cung voxel; vat can that thi co. + */ + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace perception_3d +{ + +class DepthFilterNodelet : public nodelet::Nodelet +{ +public: + DepthFilterNodelet() = default; + +private: + struct VoxelHit + { + int count = 0; + ros::Time last_seen; + }; + + void onInit() override + { + nh_ = getNodeHandle(); + pnh_ = getPrivateNodeHandle(); + + // Cat theo tam. min_range PHAI >= Min-Z that cua D410 (~0.22m @640x480). + // Gan hon nguong nay camera KHONG THAY GI - do la viec cua bumper/sieu am. + pnh_.param("min_range", min_range_, 0.22); + pnh_.param("max_range", max_range_, 4.0); + + pnh_.param("voxel_size", voxel_size_, 0.03); + + // ⚠️ Xac nhan theo thoi gian - MAC DINH TAT. + // + // Node nay chay o FRAME QUANG HOC CAMERA, ma frame do di chuyen cung robot. + // Cung mot diem trong the gioi se roi vao voxel key KHAC NHAU sau moi lan + // robot nhuch nhich -> bo dem hit khong bao gio cong don duoc -> bo loc + // VUT BO vat can that khi robot dang di, va chi "xac nhan" duoc khi dung yen. + // Dung y do ban dau hoan toan nguoc lai. + // + // Hon nua octomap_server DA lam viec nay dung cach: tich phan xac suat + // chiem dung trong frame `map` co dinh. Bat cai nay chi lam hong them. + // + // Chi bat khi robot DUNG YEN va can loc nhieu depth ngan han. + pnh_.param("enable_temporal", enable_temporal_, false); + pnh_.param("min_hits", min_hits_, 3); + pnh_.param("temporal_window", temporal_window_, 0.5); // s + + // Loc ngoai lai thong ke: hieu qua nhung TON CPU (phai dung kd-tree). + // Mac dinh TAT. Do resource_profile.py truoc khi bat tren IPC. + pnh_.param("enable_sor", enable_sor_, false); + pnh_.param("sor_mean_k", sor_mean_k_, 20); + pnh_.param("sor_stddev", sor_stddev_, 1.0); + + pub_ = nh_.advertise("cloud_filtered", 5); + sub_ = nh_.subscribe("cloud_in", 5, &DepthFilterNodelet::onCloud, this); + + NODELET_INFO("depth_filter: range [%.2f, %.2f] m, voxel %.3f m", + min_range_, max_range_, voxel_size_); + if (enable_temporal_) + NODELET_INFO("depth_filter: xac nhan thoi gian - can %d hit trong %.2fs", + min_hits_, temporal_window_); + if (enable_sor_) + NODELET_WARN("depth_filter: SOR dang BAT - ton CPU, do lai truoc khi len IPC."); + } + + inline int64_t voxelKey(float x, float y, float z) const + { + // Pack 3 chi so voxel 21-bit vao mot int64 + const int64_t ix = static_cast(std::floor(x / voxel_size_)) & 0x1FFFFF; + const int64_t iy = static_cast(std::floor(y / voxel_size_)) & 0x1FFFFF; + const int64_t iz = static_cast(std::floor(z / voxel_size_)) & 0x1FFFFF; + return (ix << 42) | (iy << 21) | iz; + } + + void onCloud(const sensor_msgs::PointCloud2::ConstPtr& msg) + { + pcl::PointCloud::Ptr cloud(new pcl::PointCloud); + pcl::fromROSMsg(*msg, *cloud); + if (cloud->empty()) + return; + + // --- 1. Cat theo tam (z la chieu sau trong frame quang hoc camera) --- + pcl::PointCloud::Ptr passed(new pcl::PointCloud); + { + pcl::PassThrough pass; + pass.setInputCloud(cloud); + pass.setFilterFieldName("z"); + pass.setFilterLimits(static_cast(min_range_), static_cast(max_range_)); + pass.filter(*passed); + } + if (passed->empty()) + { + publish(passed, msg->header); + return; + } + + // --- 2. Giam mau bang voxel grid --- + pcl::PointCloud::Ptr voxelized(new pcl::PointCloud); + { + pcl::VoxelGrid vg; + vg.setInputCloud(passed); + const float v = static_cast(voxel_size_); + vg.setLeafSize(v, v, v); + vg.filter(*voxelized); + } + + // --- 3. Loc ngoai lai thong ke (tuy chon) --- + pcl::PointCloud::Ptr cleaned = voxelized; + if (enable_sor_ && voxelized->size() > static_cast(sor_mean_k_)) + { + pcl::PointCloud::Ptr tmp(new pcl::PointCloud); + pcl::StatisticalOutlierRemoval sor; + sor.setInputCloud(voxelized); + sor.setMeanK(sor_mean_k_); + sor.setStddevMulThresh(sor_stddev_); + sor.filter(*tmp); + cleaned = tmp; + } + + // --- 4. Xac nhan theo thoi gian --- + if (!enable_temporal_) + { + publish(cleaned, msg->header); + return; + } + + const ros::Time now = msg->header.stamp; + + // Don cac voxel qua cu + for (auto it = hits_.begin(); it != hits_.end(); ) + { + if ((now - it->second.last_seen).toSec() > temporal_window_) + it = hits_.erase(it); + else + ++it; + } + + pcl::PointCloud::Ptr confirmed(new pcl::PointCloud); + confirmed->reserve(cleaned->size()); + + for (const auto& p : cleaned->points) + { + if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) + continue; + + VoxelHit& h = hits_[voxelKey(p.x, p.y, p.z)]; + h.count = std::min(h.count + 1, min_hits_ * 4); // chan tran + h.last_seen = now; + + if (h.count >= min_hits_) + confirmed->push_back(p); + } + + publish(confirmed, msg->header); + } + + void publish(const pcl::PointCloud::Ptr& cloud, + const std_msgs::Header& header) + { + sensor_msgs::PointCloud2 out; + pcl::toROSMsg(*cloud, out); + out.header = header; + pub_.publish(out); + } + + ros::NodeHandle nh_, pnh_; + ros::Subscriber sub_; + ros::Publisher pub_; + + double min_range_ = 0.22, max_range_ = 4.0, voxel_size_ = 0.03; + bool enable_temporal_ = true; + int min_hits_ = 3; + double temporal_window_ = 0.5; + bool enable_sor_ = false; + int sor_mean_k_ = 20; + double sor_stddev_ = 1.0; + + std::unordered_map hits_; +}; + +} // namespace perception_3d + +PLUGINLIB_EXPORT_CLASS(perception_3d::DepthFilterNodelet, nodelet::Nodelet) diff --git a/src/perception_3d/src/gravity_align_nodelet.cpp b/src/perception_3d/src/gravity_align_nodelet.cpp new file mode 100644 index 0000000..6ea41f2 --- /dev/null +++ b/src/perception_3d/src/gravity_align_nodelet.cpp @@ -0,0 +1,327 @@ +/** + * gravity_align_nodelet - Bu nghieng cho point cloud bang roll/pitch DO tu IMU. + * + * ================== DAY LA MAU CHOT CUA KIEN TRUC 2.5D ================== + * Ta uoc luong pose o SE(2): chi (x, y, theta). Khong uoc luong 6-DoF, vi: + * - LiDAR 2D von GIA DINH chuyen dong phang, khong cho rang buoc theo z + * - Encoder chi do duoc chuyen dong phang + * - IMU cho z troi tu do (tich phan accel hai lan) + * => Uoc luong 6-DoF tren phan cung nay chi mo them cua cho drift chui vao. + * + * NHUNG robot THUC SU co nghieng: qua go cua, len doc nhe, san khong phang. + * URDF khai bao base_footprint -> base_link la CO DINH khong nghieng, nen neu + * cu the ma dung, cloud se bi ghep sai cho khi robot nghieng: + * + * Robot chui 3 do -> cloud bi ban len tran nha + * -> OctoMap ghi vat can ma o do khong co gi + * -> robot tu chan duong chinh minh + * + * Giai phap: roll/pitch duoc DO TRUC TIEP tu huong trong luc (accelerometer), + * KHONG uoc luong trong factor graph. Do la thong tin mien phi va chinh xac - + * trong luc luon chi xuong. + * + * Node nay dung roll/pitch do duoc de dua cloud ve he quy chieu THANG DUNG: + * + * p_footprint = Translate(0,0,r) * R(roll,pitch) * T_baselink_camera * p_camera + * + * base_footprint theo dinh nghia la hinh chieu tren san -> luon thang dung, + * nen day chinh la frame dau ra dung. + * + * ================== VI SAO DUNG COMPLEMENTARY FILTER ================== + * Chi dung accelerometer thi sai khi robot tang/giam toc (gia toc rieng cong + * vao trong luc). Chi dung gyro thi troi. Ket hop: + * - Gyro cho phan ngan han (khong bi anh huong boi gia toc rieng) + * - Accel cho phan dai han (neo vao trong luc, khong troi) + */ + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include +#include + +namespace perception_3d +{ + +class GravityAlignNodelet : public nodelet::Nodelet +{ +public: + GravityAlignNodelet() = default; + +private: + void onInit() override + { + nh_ = getNodeHandle(); + pnh_ = getPrivateNodeHandle(); + + pnh_.param("base_frame", base_frame_, "base_link"); + pnh_.param("output_frame", output_frame_, "base_footprint"); + pnh_.param("wheel_radius", wheel_radius_, 0.075); + + // He so complementary filter: ty trong cua gyro. + // 0.98 @200Hz -> hang so thoi gian ~0.25s. Gyro chiem uu the ngan han, + // accel keo ve trong dai han. + pnh_.param("alpha", alpha_, 0.98); + + // Loc thong thap accel TRUOC khi dung. + // + // ⚠️ BAT BUOC, khong phai tinh chinh: accel tho tren robot banh dao dong + // rat manh (do da do trong sim: |a_z| = 8.3 ... 11.3 khi robot DUNG YEN). + // Nguon la rung do tiep xuc banh-san, khong phai nhieu cam bien - va tren + // robot that con te hon (san gach + banh cung). + // + // Neu gate len mau THO, gan nhu moi mau deu bi tu choi -> mat hieu chinh + // accel -> pitch chi con tich phan gyro va TROI (da do: 5.2 do sau ~10s). + // + // alpha 0.05 @200Hz -> hang so thoi gian ~0.1s. Huong trong luc thay doi + // cham hon nhieu nen loc manh o day khong lam mat thong tin. + pnh_.param("accel_lpf_alpha", accel_lpf_alpha_, 0.05); + + // Bo qua hieu chinh khi |a_da_loc| lech xa g -> luc do robot dang tang toc + // that su, accel khong con do duoc huong trong luc. + pnh_.param("accel_gate", accel_gate_, 1.0); // m/s^2 + + pnh_.param("imu_timeout", imu_timeout_, 0.5); + + // ⚠️ CAT DAI CHIEU CAO - BAT BUOC, va PHAI lam o day. + // + // Day la node duy nhat trong chuoi ma z mang nghia "chieu cao so voi san": + // depth_filter chay o frame quang hoc camera (z = chieu sau), con octomap + // thi da qua muon. + // + // Vi sao bat buoc: camera chuc xuong 15 do o z=0.80 nen NHIN THAY SAN tu + // ~1.1m tro ra. Diem san nam o z~0. Voi octomap resolution 0.05, tam voxel + // la 0.025 / 0.075 / 0.125..., ma nhieu depth (sigma 0.007) day mot phan + // diem san len voxel z=0.075 - LOT QUA occupancy_min_z=0.05 va bi chieu + // thanh o chiem dung. + // + // Hau qua da do: mot tham o LETHAL trai ngay truoc mui robot + // (cost 99-100 lien tuc tu 0.4m), global planner khong the sinh duong, + // move_base ABORTED. + // + // min_height 0.06: tren nhieu san (3 sigma ~0.02) nhung duoi vat can thap + // that (hop 12cm trong restaurant.world van duoc giu). + pnh_.param("min_height", min_height_, 0.06); + pnh_.param("max_height", max_height_, 1.20); + + tf_buffer_ = std::make_shared(); + tf_listener_ = std::make_shared(*tf_buffer_); + + cloud_pub_ = nh_.advertise("cloud_aligned", 5); + rp_pub_ = nh_.advertise("gravity_align/roll_pitch", 10); + + imu_sub_ = nh_.subscribe("imu/data_raw", 200, &GravityAlignNodelet::onImu, this); + cloud_sub_ = nh_.subscribe("cloud_in", 5, &GravityAlignNodelet::onCloud, this); + + NODELET_INFO("gravity_align: output_frame=%s, alpha=%.3f, chieu cao [%.2f, %.2f] m", + output_frame_.c_str(), alpha_, min_height_, max_height_); + NODELET_INFO("gravity_align: roll/pitch DO tu IMU, KHONG uoc luong. " + "Xem docs/ARCHITECTURE.md muc 2.5D."); + } + + void onImu(const sensor_msgs::Imu::ConstPtr& msg) + { + const ros::Time now = msg->header.stamp; + + if (!imu_init_) + { + last_imu_time_ = now; + imu_init_ = true; + return; + } + + double dt = (now - last_imu_time_).toSec(); + last_imu_time_ = now; + + if (dt <= 0.0 || dt > 1.0) + { + // Nhay thoi gian (reset sim / phat lai bag) - bo qua mau nay + return; + } + + // --- Du doan bang gyro --- + roll_ += msg->angular_velocity.x * dt; + pitch_ += msg->angular_velocity.y * dt; + + // --- Loc thong thap accel truoc khi dung --- + // Xem giai thich o onInit: accel tho dao dong manh do rung tiep xuc + // banh-san, gate len mau tho se tu choi gan nhu moi mau. + const double ax_raw = msg->linear_acceleration.x; + const double ay_raw = msg->linear_acceleration.y; + const double az_raw = msg->linear_acceleration.z; + + if (!accel_lpf_init_) + { + ax_f_ = ax_raw; ay_f_ = ay_raw; az_f_ = az_raw; + accel_lpf_init_ = true; + } + else + { + const double a = accel_lpf_alpha_; + ax_f_ = a * ax_raw + (1.0 - a) * ax_f_; + ay_f_ = a * ay_raw + (1.0 - a) * ay_f_; + az_f_ = a * az_raw + (1.0 - a) * az_f_; + } + + // --- Hieu chinh bang accel (chi khi dang gan trang thai tinh) --- + const double ax = ax_f_, ay = ay_f_, az = az_f_; + const double norm = std::sqrt(ax * ax + ay * ay + az * az); + + if (std::fabs(norm - 9.80665) < accel_gate_ && norm > 1e-3) + { + const double roll_acc = std::atan2(ay, az); + const double pitch_acc = std::atan2(-ax, std::sqrt(ay * ay + az * az)); + + roll_ = alpha_ * roll_ + (1.0 - alpha_) * roll_acc; + pitch_ = alpha_ * pitch_ + (1.0 - alpha_) * pitch_acc; + accel_ok_ = true; + } + else + { + // Dang tang/giam toc manh: accel khong do duoc trong luc, chi tin gyro. + accel_ok_ = false; + } + + have_imu_ = true; + + std_msgs::Float64MultiArray rp; + rp.data = { roll_, pitch_, accel_ok_ ? 1.0 : 0.0 }; + rp_pub_.publish(rp); + } + + void onCloud(const sensor_msgs::PointCloud2::ConstPtr& msg) + { + if (msg->width == 0 || msg->height == 0) + return; + + // --- Static transform camera -> base_link (tu URDF) --- + geometry_msgs::TransformStamped tf_bl_cam; + try + { + tf_bl_cam = tf_buffer_->lookupTransform(base_frame_, msg->header.frame_id, + ros::Time(0), ros::Duration(0.1)); + } + catch (const tf2::TransformException& ex) + { + NODELET_WARN_THROTTLE(5.0, "gravity_align: khong lookup duoc TF %s <- %s: %s", + base_frame_.c_str(), msg->header.frame_id.c_str(), ex.what()); + return; + } + + // --- Roll/pitch hien tai --- + double roll = 0.0, pitch = 0.0; + const bool imu_fresh = + have_imu_ && ((msg->header.stamp - last_imu_time_).toSec() < imu_timeout_); + + if (imu_fresh) + { + roll = roll_; + pitch = pitch_; + } + else + { + // Khong co IMU -> gia dinh robot phang. Van hoat dong, nhung neu robot + // that su nghieng thi cloud se ghep sai. Bao dong ro rang. + NODELET_WARN_THROTTLE(10.0, + "gravity_align: KHONG co IMU moi -> gia dinh roll=pitch=0. " + "Cloud se SAI neu robot nghieng."); + } + + // --- Ghep phep bien doi --- + // p_out = Translate(0,0,r) * R(roll,pitch,0) * T_baselink_camera * p_cam + Eigen::Affine3d t_bl_cam = Eigen::Affine3d::Identity(); + t_bl_cam.translation() << tf_bl_cam.transform.translation.x, + tf_bl_cam.transform.translation.y, + tf_bl_cam.transform.translation.z; + t_bl_cam.linear() = Eigen::Quaterniond(tf_bl_cam.transform.rotation.w, + tf_bl_cam.transform.rotation.x, + tf_bl_cam.transform.rotation.y, + tf_bl_cam.transform.rotation.z).toRotationMatrix(); + + Eigen::Affine3d tilt = Eigen::Affine3d::Identity(); + tilt.linear() = (Eigen::AngleAxisd(pitch, Eigen::Vector3d::UnitY()) * + Eigen::AngleAxisd(roll, Eigen::Vector3d::UnitX())).toRotationMatrix(); + + Eigen::Affine3d lift = Eigen::Affine3d::Identity(); + lift.translation() << 0.0, 0.0, wheel_radius_; + + const Eigen::Affine3f total = (lift * tilt * t_bl_cam).cast(); + + // --- Bien doi cloud --- + pcl::PointCloud cloud_in; + pcl::fromROSMsg(*msg, cloud_in); + if (cloud_in.empty()) + return; + + pcl::PointCloud transformed; + pcl::transformPointCloud(cloud_in, transformed, total); + + // Cat dai chieu cao - xem giai thich o onInit. + // Chi lam duoc SAU khi bien doi: truoc do z la chieu sau, khong phai chieu cao. + pcl::PointCloud cloud_out; + cloud_out.reserve(transformed.size()); + for (const auto& p : transformed.points) + { + if (!std::isfinite(p.z)) + continue; + if (p.z < min_height_ || p.z > max_height_) + continue; + cloud_out.push_back(p); + } + + if (cloud_out.empty()) + { + NODELET_DEBUG_THROTTLE(5.0, "gravity_align: khong con diem nao sau khi cat " + "chieu cao [%.2f, %.2f]", min_height_, max_height_); + return; + } + + sensor_msgs::PointCloud2 out; + pcl::toROSMsg(cloud_out, out); + out.header.stamp = msg->header.stamp; + out.header.frame_id = output_frame_; + cloud_pub_.publish(out); + } + + ros::NodeHandle nh_, pnh_; + ros::Subscriber imu_sub_, cloud_sub_; + ros::Publisher cloud_pub_, rp_pub_; + + std::shared_ptr tf_buffer_; + std::shared_ptr tf_listener_; + + std::string base_frame_, output_frame_; + double wheel_radius_ = 0.075; + double alpha_ = 0.98; + double accel_gate_ = 1.0; + double accel_lpf_alpha_ = 0.05; + double imu_timeout_ = 0.5; + double min_height_ = 0.06, max_height_ = 1.20; + + double roll_ = 0.0, pitch_ = 0.0; + double ax_f_ = 0.0, ay_f_ = 0.0, az_f_ = 9.80665; + bool accel_lpf_init_ = false; + bool have_imu_ = false, imu_init_ = false, accel_ok_ = false; + ros::Time last_imu_time_; +}; + +} // namespace perception_3d + +PLUGINLIB_EXPORT_CLASS(perception_3d::GravityAlignNodelet, nodelet::Nodelet) diff --git a/src/perception_3d/src/scan_to_cloud_nodelet.cpp b/src/perception_3d/src/scan_to_cloud_nodelet.cpp new file mode 100644 index 0000000..5aafcaf --- /dev/null +++ b/src/perception_3d/src/scan_to_cloud_nodelet.cpp @@ -0,0 +1,149 @@ +/** + * scan_to_cloud_nodelet - Chieu LaserScan 2D thanh PointCloud2 trong base_footprint. + * + * ================== VI SAO CAN NODE NAY ================== + * Kien truc da chot: LiDAR 2D la TRU COT cua ban do, camera chi bu diem mu. + * Nhung octomap_server chi nhan MOT topic cloud_in, va neu chi cho no cloud tu + * camera thi ban do sinh ra qua nho de dieu huong: + * + * Camera D410 : FOV 69 do, tam huu dung ~4m, chi nhin phia truoc + * LiDAR ToF : FOV 240 do, tam ~30m + * + * Da do hau qua: global planner phat 468k ban tin plan RONG (0 diem) va + * move_base chi xoay tai cho, vi phan lon global costmap la "unknown". + * + * Node nay chieu /scan thanh cloud roi publish len CUNG topic voi cloud da bu + * nghieng cua camera. octomap_server tich hop moi ban tin den, khong quan tam + * thu tu hay nguon - nen khong can dong bo thoi gian giua hai luong. + * + * ================== PHAN CONG ================== + * LiDAR -> hinh hoc xa & rong -> khung ban do de dieu huong + * Camera -> khoi 3D gan -> mat ban nho ra, vat thap, vat treo + * + * ================== KHONG DUNG laser_geometry ================== + * Phep chieu chi la x=r*cos(t), y=r*sin(t) roi nhan mot phep bien doi tinh. + * Tu lam thi bot mot dependency va kiem soat duoc cach xu ly frame. + */ + +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include + +#include +#include + +namespace perception_3d +{ + +class ScanToCloudNodelet : public nodelet::Nodelet +{ +public: + ScanToCloudNodelet() = default; + +private: + void onInit() override + { + nh_ = getNodeHandle(); + pnh_ = getPrivateNodeHandle(); + + pnh_.param("output_frame", output_frame_, "base_footprint"); + + // Cat bo tia qua gan/qua xa. min_range chan phan tia dam vao chinh than + // robot neu FOV cau hinh rong hon cung khong bi che. + pnh_.param("min_range", min_range_, 0.10); + pnh_.param("max_range", max_range_, 25.0); + + pub_ = nh_.advertise("cloud_out", 5); + sub_ = nh_.subscribe("scan", 10, &ScanToCloudNodelet::onScan, this); + + tf_buffer_ = std::make_shared(); + tf_listener_ = std::make_shared(*tf_buffer_); + + NODELET_INFO("scan_to_cloud: /scan -> cloud trong %s, range [%.2f, %.2f] m", + output_frame_.c_str(), min_range_, max_range_); + } + + void onScan(const sensor_msgs::LaserScan::ConstPtr& msg) + { + geometry_msgs::TransformStamped tf; + try + { + tf = tf_buffer_->lookupTransform(output_frame_, msg->header.frame_id, + ros::Time(0), ros::Duration(0.1)); + } + catch (const tf2::TransformException& ex) + { + NODELET_WARN_THROTTLE(5.0, "scan_to_cloud: khong lookup duoc TF %s <- %s: %s", + output_frame_.c_str(), msg->header.frame_id.c_str(), ex.what()); + return; + } + + pcl::PointCloud cloud; + cloud.reserve(msg->ranges.size()); + + for (size_t i = 0; i < msg->ranges.size(); ++i) + { + const float r = msg->ranges[i]; + if (!std::isfinite(r)) + continue; + if (r < msg->range_min || r > msg->range_max) + continue; + if (r < min_range_ || r > max_range_) + continue; + + const double a = msg->angle_min + i * msg->angle_increment; + pcl::PointXYZ p; + p.x = static_cast(r * std::cos(a)); + p.y = static_cast(r * std::sin(a)); + p.z = 0.0f; + cloud.push_back(p); + } + + if (cloud.empty()) + return; + + Eigen::Affine3d t = Eigen::Affine3d::Identity(); + t.translation() << tf.transform.translation.x, + tf.transform.translation.y, + tf.transform.translation.z; + t.linear() = Eigen::Quaterniond(tf.transform.rotation.w, + tf.transform.rotation.x, + tf.transform.rotation.y, + tf.transform.rotation.z).toRotationMatrix(); + + pcl::PointCloud out_cloud; + pcl::transformPointCloud(cloud, out_cloud, t.cast()); + + sensor_msgs::PointCloud2 out; + pcl::toROSMsg(out_cloud, out); + out.header.stamp = msg->header.stamp; + out.header.frame_id = output_frame_; + pub_.publish(out); + } + + ros::NodeHandle nh_, pnh_; + ros::Subscriber sub_; + ros::Publisher pub_; + std::shared_ptr tf_buffer_; + std::shared_ptr tf_listener_; + + std::string output_frame_; + double min_range_ = 0.10, max_range_ = 25.0; +}; + +} // namespace perception_3d + +PLUGINLIB_EXPORT_CLASS(perception_3d::ScanToCloudNodelet, nodelet::Nodelet) diff --git a/src/robot_bringup/CMakeLists.txt b/src/robot_bringup/CMakeLists.txt new file mode 100644 index 0000000..0db76f2 --- /dev/null +++ b/src/robot_bringup/CMakeLists.txt @@ -0,0 +1,21 @@ +cmake_minimum_required(VERSION 3.0.2) +project(robot_bringup) + +find_package(catkin REQUIRED) + +catkin_package() + +# teleop co gioi han gia toc - chay duoc truc tiep bang python3, khong bat buoc +# phai build. Cai dat de dung duoc bang `rosrun robot_bringup teleop.py`. +catkin_install_python(PROGRAMS + scripts/teleop.py + DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +) + +install(PROGRAMS scripts/start_mapping.sh + DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +) + +install(DIRECTORY urdf launch config rviz + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} +) diff --git a/src/robot_bringup/config/costmap_common.yaml b/src/robot_bringup/config/costmap_common.yaml new file mode 100644 index 0000000..c087d1d --- /dev/null +++ b/src/robot_bringup/config/costmap_common.yaml @@ -0,0 +1,69 @@ +# ============================================================= +# Tham so costmap dung chung cho local va global +# ============================================================= + +# Hinh chieu robot (m), trong base_footprint. Khop robot.urdf.xacro: +# than : x = -0.26 ... +0.14 (0.40 dai, lui -0.06), y = +-0.17 +# LiDAR : nho ra toi x = +0.28 +# banh : nho ra toi y = +-0.195 +# Footprint phai bao TOAN BO phan nho ra, khong chi than. +footprint: [[ 0.28, 0.20], + [ 0.28, -0.20], + [-0.27, -0.20], + [-0.27, 0.20]] +footprint_padding: 0.02 + +transform_tolerance: 0.5 + +# ============================================================= +# HAI NGUON VAT CAN - VAI TRO KHAC NHAU, KHONG THAY THE NHAU +# ============================================================= +obstacle_layer: + enabled: true + observation_sources: laser_scan camera_cloud + combination_method: 1 + + # ---- LiDAR 2D: xa, chinh xac, nhung CHI MOT MAT PHANG ---- + # Gan o z=0.20 nen no thay chan ban, chan ghe, tuong. + # KHONG thay: mat ban nho ra, vat thap duoi san, vat treo. + laser_scan: + sensor_frame: laser_link + data_type: LaserScan + topic: /scan + marking: true + clearing: true + obstacle_range: 6.0 + raytrace_range: 8.0 + inf_is_valid: true + + # ---- Camera 3D: gan, hep, nhung THAY CA KHOI ---- + # Day la thu bu vao dung diem mu cua LiDAR 2D. + # Cloud da duoc bu nghieng (gravity_align) nen o he quy chieu thang dung. + # + # min_obstacle_height 0.03 : bo diem tren san + # max_obstacle_height 1.10 : cao hon than robot mot chut, de bat mat ban + # nho ra va vat treo thap + # obstacle_range 3.5 : xa hon ~4m depth stereo baseline 55mm nhieu manh + camera_cloud: + sensor_frame: base_footprint + data_type: PointCloud2 + topic: /perception/cloud_aligned + marking: true + clearing: true + # Khop min_height cua gravity_align (0.06). Dat thap hon se lam SAN NHA + # bi danh dau thanh vat can va nhot robot lai - da mac loi nay. + min_obstacle_height: 0.06 + max_obstacle_height: 1.10 + obstacle_range: 3.5 + raytrace_range: 4.0 + +inflation_layer: + enabled: true + # Ban kinh robot ~0.33 (duong cheo footprint). Them le an toan cho nha hang + # dong nguoi: robot khong nen sat qua khach. + inflation_radius: 0.45 + cost_scaling_factor: 8.0 + +static_layer: + enabled: true + map_topic: /map diff --git a/src/robot_bringup/config/costmap_global.yaml b/src/robot_bringup/config/costmap_global.yaml new file mode 100644 index 0000000..035b2b1 --- /dev/null +++ b/src/robot_bringup/config/costmap_global.yaml @@ -0,0 +1,48 @@ +# ============================================================= +# Global costmap +# +# ⚠️ CHE DO HIEN TAI: CUA SO TRUOT, KHONG DUNG STATIC MAP +# +# Ly do: o giai doan nay CHUA CO BAN DO nao dang tin cay. +# - slam_core moi la passthrough (chua co scan matching, chua co mapping) +# - octomap chi chieu ra grid 2D tu cloud, KHONG phai bản do SLAM: +# khong scan matching, khong mo hinh cap nhat xac suat tinh chinh cho +# dieu huong. Da do: mau o chiem dung KHONG ON DINH giua hai lan chay +# cung mot canh tinh (0.8:100 1.0:100 1.5:0 -> 0.8:100 1.0:100 1.5:100), +# tuc nhieu chu khong phai hinh hoc. Global planner nhan ban do do se +# that bai that thuong. +# +# Dung octomap dung viec cua no: bieu dien VAT CAN 3D (/octomap_full -> +# voxel layer), khong phai lam ban do dieu huong. +# +# Cua so truot tren du lieu cam bien truc tiep la cau hinh DUNG cho robot +# chua co ban do: planner chi lap ke hoach trong pham vi thuc su quan sat duoc. +# +# ============ KHI NAO DOI LAI STATIC MAP ============ +# Khi GD3 (baseline Cartographer/RTAB-Map) hoac GD5 (slam_core + GTSAM) cho ra +# ban do that, doi lai: +# static_map: true +# rolling_window: false +# plugins: them {name: static_layer, type: "costmap_2d::StaticLayer"} +# va bo width/height (kich thuoc lay tu ban do). +# ============================================================= + +global_costmap: + global_frame: map + robot_base_frame: base_footprint + update_frequency: 2.0 + publish_frequency: 1.0 + transform_tolerance: 0.5 + + static_map: false + rolling_window: true + + # Du rong de chua duong di trong nha hang, van nhe cho IPC. + # LiDAR ToF tam 25m nhung obstacle_range da cat o 6m. + width: 16.0 + height: 16.0 + resolution: 0.05 + + plugins: + - {name: obstacle_layer, type: "costmap_2d::ObstacleLayer"} + - {name: inflation_layer, type: "costmap_2d::InflationLayer"} diff --git a/src/robot_bringup/config/costmap_global_static.yaml b/src/robot_bringup/config/costmap_global_static.yaml new file mode 100644 index 0000000..0359e4b --- /dev/null +++ b/src/robot_bringup/config/costmap_global_static.yaml @@ -0,0 +1,30 @@ +# ============================================================= +# Global costmap - BAN STATIC, dung khi DA CO ban do that +# +# Dung o che do localization (localization.launch), noi RTAB-Map da nap ban do +# tu database va publish /map on dinh. +# +# Khac ban cua so truot (costmap_global.yaml) o cho: planner nhin duoc TOAN BO +# ban do chu khong chi pham vi cam bien -> lap ke hoach duoc duong dai qua +# nhieu phong, di vong qua vat can lon. +# +# ⚠️ Chi dung file nay khi /map den tu 2D SLAM that (RTAB-Map). +# KHONG dung voi grid chieu tu octomap - da chung minh no khong on dinh +# (xem docs/SIM_VS_REAL.md muc 5). +# ============================================================= + +global_costmap: + global_frame: map + robot_base_frame: base_footprint + update_frequency: 1.0 + publish_frequency: 0.5 + transform_tolerance: 0.5 + + static_map: true + rolling_window: false + resolution: 0.05 + + plugins: + - {name: static_layer, type: "costmap_2d::StaticLayer"} + - {name: obstacle_layer, type: "costmap_2d::ObstacleLayer"} + - {name: inflation_layer, type: "costmap_2d::InflationLayer"} diff --git a/src/robot_bringup/config/costmap_local.yaml b/src/robot_bringup/config/costmap_local.yaml new file mode 100644 index 0000000..132353c --- /dev/null +++ b/src/robot_bringup/config/costmap_local.yaml @@ -0,0 +1,16 @@ +local_costmap: + global_frame: odom # local costmap bam odom -> muot, khong nhay + robot_base_frame: base_footprint + update_frequency: 5.0 + publish_frequency: 2.0 + transform_tolerance: 0.5 + + static_map: false + rolling_window: true + width: 6.0 + height: 6.0 + resolution: 0.05 + + plugins: + - {name: obstacle_layer, type: "costmap_2d::ObstacleLayer"} + - {name: inflation_layer, type: "costmap_2d::InflationLayer"} diff --git a/src/robot_bringup/config/ekf_odom.yaml b/src/robot_bringup/config/ekf_odom.yaml new file mode 100644 index 0000000..915ca36 --- /dev/null +++ b/src/robot_bringup/config/ekf_odom.yaml @@ -0,0 +1,88 @@ +# ============================================================= +# robot_localization EKF - tang odometry nen +# +# Nhiem vu: fuse encoder + IMU thanh mot nguon odometry MUOT, TAN SO CAO, +# KHONG BAO GIO MU. Publish TF odom -> base_footprint. +# +# ============ PHAN CONG TF (quan trong) ============ +# odom -> base_footprint : node NAY (muot, lien tuc, co drift) +# map -> odom : slam_core (sua drift, DUOC PHEP nhay) +# +# Hai node cung publish mot canh TF la loi kinh dien va rat kho debug - +# TF khong bao loi, no chi cho ra ket qua nhay lung tung. +# +# ============ VI SAO two_d_mode = true ============ +# Kien truc 2.5D: pose la SE(2). z/roll/pitch bi ep ve 0 o day vi khong cam +# bien nao trong bo nay quan sat duoc chung mot cach tin cay: +# - Encoder, LiDAR 2D : khong noi gi ve z +# - IMU : z troi tu do (tich phan accel hai lan) +# Uoc luong chung tu do chi mo cua cho drift, khong them thong tin that. +# +# Roll/pitch VAN duoc dung - nhung o perception_3d/gravity_align_nodelet, +# noi chung duoc DO tu trong luc de bu nghieng cho point cloud. +# ============================================================= + +ekf_odom: + frequency: 50 + sensor_timeout: 0.2 + two_d_mode: true + + map_frame: map + odom_frame: odom + base_link_frame: base_footprint + world_frame: odom # che do odometry: KHONG dung map o day + + publish_tf: true + transform_time_offset: 0.0 + print_diagnostics: true + + # ---------------- Encoder ---------------- + # Fuse VAN TOC, khong fuse pose tuyet doi: tich phan pose hai lan trong + # filter lam sai so cong don nhanh hon. + # Thu tu 15 phan tu: + # x, y, z, roll, pitch, yaw, vx, vy, vz, vroll, vpitch, vyaw, ax, ay, az + odom0: /odom + odom0_config: [false, false, false, + false, false, false, + true, false, false, # vx (vy = false: robot vi sai khong truot ngang) + false, false, true, # vyaw + false, false, false] + odom0_differential: false + odom0_relative: false + odom0_queue_size: 10 + # Cho phep wheel_odom_node dieu chinh do tin cay khi phat hien truot banh + odom0_nodelay: true + + # ---------------- IMU ---------------- + # CHI fuse van toc goc Z. KHONG fuse gia toc tuyen tinh: + # tren robot banh, accel nhieu manh do rung (san gach + banh cung) va co bias + # troi - dua vao thuong lam ket qua TE HON chu khong tot hon. + imu0: /imu/data_raw + imu0_config: [false, false, false, + false, false, false, + false, false, false, + false, false, true, # vyaw - gyro Z + false, false, false] + imu0_differential: false + imu0_relative: false + imu0_queue_size: 20 + imu0_remove_gravitational_acceleration: true + + # ---------------- Nhieu qua trinh ---------------- + # Duong cheo 15x15. Gia tri lon = "tin mo hinh it hon, tin do dac nhieu hon". + # ⚠️ Chinh lai sau khi co so lieu hieu chuan that. + process_noise_covariance: [0.05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0.05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0.06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0.03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0.03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0.06, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0.025, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0.025, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0.04, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.02, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.015] diff --git a/src/robot_bringup/config/move_base.yaml b/src/robot_bringup/config/move_base.yaml new file mode 100644 index 0000000..802bdf2 --- /dev/null +++ b/src/robot_bringup/config/move_base.yaml @@ -0,0 +1,75 @@ +# ============================================================= +# move_base - dieu huong +# +# Van toc CO Y giu thap: robot phuc vu chay giua khach hang, khong phai AGV +# trong kho. An toan va cam giac de chiu quan trong hon toc do. +# ============================================================= + +# ⚠️ KHONG bao key "move_base:" quanh nhung tham so nay. +# File duoc nap bang BEN TRONG , tuc da o +# trong namespace rieng /move_base/ roi. Them mot tang "move_base:" nua se +# thanh /move_base/move_base/... va TOAN BO tham so bi bo qua trong im lang. +# +# Da mac loi nay: recovery_behavior_enabled=false khong co tac dung, log van +# bao "Rotate recovery behavior started" - robot tu xoay tai cho giua nha hang. +controller_frequency: 10.0 +planner_frequency: 1.0 +controller_patience: 5.0 +planner_patience: 5.0 +oscillation_timeout: 10.0 +oscillation_distance: 0.2 + +base_global_planner: "navfn/NavfnROS" +base_local_planner: "base_local_planner/TrajectoryPlannerROS" + +# Hanh vi phuc hoi: robot phuc vu KHONG nen tu xoay tai cho giua nha hang +# dong nguoi khi bi ket - vua nguy hiem vua lam khach kho chiu. +# Tot hon la dung lai va bao nguoi van hanh. +recovery_behavior_enabled: false +clearing_rotation_allowed: false + +TrajectoryPlannerROS: + # ---- Van toc ---- + # ⚠️ Ha tu 0.5 xuong 0.35 m/s va gia toc tu 0.5 xuong 0.3 m/s^2. + # + # Ly do do duoc: khi tang toc gap tu dung yen len 0.5 m/s, banh TRUOT. + # slip_metric vot len 0.170 (nguong 0.15), va odometry bao da di 2.049m + # trong khi ground truth chi 1.736m - SAI SO 18%. + # Voi robot phuc vu do la chenh 31cm: khac biet giua dung canh ban va + # dung hut. + # + # 0.35 m/s cung phu hop hon voi ung dung: robot bung do an di giua khach + # khong nen chay 0.5 m/s. An toan va cam giac de chiu quan trong hon toc do. + # + # ⚠️ Day chi giam trieu chung. Nguyen nhan goc phai xu ly o GD2 bang + # hieu chuan UMBmark tren robot that (xem docs/ROADMAP.md). + max_vel_x: 0.35 + min_vel_x: 0.08 + max_vel_theta: 0.8 + min_vel_theta: -0.8 + min_in_place_vel_theta: 0.3 + + acc_lim_x: 0.3 + acc_lim_y: 0.0 + acc_lim_theta: 1.0 + + holonomic_robot: false + + # ---- Dung sai den dich ---- + # ⚠️ Voi robot phuc vu, REPEATABILITY quan trong hon do chinh xac tuyet doi: + # khach khong quan tam robot nghi minh o toa do nao, chi can no dung + # dung canh ban MOI LAN. Do bang slam_eval/repeatability.py. + xy_goal_tolerance: 0.10 + yaw_goal_tolerance: 0.15 + latch_xy_goal_tolerance: true + + # ---- Sinh quy dao ---- + sim_time: 2.0 + vx_samples: 8 + vtheta_samples: 20 + meter_scoring: true + + path_distance_bias: 32.0 + goal_distance_bias: 20.0 + occdist_scale: 0.05 + heading_lookahead: 0.325 diff --git a/src/robot_bringup/config/robot.yaml b/src/robot_bringup/config/robot.yaml new file mode 100644 index 0000000..0bde8fb --- /dev/null +++ b/src/robot_bringup/config/robot.yaml @@ -0,0 +1,33 @@ +# ============================================================= +# Thong so robot +# +# ⚠️ CAC GIA TRI HINH HOC PHAI KHOP robot_bringup/urdf/robot.urdf.xacro +# Sua mot ben thi phai sua ben kia. URDF dung cho TF/mo phong, +# file nay dung cho cac node doc tu param server. +# ============================================================= + +wheel_odom: + wheel_radius: 0.075 # m <- khop robot.urdf.xacro + wheel_separation: 0.36 # m <- khop robot.urdf.xacro + left_joint: left_wheel_joint + right_joint: right_wheel_joint + + odom_frame: odom + base_frame: base_footprint + + # ---- Phat hien truot banh ---- + # San nha hang co nuoc va dau mo. Banh truot thi encoder noi doi. + # Gyro Z khong bi anh huong -> so sanh hai nguon de phat hien. + slip_omega_threshold: 0.15 # rad/s - lech qua nguong nay thi nghi dang truot + slip_cov_multiplier: 100.0 # nhan covariance khi truot (khong vut du lieu, + # chi ha do tin cay) + imu_timeout: 0.5 + + # ---- Covariance co ban ---- + # ⚠️ PHAI hieu chuan bang UMBmark: chay hinh vuong 4x4m ca hai chieu, do lech, + # chinh lai wheel_radius trai/phai va wheel_separation. + # Buoc nay giam sai so odometry tu ~5% xuong ~1% - re nhat trong moi cai + # tien co the lam. + sigma_x: 0.02 # tren moi met di duoc + sigma_y: 0.02 + sigma_yaw: 0.02 # tren moi rad quay diff --git a/src/robot_bringup/launch/description.launch b/src/robot_bringup/launch/description.launch new file mode 100644 index 0000000..c250b46 --- /dev/null +++ b/src/robot_bringup/launch/description.launch @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/launch/localization.launch b/src/robot_bringup/launch/localization.launch new file mode 100644 index 0000000..fb1e1ca --- /dev/null +++ b/src/robot_bringup/launch/localization.launch @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/launch/mapping.launch b/src/robot_bringup/launch/mapping.launch new file mode 100644 index 0000000..cfeb353 --- /dev/null +++ b/src/robot_bringup/launch/mapping.launch @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/launch/nav.launch b/src/robot_bringup/launch/nav.launch new file mode 100644 index 0000000..980007c --- /dev/null +++ b/src/robot_bringup/launch/nav.launch @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/launch/odom.launch b/src/robot_bringup/launch/odom.launch new file mode 100644 index 0000000..38c8e20 --- /dev/null +++ b/src/robot_bringup/launch/odom.launch @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/launch/perception.launch b/src/robot_bringup/launch/perception.launch new file mode 100644 index 0000000..8b902e8 --- /dev/null +++ b/src/robot_bringup/launch/perception.launch @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/launch/robot.launch b/src/robot_bringup/launch/robot.launch new file mode 100644 index 0000000..918677e --- /dev/null +++ b/src/robot_bringup/launch/robot.launch @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/launch/rtabmap.launch b/src/robot_bringup/launch/rtabmap.launch new file mode 100644 index 0000000..bb228b0 --- /dev/null +++ b/src/robot_bringup/launch/rtabmap.launch @@ -0,0 +1,306 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/launch/sim.launch b/src/robot_bringup/launch/sim.launch new file mode 100644 index 0000000..b5d65c2 --- /dev/null +++ b/src/robot_bringup/launch/sim.launch @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/launch/slam.launch b/src/robot_bringup/launch/slam.launch new file mode 100644 index 0000000..ae09fb9 --- /dev/null +++ b/src/robot_bringup/launch/slam.launch @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/launch/teleop_joystick.launch b/src/robot_bringup/launch/teleop_joystick.launch new file mode 100644 index 0000000..19227a2 --- /dev/null +++ b/src/robot_bringup/launch/teleop_joystick.launch @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/package.xml b/src/robot_bringup/package.xml new file mode 100644 index 0000000..527090e --- /dev/null +++ b/src/robot_bringup/package.xml @@ -0,0 +1,36 @@ + + + robot_bringup + 0.1.0 + + URDF/TF, cau hinh tap trung va launch phan lop cho robot dich vu indoor. + Khong chua code - chi mo ta robot va cach khoi dong he thong. + + quangtrung + BSD + + catkin + + xacro + robot_state_publisher + joint_state_publisher + tf2_ros + rviz + + + robot_sim + robot_drivers + robot_safety + perception_3d + slam_core + + + robot_localization + move_base + map_server + + + rtabmap_slam + diff --git a/src/robot_bringup/rviz/map_view.rviz b/src/robot_bringup/rviz/map_view.rviz new file mode 100644 index 0000000..2cd84cd --- /dev/null +++ b/src/robot_bringup/rviz/map_view.rviz @@ -0,0 +1,132 @@ +Panels: + - Class: rviz/Displays + Name: Displays + Property Tree Widget: + Expanded: + - /Map1 + - /PoseGraph1 + - /Octomap3D1 + Splitter Ratio: 0.55 + Tree Height: 760 + - Class: rviz/Views + Name: Views + - Class: rviz/Tool Properties + Name: Tool Properties + +Visualization Manager: + Class: "" + Global Options: + Background Color: 48; 48; 48 + Fixed Frame: map + Frame Rate: 30 + Displays: + - Class: rviz/Grid + Name: Grid + Enabled: true + Cell Size: 1 + Plane Cell Count: 24 + Color: 90; 90; 90 + Alpha: 0.4 + + # Ban do 2D tu RTAB-Map. Day la thu chinh. + - Class: rviz/Map + Name: Map + Enabled: true + Topic: /map + Color Scheme: map + Draw Behind: true + Alpha: 0.9 + + # Do thi pose: node + LOOP CLOSURE. Cho nay dang nhin nhat. + - Class: rviz/MarkerArray + Name: PoseGraph + Enabled: true + Marker Topic: /rtabmap/mapGraph + Queue Size: 10 + + # Voxel 3D tu octomap (camera D410). Day la 3D duy nhat trong he thong - + # KHONG nam trong file .db cua RTAB-Map. + - Class: rviz/MarkerArray + Name: Octomap3D + Enabled: true + Marker Topic: /occupied_cells_vis_array + Queue Size: 10 + + - Class: rviz/RobotModel + Name: RobotModel + Enabled: true + Robot Description: robot_description + Alpha: 0.9 + + - Class: rviz/LaserScan + Name: LaserScan + Enabled: true + Topic: /scan + Size (m): 0.04 + Style: Points + Color: 255; 70; 70 + Color Transformer: FlatColor + Decay Time: 0 + + # Cloud da bu nghieng: LiDAR + camera gop lai + - Class: rviz/PointCloud2 + Name: CloudAligned + Enabled: false + Topic: /perception/cloud_aligned + Size (m): 0.02 + Style: Points + Color Transformer: AxisColor + Axis: Z + Decay Time: 0 + + # Scan LiDAR ghep theo do thi da toi uu (phang, z ~ 0.20) + - Class: rviz/PointCloud2 + Name: RtabmapCloud + Enabled: false + Topic: /rtabmap/cloud_map + Size (m): 0.03 + Style: Points + Color Transformer: FlatColor + Color: 90; 200; 220 + Decay Time: 0 + + - Class: rviz/TF + Name: TF + Enabled: false + Show Names: true + Show Axes: true + Show Arrows: false + Marker Scale: 0.35 + + - Class: rviz/Path + Name: GlobalPlan + Enabled: true + Topic: /move_base/NavfnROS/plan + Color: 60; 160; 255 + + Tools: + - Class: rviz/MoveCamera + - Class: rviz/Select + - Class: rviz/SetInitialPose + Topic: /initialpose + - Class: rviz/SetGoal + Topic: /move_base_simple/goal + + Views: + Current: + Class: rviz/Orbit + Name: Current View + Distance: 18 + Focal Point: + X: 3 + Y: 1 + Z: 0 + Pitch: 1.1 + Yaw: 1.5708 + Saved: ~ + +Window Geometry: + Height: 950 + Width: 1600 + Displays: + collapsed: false diff --git a/src/robot_bringup/rviz/slam.rviz b/src/robot_bringup/rviz/slam.rviz new file mode 100644 index 0000000..9ccdaea --- /dev/null +++ b/src/robot_bringup/rviz/slam.rviz @@ -0,0 +1,154 @@ +Panels: + - Class: rviz/Displays + Name: Displays + Property Tree Widget: + Expanded: + - /TF1 + - /LaserScan1 + - /CloudAligned1 + Splitter Ratio: 0.5 + Tree Height: 700 + - Class: rviz/Tool Properties + Name: Tool Properties + - Class: rviz/Views + Name: Views + +Visualization Manager: + Class: "" + Global Options: + Background Color: 48; 48; 48 + Fixed Frame: map + Frame Rate: 30 + Displays: + - Class: rviz/Grid + Name: Grid + Enabled: true + Cell Size: 1 + Plane Cell Count: 20 + Color: 100; 100; 100 + + - Class: rviz/RobotModel + Name: RobotModel + Enabled: true + Robot Description: robot_description + TF Prefix: "" + + - Class: rviz/TF + Name: TF + Enabled: true + Show Names: true + Show Axes: true + Show Arrows: false + Marker Scale: 0.3 + + # LiDAR 2D: xa va chinh xac, nhung CHI MOT MAT PHANG + - Class: rviz/LaserScan + Name: LaserScan + Enabled: true + Topic: /scan + Size (m): 0.03 + Style: Points + Color: 255; 60; 60 + Color Transformer: FlatColor + Decay Time: 0 + + # Cloud da bu nghieng: thay mat ban nho ra, vat thap, vat treo - + # nhung thu LaserScan o tren MU HOAN TOAN + - Class: rviz/PointCloud2 + Name: CloudAligned + Enabled: true + Topic: /perception/cloud_aligned + Size (m): 0.02 + Style: Points + Color Transformer: AxisColor + Axis: Z + Decay Time: 0 + + - Class: rviz/Map + Name: Map + Enabled: true + Topic: /map + Color Scheme: map + Draw Behind: true + + # ============ NHIN THAY PHAN "LOCALIZATION" CUA SLAM ============ + # Day la display quan trong nhat khi dang mapping, va truoc day THIEU. + # + # /rtabmap/mapGraph ve do thi pose: + # - chuoi diem noi lien tiep = quy dao robot (canh Neighbor) + # - duong TAT noi hai diem xa nhau trong quy dao = LOOP CLOSURE + # + # Luc khep vong, ca ban do giat mot cai roi thang ra - do la localization + # sua toan bo do thi cung luc. Khong co display nay thi khong thay duoc. + - Class: rviz/MarkerArray + Name: PoseGraph + Enabled: true + Marker Topic: /rtabmap/mapGraph + Queue Size: 10 + + # Scan LiDAR ghep theo do thi DA TOI UU. So no voi LaserScan (du lieu song, + # dat theo odom) se thay ro localization dang sua bao nhieu. + - Class: rviz/PointCloud2 + Name: RtabmapCloud + Enabled: false + Topic: /rtabmap/cloud_map + Size (m): 0.03 + Style: Points + Color Transformer: FlatColor + Color: 90; 200; 220 + Decay Time: 0 + + - Class: rviz/MarkerArray + Name: OctoMap + Enabled: false + Marker Topic: /occupied_cells_vis_array + + - Class: rviz/Odometry + Name: GroundTruth + Enabled: false + Topic: /ground_truth/odom + Keep: 1000 + Shape: + Color: 60; 255; 60 + Value: Arrow + Covariance: + Value: false + + - Class: rviz/Path + Name: GlobalPlan + Enabled: true + Topic: /move_base/NavfnROS/plan + Color: 60; 160; 255 + + - Class: rviz/Path + Name: LocalPlan + Enabled: true + Topic: /move_base/TrajectoryPlannerROS/local_plan + Color: 255; 255; 60 + + Tools: + - Class: rviz/MoveCamera + - Class: rviz/Select + - Class: rviz/SetInitialPose + Topic: /initialpose + - Class: rviz/SetGoal + Topic: /move_base_simple/goal + + Views: + Current: + Class: rviz/Orbit + Name: Current View + Distance: 14 + Focal Point: + X: 0 + Y: 0 + Z: 0 + Pitch: 0.9 + Yaw: 1.6 + Saved: ~ + +Window Geometry: + Height: 900 + Width: 1500 + Displays: + collapsed: false diff --git a/src/robot_bringup/scripts/start_mapping.sh b/src/robot_bringup/scripts/start_mapping.sh new file mode 100755 index 0000000..dbdf42e --- /dev/null +++ b/src/robot_bringup/scripts/start_mapping.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# +# start_mapping.sh - Chay mapping.launch MA KHONG BAO GIO xoa mat ban do cu. +# +# ============ VI SAO CAN FILE NAY ============ +# mapping.launch truyen --delete_db_on_start cho RTAB-Map. Do la dung: quet moi +# thi phai bat dau tu database rong. Nhung no xoa IM LANG, khong hoi gi ca. +# +# Da mat that: mot ban quet 483 node / 1184 link / 225 MB depth bi xoa sach chi +# vi chay lai lenh mapping voi cung database_path. +# +# Khong vá duoc o tang roslaunch: $(eval ...) chi co san list/dict/map/str/ +# float/int + env/optenv/find + math, KHONG co os, khong doc duoc file, va moi +# chuoi chua "__" deu bi tu choi. Nen phai chan o tang shell, chay TRUOC roslaunch. +# +# Cach lam: neu database da ton tai thi DOI TEN no thanh ban luu co dau thoi +# gian, roi moi chay. Khong hoi han, khong the mat du lieu. +# +# ============ DUNG ============ +# ./start_mapping.sh # world house, co 3D +# ./start_mapping.sh hospital # world khac +# ./start_mapping.sh house camera_3d:=false linear_update:=0.3 +# +# Moi tham so sau ten world duoc chuyen thang cho roslaunch. + +set -euo pipefail + +WS="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" +WORLD="${1:-house}" +shift || true + +# ---------- database_path: lay tu doi so neu co, khong thi suy ra tu world ---------- +DB="" +PASS=() +for a in "$@"; do + case "$a" in + database_path:=*) DB="${a#database_path:=}" ;; + *) PASS+=("$a") ;; + esac +done +[ -z "$DB" ] && DB="$WS/maps/map_${WORLD}.db" + +echo "==================================================================" +echo " workspace : $WS" +echo " world : $WORLD" +echo " database : $DB" +echo "==================================================================" + +# ---------- canh bao rac tu phien truoc ---------- +# Ctrl-Z chi DONG BANG roslaunch chu khong giet. Tien trinh dong bang van giu +# gzserver va /clock, lam moi phep do sau do treo. Da mat nhieu thoi gian vi cai nay. +STUCK="$(ps -eo pid,stat,args | awk '$2 ~ /^T/ && /roslaunch/ {print $1}' | wc -l)" +GZ="$(pgrep -c gzserver 2>/dev/null || true)" +if [ "$STUCK" -gt 0 ] || [ "${GZ:-0}" -gt 0 ]; then + echo + echo " ⚠️ CON RAC TU PHIEN TRUOC: $STUCK roslaunch dong bang, ${GZ:-0} gzserver" + echo " Don truoc khi chay tiep:" + echo " pkill -9 -f 'roslaunch robot_bringup'" + echo " pkill -9 -f gzserver; pkill -9 -f gzclient; pkill -9 -f rosmaster" + echo + read -r -p " Van chay tiep? [y/N] " ans + [ "${ans:-N}" = "y" ] || { echo " Da dung."; exit 1; } +fi + +# ---------- luu ban do cu ---------- +if [ -f "$DB" ]; then + SIZE="$(du -h "$DB" | cut -f1)" + BAK="${DB%.db}.$(date +%Y%m%d-%H%M%S).bak.db" + mv "$DB" "$BAK" + echo + echo " 💾 Ban do cu ($SIZE) DA DUOC LUU, khong bi xoa:" + echo " $BAK" + echo " Muon dung lai: mv '$BAK' '$DB'" +fi + +mkdir -p "$(dirname "$DB")" +echo +echo " ▶ Bat dau quet. Ctrl-C MOT LAN de dung (dung bam Ctrl-Z)." +echo + +exec roslaunch robot_bringup mapping.launch \ + world:="$WORLD" \ + database_path:="$DB" \ + "${PASS[@]}" diff --git a/src/robot_bringup/scripts/teleop.py b/src/robot_bringup/scripts/teleop.py new file mode 100755 index 0000000..d09b724 --- /dev/null +++ b/src/robot_bringup/scripts/teleop.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +""" +teleop - Lai robot bang ban phim, CO GIOI HAN GIA TOC. + +============ VI SAO KHONG DUNG teleop_twist_keyboard ============ +Goi chuan mac dinh 0.5 m/s va DOI TOC DO TUC THI (bam phim la nhay thang +len toc do dich). Da do hau qua tren robot nay: + + tang toc gap tu 0 len 0.5 m/s -> slip_metric = 0.170 (nguong 0.15) + -> odometry bao 2.05m, thuc te 1.74m + -> SAI SO 18% + +Lai map bang kieu do se cho ban do bi bien dang, vi RTAB-Map tin vao odometry +de khoi tao ICP. Ban do xay sai mot lan thi moi thu dung no deu sai theo. + +Node nay khac o hai diem: + - Mac dinh 0.20 m/s (robot phuc vu khong can nhanh hon) + - RAMP tuyen tinh toi toc do dich, gioi han boi acc_lim -> banh khong truot + +============ PHIM ============ + w / s tien / lui + a / d quay trai / phai + space dung ngay + + / - tang / giam toc do toi da + q thoat + +============ CHAY ============ + python3 src/robot_bringup/scripts/teleop.py + +Publish vao /cmd_vel de di QUA lop an toan (safety_monitor -> /cmd_vel_safe). +Khong publish thang vao /cmd_vel_safe tru khi dang test L1-L5 chua co safety. +""" + +import sys +import select +import termios +import tty + +import rospy +from geometry_msgs.msg import Twist + +HELP = """ + w/s = tien/lui a/d = quay space = dung + +/- = doi toc do q = thoat +""" + + +class Teleop(object): + def __init__(self): + self.topic = rospy.get_param('~topic', '/cmd_vel') + self.rate_hz = rospy.get_param('~rate', 20.0) + + # Mac dinh CO Y de thap - xem docstring. + self.max_lin = rospy.get_param('~max_linear', 0.20) + self.max_ang = rospy.get_param('~max_angular', 0.5) + + # Gioi han gia toc: day la diem khac biet chinh so voi teleop chuan. + self.acc_lin = rospy.get_param('~acc_linear', 0.25) # m/s^2 + self.acc_ang = rospy.get_param('~acc_angular', 1.0) # rad/s^2 + + # ⚠️ Giu lenh bao lau sau lan bam phim cuoi. + # KHONG duoc reset target ngay khi mot vong lap khong doc duoc phim: + # ban phim auto-repeat chi gui ~30 ky tu/giay va co do tre ~0.5s luc dau, + # trong khi vong lap chay 20Hz. Phan lon vong lap se khong thay phim, + # va toc do vua nhich len da bi keo ve 0 -> robot RUNG TAI CHO, + # nhin nhu khong phan hoi gi. + self.key_timeout = rospy.get_param('~key_timeout', 0.4) + + self.target_lin = 0.0 + self.target_ang = 0.0 + self.cur_lin = 0.0 + self.cur_ang = 0.0 + + self.pub = rospy.Publisher(self.topic, Twist, queue_size=1) + self.settings = termios.tcgetattr(sys.stdin) + + def get_key(self, timeout): + """Doc mot ky tu, khong chan. + + ⚠️ KHONG bat/tat raw mode o day. Terminal phai o raw mode LIEN TUC + trong suot vong lap (bat mot lan trong run(), tat trong finally). + + Loi da mac: bat raw -> select(timeout=0) -> tat raw, moi vong 20Hz. + Terminal chi o raw mode vai micro giay moi vong, con lai la cooked mode, + noi ky tu bi don vao bo dem DONG va chi nha ra khi bam Enter. + => phim 'w' gan nhu khong bao gio toi duoc chuong trinh, robot dung im + ma khong bao loi gi. + """ + r, _, _ = select.select([sys.stdin], [], [], timeout) + return sys.stdin.read(1) if r else '' + + def say(self, msg): + """In ra trong raw mode - can \\r\\n chu khong chi \\n.""" + sys.stdout.write(msg + "\r\n") + sys.stdout.flush() + + @staticmethod + def ramp(cur, target, limit, dt): + """Tien dan toi target, moi buoc khong vuot qua limit*dt.""" + step = limit * dt + if target > cur: + return min(cur + step, target) + if target < cur: + return max(cur - step, target) + return cur + + def run(self): + print(__doc__.split('============ PHIM ============')[0]) + print(HELP) + print(" Topic: %s toc do toi da: %.2f m/s, %.2f rad/s" + % (self.topic, self.max_lin, self.max_ang)) + print("") + + rate = rospy.Rate(self.rate_hz) + dt = 1.0 / self.rate_hz + last_key = rospy.Time.now() + + try: + # Bat raw mode MOT LAN va giu nguyen - xem ghi chu trong get_key(). + tty.setraw(sys.stdin.fileno()) + + while not rospy.is_shutdown(): + k = self.get_key(0.0) + + if k in ('w', 's', 'a', 'd'): + last_key = rospy.Time.now() + + if k == 'w': + self.target_lin = self.max_lin + elif k == 's': + self.target_lin = -self.max_lin + elif k == 'a': + self.target_ang = self.max_ang + elif k == 'd': + self.target_ang = -self.max_ang + elif k == ' ': + self.target_lin = 0.0 + self.target_ang = 0.0 + # Dung NGAY, khong ramp - day la lenh an toan + self.cur_lin = 0.0 + self.cur_ang = 0.0 + elif k == '+' or k == '=': + self.max_lin = min(self.max_lin + 0.05, 0.5) + self.max_ang = min(self.max_ang + 0.1, 1.0) + self.say(" toc do toi da: %.2f m/s, %.2f rad/s" + % (self.max_lin, self.max_ang)) + elif k == '-' or k == '_': + self.max_lin = max(self.max_lin - 0.05, 0.05) + self.max_ang = max(self.max_ang - 0.1, 0.1) + self.say(" toc do toi da: %.2f m/s, %.2f rad/s" + % (self.max_lin, self.max_ang)) + elif k == 'q' or k == '\x03': # q hoac Ctrl-C + break + + # Chi ve 0 khi KHONG co phim nao trong key_timeout - xem __init__. + if (rospy.Time.now() - last_key).to_sec() > self.key_timeout: + self.target_lin = 0.0 + self.target_ang = 0.0 + + self.cur_lin = self.ramp(self.cur_lin, self.target_lin, self.acc_lin, dt) + self.cur_ang = self.ramp(self.cur_ang, self.target_ang, self.acc_ang, dt) + + t = Twist() + t.linear.x = self.cur_lin + t.angular.z = self.cur_ang + self.pub.publish(t) + + sys.stdout.write("\r v=%+5.2f m/s w=%+5.2f rad/s (toi da %.2f) " + % (self.cur_lin, self.cur_ang, self.max_lin)) + sys.stdout.flush() + rate.sleep() + finally: + self.pub.publish(Twist()) + termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.settings) + print("\n Da dung.") + + +if __name__ == '__main__': + rospy.init_node('teleop', anonymous=True) + try: + Teleop().run() + except rospy.ROSInterruptException: + pass diff --git a/src/robot_bringup/urdf/robot.urdf.xacro b/src/robot_bringup/urdf/robot.urdf.xacro new file mode 100644 index 0000000..db99072 --- /dev/null +++ b/src/robot_bringup/urdf/robot.urdf.xacro @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0.00.0 + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/urdf/sensors.xacro b/src/robot_bringup/urdf/sensors.xacro new file mode 100644 index 0000000..d2fc596 --- /dev/null +++ b/src/robot_bringup/urdf/sensors.xacro @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_drivers/CMakeLists.txt b/src/robot_drivers/CMakeLists.txt new file mode 100644 index 0000000..9e71714 --- /dev/null +++ b/src/robot_drivers/CMakeLists.txt @@ -0,0 +1,37 @@ +cmake_minimum_required(VERSION 3.0.2) +project(robot_drivers) + +add_compile_options(-std=c++14) + +find_package(catkin REQUIRED COMPONENTS + roscpp + rospy + sensor_msgs + nav_msgs + std_msgs + tf2 + tf2_ros +) + +catkin_package( + CATKIN_DEPENDS roscpp rospy sensor_msgs nav_msgs std_msgs tf2 tf2_ros +) + +include_directories(${catkin_INCLUDE_DIRS}) + +add_executable(wheel_odom_node src/wheel_odom_node.cpp) +target_link_libraries(wheel_odom_node ${catkin_LIBRARIES}) +add_dependencies(wheel_odom_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + +catkin_install_python(PROGRAMS + scripts/imu_bridge_node.py + DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +) + +install(TARGETS wheel_odom_node + RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +) + +install(DIRECTORY launch config + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} +) diff --git a/src/robot_drivers/launch/drivers.launch b/src/robot_drivers/launch/drivers.launch new file mode 100644 index 0000000..f5bb316 --- /dev/null +++ b/src/robot_drivers/launch/drivers.launch @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_drivers/launch/imu_bridge.launch b/src/robot_drivers/launch/imu_bridge.launch new file mode 100644 index 0000000..a8ef01c --- /dev/null +++ b/src/robot_drivers/launch/imu_bridge.launch @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/robot_drivers/launch/richbeam.launch b/src/robot_drivers/launch/richbeam.launch new file mode 100644 index 0000000..75cc89f --- /dev/null +++ b/src/robot_drivers/launch/richbeam.launch @@ -0,0 +1,46 @@ + + + + + + + + + + + + diff --git a/src/robot_drivers/package.xml b/src/robot_drivers/package.xml new file mode 100644 index 0000000..c0ec4f8 --- /dev/null +++ b/src/robot_drivers/package.xml @@ -0,0 +1,23 @@ + + + robot_drivers + 0.1.0 + + Driver phan cung: odometry banh xe (chay chung ca sim va that), + cau noi IMU/barometer tu MCU, va wrapper cho LiDAR RICHBEAM. + + quangtrung + BSD + + catkin + + roscpp + rospy + sensor_msgs + nav_msgs + std_msgs + tf2 + tf2_ros + + python3-serial + diff --git a/src/robot_drivers/scripts/imu_bridge_node.py b/src/robot_drivers/scripts/imu_bridge_node.py new file mode 100644 index 0000000..e4b716e --- /dev/null +++ b/src/robot_drivers/scripts/imu_bridge_node.py @@ -0,0 +1,277 @@ +#!/usr/bin/env python3 +""" +imu_bridge - Cau noi giua MCU (ICM-42688-P + BMP390) va ROS. + +============ VAN DE DONG BO THOI GIAN ============ +D410 KHONG co IMU tich hop (`Imu Type: IMU_Unknown`), nen ta phai dung IMU roi +tren mot board khac, day khac, dong ho khac. KHONG CO hardware sync. + +Neu gan timestamp bang rospy.Time.now() luc nhan duoc byte tu serial, ta se +cong vao do tre cua: buffer UART + buffer kernel + lich CPU. Jitter 10-50ms. +Voi factor graph, lech 5ms da du gay drift dang ke. + +Giai phap: MCU gan timestamp NGAY LUC LAY MAU (micros()), roi host uoc luong +quan he giua dong ho MCU va dong ho ROS bang handshake ping-pong: + + host: ghi t_send -> gui ping -> MCU tra ve mcu_micros -> host ghi t_recv + + RTT = t_recv - t_send + offset = (t_send + t_recv)/2 - mcu_time (gia dinh do tre doi xung) + +Lay nhieu mau, GIU LAI cac mau RTT NHO NHAT (it bi nhieu boi lich CPU), roi +fit tuyen tinh de bat ca do lech (offset) LAN do troi tan so thach anh (skew). +Day la nguyen ly cua Cristian's algorithm / NTP. + +============ GIAO THUC SERIAL ============ +MCU -> host (text, moi dong mot ban ghi): + I,,,,,,, IMU (rad/s, m/s^2) + B,,, Baro + P,, Pong (tra loi ping) + +host -> MCU: + p, Ping + +============ KHI CHUA CO PHAN CUNG ============ +Node se log WARN va idle, KHONG crash. Dung nguyen tac: thieu phan cung thi +bao dong, khong lam sap he thong. +""" + +import collections + +import rospy +from sensor_msgs.msg import Imu, FluidPressure, Temperature + +try: + import serial + HAVE_SERIAL = True +except ImportError: + HAVE_SERIAL = False + + +class ClockSync(object): + """Uoc luong: host_time = skew * mcu_time + offset. + + Chi giu cac mau co RTT nho nhat - mau RTT lon bi nhieu boi lich CPU va + buffer, dung chung se lam hong uoc luong. + """ + + def __init__(self, window=64, keep_best=16): + self.samples = collections.deque(maxlen=window) # (rtt, mcu_s, host_s) + self.keep_best = keep_best + self.skew = 1.0 + self.offset = None + + def add(self, mcu_s, t_send, t_recv): + rtt = t_recv - t_send + host_s = 0.5 * (t_send + t_recv) # gia dinh do tre doi xung + self.samples.append((rtt, mcu_s, host_s)) + self._fit() + + def _fit(self): + if len(self.samples) < 2: + return + + best = sorted(self.samples, key=lambda s: s[0])[:self.keep_best] + if len(best) < 2: + return + + n = float(len(best)) + sx = sum(s[1] for s in best) + sy = sum(s[2] for s in best) + sxx = sum(s[1] * s[1] for s in best) + sxy = sum(s[1] * s[2] for s in best) + + denom = n * sxx - sx * sx + if abs(denom) < 1e-12: + # Cac mau qua gan nhau ve thoi gian -> chua uoc luong duoc skew + self.offset = (sy - sx) / n + self.skew = 1.0 + return + + self.skew = (n * sxy - sx * sy) / denom + self.offset = (sy - self.skew * sx) / n + + # Skew phai rat gan 1.0 (thach anh lech vai chuc ppm). + # Lech nhieu = du lieu rac, bo qua ket qua fit. + if abs(self.skew - 1.0) > 1e-3: + rospy.logwarn_throttle(30.0, + 'imu_bridge: skew bat thuong (%.6f), bo qua. Kiem tra giao thuc MCU.', + self.skew) + self.skew = 1.0 + self.offset = (sy - sx) / n + + @property + def ready(self): + return self.offset is not None + + def to_ros(self, mcu_s): + """Doi thoi gian MCU (giay) sang rospy.Time.""" + if not self.ready: + return rospy.Time.now() + return rospy.Time.from_sec(self.skew * mcu_s + self.offset) + + +class ImuBridge(object): + def __init__(self): + self.port = rospy.get_param('~port', '/dev/ttyACM0') + self.baud = rospy.get_param('~baud', 921600) + self.frame_id = rospy.get_param('~frame_id', 'imu_link') + self.ping_period = rospy.get_param('~ping_period', 1.0) # s + + # Phuong sai - CAP NHAT sau khi chay allan_variance_ros tren chip that. + self.gyro_var = rospy.get_param('~gyro_variance', 4.9e-4 ** 2) + self.accel_var = rospy.get_param('~accel_variance', 6.9e-3 ** 2) + + self.imu_pub = rospy.Publisher('imu/data_raw', Imu, queue_size=100) + self.baro_pub = rospy.Publisher('baro/pressure', FluidPressure, queue_size=10) + self.temp_pub = rospy.Publisher('baro/temperature', Temperature, queue_size=10) + + self.clock = ClockSync() + self.ser = None + self.ping_seq = 0 + self.pending_ping = {} # seq -> t_send + + def open_serial(self): + if not HAVE_SERIAL: + rospy.logwarn('imu_bridge: thieu python3-serial. ' + 'Cai: sudo apt install python3-serial') + return False + try: + self.ser = serial.Serial(self.port, self.baud, timeout=0.1) + rospy.loginfo('imu_bridge: da mo %s @ %d baud', self.port, self.baud) + return True + except (serial.SerialException, OSError) as e: + rospy.logwarn('imu_bridge: khong mo duoc %s (%s)', self.port, e) + return False + + # ---------------- Xu ly tung dong ---------------- + + def handle_imu(self, parts): + if len(parts) < 8: + return + mcu_s = float(parts[1]) * 1e-6 + gx, gy, gz = float(parts[2]), float(parts[3]), float(parts[4]) + ax, ay, az = float(parts[5]), float(parts[6]), float(parts[7]) + + msg = Imu() + msg.header.stamp = self.clock.to_ros(mcu_s) + msg.header.frame_id = self.frame_id + + msg.angular_velocity.x = gx + msg.angular_velocity.y = gy + msg.angular_velocity.z = gz + msg.linear_acceleration.x = ax + msg.linear_acceleration.y = ay + msg.linear_acceleration.z = az + + # -1 o phan tu dau = "khong cung cap orientation". + # ICM-42688 la IMU 6 truc, khong co orientation tuyet doi. + # Huong trong luc (roll/pitch) do back-end suy ra tu accel. + msg.orientation_covariance[0] = -1.0 + for i in (0, 4, 8): + msg.angular_velocity_covariance[i] = self.gyro_var + msg.linear_acceleration_covariance[i] = self.accel_var + + self.imu_pub.publish(msg) + + def handle_baro(self, parts): + if len(parts) < 4: + return + mcu_s = float(parts[1]) * 1e-6 + stamp = self.clock.to_ros(mcu_s) + + p = FluidPressure() + p.header.stamp = stamp + p.header.frame_id = self.frame_id + p.fluid_pressure = float(parts[2]) + p.variance = 9.0 + self.baro_pub.publish(p) + + t = Temperature() + t.header.stamp = stamp + t.header.frame_id = self.frame_id + t.temperature = float(parts[3]) + self.temp_pub.publish(t) + + def handle_pong(self, parts, t_recv): + if len(parts) < 3: + return + mcu_s = float(parts[1]) * 1e-6 + seq = int(parts[2]) + t_send = self.pending_ping.pop(seq, None) + if t_send is None: + return + self.clock.add(mcu_s, t_send, t_recv) + + def send_ping(self): + if self.ser is None: + return + self.ping_seq = (self.ping_seq + 1) % 65536 + self.pending_ping[self.ping_seq] = rospy.Time.now().to_sec() + # Don ping cu chua duoc tra loi + if len(self.pending_ping) > 32: + self.pending_ping.clear() + try: + self.ser.write(('p,%d\n' % self.ping_seq).encode('ascii')) + except (serial.SerialException, OSError) as e: + rospy.logwarn_throttle(5.0, 'imu_bridge: loi ghi serial: %s', e) + + # ---------------- Vong chinh ---------------- + + def spin(self): + connected = self.open_serial() + + if not connected: + rospy.logwarn('imu_bridge: chua co phan cung -> chay khong tai (idle).') + rospy.logwarn('imu_bridge: trong mo phong, IMU do plugin Gazebo publish.') + rospy.spin() + return + + last_ping = rospy.Time.now() + warned_sync = False + + while not rospy.is_shutdown(): + now = rospy.Time.now() + if (now - last_ping).to_sec() >= self.ping_period: + self.send_ping() + last_ping = now + + try: + line = self.ser.readline() + except (serial.SerialException, OSError) as e: + rospy.logerr('imu_bridge: mat ket noi serial: %s', e) + break + + if not line: + continue + + t_recv = rospy.Time.now().to_sec() + try: + parts = line.decode('ascii', errors='ignore').strip().split(',') + except UnicodeDecodeError: + continue + if not parts or not parts[0]: + continue + + try: + kind = parts[0] + if kind == 'I': + if not self.clock.ready and not warned_sync: + rospy.logwarn('imu_bridge: chua dong bo dong ho xong - ' + 'timestamp tam dung gio host.') + warned_sync = True + self.handle_imu(parts) + elif kind == 'B': + self.handle_baro(parts) + elif kind == 'P': + self.handle_pong(parts, t_recv) + except (ValueError, IndexError): + rospy.logwarn_throttle(5.0, 'imu_bridge: dong khong hop le, bo qua.') + + +if __name__ == '__main__': + rospy.init_node('imu_bridge') + try: + ImuBridge().spin() + except rospy.ROSInterruptException: + pass diff --git a/src/robot_drivers/src/wheel_odom_node.cpp b/src/robot_drivers/src/wheel_odom_node.cpp new file mode 100644 index 0000000..4c06242 --- /dev/null +++ b/src/robot_drivers/src/wheel_odom_node.cpp @@ -0,0 +1,264 @@ +/** + * wheel_odom_node - Odometry banh xe + phat hien truot. + * + * ================== NODE NAY CHAY O CA HAI NOI ================== + * Dung MOT binary nay chay ca tren Gazebo va tren robot that. Khac biet duy + * nhat la AI publish /joint_states: + * + * Mo phong : gazebo_ros_diff_drive (publishWheelJointState=true) + * Robot that : firmware MCU doc encoder, doi tick -> radian + * + * Ca hai deu dung sensor_msgs/JointState voi cung ten joint. Nho vay logic + * odometry va slip detection duoc kiem chung trong sim la dung nguyen xi + * logic se chay ngoai doi - khong phai viet lai, khong phai test lai tu dau. + * + * ================== VI SAO CAN SLIP DETECTION ================== + * San nha hang co nuoc va dau mo. Banh truot thi encoder NOI DOI: no bao robot + * da di, thuc te robot dung yen hoac truot ngang. + * + * Gyro Z khong bi anh huong boi truot banh. So sanh hai nguon: + * + * omega_encoder = (v_phai - v_trai) / wheel_separation + * omega_gyro = imu.angular_velocity.z + * + * Lech nhieu => dang truot => NANG covariance de back-end (EKF/GTSAM) tu dong + * tin encoder it di. Khong vut bo du lieu, chi ha do tin cay - dung tinh than + * uoc luong xac suat. + * + * LUU Y: node nay KHONG publish TF odom->base_footprint. Viec do la cua + * robot_localization EKF (lop L2), noi encoder va IMU duoc fuse dung cach. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace +{ +double normalizeAngle(double a) +{ + while (a > M_PI) a -= 2.0 * M_PI; + while (a < -M_PI) a += 2.0 * M_PI; + return a; +} +} // namespace + +class WheelOdom +{ +public: + WheelOdom(ros::NodeHandle& nh, ros::NodeHandle& pnh) + { + // Hinh hoc - PHAI khop robot_bringup/urdf/robot.urdf.xacro + pnh.param("wheel_radius", wheel_radius_, 0.075); + pnh.param("wheel_separation", wheel_separation_, 0.36); + pnh.param("left_joint", left_joint_, "left_wheel_joint"); + pnh.param("right_joint", right_joint_, "right_wheel_joint"); + + pnh.param("odom_frame", odom_frame_, "odom"); + pnh.param("base_frame", base_frame_, "base_footprint"); + + // Slip detection + pnh.param("slip_omega_threshold", slip_omega_threshold_, 0.15); // rad/s + pnh.param("slip_cov_multiplier", slip_cov_multiplier_, 100.0); + pnh.param("imu_timeout", imu_timeout_, 0.5); // s + + // Covariance co ban. Cap nhat sau khi hieu chuan UMBmark. + pnh.param("sigma_x", sigma_x_, 0.02); // m moi m di duoc + pnh.param("sigma_y", sigma_y_, 0.02); + pnh.param("sigma_yaw", sigma_yaw_, 0.02); // rad moi rad quay + + odom_pub_ = nh.advertise("odom", 50); + slip_pub_ = nh.advertise("wheel_odom/slip_metric", 10); + + joint_sub_ = nh.subscribe("joint_states", 50, &WheelOdom::onJointState, this); + imu_sub_ = nh.subscribe("imu/data_raw", 100, &WheelOdom::onImu, this); + + ROS_INFO("wheel_odom: r=%.4f m, separation=%.4f m", wheel_radius_, wheel_separation_); + ROS_INFO("wheel_odom: cho /joint_states (joint '%s' va '%s') ...", + left_joint_.c_str(), right_joint_.c_str()); + ROS_WARN("wheel_odom: KHONG publish TF - do robot_localization EKF (lop L2) lo."); + } + +private: + void onImu(const sensor_msgs::Imu::ConstPtr& msg) + { + gyro_z_ = msg->angular_velocity.z; + last_imu_time_ = msg->header.stamp; + have_imu_ = true; + } + + void onJointState(const sensor_msgs::JointState::ConstPtr& msg) + { + double pos_l = 0.0, pos_r = 0.0; + bool found_l = false, found_r = false; + + for (size_t i = 0; i < msg->name.size(); ++i) + { + if (i >= msg->position.size()) + break; + if (msg->name[i] == left_joint_) { pos_l = msg->position[i]; found_l = true; } + if (msg->name[i] == right_joint_) { pos_r = msg->position[i]; found_r = true; } + } + + if (!found_l || !found_r) + { + ROS_WARN_THROTTLE(5.0, + "wheel_odom: khong thay joint banh xe trong /joint_states. " + "Kiem tra tham so left_joint/right_joint."); + return; + } + + const ros::Time now = msg->header.stamp; + + if (!initialized_) + { + prev_pos_l_ = pos_l; + prev_pos_r_ = pos_r; + prev_time_ = now; + initialized_ = true; + ROS_INFO("wheel_odom: da nhan joint_states, bat dau tich phan."); + return; + } + + const double dt = (now - prev_time_).toSec(); + if (dt <= 0.0) + { + // Nhay lui thoi gian: xay ra khi reset sim hoac phat lai rosbag. + ROS_WARN("wheel_odom: dt <= 0 (%.6f s) - reset trang thai tich phan.", dt); + prev_pos_l_ = pos_l; + prev_pos_r_ = pos_r; + prev_time_ = now; + return; + } + + // Quang duong tung banh. Chuan hoa delta de an toan voi ca hai kieu + // bao cao vi tri (unwrapped hoac wrapped ve [-pi, pi]). + const double d_l = normalizeAngle(pos_l - prev_pos_l_) * wheel_radius_; + const double d_r = normalizeAngle(pos_r - prev_pos_r_) * wheel_radius_; + + const double d_center = 0.5 * (d_l + d_r); + const double d_theta = (d_r - d_l) / wheel_separation_; + + // --------- Slip detection --------- + const double omega_encoder = d_theta / dt; + double slip_metric = 0.0; + bool slipping = false; + + const bool imu_fresh = have_imu_ && ((now - last_imu_time_).toSec() < imu_timeout_); + if (imu_fresh) + { + slip_metric = std::fabs(omega_encoder - gyro_z_); + slipping = slip_metric > slip_omega_threshold_; + if (slipping) + { + ROS_WARN_THROTTLE(2.0, + "wheel_odom: nghi TRUOT BANH - omega encoder %.3f vs gyro %.3f rad/s " + "(lech %.3f). Nang covariance.", omega_encoder, gyro_z_, slip_metric); + } + } + else + { + ROS_WARN_THROTTLE(10.0, + "wheel_odom: khong co IMU moi -> KHONG phat hien duoc truot banh. " + "Odometry dang chay 'mu'."); + } + + std_msgs::Float64 slip_msg; + slip_msg.data = slip_metric; + slip_pub_.publish(slip_msg); + + // --------- Tich phan (runge-kutta bac 2) --------- + const double theta_mid = theta_ + 0.5 * d_theta; + x_ += d_center * std::cos(theta_mid); + y_ += d_center * std::sin(theta_mid); + theta_ += d_theta; + theta_ = normalizeAngle(theta_); + + // --------- Publish --------- + nav_msgs::Odometry odom; + odom.header.stamp = now; + odom.header.frame_id = odom_frame_; + odom.child_frame_id = base_frame_; + + odom.pose.pose.position.x = x_; + odom.pose.pose.position.y = y_; + odom.pose.pose.position.z = 0.0; // 2.5D: robot o tren mat phang + + tf2::Quaternion q; + q.setRPY(0.0, 0.0, theta_); + odom.pose.pose.orientation.x = q.x(); + odom.pose.pose.orientation.y = q.y(); + odom.pose.pose.orientation.z = q.z(); + odom.pose.pose.orientation.w = q.w(); + + odom.twist.twist.linear.x = d_center / dt; + odom.twist.twist.angular.z = omega_encoder; + + // Covariance ty le voi quang duong - sai so odometry tich luy theo + // quang duong di duoc, khong phai theo thoi gian. + const double mult = slipping ? slip_cov_multiplier_ : 1.0; + const double travel = std::max(std::fabs(d_center), 1e-4); + const double turn = std::max(std::fabs(d_theta), 1e-4); + + const double cov_x = std::pow(sigma_x_ * travel, 2) * mult; + const double cov_y = std::pow(sigma_y_ * travel, 2) * mult; + const double cov_yaw = std::pow(sigma_yaw_ * turn, 2) * mult; + + // Chi so: 0=x, 7=y, 14=z, 21=roll, 28=pitch, 35=yaw + odom.pose.covariance[0] = cov_x; + odom.pose.covariance[7] = cov_y; + odom.pose.covariance[14] = 1e6; // z khong quan sat duoc + odom.pose.covariance[21] = 1e6; // roll -> IMU lo + odom.pose.covariance[28] = 1e6; // pitch -> IMU lo + odom.pose.covariance[35] = cov_yaw; + + odom.twist.covariance[0] = cov_x / (dt * dt); + odom.twist.covariance[7] = cov_y / (dt * dt); + odom.twist.covariance[14] = 1e6; + odom.twist.covariance[21] = 1e6; + odom.twist.covariance[28] = 1e6; + odom.twist.covariance[35] = cov_yaw / (dt * dt); + + odom_pub_.publish(odom); + + prev_pos_l_ = pos_l; + prev_pos_r_ = pos_r; + prev_time_ = now; + } + + // Tham so + double wheel_radius_, wheel_separation_; + std::string left_joint_, right_joint_, odom_frame_, base_frame_; + double slip_omega_threshold_, slip_cov_multiplier_, imu_timeout_; + double sigma_x_, sigma_y_, sigma_yaw_; + + // Trang thai + double x_ = 0.0, y_ = 0.0, theta_ = 0.0; + double prev_pos_l_ = 0.0, prev_pos_r_ = 0.0; + ros::Time prev_time_; + bool initialized_ = false; + + double gyro_z_ = 0.0; + ros::Time last_imu_time_; + bool have_imu_ = false; + + ros::Publisher odom_pub_, slip_pub_; + ros::Subscriber joint_sub_, imu_sub_; +}; + +int main(int argc, char** argv) +{ + ros::init(argc, argv, "wheel_odom_node"); + ros::NodeHandle nh; + ros::NodeHandle pnh("~"); + WheelOdom node(nh, pnh); + ros::spin(); + return 0; +} diff --git a/src/robot_safety/CMakeLists.txt b/src/robot_safety/CMakeLists.txt new file mode 100644 index 0000000..49e0032 --- /dev/null +++ b/src/robot_safety/CMakeLists.txt @@ -0,0 +1,31 @@ +cmake_minimum_required(VERSION 3.0.2) +project(robot_safety) + +add_compile_options(-std=c++14) + +find_package(catkin REQUIRED COMPONENTS + roscpp + geometry_msgs + sensor_msgs + std_msgs + std_srvs +) + +catkin_package( + CATKIN_DEPENDS roscpp geometry_msgs sensor_msgs std_msgs std_srvs +) + +include_directories(${catkin_INCLUDE_DIRS}) + +add_executable(safety_monitor_node src/safety_monitor_node.cpp) +target_link_libraries(safety_monitor_node ${catkin_LIBRARIES}) +add_dependencies(safety_monitor_node + ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + +install(TARGETS safety_monitor_node + RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +) + +install(DIRECTORY launch config + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} +) diff --git a/src/robot_safety/config/safety.yaml b/src/robot_safety/config/safety.yaml new file mode 100644 index 0000000..3a7dd4c --- /dev/null +++ b/src/robot_safety/config/safety.yaml @@ -0,0 +1,40 @@ +# ============================================================= +# Nguong an toan +# +# ⚠️ Cac gia tri o day la DIEM KHOI DAU. Phai chinh lai sau khi khao sat +# dia diem that (docs/HARDWARE.md - bang "vat can x cam bien nao thay"). +# ============================================================= + +safety_monitor: + # Khoang cach dung/giam toc theo LiDAR + stop_distance: 0.35 # m - dung tien + slow_distance: 0.80 # m - bat dau giam toc + slow_factor: 0.35 # he so nhan van toc khi trong vung giam toc + + # Chi xet quat phia truoc +-0.6 rad (~+-34 do). + # Vat can hai ben khong can dung khan cap - de local planner lo. + front_angle: 0.6 + + # ============ SIEU AM: PHAT HIEN KINH ============ + # ⚠️ QUAN TRONG: LiDAR ToF 905nm XUYEN QUA kinh. Depth IR cung vay. + # Sieu am (song am) phan xa tot tren kinh -> la cach DUY NHAT trong bo + # cam bien nay phat hien duoc cua kinh va guong. + # Sanh khach san va mat tien nha hang gan nhu luon co kinh. + # + # Danh sach rong = CHUA CO SIEU AM = KHONG PHAT HIEN DUOC KINH. + # Node se log WARN ro rang khi khoi dong. + ultrasonic_topics: [] + # Vi du khi da lap: + # ultrasonic_topics: + # - /ultrasonic/front_left + # - /ultrasonic/front_center + # - /ultrasonic/front_right + ultrasonic_stop_distance: 0.30 + + # Watchdog + sensor_timeout: 1.0 # s - mat du lieu cam bien thi dung + cmd_timeout: 0.5 # s - khong co lenh moi thi dung + + # Chan van toc tuyet doi + max_linear: 0.7 # m/s - robot phuc vu khong nen di nhanh hon + max_angular: 1.2 # rad/s diff --git a/src/robot_safety/launch/safety.launch b/src/robot_safety/launch/safety.launch new file mode 100644 index 0000000..6e31b9b --- /dev/null +++ b/src/robot_safety/launch/safety.launch @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + diff --git a/src/robot_safety/package.xml b/src/robot_safety/package.xml new file mode 100644 index 0000000..4b4543d --- /dev/null +++ b/src/robot_safety/package.xml @@ -0,0 +1,20 @@ + + + robot_safety + 0.1.0 + + Lop an toan doc lap: bumper, sieu am (phat hien kinh), gioi han van toc. + CO Y giu phu thuoc toi thieu - khong dung TF, point cloud, map hay SLAM - + de no van song khi cac node khac chet. + + quangtrung + BSD + + catkin + + roscpp + geometry_msgs + sensor_msgs + std_msgs + std_srvs + diff --git a/src/robot_safety/src/safety_monitor_node.cpp b/src/robot_safety/src/safety_monitor_node.cpp new file mode 100644 index 0000000..8395dd8 --- /dev/null +++ b/src/robot_safety/src/safety_monitor_node.cpp @@ -0,0 +1,285 @@ +/** + * safety_monitor - Lop an toan doc lap. + * + * ================== TAI SAO NODE NAY PHAI CHAY RIENG ================== + * Robot di chuyen giua khach hang that. Neu slam_core segfault hoac treo trong + * luc toi uu factor graph, kha nang DUNG cua robot PHAI van con. + * + * Gop chung mot process = mot segfault lam mat luon bumper va e-stop. + * Do khong phai chuyen kien truc dep - do la yeu cau an toan. + * + * ================== PHU THUOC TOI THIEU LA CO Y ================== + * Node nay CHI subscribe: /cmd_vel, /scan, /bumper, /ultrasonic/* + * Node nay KHONG dung: TF, point cloud, map, SLAM, move_base + * + * Cang it phu thuoc, cang it thu co the keo no chet theo. Neu no can TF thi + * TF hong se lam hong an toan - dung dieu ta muon tranh. + * + * ================== 3 LOP BAO VE ================== + * 1. Sieu am -> KINH va GUONG. LiDAR ToF 905nm va depth IR deu XUYEN QUA kinh. + * Day la cach duy nhat phat hien cua kinh. Khong thuat toan + * SLAM nao giai duoc viec nay. + * 2. LiDAR -> vat can phia truoc trong tam quet + * 3. Bumper -> chan cuoi, bit vung mu Min-Z ~22cm ma camera khong thay + * + * Nghiem thu bat buoc: + * rosnode kill /slam_core -> safety_monitor VAN SONG va van chan duoc + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +class SafetyMonitor +{ +public: + SafetyMonitor(ros::NodeHandle& nh, ros::NodeHandle& pnh) + { + pnh.param("stop_distance", stop_distance_, 0.35); + pnh.param("slow_distance", slow_distance_, 0.80); + pnh.param("slow_factor", slow_factor_, 0.35); + + // Chi xet quat phia truoc - vat can hai ben khong can dung khan cap + pnh.param("front_angle", front_angle_, 0.6); // rad, +- + + pnh.param("ultrasonic_stop_distance", us_stop_distance_, 0.30); + pnh.param("sensor_timeout", sensor_timeout_, 1.0); + pnh.param("cmd_timeout", cmd_timeout_, 0.5); + pnh.param("max_linear", max_linear_, 0.7); + pnh.param("max_angular", max_angular_, 1.2); + + std::vector us_topics; + pnh.param("ultrasonic_topics", us_topics, std::vector()); + + cmd_pub_ = nh.advertise("cmd_vel_safe", 1); + status_pub_ = nh.advertise("safety/status", 1, true); + + cmd_sub_ = nh.subscribe("cmd_vel", 1, &SafetyMonitor::onCmd, this); + scan_sub_ = nh.subscribe("scan", 1, &SafetyMonitor::onScan, this); + bumper_sub_ = nh.subscribe("bumper", 1, &SafetyMonitor::onBumper, this); + + for (const auto& t : us_topics) + { + us_subs_.push_back(nh.subscribe( + t, 1, boost::bind(&SafetyMonitor::onRange, this, _1, t))); + ROS_INFO("safety_monitor: theo doi sieu am '%s'", t.c_str()); + } + if (us_topics.empty()) + { + ROS_WARN("safety_monitor: CHUA CAU HINH SIEU AM."); + ROS_WARN("safety_monitor: => KHONG phat hien duoc CUA KINH / GUONG."); + ROS_WARN("safety_monitor: LiDAR ToF va depth IR deu xuyen qua kinh."); + } + + reset_srv_ = nh.advertiseService("safety/reset", &SafetyMonitor::onReset, this); + estop_srv_ = nh.advertiseService("safety/estop", &SafetyMonitor::onEstop, this); + + timer_ = nh.createTimer(ros::Duration(0.05), &SafetyMonitor::onTimer, this); + + ROS_INFO("safety_monitor: stop=%.2fm slow=%.2fm us_stop=%.2fm", + stop_distance_, slow_distance_, us_stop_distance_); + publishStatus("OK"); + } + +private: + void onCmd(const geometry_msgs::Twist::ConstPtr& msg) + { + last_cmd_ = *msg; + last_cmd_time_ = ros::Time::now(); + have_cmd_ = true; + } + + void onScan(const sensor_msgs::LaserScan::ConstPtr& msg) + { + double min_front = std::numeric_limits::infinity(); + + for (size_t i = 0; i < msg->ranges.size(); ++i) + { + const double a = msg->angle_min + i * msg->angle_increment; + if (std::fabs(a) > front_angle_) + continue; + const double r = msg->ranges[i]; + if (!std::isfinite(r) || r < msg->range_min || r > msg->range_max) + continue; + min_front = std::min(min_front, static_cast(r)); + } + + scan_min_front_ = min_front; + last_scan_time_ = ros::Time::now(); + have_scan_ = true; + } + + void onBumper(const std_msgs::Bool::ConstPtr& msg) + { + if (msg->data && !bumper_latched_) + { + bumper_latched_ = true; + ROS_ERROR("safety_monitor: BUMPER KICH HOAT - dung va chot. " + "Goi /safety/reset de bo chot."); + } + last_bumper_time_ = ros::Time::now(); + have_bumper_ = true; + } + + void onRange(const sensor_msgs::Range::ConstPtr& msg, const std::string& topic) + { + if (std::isfinite(msg->range) && msg->range >= msg->min_range) + us_ranges_[topic] = msg->range; + else + us_ranges_[topic] = std::numeric_limits::infinity(); + last_us_time_ = ros::Time::now(); + } + + bool onReset(std_srvs::Trigger::Request&, std_srvs::Trigger::Response& res) + { + bumper_latched_ = false; + estop_ = false; + res.success = true; + res.message = "Da bo chot an toan."; + ROS_WARN("safety_monitor: an toan da duoc RESET bang tay."); + return true; + } + + bool onEstop(std_srvs::Trigger::Request&, std_srvs::Trigger::Response& res) + { + estop_ = true; + res.success = true; + res.message = "E-STOP kich hoat."; + ROS_ERROR("safety_monitor: E-STOP kich hoat bang tay."); + return true; + } + + void publishStatus(const std::string& s) + { + if (s == last_status_) + return; + last_status_ = s; + std_msgs::String msg; + msg.data = s; + status_pub_.publish(msg); + } + + void onTimer(const ros::TimerEvent&) + { + const ros::Time now = ros::Time::now(); + geometry_msgs::Twist out; // mac dinh = dung yen + + // --- Chot cung --- + if (estop_ || bumper_latched_) + { + cmd_pub_.publish(out); + publishStatus(estop_ ? "ESTOP" : "BUMPER"); + return; + } + + // --- Watchdog lenh dieu khien --- + if (!have_cmd_ || (now - last_cmd_time_).toSec() > cmd_timeout_) + { + cmd_pub_.publish(out); + publishStatus("NO_CMD"); + return; + } + + // --- Sieu am: kinh va guong --- + double us_min = std::numeric_limits::infinity(); + for (const auto& kv : us_ranges_) + us_min = std::min(us_min, kv.second); + + if (!us_ranges_.empty() && (now - last_us_time_).toSec() > sensor_timeout_) + { + cmd_pub_.publish(out); + publishStatus("US_TIMEOUT"); + ROS_ERROR_THROTTLE(2.0, "safety_monitor: mat du lieu sieu am -> dung."); + return; + } + + if (us_min < us_stop_distance_) + { + cmd_pub_.publish(out); + publishStatus("US_BLOCKED"); + ROS_WARN_THROTTLE(1.0, + "safety_monitor: sieu am %.2fm (< %.2f) - co the la KINH. Dung.", + us_min, us_stop_distance_); + return; + } + + // --- LiDAR --- + if (have_scan_ && (now - last_scan_time_).toSec() > sensor_timeout_) + { + cmd_pub_.publish(out); + publishStatus("SCAN_TIMEOUT"); + ROS_ERROR_THROTTLE(2.0, "safety_monitor: mat du lieu LiDAR -> dung."); + return; + } + + out = last_cmd_; + std::string status = "OK"; + + if (have_scan_ && out.linear.x > 0.0) // chi xet khi dang tien + { + if (scan_min_front_ < stop_distance_) + { + out.linear.x = 0.0; + status = "SCAN_STOP"; + ROS_WARN_THROTTLE(1.0, "safety_monitor: vat can %.2fm phia truoc - dung tien.", + scan_min_front_); + } + else if (scan_min_front_ < slow_distance_) + { + out.linear.x *= slow_factor_; + status = "SCAN_SLOW"; + } + } + + // --- Chan van toc --- + out.linear.x = std::max(-max_linear_, std::min(max_linear_, out.linear.x)); + out.angular.z = std::max(-max_angular_, std::min(max_angular_, out.angular.z)); + + cmd_pub_.publish(out); + publishStatus(status); + } + + double stop_distance_, slow_distance_, slow_factor_, front_angle_; + double us_stop_distance_, sensor_timeout_, cmd_timeout_; + double max_linear_, max_angular_; + + geometry_msgs::Twist last_cmd_; + ros::Time last_cmd_time_, last_scan_time_, last_bumper_time_, last_us_time_; + bool have_cmd_ = false, have_scan_ = false, have_bumper_ = false; + + double scan_min_front_ = std::numeric_limits::infinity(); + std::map us_ranges_; + + bool bumper_latched_ = false; + bool estop_ = false; + std::string last_status_; + + ros::Publisher cmd_pub_, status_pub_; + ros::Subscriber cmd_sub_, scan_sub_, bumper_sub_; + std::vector us_subs_; + ros::ServiceServer reset_srv_, estop_srv_; + ros::Timer timer_; +}; + +int main(int argc, char** argv) +{ + ros::init(argc, argv, "safety_monitor"); + ros::NodeHandle nh; + ros::NodeHandle pnh("~"); + SafetyMonitor node(nh, pnh); + ros::spin(); + return 0; +} diff --git a/src/robot_sim/CMakeLists.txt b/src/robot_sim/CMakeLists.txt new file mode 100644 index 0000000..b234203 --- /dev/null +++ b/src/robot_sim/CMakeLists.txt @@ -0,0 +1,19 @@ +cmake_minimum_required(VERSION 3.0.2) +project(robot_sim) + +# Package nay khong co code C++ - chi co script Python, URDF plugin va world. +# Khong find_package COMPONENTS: chung deu la exec_depend, khong phai build_depend. +find_package(catkin REQUIRED) + +catkin_package() + +catkin_install_python(PROGRAMS + scripts/baro_sim.py + scripts/elevator_sim.py + scripts/sim_degradation.py + DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +) + +install(DIRECTORY urdf worlds launch config + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} +) diff --git a/src/robot_sim/config/sim_sensors.yaml b/src/robot_sim/config/sim_sensors.yaml new file mode 100644 index 0000000..dbcea23 --- /dev/null +++ b/src/robot_sim/config/sim_sensors.yaml @@ -0,0 +1,50 @@ +# ============================================================= +# Tham so mo phong cam bien +# +# Cac gia tri nhieu o day PHAI duoc cap nhat lai sau khi chay +# allan_variance_ros tren con IMU that va do dac cam bien that. +# Datasheet luon lac quan hon thuc te. +# ============================================================= + +baro_sim: + rate: 25.0 + frame_id: imu_link + ground_altitude: 15.0 # m so voi muc nuoc bien (Ha Noi ~15m) + noise_std: 3.0 # Pa - nhieu ngau nhien moi mau + drift_rate: 20.0 # Pa/gio - troi do thoi tiet. CO Y, dung bo di. + drift_period: 600.0 # s + +elevator_sim: + model_name: service_robot + # PHAI khop localization_ops/config/floors.yaml:floor_height, va khop world. + # Do tu hospital_two_floors / three_floors: model tap trung o z = 0, 3, 6. + floor_height: 3.0 # m moi tang + travel_speed: 1.0 # m/s + start_floor: 1 + landing_x: 0.0 + landing_y: 0.0 + +# ============================================================= +# sim_degradation - bom nhieu thuc te +# +# MAC DINH TAT (danh sach rong). Bat dan tung muc khi da qua duoc +# L4 (SLAM chay tot tren du lieu sach), de biet stack chiu duoc den dau. +# +# Gia tri tham khao cho phan cung that: +# D410 qua USB, Global Time bat -> offset ~0, jitter 5-15 ms +# LiDAR qua USB, driver gan stamp -> offset 10-30 ms, jitter 10-50 ms +# LiDAR qua Ethernet co timestamp -> offset ~0, jitter 1-5 ms +# IMU qua UART, MCU gan stamp -> offset ~0, jitter 1-3 ms +# ============================================================= +sim_degradation: + topics: [] + + # Vi du - bo comment de bat: + # + # topics: + # - {in: /scan, out: /scan_degraded, + # type: LaserScan, offset_ms: 20.0, jitter_ms: 30.0, drop: 0.01} + # - {in: /imu/data_raw, out: /imu/data_raw_degraded, + # type: Imu, offset_ms: 0.0, jitter_ms: 2.0, drop: 0.001} + # - {in: /camera/depth/image_rect_raw, out: /camera/depth/image_degraded, + # type: Image, offset_ms: 5.0, jitter_ms: 15.0, drop: 0.02} diff --git a/src/robot_sim/launch/gazebo.launch b/src/robot_sim/launch/gazebo.launch new file mode 100644 index 0000000..a807959 --- /dev/null +++ b/src/robot_sim/launch/gazebo.launch @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_sim/package.xml b/src/robot_sim/package.xml new file mode 100644 index 0000000..24a0121 --- /dev/null +++ b/src/robot_sim/package.xml @@ -0,0 +1,30 @@ + + + robot_sim + 0.1.0 + + Moi truong mo phong Gazebo cho robot dich vu indoor. + Publish CUNG topic/frame voi phan cung that (nguyen tac parity), cong them + ground truth tu plugin p3d de danh gia ATE/RPE - thu khong the co trong + nha hang that. + + quangtrung + BSD + + catkin + + gazebo_ros + gazebo_plugins + xacro + rospy + sensor_msgs + nav_msgs + geometry_msgs + gazebo_msgs + tf2_ros + + + + + + diff --git a/src/robot_sim/scripts/baro_sim.py b/src/robot_sim/scripts/baro_sim.py new file mode 100644 index 0000000..1356462 --- /dev/null +++ b/src/robot_sim/scripts/baro_sim.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +""" +Mo phong barometer BMP390. + +Gazebo khong co plugin barometer san, nen node nay lay do cao that tu +/ground_truth/odom roi doi sang ap suat theo cong thuc khi quyen. + +============ DIEM THIET KE QUAN TRONG ============ +Node nay CO Y bom vao mot thanh phan TROI CHAM (drift). Ly do: + + - Do phan giai BMP390 rat tot (~0.02 Pa) -> phat hien duoc thay doi vai cm + - NHUNG ap suat tuyet doi troi theo thoi tiet va nhiet do hang tram Pa/gio + + => KHONG BAO GIO duoc suy ra "dang o tang may" tu ap suat tuyet doi. + => Chi duoc dung CHENH LECH ngan han de phat hien DA DOI TANG. + => Xac dinh tang nao la viec cua AprilTag (localization_ops/floor_detector.py) + +Neu bo drift di, floor_detector se chay ngon trong sim roi that bai ngoai doi. +""" + +import math +import random + +import rospy +from nav_msgs.msg import Odometry +from sensor_msgs.msg import FluidPressure + +# Khi quyen tieu chuan +P0 = 101325.0 # Pa tai muc nuoc bien +T0 = 288.15 # K +L = 0.0065 # K/m - gradient nhiet do +G = 9.80665 +M = 0.0289644 +R = 8.31447 + + +def altitude_to_pressure(h_m, ground_altitude_m): + """Doi do cao (m) sang ap suat (Pa) theo cong thuc khi quyen tieu chuan.""" + h = ground_altitude_m + h_m + return P0 * math.pow(1.0 - (L * h) / T0, (G * M) / (R * L)) + + +class BaroSim(object): + def __init__(self): + self.rate_hz = rospy.get_param('~rate', 25.0) + self.frame_id = rospy.get_param('~frame_id', 'imu_link') + + # Do cao dia diem so voi muc nuoc bien (Ha Noi ~ 15m) + self.ground_altitude = rospy.get_param('~ground_altitude', 15.0) + + # Nhieu ngau nhien moi mau - BMP390 voi oversampling cao + self.noise_std = rospy.get_param('~noise_std', 3.0) # Pa + + # Troi cham do thoi tiet/nhiet do. Bat buoc phai co - xem docstring. + self.drift_rate = rospy.get_param('~drift_rate', 20.0) # Pa/gio + self.drift_period = rospy.get_param('~drift_period', 600.0) # s + + self.z = 0.0 + self.got_odom = False + self.t_start = None + + self.pub = rospy.Publisher('/baro/pressure', FluidPressure, queue_size=10) + rospy.Subscriber('/ground_truth/odom', Odometry, self.on_odom, queue_size=1) + + rospy.loginfo('baro_sim: cho /ground_truth/odom ...') + rospy.loginfo('baro_sim: drift %.1f Pa/gio - CO Y, dung suy tang tu ap suat tuyet doi', + self.drift_rate) + + def on_odom(self, msg): + self.z = msg.pose.pose.position.z + if not self.got_odom: + self.got_odom = True + rospy.loginfo('baro_sim: da nhan ground truth, bat dau publish') + + def current_drift(self, t_now): + """Troi cham dang sin - mo phong thay doi thoi tiet trong ngay.""" + if self.t_start is None: + self.t_start = t_now + dt = t_now - self.t_start + amplitude = self.drift_rate # Pa + return amplitude * math.sin(2.0 * math.pi * dt / self.drift_period) + + def spin(self): + rate = rospy.Rate(self.rate_hz) + while not rospy.is_shutdown(): + if self.got_odom: + now = rospy.Time.now() + p_true = altitude_to_pressure(self.z, self.ground_altitude) + p = p_true + self.current_drift(now.to_sec()) + p += random.gauss(0.0, self.noise_std) + + msg = FluidPressure() + msg.header.stamp = now + msg.header.frame_id = self.frame_id + msg.fluid_pressure = p + msg.variance = self.noise_std ** 2 + self.pub.publish(msg) + rate.sleep() + + +if __name__ == '__main__': + rospy.init_node('baro_sim') + try: + BaroSim().spin() + except rospy.ROSInterruptException: + pass diff --git a/src/robot_sim/scripts/elevator_sim.py b/src/robot_sim/scripts/elevator_sim.py new file mode 100644 index 0000000..36ffbbe --- /dev/null +++ b/src/robot_sim/scripts/elevator_sim.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +""" +Mo phong thang may de test logic da tang (localization_ops). + +============ BAI TOAN DA TANG KHONG PHAI 6-DoF SLAM ============ +Robot khach san phai di thang may. Day KHONG phai bai toan uoc luong pose 6-DoF - +no la bai toan QUAN LY DA BAN DO: + + - Moi tang = mot ban do rieng (map_floor_N), neo boi vi tri thang may + - Barometer phat hien CO doi tang + - AprilTag xac nhan tang NAO (cac tang khach san trong giong het nhau, + nen nhan dang bang hinh hoc/anh la khong du) + +Node nay di chuyen robot theo truc Z tu tu (khong teleport tuc thi) de: + 1. Barometer thay chuyen tiep that -> floor_detector duoc test dung + 2. Cam bien thay canh thay doi dot ngot -> test duoc viec chuyen map + + Su dung: + rostopic pub /elevator/goto_floor std_msgs/Int32 "data: 2" +""" + +import rospy +from std_msgs.msg import Int32, String +from gazebo_msgs.msg import ModelState +from gazebo_msgs.srv import GetModelState + + +class ElevatorSim(object): + def __init__(self): + self.model_name = rospy.get_param('~model_name', 'service_robot') + self.floor_height = rospy.get_param('~floor_height', 3.5) # m moi tang + self.travel_speed = rospy.get_param('~travel_speed', 1.0) # m/s + self.rate_hz = rospy.get_param('~rate', 50.0) + + # Vi tri sanh thang may tren moi tang (x, y) - robot xuat hien o day + self.landing_x = rospy.get_param('~landing_x', 0.0) + self.landing_y = rospy.get_param('~landing_y', 0.0) + + self.current_floor = rospy.get_param('~start_floor', 1) + self.target_floor = self.current_floor + self.moving = False + + self.state_pub = rospy.Publisher('/gazebo/set_model_state', ModelState, queue_size=1) + self.status_pub = rospy.Publisher('/elevator/status', String, queue_size=1, latch=True) + + rospy.Subscriber('/elevator/goto_floor', Int32, self.on_goto, queue_size=1) + + rospy.wait_for_service('/gazebo/get_model_state', timeout=30.0) + self.get_state = rospy.ServiceProxy('/gazebo/get_model_state', GetModelState) + + self.publish_status('idle') + rospy.loginfo('elevator_sim: san sang. Dang o tang %d.', self.current_floor) + rospy.loginfo('elevator_sim: rostopic pub /elevator/goto_floor std_msgs/Int32 "data: 2"') + + def publish_status(self, state): + self.status_pub.publish(String(data='%s:floor_%d' % (state, self.current_floor))) + + def on_goto(self, msg): + if self.moving: + rospy.logwarn('elevator_sim: dang di chuyen, bo qua yeu cau.') + return + if msg.data == self.current_floor: + rospy.loginfo('elevator_sim: da o tang %d roi.', msg.data) + return + self.target_floor = msg.data + self.moving = True + rospy.loginfo('elevator_sim: tang %d -> tang %d', self.current_floor, self.target_floor) + + def move(self): + """Di chuyen tu tu theo Z de barometer thay chuyen tiep that.""" + try: + cur = self.get_state(self.model_name, 'world') + except rospy.ServiceException as e: + rospy.logerr('elevator_sim: get_model_state loi: %s', e) + self.moving = False + return + + z_start = cur.pose.position.z + z_goal = (self.target_floor - 1) * self.floor_height + + self.publish_status('moving') + rate = rospy.Rate(self.rate_hz) + step = self.travel_speed / self.rate_hz + z = z_start + + while not rospy.is_shutdown(): + if abs(z_goal - z) < step: + z = z_goal + done = True + else: + z += step if z_goal > z else -step + done = False + + st = ModelState() + st.model_name = self.model_name + st.pose.position.x = self.landing_x + st.pose.position.y = self.landing_y + st.pose.position.z = z + st.pose.orientation.w = 1.0 + st.reference_frame = 'world' + self.state_pub.publish(st) + + if done: + break + rate.sleep() + + self.current_floor = self.target_floor + self.moving = False + self.publish_status('arrived') + rospy.loginfo('elevator_sim: da den tang %d (z=%.2f)', self.current_floor, z_goal) + + def spin(self): + rate = rospy.Rate(10) + while not rospy.is_shutdown(): + if self.moving: + self.move() + rate.sleep() + + +if __name__ == '__main__': + rospy.init_node('elevator_sim') + try: + ElevatorSim().spin() + except (rospy.ROSInterruptException, rospy.ROSException) as e: + rospy.logerr('elevator_sim: %s', e) diff --git a/src/robot_sim/scripts/sim_degradation.py b/src/robot_sim/scripts/sim_degradation.py new file mode 100644 index 0000000..be2ae14 --- /dev/null +++ b/src/robot_sim/scripts/sim_degradation.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +""" +Bom nhieu THUC TE vao topic mo phong. + +============ VI SAO CAN NODE NAY ============ +Gazebo dung /clock dong bo hoan hao: moi message deu co timestamp chinh xac +tuyet doi, khong bao gio drop, khong bao gio lech. + +Tren robot that: + - Camera cam USB, LiDAR cam Ethernet, IMU qua UART -> BA dong ho khac nhau + - Khong co hardware sync (D410 khong co IMU tich hop) + - Jitter timestamp 10-50ms la binh thuong + - Drop frame khi CPU ban + +Kinh nghiem nganh: ~80% loi SLAM thuc te den tu HIEU CHUAN SAI hoac DONG BO SAI, +khong phai tu thuat toan. Neu chi test tren sim sach, ban se tin nham rang +he thong da chay tot. + +Node nay cho phep bat dan tung muc do te di, de biet stack chiu duoc den dau +TRUOC KHI gap phan cung that. + + Vi du: + rosrun robot_sim sim_degradation.py \ + _topics:="[{in: /scan, out: /scan_degraded, type: LaserScan, jitter_ms: 30, drop: 0.02}]" +""" + +import random + +import rospy +from sensor_msgs.msg import LaserScan, Imu, Image, PointCloud2, FluidPressure +from nav_msgs.msg import Odometry + +TYPE_MAP = { + 'LaserScan': LaserScan, + 'Imu': Imu, + 'Image': Image, + 'PointCloud2': PointCloud2, + 'FluidPressure': FluidPressure, + 'Odometry': Odometry, +} + + +class Degrader(object): + """Mot kenh: nhan topic sach -> publish topic da lam te di.""" + + def __init__(self, cfg): + self.name = cfg['in'] + msg_type = TYPE_MAP[cfg['type']] + + # Lech co he thong (bias) - mo phong offset dong ho chua hieu chuan + self.offset_ms = float(cfg.get('offset_ms', 0.0)) + # Jitter ngau nhien quanh offset + self.jitter_ms = float(cfg.get('jitter_ms', 0.0)) + # Ty le drop message [0..1] + self.drop = float(cfg.get('drop', 0.0)) + + self.n_in = 0 + self.n_dropped = 0 + + self.pub = rospy.Publisher(cfg['out'], msg_type, queue_size=10) + self.sub = rospy.Subscriber(cfg['in'], msg_type, self.cb, queue_size=10) + + rospy.loginfo('sim_degradation: %s -> %s (offset %.1fms, jitter %.1fms, drop %.1f%%)', + cfg['in'], cfg['out'], self.offset_ms, self.jitter_ms, self.drop * 100) + + def cb(self, msg): + self.n_in += 1 + + if self.drop > 0.0 and random.random() < self.drop: + self.n_dropped += 1 + return + + if self.offset_ms != 0.0 or self.jitter_ms != 0.0: + shift = self.offset_ms + if self.jitter_ms > 0.0: + shift += random.gauss(0.0, self.jitter_ms) + try: + msg.header.stamp += rospy.Duration.from_sec(shift / 1000.0) + except AttributeError: + rospy.logwarn_once('sim_degradation: %s khong co header, bo qua jitter', self.name) + + self.pub.publish(msg) + + def report(self): + if self.n_in == 0: + return + rospy.loginfo('sim_degradation: %s - nhan %d, drop %d (%.1f%%)', + self.name, self.n_in, self.n_dropped, + 100.0 * self.n_dropped / self.n_in) + + +def main(): + rospy.init_node('sim_degradation') + + topics = rospy.get_param('~topics', []) + if not topics: + rospy.logwarn('sim_degradation: chua cau hinh ~topics, node khong lam gi.') + rospy.logwarn('Xem robot_sim/config/sim_sensors.yaml de biet vi du.') + + degraders = [Degrader(t) for t in topics] + + def on_shutdown(): + for d in degraders: + d.report() + + rospy.on_shutdown(on_shutdown) + rospy.spin() + + +if __name__ == '__main__': + try: + main() + except rospy.ROSInterruptException: + pass diff --git a/src/robot_sim/urdf/gazebo_sensors.xacro b/src/robot_sim/urdf/gazebo_sensors.xacro new file mode 100644 index 0000000..d25a7f4 --- /dev/null +++ b/src/robot_sim/urdf/gazebo_sensors.xacro @@ -0,0 +1,336 @@ + + + + + + + Gazebo/Grey + + + Gazebo/Blue + + + Gazebo/White + + + + + + + 1.0 + 1.0 + 1000000.0 + 100.0 + 0.001 + 0.1 + Gazebo/Black + + + + + + + + + 0.1 + 0.1 + + 300000.0 + + 800.0 + 0.001 + + 0.1 + Gazebo/DarkGrey + + + + + + + + + + false + true + 50 + left_wheel_joint + right_wheel_joint + ${wheel_separation} + ${2*wheel_radius} + 20 + 1.0 + + cmd_vel_safe + base_footprint + gazebo/odom_unused + odom + encoder + + + true + false + false + false + + + + + + + + 0 0 0 0 0 0 + false + 15 + + + + 960 + 1 + + -2.0944 + 2.0944 + + + + 0.05 + 30.0 + 0.01 + + + gaussian + 0.0 + 0.01 + + + + /scan + laser_link + + + + + + + + + true + 30.0 + + 1.204 + + 640 + 480 + L8 + + + 0.22 + 10.0 + + + gaussian + 0.0 + 0.007 + + + + true + 30.0 + camera + 0.055 + + + infra1/image_rect_raw + infra1/camera_info + depth/image_rect_raw + depth/camera_info + depth/points + + camera_depth_optical_frame + 0.22 + 10.0 + + 0.0 + 0.0 + 0.0 + 0.0 + 0.0 + + + + + + + + true + + true + 200 + false + + + 0.04.9e-4 + 1.0e-51.0e-6 + 0.04.9e-4 + 1.0e-51.0e-6 + 0.04.9e-4 + 1.0e-51.0e-6 + + + 0.06.9e-3 + 0.010.001 + 0.06.9e-3 + 0.010.001 + 0.06.9e-3 + 0.010.001 + + + + /imu/data_raw + imu_link + imu_link + 200.0 + 0.0 + false + + + + + + + + + true + 50.0 + base_footprint + /ground_truth/odom + world + 0.0 + 0 0 0 + 0 0 0 + + + + diff --git a/src/robot_sim/worlds/hospital.world b/src/robot_sim/worlds/hospital.world new file mode 100644 index 0000000..dd40542 --- /dev/null +++ b/src/robot_sim/worlds/hospital.world @@ -0,0 +1,1290 @@ + + + + 0 0 -9.8 + + 0.001 + 1 + 1000 + + + 0.6 0.6 0.6 1 + 0.4 0.4 0.4 1 + false + + + model://sun + + + model://ground_plane + 0 0 -0.1 0 -0 0 + + + + model://aws_robomaker_hospital_floor_01_floor + true + -0.001425 -0.014447 0 0 -0 0 + + + + + model://aws_robomaker_hospital_floor_01_walls + true + -0.013823 -0.013783 0 0 -0 0 + + + + + model://aws_robomaker_hospital_nursesstation_01 + true + 0 1.5 0 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + -1.50654 19.4813 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + 1.51134 19.487 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_car + true + -1.49587 19.35 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_car + true + 1.5407 19.35 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + -1.51 19.35 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + 1.52843 19.3627 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0216 -13.8069 0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + -11.022 -7.27757 0 0 -0 1.57907 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1417 -21.4039 0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1068 -17.8472 0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1374 -14.1551 0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0332 -17.61 0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0086 -21.7566 0 0 -0 1.55358 + + + + + model://CGMClassic + true + 11.1777 -18.4129 0 0 0 -3.13719 + + + + + model://StorageRack + true + 9.07005 -10.3582 -7.57769e+08 -2e-06 0 0 + + + + + model://CGMClassic + true + 11.1179 -14.6493 0 0 0 -3.13599 + + + + + model://Chair + true + -0.603067 -0.77859 -1e-05 0 0 -1.54998 + + + + + model://Chair + true + 0.626494 -0.743667 -0 0 1e-06 -1.53446 + + + + + model://Scrubs + true + -9.61916 -12.5112 0 0 0 -3.12353 + + + + + model://Scrubs + true + 0.054597 4.05849 0 0 -0 3.12413 + + + + + model://PatientWheelChair + true + -5.46091 1.23577 0 0 0 -1.54828 + + + + + model://Scrubs + true + -5.38513 1.82526 0 0 0 -1.63757 + + + + + model://WhiteChipChair + true + -8.87142 9.15707 -7.57769e+08 0 -0.152685 0 + + + + + model://TrolleyBed + true + 4.85934 -4.87229 -7.57769e+08 0 -1e-06 0 + + + + + model://SurgicalTrolley + true + 11.4301 3.56328 0 0 -0 0 + + + + + model://CGMClassic + true + -11.2304 -21.1134 0 0 0 -3.11834 + + + + + model://PotatoChipChair + true + -7.9025 6.49258 0 0 -0 0 + + + + + model://PotatoChipChair + true + -7.89464 8.01997 0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.39087 6.45458 0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.41405 8.00716 0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.32415 6.47504 0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.32415 8.03277 0 0 -0 0 + + + + + model://PotatoChipChair + true + -4.83084 6.47504 0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -4.85665 8.03277 0 0 0 -3.13096 + + + + + model://VisitorKidSit + true + -7.69163 6.9857 0 0 -0 1.56778 + + + + + model://FemaleVisitorSit + true + -7.61435 7.50057 0 0 -0 1.60052 + + + + + model://AdjTable + true + 1.2174 -5.60888 0 0 0 -0.008733 + + + + + model://PotatoChipChair + true + 8.18933 6.61196 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 8.18939 8.16786 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.80281 6.60106 0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.80281 8.1542 0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.73748 6.5915 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.7505 8.15453 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 5.17897 6.59309 0 0 -0 0 + + + + + model://PotatoChipChair + true + 5.1811 8.14489 0 0 -0 0 + + + + + model://aws_robomaker_residential_CoffeeTable_01 + true + -10.2383 -29.9144 0 0 -0 0 + + + + + model://aws_robomaker_residential_Sofa_01 + true + -11.077 -30.5544 -1e-05 2.6e-05 -3e-06 1.56984 + + + + + model://aws_robomaker_residential_TV_02 + true + -12.4122 -28.4594 1.53211 0 -0 3.13999 + + + + + model://aws_robomaker_residential_KitchenCabinet_01 + true + -11.1379 -25.6941 0 0 -0 0 + + + + + model://aws_robomaker_residential_Refrigerator_01 + true + -9.28238 -24.5015 0 0 -0 0 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -10.8238 -28.6662 -5e-06 -1.3e-05 -2e-06 -1.56116 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -9.73697 -28.6538 -3e-06 1.3e-05 -4e-06 -1.56077 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + 1.14738 -6.92303 1.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 2.40772 -3.61975 1.54508 0 0 -1.57619 + + + + + model://MopCart3 + true + 1.07736 -8.59036 -6.7e-05 0 1e-06 0 + + + + + model://MaleVisitorSit + true + 6.41259 8.18749 0 0.000578 -0 -1.56624 + + + + + model://Drawer + true + 3.18472 -6.54185 0 0 0 -1.55907 + + + + + model://Drawer + true + 3.19085 -5.94838 0 0 0 -1.55907 + + + + + model://OfficeChairBlack + true + 1.20234 -6.39435 0 0 -0 3.13125 + + + + + model://OfficeChairBlack + true + -1.25321 -6.4505 0 0 -0 3.13125 + + + + + model://AdjTable + true + -1.26728 -5.69226 0 0 0 -0.008733 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -0.706092 -6.93108 1.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -1.97245 -6.9216 1.41115 0 -0 0 + + + + + model://Drawer + true + -3.02001 -6.54343 0 0 -0 1.56555 + + + + + model://Drawer + true + -2.99762 -5.94782 0 0 -0 1.56555 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -2.43341 -3.38621 1.54508 0 -0 1.57083 + + + + + model://ElderLadyPatient + true + -10.9972 0.231354 0.001654 0 -0 0 + + + + + model://ElderLadyPatient + true + -10.8133 -13.5925 0.001657 0 -2e-06 -0.025052 + + + + + model://CGMClassic + true + -11.0878 -7.00992 0 0 -0 3.1351 + + + + + model://aws_robomaker_residential_Trash_01 + true + 0.316178 -6.58235 0.000903 0 -2e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -0.436645 -6.57758 0.000903 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -12.1773 -27.6293 0.000894 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -9.06141 -31.9238 1.38136 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -11.7398 -31.9011 1.38136 0 -0 0 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 0 0 -0 1.56702 + + + + + model://ElderMalePatient + true + -11.1165 -17.2377 0.001656 0 3e-06 0 + + + + + model://InstrumentCart2 + true + -12.0906 -1.87329 0.051875 0 -0 1.57773 + + + + + model://InstrumentCart2 + true + -11.5231 1.34237 0 0 -0 0 + + + + + model://aws_robomaker_residential_Carpet_01 + true + -10.7338 -29.9243 0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1128 11.6546 0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1876 4.2888 0 0 -0 3.1387 + + + + + model://CGMClassic + true + -11.0106 8.9505 -0.008203 -0.035019 -0.000392 3.13388 + + + + + model://CGMClassic + true + -11.025 7.10335 0 -0.035021 1.8e-05 -3.13762 + + + + + model://BedTable + true + -10.4759 1.39442 0.001184 0 -3e-06 0 + + + + + model://BedTable + true + -10.5874 -12.5084 0.001189 0 -0 3.11588 + + + + + model://BedsideTable + true + -12.1499 -2.63111 0.00018 1e-06 -0 -0.00878 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0426 0.066126 0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0309 -3.75145 0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_floor_01_ceiling + true + 0.016552 0.050728 0 0 -0 0 + + + + + model://aws_robomaker_hospital_ramp_01 + true + -1.70996 16.3685 0 0 -0 0 + + + + + model://AnesthesiaMachine + true + -1.28478 -21.1127 0 0 0 -3.12971 + + + + + model://TrolleyBedPatient + true + -1.83202 -19.2612 0 0 -0 0 + + + + + model://Scrubs + true + -0.93616 -18.2252 0 0 -0 1.62572 + + + + + model://Shower + true + -1.07422 -16.1332 0 0 -0 0 + + + + + model://Shower + true + 0.853327 -16.1492 0 0 -0 0 + + + + + model://SurgicalTrolley + true + -0.411421 -22.2085 0 0 0 -1.58175 + + + + + model://SurgicalTrolley + true + 3.11747 -19.6565 0 0 -0 1.57031 + + + + + model://SurgicalTrolleyMed + true + 0.770804 -19.7749 0 0 0 -1.56798 + + + + + model://Scrubs + true + -2.66657 -18.3733 0 -0.002221 -0.006608 -1.24025 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 0 0 -0 1.56702 + + + + + model://InstrumentCart2 + true + -0.869537 -17.7436 0 0 0 -0.002595 + + + + + model://StorageRackCovered + true + 0.546476 -18.3985 -0 0 -0 1.56584 + + + + + model://StorageRack + true + -2.69866 -22.4178 -8e-06 0 4e-06 0 + + + + + model://KitchenSink + true + 3.06236 -11.8809 -0.001614 0 -0 3.1391 + + + + + model://KitchenSink + true + -3.09305 -11.8988 -0.001609 0 -0 0 + + + + + model://Toilet + true + 0.464522 -11.8023 0.005252 0 0.016801 0 + + + + + model://Toilet + true + -0.54552 -11.8033 0.000387 0 0 -3.139 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.14723 -10.143 1.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.16956 -10.1327 1.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.2703 -12.9084 1.57344 0 0 -3.14134 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.06108 -12.9155 1.57344 0 0 -3.14134 + + + + + model://Toilet + true + 7.4839 1.42958 0.000387 0 -0 -3.13589 + + + + + model://Toilet + true + -7.01185 1.4183 0.000387 0 0 -3.13589 + + + + + model://Toilet + true + -7.02851 -12.7728 0.000377 0 0 -3.13589 + + + + + model://Toilet + true + 7.48696 -12.617 0.000386 0 0 -3.13589 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.89294 -13.6155 1.54508 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.88791 0.445446 1.54508 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.92095 0.84255 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.90937 -13.3417 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.3841 6.01232 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.4276 9.98828 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08927 9.19494 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -8.94468 7.73571 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08305 7.04089 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -9.9148 11.9172 1.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -10.2134 7.89752 1.40573 0 -0 0 + + + + + model://CGMClassic + true + 10.6166 9.06291 -0.008203 -0.03501 0.000885 -3.11285 + + + + + model://CGMClassic + true + 10.6006 6.90956 -0.008203 -0.035003 0.001133 -3.10576 + + + + + model://MetalCabinet + true + 11.1356 4.33826 0 0 -0 3.1387 + + + + + model://MetalCabinet + true + 11.1318 11.6838 0 0 0 -0.023701 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 6.78742 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 9.05858 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 6.98849 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 8.87466 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.4385 -6.00525 1.84129 0 -0 1.56777 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 10.596 7.88308 1.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 9.98896 11.914 1.40573 0 -0 0 + + + + + model://ParkingTrolleyMin + true + 0.715846 -17.1496 -0.000121 -1e-06 -0 0 + + + + + model://PatientFSit + true + -10.8902 9.18683 0.228965 0 -0 1.58161 + + + + + model://MaleVisitorOnPhone + true + -0.760316 7.58474 0 0 0 -1.14974 + + + + + model://FemaleVisitor + true + 0.416835 7.44353 0 0 -0 0 + + + + + model://MaleVisitorSit + true + -5.98588 6.41261 0 0 -0 1.58808 + + + + + model://Scrubs + true + -1.29468 -20.4093 0 0 0 -1.51066 + + + + + model://aws_robomaker_hospital_curtain_open_01 + true + 11.0051 -6.91002 0 0 0 -1.58737 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 11.0303 -3.70124 0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9586 0.159483 0 0 0 -1.58306 + + + + + model://MalePatientBed + true + 11.3771 -7.38891 0.001658 -1e-06 1e-06 3.11598 + + + + + model://CGMClassic + true + 11.3613 -21.8867 0 0 0 -3.12292 + + + + + model://StorageRackCoverOpen + true + 9.15016 3.44263 -9e-06 1e-06 2e-06 0 + + + + + model://aws_robomaker_warehouse_ClutteringC_01 + true + -10.5553 15.0297 0 0 -0 0 + + + + + model://aws_robomaker_warehouse_ClutteringA_01 + true + 10.8233 15.2153 0 0 -0 0 + + + + + model://StorageRack + true + -10.1178 -10.4694 -0 0 -0 0 + + + + + model://StorageRack + true + -9.91557 3.5644 -9e-06 1e-06 1e-06 -0.000273 + + + + + model://StorageRackCovered + true + 10.294 -10.577 -7e-06 3e-06 -0 3.13389 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9819 -26.2149 0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 1.31506 -30.5771 0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 5.49659 -30.5364 0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 9.80048 -30.5918 0 0 -0 3.1401 + + + + + model://FemaleVisitorSit + true + 7.85005 6.59766 0 0 0 -1.5621 + + + + + model://InstrumentCart1 + true + -1.83539 -17.5879 0 0 -0 0 + + + + + model://ParkingTrolleyMax + true + 7.71054 -25.1326 -0.000121 1e-06 -0 -1.59536 + + + + + model://ElderMalePatient + true + -11.2471 -3.5813 0.001656 0 -0 -0.054192 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.74211 14.8725 1.54379 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + 3.85701 14.8779 1.69742 0 -0 0 + + + + + model://Chair + true + -1.37633 -0.795802 0 -1e-06 0 -1.54998 + + + + + model://XRayMachine + true + 1.79424 -21.3329 0 0 -0 0 + + + + + model://IVStand + true + -11.0966 -16.4963 0 0 -0 0 + + + + + model://BloodPressureMonitor + true + -9.96258 -11.9361 0 0 -0 0 + + + + + model://IVStand + true + -2.30593 -20.2447 0 0 -0 0 + + + + + model://BMWCart + true + -10.931 -1.9483 0 0 -0 0 + + + + + model://Scrubs + true + -9.75875 -2.67552 0 0 -0 0 + + + + + model://BPCart + true + -10.1788 11.173 0.003446 1e-06 -0 0.003096 + + + + + model://BPCart + true + 12.0072 4.64765 0 0 -0 0 + + + + + model://BPCart + true + -11.7236 11.4294 0 0 -0 0 + + + + + model://BPCart + true + -11.4703 5.05999 0.003446 1e-06 -0 0.003096 + + + + + model://VendingMachine + true + -8.45694 9.63064 0 0 -0 0 + + + + + model://VendingMachine + true + 8.35378 9.64852 -3e-06 -6e-06 0 0 + + + + + model://Chair + true + 1.30985 -0.727185 -0 0 0 -1.53446 + + + + diff --git a/src/robot_sim/worlds/hospital_three_floors.world b/src/robot_sim/worlds/hospital_three_floors.world new file mode 100644 index 0000000..f01ab27 --- /dev/null +++ b/src/robot_sim/worlds/hospital_three_floors.world @@ -0,0 +1,3796 @@ + + + + 0 0 -9.8 + + 0.001 + 1 + 1000 + + + 0.6 0.6 0.6 1 + 0.4 0.4 0.4 1 + false + + + model://sun + + + model://ground_plane + 0 0 -0.1 0 -0 0 + + + + model://aws_robomaker_hospital_floor_01_floor + true + -0.001425 -0.014447 0 0 -0 0 + + + + + model://aws_robomaker_hospital_floor_01_walls + true + -0.013823 -0.013783 0 0 -0 0 + + + + + model://aws_robomaker_hospital_nursesstation_01 + true + 0 1.5 0 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + -1.50654 19.4813 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + 1.51134 19.487 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_car + true + -1.49587 19.35 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_car + true + 1.5407 19.35 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + -1.51 19.35 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + 1.52843 19.3627 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0216 -13.8069 0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + -11.022 -7.27757 0 0 -0 1.57907 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1417 -21.4039 0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1068 -17.8472 0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1374 -14.1551 0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0332 -17.61 0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0086 -21.7566 0 0 -0 1.55358 + + + + + model://CGMClassic + true + 11.1777 -18.4129 0 0 0 -3.13719 + + + + + model://StorageRack + true + 9.07005 -10.3582 -7.57769e+08 -2e-06 0 0 + + + + + model://CGMClassic + true + 11.1179 -14.6493 0 0 0 -3.13599 + + + + + model://Chair + true + -0.603067 -0.77859 -1e-05 0 0 -1.54998 + + + + + model://Chair + true + 0.626494 -0.743667 -0 0 1e-06 -1.53446 + + + + + model://Scrubs + true + -9.61916 -12.5112 0 0 0 -3.12353 + + + + + model://Scrubs + true + 0.054597 4.05849 0 0 -0 3.12413 + + + + + model://PatientWheelChair + true + -5.46091 1.23577 0 0 0 -1.54828 + + + + + model://Scrubs + true + -5.38513 1.82526 0 0 0 -1.63757 + + + + + model://WhiteChipChair + true + -8.87142 9.15707 -7.57769e+08 0 -0.152685 0 + + + + + model://TrolleyBed + true + 4.85934 -4.87229 -7.57769e+08 0 -1e-06 0 + + + + + model://SurgicalTrolley + true + 11.4301 3.56328 0 0 -0 0 + + + + + model://CGMClassic + true + -11.2304 -21.1134 0 0 0 -3.11834 + + + + + model://PotatoChipChair + true + -7.9025 6.49258 0 0 -0 0 + + + + + model://PotatoChipChair + true + -7.89464 8.01997 0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.39087 6.45458 0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.41405 8.00716 0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.32415 6.47504 0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.32415 8.03277 0 0 -0 0 + + + + + model://PotatoChipChair + true + -4.83084 6.47504 0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -4.85665 8.03277 0 0 0 -3.13096 + + + + + model://VisitorKidSit + true + -7.69163 6.9857 0 0 -0 1.56778 + + + + + model://FemaleVisitorSit + true + -7.61435 7.50057 0 0 -0 1.60052 + + + + + model://AdjTable + true + 1.2174 -5.60888 0 0 0 -0.008733 + + + + + model://PotatoChipChair + true + 8.18933 6.61196 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 8.18939 8.16786 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.80281 6.60106 0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.80281 8.1542 0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.73748 6.5915 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.7505 8.15453 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 5.17897 6.59309 0 0 -0 0 + + + + + model://PotatoChipChair + true + 5.1811 8.14489 0 0 -0 0 + + + + + model://aws_robomaker_residential_CoffeeTable_01 + true + -10.2383 -29.9144 0 0 -0 0 + + + + + model://aws_robomaker_residential_Sofa_01 + true + -11.077 -30.5544 -1e-05 2.6e-05 -3e-06 1.56984 + + + + + model://aws_robomaker_residential_TV_02 + true + -12.4122 -28.4594 1.53211 0 -0 3.13999 + + + + + model://aws_robomaker_residential_KitchenCabinet_01 + true + -11.1379 -25.6941 0 0 -0 0 + + + + + model://aws_robomaker_residential_Refrigerator_01 + true + -9.28238 -24.5015 0 0 -0 0 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -10.8238 -28.6662 -5e-06 -1.3e-05 -2e-06 -1.56116 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -9.73697 -28.6538 -3e-06 1.3e-05 -4e-06 -1.56077 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + 1.14738 -6.92303 1.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 2.40772 -3.61975 1.54508 0 0 -1.57619 + + + + + model://MopCart3 + true + 1.07736 -8.59036 -6.7e-05 0 1e-06 0 + + + + + model://MaleVisitorSit + true + 6.41259 8.18749 0 0.000578 -0 -1.56624 + + + + + model://Drawer + true + 3.18472 -6.54185 0 0 0 -1.55907 + + + + + model://Drawer + true + 3.19085 -5.94838 0 0 0 -1.55907 + + + + + model://OfficeChairBlack + true + 1.20234 -6.39435 0 0 -0 3.13125 + + + + + model://OfficeChairBlack + true + -1.25321 -6.4505 0 0 -0 3.13125 + + + + + model://AdjTable + true + -1.26728 -5.69226 0 0 0 -0.008733 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -0.706092 -6.93108 1.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -1.97245 -6.9216 1.41115 0 -0 0 + + + + + model://Drawer + true + -3.02001 -6.54343 0 0 -0 1.56555 + + + + + model://Drawer + true + -2.99762 -5.94782 0 0 -0 1.56555 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -2.43341 -3.38621 1.54508 0 -0 1.57083 + + + + + model://ElderLadyPatient + true + -10.9972 0.231354 0.001654 0 -0 0 + + + + + model://ElderLadyPatient + true + -10.8133 -13.5925 0.001657 0 -2e-06 -0.025052 + + + + + model://CGMClassic + true + -11.0878 -7.00992 0 0 -0 3.1351 + + + + + model://aws_robomaker_residential_Trash_01 + true + 0.316178 -6.58235 0.000903 0 -2e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -0.436645 -6.57758 0.000903 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -12.1773 -27.6293 0.000894 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -9.06141 -31.9238 1.38136 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -11.7398 -31.9011 1.38136 0 -0 0 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 0 0 -0 1.56702 + + + + + model://ElderMalePatient + true + -11.1165 -17.2377 0.001656 0 3e-06 0 + + + + + model://InstrumentCart2 + true + -12.0906 -1.87329 0.051875 0 -0 1.57773 + + + + + model://InstrumentCart2 + true + -11.5231 1.34237 0 0 -0 0 + + + + + model://aws_robomaker_residential_Carpet_01 + true + -10.7338 -29.9243 0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1128 11.6546 0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1876 4.2888 0 0 -0 3.1387 + + + + + model://CGMClassic + true + -11.0106 8.9505 -0.008203 -0.035019 -0.000392 3.13388 + + + + + model://CGMClassic + true + -11.025 7.10335 0 -0.035021 1.8e-05 -3.13762 + + + + + model://BedTable + true + -10.4759 1.39442 0.001184 0 -3e-06 0 + + + + + model://BedTable + true + -10.5874 -12.5084 0.001189 0 -0 3.11588 + + + + + model://BedsideTable + true + -12.1499 -2.63111 0.00018 1e-06 -0 -0.00878 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0426 0.066126 0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0309 -3.75145 0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_floor_01_ceiling + true + 0.016552 0.050728 0 0 -0 0 + + + + + model://aws_robomaker_hospital_ramp_01 + true + -1.70996 16.3685 0 0 -0 0 + + + + + model://AnesthesiaMachine + true + -1.28478 -21.1127 0 0 0 -3.12971 + + + + + model://TrolleyBedPatient + true + -1.83202 -19.2612 0 0 -0 0 + + + + + model://Scrubs + true + -0.93616 -18.2252 0 0 -0 1.62572 + + + + + model://Shower + true + -1.07422 -16.1332 0 0 -0 0 + + + + + model://Shower + true + 0.853327 -16.1492 0 0 -0 0 + + + + + model://SurgicalTrolley + true + -0.411421 -22.2085 0 0 0 -1.58175 + + + + + model://SurgicalTrolley + true + 3.11747 -19.6565 0 0 -0 1.57031 + + + + + model://SurgicalTrolleyMed + true + 0.770804 -19.7749 0 0 0 -1.56798 + + + + + model://Scrubs + true + -2.66657 -18.3733 0 -0.002221 -0.006608 -1.24025 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 0 0 -0 1.56702 + + + + + model://InstrumentCart2 + true + -0.869537 -17.7436 0 0 0 -0.002595 + + + + + model://StorageRackCovered + true + 0.546476 -18.3985 -0 0 -0 1.56584 + + + + + model://StorageRack + true + -2.69866 -22.4178 -8e-06 0 4e-06 0 + + + + + model://KitchenSink + true + 3.06236 -11.8809 -0.001614 0 -0 3.1391 + + + + + model://KitchenSink + true + -3.09305 -11.8988 -0.001609 0 -0 0 + + + + + model://Toilet + true + 0.464522 -11.8023 0.005252 0 0.016801 0 + + + + + model://Toilet + true + -0.54552 -11.8033 0.000387 0 0 -3.139 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.14723 -10.143 1.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.16956 -10.1327 1.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.2703 -12.9084 1.57344 0 0 -3.14134 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.06108 -12.9155 1.57344 0 0 -3.14134 + + + + + model://Toilet + true + 7.4839 1.42958 0.000387 0 -0 -3.13589 + + + + + model://Toilet + true + -7.01185 1.4183 0.000387 0 0 -3.13589 + + + + + model://Toilet + true + -7.02851 -12.7728 0.000377 0 0 -3.13589 + + + + + model://Toilet + true + 7.48696 -12.617 0.000386 0 0 -3.13589 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.89294 -13.6155 1.54508 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.88791 0.445446 1.54508 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.92095 0.84255 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.90937 -13.3417 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.3841 6.01232 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.4276 9.98828 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08927 9.19494 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -8.94468 7.73571 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08305 7.04089 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -9.9148 11.9172 1.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -10.2134 7.89752 1.40573 0 -0 0 + + + + + model://CGMClassic + true + 10.6166 9.06291 -0.008203 -0.03501 0.000885 -3.11285 + + + + + model://CGMClassic + true + 10.6006 6.90956 -0.008203 -0.035003 0.001133 -3.10576 + + + + + model://MetalCabinet + true + 11.1356 4.33826 0 0 -0 3.1387 + + + + + model://MetalCabinet + true + 11.1318 11.6838 0 0 0 -0.023701 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 6.78742 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 9.05858 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 6.98849 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 8.87466 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.4385 -6.00525 1.84129 0 -0 1.56777 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 10.596 7.88308 1.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 9.98896 11.914 1.40573 0 -0 0 + + + + + model://ParkingTrolleyMin + true + 0.715846 -17.1496 -0.000121 -1e-06 -0 0 + + + + + model://PatientFSit + true + -10.8902 9.18683 0.228965 0 -0 1.58161 + + + + + model://MaleVisitorOnPhone + true + -0.760316 7.58474 0 0 0 -1.14974 + + + + + model://FemaleVisitor + true + 0.416835 7.44353 0 0 -0 0 + + + + + model://MaleVisitorSit + true + -5.98588 6.41261 0 0 -0 1.58808 + + + + + model://Scrubs + true + -1.29468 -20.4093 0 0 0 -1.51066 + + + + + model://aws_robomaker_hospital_curtain_open_01 + true + 11.0051 -6.91002 0 0 0 -1.58737 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 11.0303 -3.70124 0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9586 0.159483 0 0 0 -1.58306 + + + + + model://MalePatientBed + true + 11.3771 -7.38891 0.001658 -1e-06 1e-06 3.11598 + + + + + model://CGMClassic + true + 11.3613 -21.8867 0 0 0 -3.12292 + + + + + model://StorageRackCoverOpen + true + 9.15016 3.44263 -9e-06 1e-06 2e-06 0 + + + + + model://aws_robomaker_warehouse_ClutteringC_01 + true + -10.5553 15.0297 0 0 -0 0 + + + + + model://aws_robomaker_warehouse_ClutteringA_01 + true + 10.8233 15.2153 0 0 -0 0 + + + + + model://StorageRack + true + -10.1178 -10.4694 -0 0 -0 0 + + + + + model://StorageRack + true + -9.91557 3.5644 -9e-06 1e-06 1e-06 -0.000273 + + + + + model://StorageRackCovered + true + 10.294 -10.577 -7e-06 3e-06 -0 3.13389 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9819 -26.2149 0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 1.31506 -30.5771 0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 5.49659 -30.5364 0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 9.80048 -30.5918 0 0 -0 3.1401 + + + + + model://FemaleVisitorSit + true + 7.85005 6.59766 0 0 0 -1.5621 + + + + + model://InstrumentCart1 + true + -1.83539 -17.5879 0 0 -0 0 + + + + + model://ParkingTrolleyMax + true + 7.71054 -25.1326 -0.000121 1e-06 -0 -1.59536 + + + + + model://ElderMalePatient + true + -11.2471 -3.5813 0.001656 0 -0 -0.054192 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.74211 14.8725 1.54379 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + 3.85701 14.8779 1.69742 0 -0 0 + + + + + model://Chair + true + -1.37633 -0.795802 0 -1e-06 0 -1.54998 + + + + + model://XRayMachine + true + 1.79424 -21.3329 0 0 -0 0 + + + + + model://IVStand + true + -11.0966 -16.4963 0 0 -0 0 + + + + + model://BloodPressureMonitor + true + -9.96258 -11.9361 0 0 -0 0 + + + + + model://IVStand + true + -2.30593 -20.2447 0 0 -0 0 + + + + + model://BMWCart + true + -10.931 -1.9483 0 0 -0 0 + + + + + model://Scrubs + true + -9.75875 -2.67552 0 0 -0 0 + + + + + model://BPCart + true + -10.1788 11.173 0.003446 1e-06 -0 0.003096 + + + + + model://BPCart + true + 12.0072 4.64765 0 0 -0 0 + + + + + model://BPCart + true + -11.7236 11.4294 0 0 -0 0 + + + + + model://BPCart + true + -11.4703 5.05999 0.003446 1e-06 -0 0.003096 + + + + + model://VendingMachine + true + -8.45694 9.63064 0 0 -0 0 + + + + + model://VendingMachine + true + 8.35378 9.64852 -3e-06 -6e-06 0 0 + + + + + model://Chair + true + 1.30985 -0.727185 -0 0 0 -1.53446 + + + + + model://aws_robomaker_hospital_floor_01_floor + true + -0.001425 -0.014447 3.0 0 -0 0 + + + + + model://aws_robomaker_hospital_floor_01_walls + true + -0.013823 -0.013783 3.0 0 -0 0 + + + + + model://aws_robomaker_hospital_nursesstation_01 + true + 0 1.5 3.0 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + -1.50654 19.4813 3.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + 1.51134 19.487 3.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + -1.51 19.35 3.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + 1.52843 19.3627 3.19 0 -0 0 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0216 -13.8069 3.0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + -11.022 -7.27757 3.0 0 -0 1.57907 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1417 -21.4039 3.0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1068 -17.8472 3.0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1374 -14.1551 3.0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0332 -17.61 3.0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0086 -21.7566 3.0 0 -0 1.55358 + + + + + model://CGMClassic + true + 11.1777 -18.4129 3.0 0 0 -3.13719 + + + + + model://StorageRack + true + 9.07005 -10.3582 -757768997.0 -2e-06 0 0 + + + + + model://CGMClassic + true + 11.1179 -14.6493 3.0 0 0 -3.13599 + + + + + model://Chair + true + -0.603067 -0.77859 2.99999 0 0 -1.54998 + + + + + model://Chair + true + 0.626494 -0.743667 3.0 0 1e-06 -1.53446 + + + + + model://Scrubs + true + -9.61916 -12.5112 3.0 0 0 -3.12353 + + + + + model://Scrubs + true + 0.054597 4.05849 3.0 0 -0 3.12413 + + + + + model://PatientWheelChair + true + -5.46091 1.23577 3.0 0 0 -1.54828 + + + + + model://Scrubs + true + -5.38513 1.82526 3.0 0 0 -1.63757 + + + + + model://WhiteChipChair + true + -8.87142 9.15707 -757768997.0 0 -0.152685 0 + + + + + model://TrolleyBed + true + 4.85934 -4.87229 -757768997.0 0 -1e-06 0 + + + + + model://SurgicalTrolley + true + 11.4301 3.56328 3.0 0 -0 0 + + + + + model://CGMClassic + true + -11.2304 -21.1134 3.0 0 0 -3.11834 + + + + + model://PotatoChipChair + true + -7.9025 6.49258 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + -7.89464 8.01997 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.39087 6.45458 3.0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.41405 8.00716 3.0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.32415 6.47504 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.32415 8.03277 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + -4.83084 6.47504 3.0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -4.85665 8.03277 3.0 0 0 -3.13096 + + + + + model://VisitorKidSit + true + -7.69163 6.9857 3.0 0 -0 1.56778 + + + + + model://FemaleVisitorSit + true + -7.61435 7.50057 3.0 0 -0 1.60052 + + + + + model://AdjTable + true + 1.2174 -5.60888 3.0 0 0 -0.008733 + + + + + model://PotatoChipChair + true + 8.18933 6.61196 3.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 8.18939 8.16786 3.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.80281 6.60106 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.80281 8.1542 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.73748 6.5915 3.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.7505 8.15453 3.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 5.17897 6.59309 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + 5.1811 8.14489 3.0 0 -0 0 + + + + + model://aws_robomaker_residential_CoffeeTable_01 + true + -10.2383 -29.9144 3.0 0 -0 0 + + + + + model://aws_robomaker_residential_Sofa_01 + true + -11.077 -30.5544 2.99999 2.6e-05 -3e-06 1.56984 + + + + + model://aws_robomaker_residential_TV_02 + true + -12.4122 -28.4594 4.53211 0 -0 3.13999 + + + + + model://aws_robomaker_residential_KitchenCabinet_01 + true + -11.1379 -25.6941 3.0 0 -0 0 + + + + + model://aws_robomaker_residential_Refrigerator_01 + true + -9.28238 -24.5015 3.0 0 -0 0 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -10.8238 -28.6662 2.999995 -1.3e-05 -2e-06 -1.56116 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -9.73697 -28.6538 2.999997 1.3e-05 -4e-06 -1.56077 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + 1.14738 -6.92303 4.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 2.40772 -3.61975 4.5450800000000005 0 0 -1.57619 + + + + + model://MopCart3 + true + 1.07736 -8.59036 2.999933 0 1e-06 0 + + + + + model://MaleVisitorSit + true + 6.41259 8.18749 3.0 0.000578 -0 -1.56624 + + + + + model://Drawer + true + 3.18472 -6.54185 3.0 0 0 -1.55907 + + + + + model://Drawer + true + 3.19085 -5.94838 3.0 0 0 -1.55907 + + + + + model://OfficeChairBlack + true + 1.20234 -6.39435 3.0 0 -0 3.13125 + + + + + model://OfficeChairBlack + true + -1.25321 -6.4505 3.0 0 -0 3.13125 + + + + + model://AdjTable + true + -1.26728 -5.69226 3.0 0 0 -0.008733 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -0.706092 -6.93108 4.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -1.97245 -6.9216 4.41115 0 -0 0 + + + + + model://Drawer + true + -3.02001 -6.54343 3.0 0 -0 1.56555 + + + + + model://Drawer + true + -2.99762 -5.94782 3.0 0 -0 1.56555 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -2.43341 -3.38621 4.5450800000000005 0 -0 1.57083 + + + + + model://ElderLadyPatient + true + -10.9972 0.231354 3.001654 0 -0 0 + + + + + model://ElderLadyPatient + true + -10.8133 -13.5925 3.001657 0 -2e-06 -0.025052 + + + + + model://CGMClassic + true + -11.0878 -7.00992 3.0 0 -0 3.1351 + + + + + model://aws_robomaker_residential_Trash_01 + true + 0.316178 -6.58235 3.000903 0 -2e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -0.436645 -6.57758 3.000903 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -12.1773 -27.6293 3.000894 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -9.06141 -31.9238 4.38136 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -11.7398 -31.9011 4.38136 0 -0 0 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 3.0 0 -0 1.56702 + + + + + model://ElderMalePatient + true + -11.1165 -17.2377 3.001656 0 3e-06 0 + + + + + model://InstrumentCart2 + true + -12.0906 -1.87329 3.051875 0 -0 1.57773 + + + + + model://InstrumentCart2 + true + -11.5231 1.34237 3.0 0 -0 0 + + + + + model://aws_robomaker_residential_Carpet_01 + true + -10.7338 -29.9243 3.0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1128 11.6546 3.0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1876 4.2888 3.0 0 -0 3.1387 + + + + + model://CGMClassic + true + -11.0106 8.9505 2.991797 -0.035019 -0.000392 3.13388 + + + + + model://CGMClassic + true + -11.025 7.10335 3.0 -0.035021 1.8e-05 -3.13762 + + + + + model://BedTable + true + -10.4759 1.39442 3.001184 0 -3e-06 0 + + + + + model://BedTable + true + -10.5874 -12.5084 3.001189 0 -0 3.11588 + + + + + model://BedsideTable + true + -12.1499 -2.63111 3.00018 1e-06 -0 -0.00878 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0426 0.066126 3.0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0309 -3.75145 3.0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_floor_01_ceiling + true + 0.016552 0.050728 3.0 0 -0 0 + + + + + model://aws_robomaker_hospital_ramp_01 + true + -1.70996 16.3685 3.0 0 -0 0 + + + + + model://AnesthesiaMachine + true + -1.28478 -21.1127 3.0 0 0 -3.12971 + + + + + model://TrolleyBedPatient + true + -1.83202 -19.2612 3.0 0 -0 0 + + + + + model://Scrubs + true + -0.93616 -18.2252 3.0 0 -0 1.62572 + + + + + model://Shower + true + -1.07422 -16.1332 3.0 0 -0 0 + + + + + model://Shower + true + 0.853327 -16.1492 3.0 0 -0 0 + + + + + model://SurgicalTrolley + true + -0.411421 -22.2085 3.0 0 0 -1.58175 + + + + + model://SurgicalTrolley + true + 3.11747 -19.6565 3.0 0 -0 1.57031 + + + + + model://SurgicalTrolleyMed + true + 0.770804 -19.7749 3.0 0 0 -1.56798 + + + + + model://Scrubs + true + -2.66657 -18.3733 3.0 -0.002221 -0.006608 -1.24025 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 3.0 0 -0 1.56702 + + + + + model://InstrumentCart2 + true + -0.869537 -17.7436 3.0 0 0 -0.002595 + + + + + model://StorageRackCovered + true + 0.546476 -18.3985 3.0 0 -0 1.56584 + + + + + model://StorageRack + true + -2.69866 -22.4178 2.999992 0 4e-06 0 + + + + + model://KitchenSink + true + 3.06236 -11.8809 2.998386 0 -0 3.1391 + + + + + model://KitchenSink + true + -3.09305 -11.8988 2.998391 0 -0 0 + + + + + model://Toilet + true + 0.464522 -11.8023 3.005252 0 0.016801 0 + + + + + model://Toilet + true + -0.54552 -11.8033 3.000387 0 0 -3.139 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.14723 -10.143 4.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.16956 -10.1327 4.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.2703 -12.9084 4.57344 0 0 -3.14134 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.06108 -12.9155 4.57344 0 0 -3.14134 + + + + + model://Toilet + true + 7.4839 1.42958 3.000387 0 -0 -3.13589 + + + + + model://Toilet + true + -7.01185 1.4183 3.000387 0 0 -3.13589 + + + + + model://Toilet + true + -7.02851 -12.7728 3.000377 0 0 -3.13589 + + + + + model://Toilet + true + 7.48696 -12.617 3.000386 0 0 -3.13589 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.89294 -13.6155 4.5450800000000005 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.88791 0.445446 4.5450800000000005 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.92095 0.84255 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.90937 -13.3417 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.3841 6.01232 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.4276 9.98828 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08927 9.19494 4.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -8.94468 7.73571 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08305 7.04089 4.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -9.9148 11.9172 4.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -10.2134 7.89752 4.40573 0 -0 0 + + + + + model://CGMClassic + true + 10.6166 9.06291 2.991797 -0.03501 0.000885 -3.11285 + + + + + model://CGMClassic + true + 10.6006 6.90956 2.991797 -0.035003 0.001133 -3.10576 + + + + + model://MetalCabinet + true + 11.1356 4.33826 3.0 0 -0 3.1387 + + + + + model://MetalCabinet + true + 11.1318 11.6838 3.0 0 0 -0.023701 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 6.78742 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 9.05858 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 6.98849 4.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 8.87466 4.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.4385 -6.00525 4.84129 0 -0 1.56777 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 10.596 7.88308 4.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 9.98896 11.914 4.40573 0 -0 0 + + + + + model://ParkingTrolleyMin + true + 0.715846 -17.1496 2.999879 -1e-06 -0 0 + + + + + model://PatientFSit + true + -10.8902 9.18683 3.228965 0 -0 1.58161 + + + + + model://MaleVisitorOnPhone + true + -0.760316 7.58474 3.0 0 0 -1.14974 + + + + + model://FemaleVisitor + true + 0.416835 7.44353 3.0 0 -0 0 + + + + + model://MaleVisitorSit + true + -5.98588 6.41261 3.0 0 -0 1.58808 + + + + + model://Scrubs + true + -1.29468 -20.4093 3.0 0 0 -1.51066 + + + + + model://aws_robomaker_hospital_curtain_open_01 + true + 11.0051 -6.91002 3.0 0 0 -1.58737 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 11.0303 -3.70124 3.0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9586 0.159483 3.0 0 0 -1.58306 + + + + + model://MalePatientBed + true + 11.3771 -7.38891 3.001658 -1e-06 1e-06 3.11598 + + + + + model://CGMClassic + true + 11.3613 -21.8867 3.0 0 0 -3.12292 + + + + + model://StorageRackCoverOpen + true + 9.15016 3.44263 2.999991 1e-06 2e-06 0 + + + + + model://aws_robomaker_warehouse_ClutteringC_01 + true + -10.5553 15.0297 3.0 0 -0 0 + + + + + model://aws_robomaker_warehouse_ClutteringA_01 + true + 10.8233 15.2153 3.0 0 -0 0 + + + + + model://StorageRack + true + -10.1178 -10.4694 3.0 0 -0 0 + + + + + model://StorageRack + true + -9.91557 3.5644 2.999991 1e-06 1e-06 -0.000273 + + + + + model://StorageRackCovered + true + 10.294 -10.577 2.999993 3e-06 -0 3.13389 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9819 -26.2149 3.0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 1.31506 -30.5771 3.0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 5.49659 -30.5364 3.0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 9.80048 -30.5918 3.0 0 -0 3.1401 + + + + + model://FemaleVisitorSit + true + 7.85005 6.59766 3.0 0 0 -1.5621 + + + + + model://InstrumentCart1 + true + -1.83539 -17.5879 3.0 0 -0 0 + + + + + model://ParkingTrolleyMax + true + 7.71054 -25.1326 2.999879 1e-06 -0 -1.59536 + + + + + model://ElderMalePatient + true + -11.2471 -3.5813 3.001656 0 -0 -0.054192 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.74211 14.8725 4.5437899999999996 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + 3.85701 14.8779 4.69742 0 -0 0 + + + + + model://Chair + true + -1.37633 -0.795802 3.0 -1e-06 0 -1.54998 + + + + + model://XRayMachine + true + 1.79424 -21.3329 3.0 0 -0 0 + + + + + model://IVStand + true + -11.0966 -16.4963 3.0 0 -0 0 + + + + + model://BloodPressureMonitor + true + -9.96258 -11.9361 3.0 0 -0 0 + + + + + model://IVStand + true + -2.30593 -20.2447 3.0 0 -0 0 + + + + + model://BMWCart + true + -10.931 -1.9483 3.0 0 -0 0 + + + + + model://Scrubs + true + -9.75875 -2.67552 3.0 0 -0 0 + + + + + model://BPCart + true + -10.1788 11.173 3.003446 1e-06 -0 0.003096 + + + + + model://BPCart + true + 12.0072 4.64765 3.0 0 -0 0 + + + + + model://BPCart + true + -11.7236 11.4294 3.0 0 -0 0 + + + + + model://BPCart + true + -11.4703 5.05999 3.003446 1e-06 -0 0.003096 + + + + + model://VendingMachine + true + -8.45694 9.63064 3.0 0 -0 0 + + + + + model://VendingMachine + true + 8.35378 9.64852 2.999997 -6e-06 0 0 + + + + + model://Chair + true + 1.30985 -0.727185 3.0 0 0 -1.53446 + + + + + model://aws_robomaker_hospital_floor_01_floor + true + -0.001425 -0.014447 6.0 0 -0 0 + + + + + model://aws_robomaker_hospital_floor_01_walls + true + -0.013823 -0.013783 6.0 0 -0 0 + + + + + model://aws_robomaker_hospital_nursesstation_01 + true + 0 1.5 6.0 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + -1.50654 19.4813 6.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + 1.51134 19.487 6.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + -1.51 19.35 6.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + 1.52843 19.3627 6.19 0 -0 0 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0216 -13.8069 6.0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + -11.022 -7.27757 6.0 0 -0 1.57907 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1417 -21.4039 6.0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1068 -17.8472 6.0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1374 -14.1551 6.0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0332 -17.61 6.0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0086 -21.7566 6.0 0 -0 1.55358 + + + + + model://CGMClassic + true + 11.1777 -18.4129 6.0 0 0 -3.13719 + + + + + model://StorageRack + true + 9.07005 -10.3582 -757768994.0 -2e-06 0 0 + + + + + model://CGMClassic + true + 11.1179 -14.6493 6.0 0 0 -3.13599 + + + + + model://Chair + true + -0.603067 -0.77859 5.99999 0 0 -1.54998 + + + + + model://Chair + true + 0.626494 -0.743667 6.0 0 1e-06 -1.53446 + + + + + model://Scrubs + true + -9.61916 -12.5112 6.0 0 0 -3.12353 + + + + + model://Scrubs + true + 0.054597 4.05849 6.0 0 -0 3.12413 + + + + + model://PatientWheelChair + true + -5.46091 1.23577 6.0 0 0 -1.54828 + + + + + model://Scrubs + true + -5.38513 1.82526 6.0 0 0 -1.63757 + + + + + model://WhiteChipChair + true + -8.87142 9.15707 -757768994.0 0 -0.152685 0 + + + + + model://TrolleyBed + true + 4.85934 -4.87229 -757768994.0 0 -1e-06 0 + + + + + model://SurgicalTrolley + true + 11.4301 3.56328 6.0 0 -0 0 + + + + + model://CGMClassic + true + -11.2304 -21.1134 6.0 0 0 -3.11834 + + + + + model://PotatoChipChair + true + -7.9025 6.49258 6.0 0 -0 0 + + + + + model://PotatoChipChair + true + -7.89464 8.01997 6.0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.39087 6.45458 6.0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.41405 8.00716 6.0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.32415 6.47504 6.0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.32415 8.03277 6.0 0 -0 0 + + + + + model://PotatoChipChair + true + -4.83084 6.47504 6.0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -4.85665 8.03277 6.0 0 0 -3.13096 + + + + + model://VisitorKidSit + true + -7.69163 6.9857 6.0 0 -0 1.56778 + + + + + model://FemaleVisitorSit + true + -7.61435 7.50057 6.0 0 -0 1.60052 + + + + + model://AdjTable + true + 1.2174 -5.60888 6.0 0 0 -0.008733 + + + + + model://PotatoChipChair + true + 8.18933 6.61196 6.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 8.18939 8.16786 6.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.80281 6.60106 6.0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.80281 8.1542 6.0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.73748 6.5915 6.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.7505 8.15453 6.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 5.17897 6.59309 6.0 0 -0 0 + + + + + model://PotatoChipChair + true + 5.1811 8.14489 6.0 0 -0 0 + + + + + model://aws_robomaker_residential_CoffeeTable_01 + true + -10.2383 -29.9144 6.0 0 -0 0 + + + + + model://aws_robomaker_residential_Sofa_01 + true + -11.077 -30.5544 5.99999 2.6e-05 -3e-06 1.56984 + + + + + model://aws_robomaker_residential_TV_02 + true + -12.4122 -28.4594 7.53211 0 -0 3.13999 + + + + + model://aws_robomaker_residential_KitchenCabinet_01 + true + -11.1379 -25.6941 6.0 0 -0 0 + + + + + model://aws_robomaker_residential_Refrigerator_01 + true + -9.28238 -24.5015 6.0 0 -0 0 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -10.8238 -28.6662 5.999995 -1.3e-05 -2e-06 -1.56116 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -9.73697 -28.6538 5.999997 1.3e-05 -4e-06 -1.56077 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + 1.14738 -6.92303 7.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 2.40772 -3.61975 7.5450800000000005 0 0 -1.57619 + + + + + model://MopCart3 + true + 1.07736 -8.59036 5.999933 0 1e-06 0 + + + + + model://MaleVisitorSit + true + 6.41259 8.18749 6.0 0.000578 -0 -1.56624 + + + + + model://Drawer + true + 3.18472 -6.54185 6.0 0 0 -1.55907 + + + + + model://Drawer + true + 3.19085 -5.94838 6.0 0 0 -1.55907 + + + + + model://OfficeChairBlack + true + 1.20234 -6.39435 6.0 0 -0 3.13125 + + + + + model://OfficeChairBlack + true + -1.25321 -6.4505 6.0 0 -0 3.13125 + + + + + model://AdjTable + true + -1.26728 -5.69226 6.0 0 0 -0.008733 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -0.706092 -6.93108 7.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -1.97245 -6.9216 7.41115 0 -0 0 + + + + + model://Drawer + true + -3.02001 -6.54343 6.0 0 -0 1.56555 + + + + + model://Drawer + true + -2.99762 -5.94782 6.0 0 -0 1.56555 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -2.43341 -3.38621 7.5450800000000005 0 -0 1.57083 + + + + + model://ElderLadyPatient + true + -10.9972 0.231354 6.001654 0 -0 0 + + + + + model://ElderLadyPatient + true + -10.8133 -13.5925 6.001657 0 -2e-06 -0.025052 + + + + + model://CGMClassic + true + -11.0878 -7.00992 6.0 0 -0 3.1351 + + + + + model://aws_robomaker_residential_Trash_01 + true + 0.316178 -6.58235 6.000903 0 -2e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -0.436645 -6.57758 6.000903 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -12.1773 -27.6293 6.000894 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -9.06141 -31.9238 7.38136 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -11.7398 -31.9011 7.38136 0 -0 0 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 6.0 0 -0 1.56702 + + + + + model://ElderMalePatient + true + -11.1165 -17.2377 6.001656 0 3e-06 0 + + + + + model://InstrumentCart2 + true + -12.0906 -1.87329 6.051875 0 -0 1.57773 + + + + + model://InstrumentCart2 + true + -11.5231 1.34237 6.0 0 -0 0 + + + + + model://aws_robomaker_residential_Carpet_01 + true + -10.7338 -29.9243 6.0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1128 11.6546 6.0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1876 4.2888 6.0 0 -0 3.1387 + + + + + model://CGMClassic + true + -11.0106 8.9505 5.991797 -0.035019 -0.000392 3.13388 + + + + + model://CGMClassic + true + -11.025 7.10335 6.0 -0.035021 1.8e-05 -3.13762 + + + + + model://BedTable + true + -10.4759 1.39442 6.001184 0 -3e-06 0 + + + + + model://BedTable + true + -10.5874 -12.5084 6.001189 0 -0 3.11588 + + + + + model://BedsideTable + true + -12.1499 -2.63111 6.00018 1e-06 -0 -0.00878 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0426 0.066126 6.0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0309 -3.75145 6.0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_floor_01_ceiling + true + 0.016552 0.050728 6.0 0 -0 0 + + + + + model://aws_robomaker_hospital_ramp_01 + true + -1.70996 16.3685 6.0 0 -0 0 + + + + + model://AnesthesiaMachine + true + -1.28478 -21.1127 6.0 0 0 -3.12971 + + + + + model://TrolleyBedPatient + true + -1.83202 -19.2612 6.0 0 -0 0 + + + + + model://Scrubs + true + -0.93616 -18.2252 6.0 0 -0 1.62572 + + + + + model://Shower + true + -1.07422 -16.1332 6.0 0 -0 0 + + + + + model://Shower + true + 0.853327 -16.1492 6.0 0 -0 0 + + + + + model://SurgicalTrolley + true + -0.411421 -22.2085 6.0 0 0 -1.58175 + + + + + model://SurgicalTrolley + true + 3.11747 -19.6565 6.0 0 -0 1.57031 + + + + + model://SurgicalTrolleyMed + true + 0.770804 -19.7749 6.0 0 0 -1.56798 + + + + + model://Scrubs + true + -2.66657 -18.3733 6.0 -0.002221 -0.006608 -1.24025 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 6.0 0 -0 1.56702 + + + + + model://InstrumentCart2 + true + -0.869537 -17.7436 6.0 0 0 -0.002595 + + + + + model://StorageRackCovered + true + 0.546476 -18.3985 6.0 0 -0 1.56584 + + + + + model://StorageRack + true + -2.69866 -22.4178 5.999992 0 4e-06 0 + + + + + model://KitchenSink + true + 3.06236 -11.8809 5.998386 0 -0 3.1391 + + + + + model://KitchenSink + true + -3.09305 -11.8988 5.998391 0 -0 0 + + + + + model://Toilet + true + 0.464522 -11.8023 6.005252 0 0.016801 0 + + + + + model://Toilet + true + -0.54552 -11.8033 6.000387 0 0 -3.139 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.14723 -10.143 7.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.16956 -10.1327 7.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.2703 -12.9084 7.57344 0 0 -3.14134 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.06108 -12.9155 7.57344 0 0 -3.14134 + + + + + model://Toilet + true + 7.4839 1.42958 6.000387 0 -0 -3.13589 + + + + + model://Toilet + true + -7.01185 1.4183 6.000387 0 0 -3.13589 + + + + + model://Toilet + true + -7.02851 -12.7728 6.000377 0 0 -3.13589 + + + + + model://Toilet + true + 7.48696 -12.617 6.000386 0 0 -3.13589 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.89294 -13.6155 7.5450800000000005 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.88791 0.445446 7.5450800000000005 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.92095 0.84255 7.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.90937 -13.3417 7.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.3841 6.01232 7.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.4276 9.98828 7.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08927 9.19494 7.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -8.94468 7.73571 7.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08305 7.04089 7.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -9.9148 11.9172 7.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -10.2134 7.89752 7.40573 0 -0 0 + + + + + model://CGMClassic + true + 10.6166 9.06291 5.991797 -0.03501 0.000885 -3.11285 + + + + + model://CGMClassic + true + 10.6006 6.90956 5.991797 -0.035003 0.001133 -3.10576 + + + + + model://MetalCabinet + true + 11.1356 4.33826 6.0 0 -0 3.1387 + + + + + model://MetalCabinet + true + 11.1318 11.6838 6.0 0 0 -0.023701 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 6.78742 7.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 9.05858 7.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 6.98849 7.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 8.87466 7.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.4385 -6.00525 7.84129 0 -0 1.56777 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 10.596 7.88308 7.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 9.98896 11.914 7.40573 0 -0 0 + + + + + model://ParkingTrolleyMin + true + 0.715846 -17.1496 5.999879 -1e-06 -0 0 + + + + + model://PatientFSit + true + -10.8902 9.18683 6.228965 0 -0 1.58161 + + + + + model://MaleVisitorOnPhone + true + -0.760316 7.58474 6.0 0 0 -1.14974 + + + + + model://FemaleVisitor + true + 0.416835 7.44353 6.0 0 -0 0 + + + + + model://MaleVisitorSit + true + -5.98588 6.41261 6.0 0 -0 1.58808 + + + + + model://Scrubs + true + -1.29468 -20.4093 6.0 0 0 -1.51066 + + + + + model://aws_robomaker_hospital_curtain_open_01 + true + 11.0051 -6.91002 6.0 0 0 -1.58737 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 11.0303 -3.70124 6.0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9586 0.159483 6.0 0 0 -1.58306 + + + + + model://MalePatientBed + true + 11.3771 -7.38891 6.001658 -1e-06 1e-06 3.11598 + + + + + model://CGMClassic + true + 11.3613 -21.8867 6.0 0 0 -3.12292 + + + + + model://StorageRackCoverOpen + true + 9.15016 3.44263 5.999991 1e-06 2e-06 0 + + + + + model://aws_robomaker_warehouse_ClutteringC_01 + true + -10.5553 15.0297 6.0 0 -0 0 + + + + + model://aws_robomaker_warehouse_ClutteringA_01 + true + 10.8233 15.2153 6.0 0 -0 0 + + + + + model://StorageRack + true + -10.1178 -10.4694 6.0 0 -0 0 + + + + + model://StorageRack + true + -9.91557 3.5644 5.999991 1e-06 1e-06 -0.000273 + + + + + model://StorageRackCovered + true + 10.294 -10.577 5.999993 3e-06 -0 3.13389 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9819 -26.2149 6.0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 1.31506 -30.5771 6.0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 5.49659 -30.5364 6.0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 9.80048 -30.5918 6.0 0 -0 3.1401 + + + + + model://FemaleVisitorSit + true + 7.85005 6.59766 6.0 0 0 -1.5621 + + + + + model://InstrumentCart1 + true + -1.83539 -17.5879 6.0 0 -0 0 + + + + + model://ParkingTrolleyMax + true + 7.71054 -25.1326 5.999879 1e-06 -0 -1.59536 + + + + + model://ElderMalePatient + true + -11.2471 -3.5813 6.001656 0 -0 -0.054192 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.74211 14.8725 7.5437899999999996 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + 3.85701 14.8779 7.69742 0 -0 0 + + + + + model://Chair + true + -1.37633 -0.795802 6.0 -1e-06 0 -1.54998 + + + + + model://XRayMachine + true + 1.79424 -21.3329 6.0 0 -0 0 + + + + + model://IVStand + true + -11.0966 -16.4963 6.0 0 -0 0 + + + + + model://BloodPressureMonitor + true + -9.96258 -11.9361 6.0 0 -0 0 + + + + + model://IVStand + true + -2.30593 -20.2447 6.0 0 -0 0 + + + + + model://BMWCart + true + -10.931 -1.9483 6.0 0 -0 0 + + + + + model://Scrubs + true + -9.75875 -2.67552 6.0 0 -0 0 + + + + + model://BPCart + true + -10.1788 11.173 6.003446 1e-06 -0 0.003096 + + + + + model://BPCart + true + 12.0072 4.64765 6.0 0 -0 0 + + + + + model://BPCart + true + -11.7236 11.4294 6.0 0 -0 0 + + + + + model://BPCart + true + -11.4703 5.05999 6.003446 1e-06 -0 0.003096 + + + + + model://VendingMachine + true + -8.45694 9.63064 6.0 0 -0 0 + + + + + model://VendingMachine + true + 8.35378 9.64852 5.999997 -6e-06 0 0 + + + + + model://Chair + true + 1.30985 -0.727185 6.0 0 0 -1.53446 + + + + diff --git a/src/robot_sim/worlds/hospital_two_floors.world b/src/robot_sim/worlds/hospital_two_floors.world new file mode 100644 index 0000000..0ff28f6 --- /dev/null +++ b/src/robot_sim/worlds/hospital_two_floors.world @@ -0,0 +1,2543 @@ + + + + 0 0 -9.8 + + 0.001 + 1 + 1000 + + + 0.6 0.6 0.6 1 + 0.4 0.4 0.4 1 + false + + + model://sun + + + model://ground_plane + 0 0 -0.1 0 -0 0 + + + + model://aws_robomaker_hospital_floor_01_floor + true + -0.001425 -0.014447 0 0 -0 0 + + + + + model://aws_robomaker_hospital_floor_01_walls + true + -0.013823 -0.013783 0 0 -0 0 + + + + + model://aws_robomaker_hospital_nursesstation_01 + true + 0 1.5 0 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + -1.50654 19.4813 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + 1.51134 19.487 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_car + true + -1.49587 19.35 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_car + true + 1.5407 19.35 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + -1.51 19.35 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + 1.52843 19.3627 0.19 0 -0 0 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0216 -13.8069 0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + -11.022 -7.27757 0 0 -0 1.57907 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1417 -21.4039 0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1068 -17.8472 0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1374 -14.1551 0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0332 -17.61 0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0086 -21.7566 0 0 -0 1.55358 + + + + + model://CGMClassic + true + 11.1777 -18.4129 0 0 0 -3.13719 + + + + + model://StorageRack + true + 9.07005 -10.3582 -7.57769e+08 -2e-06 0 0 + + + + + model://CGMClassic + true + 11.1179 -14.6493 0 0 0 -3.13599 + + + + + model://Chair + true + -0.603067 -0.77859 -1e-05 0 0 -1.54998 + + + + + model://Chair + true + 0.626494 -0.743667 -0 0 1e-06 -1.53446 + + + + + model://Scrubs + true + -9.61916 -12.5112 0 0 0 -3.12353 + + + + + model://Scrubs + true + 0.054597 4.05849 0 0 -0 3.12413 + + + + + model://PatientWheelChair + true + -5.46091 1.23577 0 0 0 -1.54828 + + + + + model://Scrubs + true + -5.38513 1.82526 0 0 0 -1.63757 + + + + + model://WhiteChipChair + true + -8.87142 9.15707 -7.57769e+08 0 -0.152685 0 + + + + + model://TrolleyBed + true + 4.85934 -4.87229 -7.57769e+08 0 -1e-06 0 + + + + + model://SurgicalTrolley + true + 11.4301 3.56328 0 0 -0 0 + + + + + model://CGMClassic + true + -11.2304 -21.1134 0 0 0 -3.11834 + + + + + model://PotatoChipChair + true + -7.9025 6.49258 0 0 -0 0 + + + + + model://PotatoChipChair + true + -7.89464 8.01997 0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.39087 6.45458 0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.41405 8.00716 0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.32415 6.47504 0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.32415 8.03277 0 0 -0 0 + + + + + model://PotatoChipChair + true + -4.83084 6.47504 0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -4.85665 8.03277 0 0 0 -3.13096 + + + + + model://VisitorKidSit + true + -7.69163 6.9857 0 0 -0 1.56778 + + + + + model://FemaleVisitorSit + true + -7.61435 7.50057 0 0 -0 1.60052 + + + + + model://AdjTable + true + 1.2174 -5.60888 0 0 0 -0.008733 + + + + + model://PotatoChipChair + true + 8.18933 6.61196 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 8.18939 8.16786 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.80281 6.60106 0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.80281 8.1542 0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.73748 6.5915 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.7505 8.15453 0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 5.17897 6.59309 0 0 -0 0 + + + + + model://PotatoChipChair + true + 5.1811 8.14489 0 0 -0 0 + + + + + model://aws_robomaker_residential_CoffeeTable_01 + true + -10.2383 -29.9144 0 0 -0 0 + + + + + model://aws_robomaker_residential_Sofa_01 + true + -11.077 -30.5544 -1e-05 2.6e-05 -3e-06 1.56984 + + + + + model://aws_robomaker_residential_TV_02 + true + -12.4122 -28.4594 1.53211 0 -0 3.13999 + + + + + model://aws_robomaker_residential_KitchenCabinet_01 + true + -11.1379 -25.6941 0 0 -0 0 + + + + + model://aws_robomaker_residential_Refrigerator_01 + true + -9.28238 -24.5015 0 0 -0 0 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -10.8238 -28.6662 -5e-06 -1.3e-05 -2e-06 -1.56116 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -9.73697 -28.6538 -3e-06 1.3e-05 -4e-06 -1.56077 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + 1.14738 -6.92303 1.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 2.40772 -3.61975 1.54508 0 0 -1.57619 + + + + + model://MopCart3 + true + 1.07736 -8.59036 -6.7e-05 0 1e-06 0 + + + + + model://MaleVisitorSit + true + 6.41259 8.18749 0 0.000578 -0 -1.56624 + + + + + model://Drawer + true + 3.18472 -6.54185 0 0 0 -1.55907 + + + + + model://Drawer + true + 3.19085 -5.94838 0 0 0 -1.55907 + + + + + model://OfficeChairBlack + true + 1.20234 -6.39435 0 0 -0 3.13125 + + + + + model://OfficeChairBlack + true + -1.25321 -6.4505 0 0 -0 3.13125 + + + + + model://AdjTable + true + -1.26728 -5.69226 0 0 0 -0.008733 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -0.706092 -6.93108 1.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -1.97245 -6.9216 1.41115 0 -0 0 + + + + + model://Drawer + true + -3.02001 -6.54343 0 0 -0 1.56555 + + + + + model://Drawer + true + -2.99762 -5.94782 0 0 -0 1.56555 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -2.43341 -3.38621 1.54508 0 -0 1.57083 + + + + + model://ElderLadyPatient + true + -10.9972 0.231354 0.001654 0 -0 0 + + + + + model://ElderLadyPatient + true + -10.8133 -13.5925 0.001657 0 -2e-06 -0.025052 + + + + + model://CGMClassic + true + -11.0878 -7.00992 0 0 -0 3.1351 + + + + + model://aws_robomaker_residential_Trash_01 + true + 0.316178 -6.58235 0.000903 0 -2e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -0.436645 -6.57758 0.000903 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -12.1773 -27.6293 0.000894 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -9.06141 -31.9238 1.38136 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -11.7398 -31.9011 1.38136 0 -0 0 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 0 0 -0 1.56702 + + + + + model://ElderMalePatient + true + -11.1165 -17.2377 0.001656 0 3e-06 0 + + + + + model://InstrumentCart2 + true + -12.0906 -1.87329 0.051875 0 -0 1.57773 + + + + + model://InstrumentCart2 + true + -11.5231 1.34237 0 0 -0 0 + + + + + model://aws_robomaker_residential_Carpet_01 + true + -10.7338 -29.9243 0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1128 11.6546 0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1876 4.2888 0 0 -0 3.1387 + + + + + model://CGMClassic + true + -11.0106 8.9505 -0.008203 -0.035019 -0.000392 3.13388 + + + + + model://CGMClassic + true + -11.025 7.10335 0 -0.035021 1.8e-05 -3.13762 + + + + + model://BedTable + true + -10.4759 1.39442 0.001184 0 -3e-06 0 + + + + + model://BedTable + true + -10.5874 -12.5084 0.001189 0 -0 3.11588 + + + + + model://BedsideTable + true + -12.1499 -2.63111 0.00018 1e-06 -0 -0.00878 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0426 0.066126 0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0309 -3.75145 0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_floor_01_ceiling + true + 0.016552 0.050728 0 0 -0 0 + + + + + model://aws_robomaker_hospital_ramp_01 + true + -1.70996 16.3685 0 0 -0 0 + + + + + model://AnesthesiaMachine + true + -1.28478 -21.1127 0 0 0 -3.12971 + + + + + model://TrolleyBedPatient + true + -1.83202 -19.2612 0 0 -0 0 + + + + + model://Scrubs + true + -0.93616 -18.2252 0 0 -0 1.62572 + + + + + model://Shower + true + -1.07422 -16.1332 0 0 -0 0 + + + + + model://Shower + true + 0.853327 -16.1492 0 0 -0 0 + + + + + model://SurgicalTrolley + true + -0.411421 -22.2085 0 0 0 -1.58175 + + + + + model://SurgicalTrolley + true + 3.11747 -19.6565 0 0 -0 1.57031 + + + + + model://SurgicalTrolleyMed + true + 0.770804 -19.7749 0 0 0 -1.56798 + + + + + model://Scrubs + true + -2.66657 -18.3733 0 -0.002221 -0.006608 -1.24025 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 0 0 -0 1.56702 + + + + + model://InstrumentCart2 + true + -0.869537 -17.7436 0 0 0 -0.002595 + + + + + model://StorageRackCovered + true + 0.546476 -18.3985 -0 0 -0 1.56584 + + + + + model://StorageRack + true + -2.69866 -22.4178 -8e-06 0 4e-06 0 + + + + + model://KitchenSink + true + 3.06236 -11.8809 -0.001614 0 -0 3.1391 + + + + + model://KitchenSink + true + -3.09305 -11.8988 -0.001609 0 -0 0 + + + + + model://Toilet + true + 0.464522 -11.8023 0.005252 0 0.016801 0 + + + + + model://Toilet + true + -0.54552 -11.8033 0.000387 0 0 -3.139 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.14723 -10.143 1.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.16956 -10.1327 1.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.2703 -12.9084 1.57344 0 0 -3.14134 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.06108 -12.9155 1.57344 0 0 -3.14134 + + + + + model://Toilet + true + 7.4839 1.42958 0.000387 0 -0 -3.13589 + + + + + model://Toilet + true + -7.01185 1.4183 0.000387 0 0 -3.13589 + + + + + model://Toilet + true + -7.02851 -12.7728 0.000377 0 0 -3.13589 + + + + + model://Toilet + true + 7.48696 -12.617 0.000386 0 0 -3.13589 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.89294 -13.6155 1.54508 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.88791 0.445446 1.54508 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.92095 0.84255 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.90937 -13.3417 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.3841 6.01232 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.4276 9.98828 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08927 9.19494 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -8.94468 7.73571 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08305 7.04089 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -9.9148 11.9172 1.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -10.2134 7.89752 1.40573 0 -0 0 + + + + + model://CGMClassic + true + 10.6166 9.06291 -0.008203 -0.03501 0.000885 -3.11285 + + + + + model://CGMClassic + true + 10.6006 6.90956 -0.008203 -0.035003 0.001133 -3.10576 + + + + + model://MetalCabinet + true + 11.1356 4.33826 0 0 -0 3.1387 + + + + + model://MetalCabinet + true + 11.1318 11.6838 0 0 0 -0.023701 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 6.78742 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 9.05858 1.54508 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 6.98849 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 8.87466 1.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.4385 -6.00525 1.84129 0 -0 1.56777 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 10.596 7.88308 1.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 9.98896 11.914 1.40573 0 -0 0 + + + + + model://ParkingTrolleyMin + true + 0.715846 -17.1496 -0.000121 -1e-06 -0 0 + + + + + model://PatientFSit + true + -10.8902 9.18683 0.228965 0 -0 1.58161 + + + + + model://MaleVisitorOnPhone + true + -0.760316 7.58474 0 0 0 -1.14974 + + + + + model://FemaleVisitor + true + 0.416835 7.44353 0 0 -0 0 + + + + + model://MaleVisitorSit + true + -5.98588 6.41261 0 0 -0 1.58808 + + + + + model://Scrubs + true + -1.29468 -20.4093 0 0 0 -1.51066 + + + + + model://aws_robomaker_hospital_curtain_open_01 + true + 11.0051 -6.91002 0 0 0 -1.58737 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 11.0303 -3.70124 0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9586 0.159483 0 0 0 -1.58306 + + + + + model://MalePatientBed + true + 11.3771 -7.38891 0.001658 -1e-06 1e-06 3.11598 + + + + + model://CGMClassic + true + 11.3613 -21.8867 0 0 0 -3.12292 + + + + + model://StorageRackCoverOpen + true + 9.15016 3.44263 -9e-06 1e-06 2e-06 0 + + + + + model://aws_robomaker_warehouse_ClutteringC_01 + true + -10.5553 15.0297 0 0 -0 0 + + + + + model://aws_robomaker_warehouse_ClutteringA_01 + true + 10.8233 15.2153 0 0 -0 0 + + + + + model://StorageRack + true + -10.1178 -10.4694 -0 0 -0 0 + + + + + model://StorageRack + true + -9.91557 3.5644 -9e-06 1e-06 1e-06 -0.000273 + + + + + model://StorageRackCovered + true + 10.294 -10.577 -7e-06 3e-06 -0 3.13389 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9819 -26.2149 0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 1.31506 -30.5771 0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 5.49659 -30.5364 0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 9.80048 -30.5918 0 0 -0 3.1401 + + + + + model://FemaleVisitorSit + true + 7.85005 6.59766 0 0 0 -1.5621 + + + + + model://InstrumentCart1 + true + -1.83539 -17.5879 0 0 -0 0 + + + + + model://ParkingTrolleyMax + true + 7.71054 -25.1326 -0.000121 1e-06 -0 -1.59536 + + + + + model://ElderMalePatient + true + -11.2471 -3.5813 0.001656 0 -0 -0.054192 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.74211 14.8725 1.54379 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + 3.85701 14.8779 1.69742 0 -0 0 + + + + + model://Chair + true + -1.37633 -0.795802 0 -1e-06 0 -1.54998 + + + + + model://XRayMachine + true + 1.79424 -21.3329 0 0 -0 0 + + + + + model://IVStand + true + -11.0966 -16.4963 0 0 -0 0 + + + + + model://BloodPressureMonitor + true + -9.96258 -11.9361 0 0 -0 0 + + + + + model://IVStand + true + -2.30593 -20.2447 0 0 -0 0 + + + + + model://BMWCart + true + -10.931 -1.9483 0 0 -0 0 + + + + + model://Scrubs + true + -9.75875 -2.67552 0 0 -0 0 + + + + + model://BPCart + true + -10.1788 11.173 0.003446 1e-06 -0 0.003096 + + + + + model://BPCart + true + 12.0072 4.64765 0 0 -0 0 + + + + + model://BPCart + true + -11.7236 11.4294 0 0 -0 0 + + + + + model://BPCart + true + -11.4703 5.05999 0.003446 1e-06 -0 0.003096 + + + + + model://VendingMachine + true + -8.45694 9.63064 0 0 -0 0 + + + + + model://VendingMachine + true + 8.35378 9.64852 -3e-06 -6e-06 0 0 + + + + + model://Chair + true + 1.30985 -0.727185 -0 0 0 -1.53446 + + + + + model://aws_robomaker_hospital_floor_01_floor + true + -0.001425 -0.014447 3.0 0 -0 0 + + + + + model://aws_robomaker_hospital_floor_01_walls + true + -0.013823 -0.013783 3.0 0 -0 0 + + + + + model://aws_robomaker_hospital_nursesstation_01 + true + 0 1.5 3.0 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + -1.50654 19.4813 3.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_portal + true + 1.51134 19.487 3.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + -1.51 19.35 3.19 0 -0 0 + + + + + model://aws_robomaker_hospital_elevator_01_door + true + 1.52843 19.3627 3.19 0 -0 0 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0216 -13.8069 3.0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + -11.022 -7.27757 3.0 0 -0 1.57907 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1417 -21.4039 3.0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1068 -17.8472 3.0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + 11.1374 -14.1551 3.0 0 0 -1.55117 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0332 -17.61 3.0 0 -0 1.55358 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0086 -21.7566 3.0 0 -0 1.55358 + + + + + model://CGMClassic + true + 11.1777 -18.4129 3.0 0 0 -3.13719 + + + + + model://StorageRack + true + 9.07005 -10.3582 -757768997.0 -2e-06 0 0 + + + + + model://CGMClassic + true + 11.1179 -14.6493 3.0 0 0 -3.13599 + + + + + model://Chair + true + -0.603067 -0.77859 2.99999 0 0 -1.54998 + + + + + model://Chair + true + 0.626494 -0.743667 3.0 0 1e-06 -1.53446 + + + + + model://Scrubs + true + -9.61916 -12.5112 3.0 0 0 -3.12353 + + + + + model://Scrubs + true + 0.054597 4.05849 3.0 0 -0 3.12413 + + + + + model://PatientWheelChair + true + -5.46091 1.23577 3.0 0 0 -1.54828 + + + + + model://Scrubs + true + -5.38513 1.82526 3.0 0 0 -1.63757 + + + + + model://WhiteChipChair + true + -8.87142 9.15707 -757768997.0 0 -0.152685 0 + + + + + model://TrolleyBed + true + 4.85934 -4.87229 -757768997.0 0 -1e-06 0 + + + + + model://SurgicalTrolley + true + 11.4301 3.56328 3.0 0 -0 0 + + + + + model://CGMClassic + true + -11.2304 -21.1134 3.0 0 0 -3.11834 + + + + + model://PotatoChipChair + true + -7.9025 6.49258 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + -7.89464 8.01997 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.39087 6.45458 3.0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.41405 8.00716 3.0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -6.32415 6.47504 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + -6.32415 8.03277 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + -4.83084 6.47504 3.0 0 0 -3.13096 + + + + + model://PotatoChipChair + true + -4.85665 8.03277 3.0 0 0 -3.13096 + + + + + model://VisitorKidSit + true + -7.69163 6.9857 3.0 0 -0 1.56778 + + + + + model://FemaleVisitorSit + true + -7.61435 7.50057 3.0 0 -0 1.60052 + + + + + model://AdjTable + true + 1.2174 -5.60888 3.0 0 0 -0.008733 + + + + + model://PotatoChipChair + true + 8.18933 6.61196 3.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 8.18939 8.16786 3.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.80281 6.60106 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.80281 8.1542 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + 6.73748 6.5915 3.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 6.7505 8.15453 3.0 0 -0 3.13621 + + + + + model://PotatoChipChair + true + 5.17897 6.59309 3.0 0 -0 0 + + + + + model://PotatoChipChair + true + 5.1811 8.14489 3.0 0 -0 0 + + + + + model://aws_robomaker_residential_CoffeeTable_01 + true + -10.2383 -29.9144 3.0 0 -0 0 + + + + + model://aws_robomaker_residential_Sofa_01 + true + -11.077 -30.5544 2.99999 2.6e-05 -3e-06 1.56984 + + + + + model://aws_robomaker_residential_TV_02 + true + -12.4122 -28.4594 4.53211 0 -0 3.13999 + + + + + model://aws_robomaker_residential_KitchenCabinet_01 + true + -11.1379 -25.6941 3.0 0 -0 0 + + + + + model://aws_robomaker_residential_Refrigerator_01 + true + -9.28238 -24.5015 3.0 0 -0 0 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -10.8238 -28.6662 2.999995 -1.3e-05 -2e-06 -1.56116 + + + + + model://aws_robomaker_residential_SofaB_01 + true + -9.73697 -28.6538 2.999997 1.3e-05 -4e-06 -1.56077 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + 1.14738 -6.92303 4.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 2.40772 -3.61975 4.5450800000000005 0 0 -1.57619 + + + + + model://MopCart3 + true + 1.07736 -8.59036 2.999933 0 1e-06 0 + + + + + model://MaleVisitorSit + true + 6.41259 8.18749 3.0 0.000578 -0 -1.56624 + + + + + model://Drawer + true + 3.18472 -6.54185 3.0 0 0 -1.55907 + + + + + model://Drawer + true + 3.19085 -5.94838 3.0 0 0 -1.55907 + + + + + model://OfficeChairBlack + true + 1.20234 -6.39435 3.0 0 -0 3.13125 + + + + + model://OfficeChairBlack + true + -1.25321 -6.4505 3.0 0 -0 3.13125 + + + + + model://AdjTable + true + -1.26728 -5.69226 3.0 0 0 -0.008733 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -0.706092 -6.93108 4.41115 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitA_01 + true + -1.97245 -6.9216 4.41115 0 -0 0 + + + + + model://Drawer + true + -3.02001 -6.54343 3.0 0 -0 1.56555 + + + + + model://Drawer + true + -2.99762 -5.94782 3.0 0 -0 1.56555 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -2.43341 -3.38621 4.5450800000000005 0 -0 1.57083 + + + + + model://ElderLadyPatient + true + -10.9972 0.231354 3.001654 0 -0 0 + + + + + model://ElderLadyPatient + true + -10.8133 -13.5925 3.001657 0 -2e-06 -0.025052 + + + + + model://CGMClassic + true + -11.0878 -7.00992 3.0 0 -0 3.1351 + + + + + model://aws_robomaker_residential_Trash_01 + true + 0.316178 -6.58235 3.000903 0 -2e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -0.436645 -6.57758 3.000903 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_Trash_01 + true + -12.1773 -27.6293 3.000894 -1e-06 -1e-06 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -9.06141 -31.9238 4.38136 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + -11.7398 -31.9011 4.38136 0 -0 0 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 3.0 0 -0 1.56702 + + + + + model://ElderMalePatient + true + -11.1165 -17.2377 3.001656 0 3e-06 0 + + + + + model://InstrumentCart2 + true + -12.0906 -1.87329 3.051875 0 -0 1.57773 + + + + + model://InstrumentCart2 + true + -11.5231 1.34237 3.0 0 -0 0 + + + + + model://aws_robomaker_residential_Carpet_01 + true + -10.7338 -29.9243 3.0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1128 11.6546 3.0 0 -0 0 + + + + + model://MetalCabinet + true + -11.1876 4.2888 3.0 0 -0 3.1387 + + + + + model://CGMClassic + true + -11.0106 8.9505 2.991797 -0.035019 -0.000392 3.13388 + + + + + model://CGMClassic + true + -11.025 7.10335 3.0 -0.035021 1.8e-05 -3.13762 + + + + + model://BedTable + true + -10.4759 1.39442 3.001184 0 -3e-06 0 + + + + + model://BedTable + true + -10.5874 -12.5084 3.001189 0 -0 3.11588 + + + + + model://BedsideTable + true + -12.1499 -2.63111 3.00018 1e-06 -0 -0.00878 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0426 0.066126 3.0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_curtain_half_open_01 + true + -11.0309 -3.75145 3.0 0 -0 1.56614 + + + + + model://aws_robomaker_hospital_floor_01_ceiling + true + 0.016552 0.050728 3.0 0 -0 0 + + + + + model://aws_robomaker_hospital_ramp_01 + true + -1.70996 16.3685 3.0 0 -0 0 + + + + + model://AnesthesiaMachine + true + -1.28478 -21.1127 3.0 0 0 -3.12971 + + + + + model://TrolleyBedPatient + true + -1.83202 -19.2612 3.0 0 -0 0 + + + + + model://Scrubs + true + -0.93616 -18.2252 3.0 0 -0 1.62572 + + + + + model://Shower + true + -1.07422 -16.1332 3.0 0 -0 0 + + + + + model://Shower + true + 0.853327 -16.1492 3.0 0 -0 0 + + + + + model://SurgicalTrolley + true + -0.411421 -22.2085 3.0 0 0 -1.58175 + + + + + model://SurgicalTrolley + true + 3.11747 -19.6565 3.0 0 -0 1.57031 + + + + + model://SurgicalTrolleyMed + true + 0.770804 -19.7749 3.0 0 0 -1.56798 + + + + + model://Scrubs + true + -2.66657 -18.3733 3.0 -0.002221 -0.006608 -1.24025 + + + + + model://InstrumentCart1 + true + -11.8071 -16.1825 3.0 0 -0 1.56702 + + + + + model://InstrumentCart2 + true + -0.869537 -17.7436 3.0 0 0 -0.002595 + + + + + model://StorageRackCovered + true + 0.546476 -18.3985 3.0 0 -0 1.56584 + + + + + model://StorageRack + true + -2.69866 -22.4178 2.999992 0 4e-06 0 + + + + + model://KitchenSink + true + 3.06236 -11.8809 2.998386 0 -0 3.1391 + + + + + model://KitchenSink + true + -3.09305 -11.8988 2.998391 0 -0 0 + + + + + model://Toilet + true + 0.464522 -11.8023 3.005252 0 0.016801 0 + + + + + model://Toilet + true + -0.54552 -11.8033 3.000387 0 0 -3.139 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.14723 -10.143 4.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.16956 -10.1327 4.57344 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 1.2703 -12.9084 4.57344 0 0 -3.14134 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -1.06108 -12.9155 4.57344 0 0 -3.14134 + + + + + model://Toilet + true + 7.4839 1.42958 3.000387 0 -0 -3.13589 + + + + + model://Toilet + true + -7.01185 1.4183 3.000387 0 0 -3.13589 + + + + + model://Toilet + true + -7.02851 -12.7728 3.000377 0 0 -3.13589 + + + + + model://Toilet + true + 7.48696 -12.617 3.000386 0 0 -3.13589 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.89294 -13.6155 4.5450800000000005 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 7.88791 0.445446 4.5450800000000005 0 0 -1.57619 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.92095 0.84255 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -7.90937 -13.3417 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.3841 6.01232 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -12.4276 9.98828 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08927 9.19494 4.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + -8.94468 7.73571 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -9.08305 7.04089 4.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -9.9148 11.9172 4.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + -10.2134 7.89752 4.40573 0 -0 0 + + + + + model://CGMClassic + true + 10.6166 9.06291 2.991797 -0.03501 0.000885 -3.11285 + + + + + model://CGMClassic + true + 10.6006 6.90956 2.991797 -0.035003 0.001133 -3.10576 + + + + + model://MetalCabinet + true + 11.1356 4.33826 3.0 0 -0 3.1387 + + + + + model://MetalCabinet + true + 11.1318 11.6838 3.0 0 0 -0.023701 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 6.78742 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitD_02 + true + 9.06517 9.05858 4.5450800000000005 0 -0 1.57083 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 6.98849 4.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + 12.3972 8.87466 4.84129 0 0 -1.5625 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.4385 -6.00525 4.84129 0 -0 1.56777 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 10.596 7.88308 4.40573 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitD_01 + true + 9.98896 11.914 4.40573 0 -0 0 + + + + + model://ParkingTrolleyMin + true + 0.715846 -17.1496 2.999879 -1e-06 -0 0 + + + + + model://PatientFSit + true + -10.8902 9.18683 3.228965 0 -0 1.58161 + + + + + model://MaleVisitorOnPhone + true + -0.760316 7.58474 3.0 0 0 -1.14974 + + + + + model://FemaleVisitor + true + 0.416835 7.44353 3.0 0 -0 0 + + + + + model://MaleVisitorSit + true + -5.98588 6.41261 3.0 0 -0 1.58808 + + + + + model://Scrubs + true + -1.29468 -20.4093 3.0 0 0 -1.51066 + + + + + model://aws_robomaker_hospital_curtain_open_01 + true + 11.0051 -6.91002 3.0 0 0 -1.58737 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 11.0303 -3.70124 3.0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9586 0.159483 3.0 0 0 -1.58306 + + + + + model://MalePatientBed + true + 11.3771 -7.38891 3.001658 -1e-06 1e-06 3.11598 + + + + + model://CGMClassic + true + 11.3613 -21.8867 3.0 0 0 -3.12292 + + + + + model://StorageRackCoverOpen + true + 9.15016 3.44263 2.999991 1e-06 2e-06 0 + + + + + model://aws_robomaker_warehouse_ClutteringC_01 + true + -10.5553 15.0297 3.0 0 -0 0 + + + + + model://aws_robomaker_warehouse_ClutteringA_01 + true + 10.8233 15.2153 3.0 0 -0 0 + + + + + model://StorageRack + true + -10.1178 -10.4694 3.0 0 -0 0 + + + + + model://StorageRack + true + -9.91557 3.5644 2.999991 1e-06 1e-06 -0.000273 + + + + + model://StorageRackCovered + true + 10.294 -10.577 2.999993 3e-06 -0 3.13389 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 10.9819 -26.2149 3.0 0 0 -1.58306 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 1.31506 -30.5771 3.0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 5.49659 -30.5364 3.0 0 -0 3.1401 + + + + + model://aws_robomaker_hospital_curtain_closed_01 + true + 9.80048 -30.5918 3.0 0 -0 3.1401 + + + + + model://FemaleVisitorSit + true + 7.85005 6.59766 3.0 0 0 -1.5621 + + + + + model://InstrumentCart1 + true + -1.83539 -17.5879 3.0 0 -0 0 + + + + + model://ParkingTrolleyMax + true + 7.71054 -25.1326 2.999879 1e-06 -0 -1.59536 + + + + + model://ElderMalePatient + true + -11.2471 -3.5813 3.001656 0 -0 -0.054192 + + + + + model://aws_robomaker_residential_PortraitE_02 + true + -3.74211 14.8725 4.5437899999999996 0 -0 0 + + + + + model://aws_robomaker_residential_PortraitE_01 + true + 3.85701 14.8779 4.69742 0 -0 0 + + + + + model://Chair + true + -1.37633 -0.795802 3.0 -1e-06 0 -1.54998 + + + + + model://XRayMachine + true + 1.79424 -21.3329 3.0 0 -0 0 + + + + + model://IVStand + true + -11.0966 -16.4963 3.0 0 -0 0 + + + + + model://BloodPressureMonitor + true + -9.96258 -11.9361 3.0 0 -0 0 + + + + + model://IVStand + true + -2.30593 -20.2447 3.0 0 -0 0 + + + + + model://BMWCart + true + -10.931 -1.9483 3.0 0 -0 0 + + + + + model://Scrubs + true + -9.75875 -2.67552 3.0 0 -0 0 + + + + + model://BPCart + true + -10.1788 11.173 3.003446 1e-06 -0 0.003096 + + + + + model://BPCart + true + 12.0072 4.64765 3.0 0 -0 0 + + + + + model://BPCart + true + -11.7236 11.4294 3.0 0 -0 0 + + + + + model://BPCart + true + -11.4703 5.05999 3.003446 1e-06 -0 0.003096 + + + + + model://VendingMachine + true + -8.45694 9.63064 3.0 0 -0 0 + + + + + model://VendingMachine + true + 8.35378 9.64852 2.999997 -6e-06 0 0 + + + + + model://Chair + true + 1.30985 -0.727185 3.0 0 0 -1.53446 + + + + diff --git a/src/robot_sim/worlds/hotel_corridor.world b/src/robot_sim/worlds/hotel_corridor.world new file mode 100644 index 0000000..961ed23 --- /dev/null +++ b/src/robot_sim/worlds/hotel_corridor.world @@ -0,0 +1,145 @@ + + + + + + model://sun + model://ground_plane + + + 0.001 + 1.0 + 1000 + + + + 0.5 0.48 0.45 1 + 0.7 0.68 0.65 1 + + + + + true + + + 0 1.2 1.25 0 0 0 + 30 0.15 2.5 + 0 1.2 1.25 0 0 0 + 30 0.15 2.5 + 0.85 0.82 0.75 10.85 0.82 0.75 1 + + + 0 -1.2 1.25 0 0 0 + 30 0.15 2.5 + 0 -1.2 1.25 0 0 0 + 30 0.15 2.5 + 0.85 0.82 0.75 10.85 0.82 0.75 1 + + + 15 0 1.25 0 0 0 + 0.15 2.55 2.5 + 15 0 1.25 0 0 0 + 0.15 2.55 2.5 + 0.85 0.82 0.75 10.85 0.82 0.75 1 + + -15 0 1.25 0 0 0 + 0.15 2.55 2.5 + -15 0 1.25 0 0 0 + 0.15 2.55 2.5 + 0.85 0.82 0.75 10.85 0.82 0.75 1 + + + + + + true + + -13.5 1.06 1.05 0 0 00.9 0.08 2.1 + -13.5 1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + -10.5 1.06 1.05 0 0 00.9 0.08 2.1 + -10.5 1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + -7.5 1.06 1.05 0 0 00.9 0.08 2.1 + -7.5 1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + -4.5 1.06 1.05 0 0 00.9 0.08 2.1 + -4.5 1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + -1.5 1.06 1.05 0 0 00.9 0.08 2.1 + -1.5 1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + 1.5 1.06 1.05 0 0 00.9 0.08 2.1 + 1.5 1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + 4.5 1.06 1.05 0 0 00.9 0.08 2.1 + 4.5 1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + 7.5 1.06 1.05 0 0 00.9 0.08 2.1 + 7.5 1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + 10.5 1.06 1.05 0 0 00.9 0.08 2.1 + 10.5 1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + 13.5 1.06 1.05 0 0 00.9 0.08 2.1 + 13.5 1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + + + + + true + + -13.5 -1.06 1.05 0 0 00.9 0.08 2.1 + -13.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + -10.5 -1.06 1.05 0 0 00.9 0.08 2.1 + -10.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + -7.5 -1.06 1.05 0 0 00.9 0.08 2.1 + -7.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + -4.5 -1.06 1.05 0 0 00.9 0.08 2.1 + -4.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + -1.5 -1.06 1.05 0 0 00.9 0.08 2.1 + -1.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + 1.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 1.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + 4.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 4.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + 7.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 7.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + 10.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 10.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + 13.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 13.5 -1.06 1.05 0 0 00.9 0.08 2.1 + 0.4 0.25 0.15 10.4 0.25 0.15 1 + + + + + diff --git a/src/robot_sim/worlds/house.world b/src/robot_sim/worlds/house.world new file mode 100644 index 0000000..eec85dc --- /dev/null +++ b/src/robot_sim/worlds/house.world @@ -0,0 +1,52 @@ + + + + + model://sun + + + + + model://ground_plane + + + + 1000.0 + 0.001 + 1 + + + quick + 150 + 0 + 1.400000 + 1 + + + 0.00001 + 0.2 + 2000.000000 + 0.01000 + + + + + + + model://turtlebot3_house + + + + 0.4 0.4 0.4 1 + 0.7 0.7 0.7 1 + true + + + + + 0.0 0.0 17.0 0 1.5708 0 + orbit + + + + diff --git a/src/robot_sim/worlds/restaurant.world b/src/robot_sim/worlds/restaurant.world new file mode 100644 index 0000000..bc49eea --- /dev/null +++ b/src/robot_sim/worlds/restaurant.world @@ -0,0 +1,246 @@ + + + + + + model://sun + model://ground_plane + + + 0.001 + 1.0 + 1000 + + + + 0.6 0.6 0.6 1 + 0.8 0.8 0.85 1 + true + + + + + true + + + + 0 5 1.25 0 0 0 + 12.15 0.15 2.5 + 0 5 1.25 0 0 0 + 12.15 0.15 2.5 + 0.9 0.88 0.82 10.9 0.88 0.82 1 + + + 0 -5 1.25 0 0 0 + 12.15 0.15 2.5 + 0 -5 1.25 0 0 0 + 12.15 0.15 2.5 + 0.9 0.88 0.82 10.9 0.88 0.82 1 + + + 6 0 1.25 0 0 0 + 0.15 10 2.5 + 6 0 1.25 0 0 0 + 0.15 10 2.5 + 0.9 0.88 0.82 10.9 0.88 0.82 1 + + + -6 0 1.25 0 0 0 + 0.15 10 2.5 + -6 0 1.25 0 0 0 + 0.15 10 2.5 + 0.9 0.88 0.82 10.9 0.88 0.82 1 + + + + + + + + true + + -2 0 1.25 0 0 0 + 0.222.5 + -2 0 1.25 0 0 0 + 0.222.5 + 0.75 0.72 0.68 10.75 0.72 0.68 1 + + 2 0 1.25 0 0 0 + 0.222.5 + 2 0 1.25 0 0 0 + 0.222.5 + 0.75 0.72 0.68 10.75 0.72 0.68 1 + + + + + + true + + 0 4.2 0.55 0 0 0 + 5.0 0.6 1.1 + 0 4.2 0.55 0 0 0 + 5.0 0.6 1.1 + 0.35 0.22 0.12 10.35 0.22 0.12 1 + + + + + + true-3.5 2.0 0 0 0 0 + + 0 0 0.755 0 0 01.2 0.8 0.05 + 0 0 0.755 0 0 01.2 0.8 0.05 + 0.45 0.28 0.15 10.45 0.28 0.15 1 + 0.45 0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + + + + + true3.5 2.0 0 0 0 0 + + 0 0 0.755 0 0 01.2 0.8 0.05 + 0 0 0.755 0 0 01.2 0.8 0.05 + 0.45 0.28 0.15 10.45 0.28 0.15 1 + 0.45 0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + + + + + true-3.5 -2.0 0 0 0 0 + + 0 0 0.755 0 0 01.2 0.8 0.05 + 0 0 0.755 0 0 01.2 0.8 0.05 + 0.45 0.28 0.15 10.45 0.28 0.15 1 + 0.45 0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + + + + + true3.5 -2.0 0 0 0 0 + + 0 0 0.755 0 0 01.2 0.8 0.05 + 0 0 0.755 0 0 01.2 0.8 0.05 + 0.45 0.28 0.15 10.45 0.28 0.15 1 + 0.45 0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + 0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + -0.45 -0.25 0.365 0 0 00.06 0.06 0.73 + + + + + + true + + + -4.4 2.0 0.45 0 0 00.42 0.42 0.05 + -4.4 2.0 0.45 0 0 00.42 0.42 0.05 + 0.2 0.2 0.22 10.2 0.2 0.22 1 + -4.6 2.0 0.68 0 0 00.05 0.42 0.42 + -4.6 2.0 0.68 0 0 00.05 0.42 0.42 + + -2.6 2.0 0.45 0 0 00.42 0.42 0.05 + -2.6 2.0 0.45 0 0 00.42 0.42 0.05 + 0.2 0.2 0.22 10.2 0.2 0.22 1 + + + 4.4 2.0 0.45 0 0 00.42 0.42 0.05 + 4.4 2.0 0.45 0 0 00.42 0.42 0.05 + 0.2 0.2 0.22 10.2 0.2 0.22 1 + + 2.6 2.0 0.45 0 0 00.42 0.42 0.05 + 2.6 2.0 0.45 0 0 00.42 0.42 0.05 + 0.2 0.2 0.22 10.2 0.2 0.22 1 + + + -4.4 -2.0 0.45 0 0 00.42 0.42 0.05 + -4.4 -2.0 0.45 0 0 00.42 0.42 0.05 + 0.2 0.2 0.22 10.2 0.2 0.22 1 + + 4.4 -2.0 0.45 0 0 00.42 0.42 0.05 + 4.4 -2.0 0.45 0 0 00.42 0.42 0.05 + 0.2 0.2 0.22 10.2 0.2 0.22 1 + + + -4.4 2.0 0.21 0 0 00.35 0.35 0.42 + -4.4 2.0 0.21 0 0 00.35 0.35 0.42 + -2.6 2.0 0.21 0 0 00.35 0.35 0.42 + -2.6 2.0 0.21 0 0 00.35 0.35 0.42 + 4.4 2.0 0.21 0 0 00.35 0.35 0.42 + 4.4 2.0 0.21 0 0 00.35 0.35 0.42 + 2.6 2.0 0.21 0 0 00.35 0.35 0.42 + 2.6 2.0 0.21 0 0 00.35 0.35 0.42 + -4.4 -2.0 0.21 0 0 00.35 0.35 0.42 + -4.4 -2.0 0.21 0 0 00.35 0.35 0.42 + 4.4 -2.0 0.21 0 0 00.35 0.35 0.42 + 4.4 -2.0 0.21 0 0 00.35 0.35 0.42 + + + + + + true + + 0 -3.5 0.06 0 0 0 + 0.35 0.25 0.12 + 0 -3.5 0.06 0 0 0 + 0.35 0.25 0.12 + 0.6 0.1 0.1 10.6 0.1 0.1 1 + + + + + diff --git a/src/slam_core/CMakeLists.txt b/src/slam_core/CMakeLists.txt new file mode 100644 index 0000000..6334800 --- /dev/null +++ b/src/slam_core/CMakeLists.txt @@ -0,0 +1,78 @@ +cmake_minimum_required(VERSION 3.0.2) +project(slam_core) + +add_compile_options(-std=c++14) + +find_package(catkin REQUIRED COMPONENTS + roscpp + nav_msgs + sensor_msgs + geometry_msgs + std_msgs + tf2 + tf2_ros + tf2_geometry_msgs +) + +find_package(Eigen3 REQUIRED) + +# ============================================================ +# GTSAM la TUY CHON o giai doan nay. +# +# GTSAM khong phai catkin package - phai build ngoai workspace: +# git clone https://github.com/borglab/gtsam.git ~/libs/gtsam +# cmake -DGTSAM_USE_SYSTEM_EIGEN=ON -DGTSAM_BUILD_TESTS=OFF .. +# make -j && sudo make install +# +# QUIET de workspace van build xanh khi chua co. Khi da cai, macro +# SLAM_CORE_HAS_GTSAM duoc bat va phan cai dat that thay cho stub. +# ============================================================ +find_package(GTSAM QUIET) + +catkin_package( + INCLUDE_DIRS include + LIBRARIES ${PROJECT_NAME} + CATKIN_DEPENDS roscpp nav_msgs sensor_msgs geometry_msgs std_msgs + tf2 tf2_ros tf2_geometry_msgs +) + +include_directories( + include + ${catkin_INCLUDE_DIRS} + ${EIGEN3_INCLUDE_DIRS} +) + +add_library(${PROJECT_NAME} src/graph_builder.cpp) +target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES}) + +if(GTSAM_FOUND) + message(STATUS "slam_core: GTSAM ${GTSAM_VERSION} - bien dich voi back-end that") + target_include_directories(${PROJECT_NAME} PUBLIC ${GTSAM_INCLUDE_DIR}) + target_link_libraries(${PROJECT_NAME} gtsam) + target_compile_definitions(${PROJECT_NAME} PUBLIC SLAM_CORE_HAS_GTSAM) +else() + message(WARNING + "slam_core: KHONG tim thay GTSAM -> bien dich o che do PASSTHROUGH.\n" + " Node se chay va publish pose, nhung chi tich phan odometry:\n" + " khong toi uu, khong loop closure, pose se troi khong gioi han.\n" + " Day la du kien o giai doan nay - xem docs/ROADMAP.md GD5.") +endif() + +add_executable(slam_core_node src/slam_core_node.cpp) +target_link_libraries(slam_core_node ${PROJECT_NAME} ${catkin_LIBRARIES}) +add_dependencies(slam_core_node + ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + +install(TARGETS ${PROJECT_NAME} slam_core_node + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +) + +install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} +) + +install(DIRECTORY launch config + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} +) diff --git a/src/slam_core/config/slam_core.yaml b/src/slam_core/config/slam_core.yaml new file mode 100644 index 0000000..18dfedf --- /dev/null +++ b/src/slam_core/config/slam_core.yaml @@ -0,0 +1,46 @@ +# ============================================================= +# slam_core - tham so factor graph 2.5D +# +# ⚠️⚠️ CAC GIA TRI COVARIANCE O DAY LA CHO TAM, CHUA DUOC HIEU CHUAN ⚠️⚠️ +# +# Chung PHAI duoc thay bang so do that: +# gyro_noise_sigma <- allan_variance_ros, de yen >= 3 gio tren chip that +# odom_sigma_* <- UMBmark: chay hinh vuong 4x4m ca hai chieu, do lech +# scan_sigma_* <- do phan tan cua scan matching tren du lieu tinh +# +# Doan bua o day se lam ca he thong sai ma khong biet vi sao: back-end se tin +# nham nguon du lieu xau va bo qua nguon tot. Day cung la ly do kinh nghiem +# nganh noi ~80% loi SLAM thuc te den tu hieu chuan/dong bo, khong phai thuat toan. +# ============================================================= + +slam_core: + map_frame: map + odom_frame: odom + base_frame: base_footprint + + # Tao keyframe moi khi di duoc bao xa / quay bao nhieu + keyframe_distance: 0.25 # m + keyframe_angle: 0.20 # rad (~11 do) + + publish_tf: true # map -> odom. KHONG publish odom -> base_footprint. + + # ---- Odometry banh xe ---- + # sigma tren MOI MET di duoc (sai so tich luy theo quang duong, khong theo thoi gian) + odom_sigma_xy: 0.02 + odom_sigma_theta: 0.02 + odom_slip_multiplier: 100.0 # nhan covariance khi wheel_odom bao truot + + # ---- IMU ---- + gyro_noise_sigma: 4.9e-4 # rad/s - tam tinh tu datasheet ICM-42688-P + gyro_bias_rw_sigma: 1.0e-5 + + # ---- LiDAR scan matching (GD5) ---- + scan_sigma_xy: 0.03 + scan_sigma_theta: 0.02 + + # ---- Loop closure (GD5) ---- + # CO Y de long: chong loop sai bang SWITCHABLE CONSTRAINT, khong phai bang + # nguong covariance chat. Hanh lang khach san co hang chuc cua giong het nhau; + # mot false loop closure duy nhat pha nat toan bo ban do. + loop_sigma_xy: 0.10 + loop_sigma_theta: 0.05 diff --git a/src/slam_core/include/slam_core/graph_builder.hpp b/src/slam_core/include/slam_core/graph_builder.hpp new file mode 100644 index 0000000..5d762d4 --- /dev/null +++ b/src/slam_core/include/slam_core/graph_builder.hpp @@ -0,0 +1,82 @@ +/** + * graph_builder - Giao dien xay dung factor graph 2.5D. + * + * ================== TRANG THAI: KHUNG, CHUA CO THUAT TOAN ================== + * Giai doan nay chi dung DUONG ONG ROS va cho trong cho graph. Phan toi uu + * that (GTSAM iSAM2) lam o giai doan sau - xem docs/ROADMAP.md GD5. + * + * Ly do lam theo thu tu nay: phai co baseline (Cartographer / RTAB-Map) va + * rosbag that TRUOC, de con biet factor graph tu viet co thuc su tot hon khong. + * Xay 8 tuan roi moi phat hien thua giai phap co san la that bai dat gia. + * + * ================== THIET KE GRAPH DU KIEN ================== + * Bien: Pose2D moi keyframe + bias gyro Z + * + * Factor: + * ImuFactor <- IMU. CHI XUAT HIEN O DAY, khong noi nao khac. + * BetweenFactor <- wheel odometry (covariance dong theo slip) + * BetweenFactor <- LiDAR scan-to-map [rang buoc chinh] + * LoopClosureFactor <- co switchable constraint / DCS + * + * Toi uu: iSAM2 (tang dan, khong giai lai tu dau moi lan) + * + * ================== VI SAO LOOP CLOSURE PHAI CO SWITCHABLE CONSTRAINT ================== + * Hanh lang khach san co hang chuc cua GIONG HET NHAU. Mot false loop closure + * duy nhat PHA NAT toan bo ban do. Switchable constraint cho optimizer kha nang + * tu "tat" mot loop dang ngo thay vi bi no keo lech. + * + * Kiem chung bang world hotel_corridor truoc khi tin vao ket qua o restaurant. + */ + +#ifndef SLAM_CORE_GRAPH_BUILDER_HPP +#define SLAM_CORE_GRAPH_BUILDER_HPP + +#include "slam_core/types.hpp" + +#include +#include + +namespace slam_core +{ + +class GraphBuilder +{ +public: + explicit GraphBuilder(const NoiseConfig& noise); + ~GraphBuilder(); + + /** GTSAM co san luc bien dich khong? + * false -> dang chay che do passthrough (chi tich phan odometry). */ + static bool hasBackend(); + + /** Them mot keyframe, noi voi keyframe truoc bang rang buoc odometry. */ + void addOdometryConstraint(const ros::Time& stamp, const Pose2D& delta, + double sigma_scale); + + /** Them rang buoc tu LiDAR scan matching giua hai keyframe. */ + void addScanConstraint(uint64_t from_id, uint64_t to_id, const Pose2D& relative); + + /** Them loop closure. `switch_prior` la do tin cay ban dau [0..1] - + * optimizer duoc phep ha xuong neu rang buoc nay mau thuan phan con lai. */ + void addLoopClosure(uint64_t from_id, uint64_t to_id, const Pose2D& relative, + double switch_prior); + + /** Chay mot buoc toi uu tang dan. */ + void update(); + + /** Pose moi nhat sau toi uu. */ + Pose2D latestPose() const; + + /** Toan bo quy dao (de danh gia bang slam_eval/eval_ate.py). */ + std::vector trajectory() const; + + size_t size() const; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace slam_core + +#endif // SLAM_CORE_GRAPH_BUILDER_HPP diff --git a/src/slam_core/include/slam_core/types.hpp b/src/slam_core/include/slam_core/types.hpp new file mode 100644 index 0000000..cad6ddb --- /dev/null +++ b/src/slam_core/include/slam_core/types.hpp @@ -0,0 +1,96 @@ +/** + * Kieu du lieu chung cho slam_core. + * + * ================== VI SAO TRANG THAI LA SE(2), KHONG PHAI SE(3) ================== + * Robot dich vu chay tren san phang. Voi bo cam bien nay, ba chieu tu do bo sung + * (z, roll, pitch) gan nhu KHONG DUOC QUAN SAT: + * + * Encoder -> khong noi gi ve z/roll/pitch (chi do chuyen dong phang) + * LiDAR 2D -> khong noi gi ve z (chi quet MOT mat phang) + * IMU -> roll/pitch tot (tu trong luc), nhung z TROI TU DO + * D410 -> co, nhung yeu: rolling shutter, FOV 69, emitter lam nhieu feature + * + * => Chi co ~1.5 nguon cho 3 chieu bo sung. Uoc luong tu do chung se cho ra + * z troi va pitch troi - sai so KHONG CO co so vat ly nao, vi robot van + * dang o tren san phang. + * + * => Te hon: LiDAR 2D VON GIA DINH chuyen dong phang. Khi robot nghieng, mat + * phang quet lech len tran / xuong san va scan matching nhan du lieu RAC. + * Nghia la rang buoc MANH NHAT trong he lai la rang buoc DOI HOI mat phang. + * + * Nguyen tac: dung uoc luong bien ma cam bien khong quan sat duoc. Moi chieu + * tu do thua la mot kenh cho drift chui vao, khong phai mot tinh nang. + * + * Roll/pitch van duoc DUNG - nhung o perception_3d/gravity_align_nodelet, noi + * chung duoc DO tu trong luc de bu nghieng cho point cloud. + */ + +#ifndef SLAM_CORE_TYPES_HPP +#define SLAM_CORE_TYPES_HPP + +#include +#include + +namespace slam_core +{ + +/** Pose 2D. Day la BIEN DUOC TOI UU trong factor graph. */ +struct Pose2D +{ + double x = 0.0; + double y = 0.0; + double theta = 0.0; +}; + +/** Mot node trong factor graph (mot keyframe). */ +struct KeyframeState +{ + uint64_t id = 0; + ros::Time stamp; + Pose2D pose; + + // Bias IMU - duoc toi uu cung voi pose. Bias gyro Z quan trong nhat: + // no truc tiep gay troi yaw, va troi yaw la thu giet odometry robot mat dat. + double gyro_bias_z = 0.0; + + // Roll/pitch DO tu trong luc tai thoi diem nay. KHONG PHAI bien toi uu - + // luu lai de bu nghieng khi ghep du lieu cam bien. + double measured_roll = 0.0; + double measured_pitch = 0.0; +}; + +/** Trong so cho tung loai rang buoc. + * + * ⚠️ Cac gia tri nay PHAI den tu hieu chuan that: + * - IMU : allan_variance_ros chay >= 3 gio tren chip that + * - Encoder : UMBmark (chay hinh vuong 4x4m ca hai chieu) + * - LiDAR : do phan tan cua scan matching tren du lieu tinh + * Doan bua o day se lam ca he thong sai ma khong biet vi sao. + */ +struct NoiseConfig +{ + // Odometry banh xe - sigma tren MOI MET di duoc (khong phai moi giay: + // sai so odometry tich luy theo quang duong, khong theo thoi gian) + double odom_sigma_xy = 0.02; + double odom_sigma_theta = 0.02; + + // Nhan covariance khi phat hien truot banh + double odom_slip_multiplier = 100.0; + + // IMU + double gyro_noise_sigma = 4.9e-4; + double gyro_bias_rw_sigma = 1.0e-5; + + // LiDAR scan matching + double scan_sigma_xy = 0.03; + double scan_sigma_theta = 0.02; + + // Loop closure - CO Y de long hon, vi dung cach chong loop sai la + // switchable constraint chu khong phai nguong covariance chat. + double loop_sigma_xy = 0.10; + double loop_sigma_theta = 0.05; +}; + +} // namespace slam_core + +#endif // SLAM_CORE_TYPES_HPP diff --git a/src/slam_core/launch/slam_core.launch b/src/slam_core/launch/slam_core.launch new file mode 100644 index 0000000..99945f3 --- /dev/null +++ b/src/slam_core/launch/slam_core.launch @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/src/slam_core/package.xml b/src/slam_core/package.xml new file mode 100644 index 0000000..b63c7b5 --- /dev/null +++ b/src/slam_core/package.xml @@ -0,0 +1,28 @@ + + + slam_core + 0.1.0 + + Factor graph 2.5D cho robot dich vu: pose SE(2) + bias gyro. + Hien tai la khung duong ong ROS o che do passthrough; phan toi uu GTSAM + lam o giai doan 5 (xem docs/ROADMAP.md). + + GTSAM la thu vien CMake thuan, KHONG phai catkin package - build ngoai + workspace. CMakeLists dung find_package(GTSAM QUIET) nen package nay van + build xanh khi chua cai GTSAM. + + quangtrung + BSD + + catkin + + roscpp + nav_msgs + sensor_msgs + geometry_msgs + std_msgs + tf2 + tf2_ros + tf2_geometry_msgs + eigen + diff --git a/src/slam_core/src/graph_builder.cpp b/src/slam_core/src/graph_builder.cpp new file mode 100644 index 0000000..6121001 --- /dev/null +++ b/src/slam_core/src/graph_builder.cpp @@ -0,0 +1,146 @@ +/** + * graph_builder - Hien tai la PASSTHROUGH (chi tich phan odometry). + * + * File nay bien dich duoc CA KHI CHUA CAI GTSAM. Ly do: GTSAM la thu vien + * CMake thuan, khong phai catkin package, phai build ngoai workspace. Neu bat + * buoc phai co no thi ca workspace se khong build duoc tu ngay dau - lam cham + * moi thu khac ma khong doi lai loi ich gi. + * + * CMakeLists dung find_package(GTSAM QUIET). Khi nao cai GTSAM roi, macro + * SLAM_CORE_HAS_GTSAM se duoc bat va phan cai dat that thay cho stub nay. + */ + +#include "slam_core/graph_builder.hpp" + +#include + +#include + +#ifdef SLAM_CORE_HAS_GTSAM +// GD5: them include GTSAM o day (NonlinearFactorGraph, ISAM2, Pose2, ...) +#endif + +namespace slam_core +{ +namespace +{ +double normalizeAngle(double a) +{ + while (a > M_PI) a -= 2.0 * M_PI; + while (a < -M_PI) a += 2.0 * M_PI; + return a; +} +} // namespace + +struct GraphBuilder::Impl +{ + NoiseConfig noise; + std::vector keyframes; + uint64_t next_id = 0; + +#ifdef SLAM_CORE_HAS_GTSAM + // GD5: gtsam::NonlinearFactorGraph graph; + // gtsam::Values values; + // std::unique_ptr isam; +#endif +}; + +GraphBuilder::GraphBuilder(const NoiseConfig& noise) + : impl_(new Impl) +{ + impl_->noise = noise; + + if (!hasBackend()) + { + ROS_WARN("slam_core: GTSAM chua co -> chay che do PASSTHROUGH."); + ROS_WARN("slam_core: chi tich phan odometry, KHONG co toi uu, KHONG loop closure."); + ROS_WARN("slam_core: pose se TROI khong gioi han. Day la du kien o giai doan nay."); + } + else + { + ROS_INFO("slam_core: GTSAM san sang."); + } + + // Keyframe goc + KeyframeState origin; + origin.id = impl_->next_id++; + origin.stamp = ros::Time(0); + impl_->keyframes.push_back(origin); +} + +GraphBuilder::~GraphBuilder() = default; + +bool GraphBuilder::hasBackend() +{ +#ifdef SLAM_CORE_HAS_GTSAM + return true; +#else + return false; +#endif +} + +void GraphBuilder::addOdometryConstraint(const ros::Time& stamp, const Pose2D& delta, + double sigma_scale) +{ + (void)sigma_scale; // GD5: dung de dieu chinh trong so khi truot banh + + const KeyframeState& prev = impl_->keyframes.back(); + + KeyframeState kf; + kf.id = impl_->next_id++; + kf.stamp = stamp; + kf.gyro_bias_z = prev.gyro_bias_z; + + // Ghep pose: p_new = p_prev (+) delta (delta o he toa do cua p_prev) + const double c = std::cos(prev.pose.theta); + const double s = std::sin(prev.pose.theta); + kf.pose.x = prev.pose.x + c * delta.x - s * delta.y; + kf.pose.y = prev.pose.y + s * delta.x + c * delta.y; + kf.pose.theta = normalizeAngle(prev.pose.theta + delta.theta); + + impl_->keyframes.push_back(kf); + +#ifdef SLAM_CORE_HAS_GTSAM + // GD5: graph.add(BetweenFactor(prev.id, kf.id, Pose2(...), noise_model)); +#endif +} + +void GraphBuilder::addScanConstraint(uint64_t from_id, uint64_t to_id, + const Pose2D& relative) +{ + (void)from_id; (void)to_id; (void)relative; + ROS_WARN_ONCE("slam_core: addScanConstraint chua cai dat (GD5)."); +} + +void GraphBuilder::addLoopClosure(uint64_t from_id, uint64_t to_id, + const Pose2D& relative, double switch_prior) +{ + (void)from_id; (void)to_id; (void)relative; (void)switch_prior; + ROS_WARN_ONCE("slam_core: addLoopClosure chua cai dat (GD5). " + "Khi cai, BAT BUOC dung switchable constraint - hanh lang khach san " + "co hang chuc cua giong het nhau."); +} + +void GraphBuilder::update() +{ +#ifdef SLAM_CORE_HAS_GTSAM + // GD5: isam->update(graph, values); values = isam->calculateEstimate(); +#endif +} + +Pose2D GraphBuilder::latestPose() const +{ + return impl_->keyframes.back().pose; +} + +std::vector GraphBuilder::trajectory() const +{ + return impl_->keyframes; +} + +size_t GraphBuilder::size() const +{ + return impl_->keyframes.size(); +} + +} // namespace slam_core diff --git a/src/slam_core/src/slam_core_node.cpp b/src/slam_core/src/slam_core_node.cpp new file mode 100644 index 0000000..7cd281a --- /dev/null +++ b/src/slam_core/src/slam_core_node.cpp @@ -0,0 +1,231 @@ +/** + * slam_core_node - Duong ong ROS cho SLAM 2.5D. + * + * ================== TRANG THAI HIEN TAI ================== + * Duong ong day du (subscribe / TF / publish), nhung back-end la PASSTHROUGH: + * chi tich phan odometry, chua toi uu, chua loop closure. Pose se troi. + * Day la DU KIEN - xem graph_builder.cpp va docs/ROADMAP.md GD5. + * + * ================== QUY UOC TF ================== + * map -> odom : node NAY publish (sua drift, DUOC PHEP nhay) + * odom -> base_footprint : robot_localization EKF publish (muot, lien tuc, co drift) + * + * Khong duoc publish odom -> base_footprint o day. Hai node cung publish mot + * canh TF la loi kinh dien, va rat kho debug vi TF khong bao loi - no chi cho + * ra ket qua nhay lung tung. + * + * Che do passthrough thi map->odom = identity, dung nhu ky vong. + */ + +#include "slam_core/graph_builder.hpp" +#include "slam_core/types.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace +{ +double normalizeAngle(double a) +{ + while (a > M_PI) a -= 2.0 * M_PI; + while (a < -M_PI) a += 2.0 * M_PI; + return a; +} +} // namespace + +class SlamCoreNode +{ +public: + SlamCoreNode(ros::NodeHandle& nh, ros::NodeHandle& pnh) + { + pnh.param("map_frame", map_frame_, "map"); + pnh.param("odom_frame", odom_frame_, "odom"); + pnh.param("base_frame", base_frame_, "base_footprint"); + + pnh.param("keyframe_distance", keyframe_distance_, 0.25); // m + pnh.param("keyframe_angle", keyframe_angle_, 0.20); // rad + pnh.param("publish_tf", publish_tf_, true); + + slam_core::NoiseConfig noise; + pnh.param("odom_sigma_xy", noise.odom_sigma_xy, noise.odom_sigma_xy); + pnh.param("odom_sigma_theta", noise.odom_sigma_theta, noise.odom_sigma_theta); + pnh.param("odom_slip_multiplier", noise.odom_slip_multiplier, noise.odom_slip_multiplier); + pnh.param("gyro_noise_sigma", noise.gyro_noise_sigma, noise.gyro_noise_sigma); + pnh.param("scan_sigma_xy", noise.scan_sigma_xy, noise.scan_sigma_xy); + pnh.param("scan_sigma_theta", noise.scan_sigma_theta, noise.scan_sigma_theta); + + graph_ = std::make_shared(noise); + + pose_pub_ = nh.advertise("slam/pose", 10); + + odom_sub_ = nh.subscribe("odom", 50, &SlamCoreNode::onOdom, this); + scan_sub_ = nh.subscribe("scan", 10, &SlamCoreNode::onScan, this); + imu_sub_ = nh.subscribe("imu/data_raw", 200, &SlamCoreNode::onImu, this); + + ROS_INFO("slam_core: keyframe moi %.2f m hoac %.2f rad", + keyframe_distance_, keyframe_angle_); + ROS_INFO("slam_core: publish TF %s -> %s%s", + map_frame_.c_str(), odom_frame_.c_str(), + publish_tf_ ? "" : " (DA TAT)"); + ROS_WARN("slam_core: KHONG publish %s -> %s (do robot_localization EKF lo).", + odom_frame_.c_str(), base_frame_.c_str()); + } + +private: + void onImu(const sensor_msgs::Imu::ConstPtr& msg) + { + // Roll/pitch DO tu trong luc - luu de gan vao keyframe. + // Khong phai bien toi uu; xem types.hpp. + const double ax = msg->linear_acceleration.x; + const double ay = msg->linear_acceleration.y; + const double az = msg->linear_acceleration.z; + const double n = std::sqrt(ax * ax + ay * ay + az * az); + if (n > 1e-3) + { + measured_roll_ = std::atan2(ay, az); + measured_pitch_ = std::atan2(-ax, std::sqrt(ay * ay + az * az)); + } + have_imu_ = true; + } + + void onScan(const sensor_msgs::LaserScan::ConstPtr& msg) + { + last_scan_ = msg; + have_scan_ = true; + // GD5: scan matching -> graph_->addScanConstraint(...) + // va phat hien loop closure -> graph_->addLoopClosure(...) + ROS_WARN_ONCE("slam_core: scan matching chua cai dat - /scan chi duoc nhan, " + "chua dung. Xem docs/ROADMAP.md GD5."); + } + + void onOdom(const nav_msgs::Odometry::ConstPtr& msg) + { + const double x = msg->pose.pose.position.x; + const double y = msg->pose.pose.position.y; + const double yaw = tf2::getYaw(msg->pose.pose.orientation); + + if (!have_odom_) + { + last_kf_x_ = x; last_kf_y_ = y; last_kf_yaw_ = yaw; + have_odom_ = true; + ROS_INFO("slam_core: da nhan odometry dau tien."); + return; + } + + const double dx = x - last_kf_x_; + const double dy = y - last_kf_y_; + const double dist = std::hypot(dx, dy); + const double dyaw = std::fabs(normalizeAngle(yaw - last_kf_yaw_)); + + if (dist >= keyframe_distance_ || dyaw >= keyframe_angle_) + { + // Delta trong he toa do cua keyframe truoc + const double c = std::cos(last_kf_yaw_); + const double s = std::sin(last_kf_yaw_); + + slam_core::Pose2D delta; + delta.x = c * dx + s * dy; + delta.y = -s * dx + c * dy; + delta.theta = normalizeAngle(yaw - last_kf_yaw_); + + graph_->addOdometryConstraint(msg->header.stamp, delta, 1.0); + graph_->update(); + + last_kf_x_ = x; last_kf_y_ = y; last_kf_yaw_ = yaw; + } + + publishPose(msg->header.stamp, x, y, yaw); + } + + void publishPose(const ros::Time& stamp, double odom_x, double odom_y, double odom_yaw) + { + const slam_core::Pose2D est = graph_->latestPose(); + + geometry_msgs::PoseWithCovarianceStamped p; + p.header.stamp = stamp; + p.header.frame_id = map_frame_; + p.pose.pose.position.x = est.x; + p.pose.pose.position.y = est.y; + + tf2::Quaternion q; + q.setRPY(0.0, 0.0, est.theta); + p.pose.pose.orientation.x = q.x(); + p.pose.pose.orientation.y = q.y(); + p.pose.pose.orientation.z = q.z(); + p.pose.pose.orientation.w = q.w(); + + // Che do passthrough: khong co uoc luong covariance dang tin. + // Danh dau bang gia tri lon de tang tren khong tin nham. + p.pose.covariance[0] = 1.0; + p.pose.covariance[7] = 1.0; + p.pose.covariance[35] = 1.0; + pose_pub_.publish(p); + + if (!publish_tf_) + return; + + // map -> odom = T_map_base * (T_odom_base)^-1 + // Passthrough thi hai cai bang nhau -> ket qua la identity. + const double c = std::cos(-odom_yaw); + const double s = std::sin(-odom_yaw); + const double inv_x = -(c * odom_x - s * odom_y); + const double inv_y = -(s * odom_x + c * odom_y); + const double inv_yaw = -odom_yaw; + + const double ce = std::cos(est.theta); + const double se = std::sin(est.theta); + + geometry_msgs::TransformStamped tf; + tf.header.stamp = stamp; + tf.header.frame_id = map_frame_; + tf.child_frame_id = odom_frame_; + tf.transform.translation.x = est.x + ce * inv_x - se * inv_y; + tf.transform.translation.y = est.y + se * inv_x + ce * inv_y; + tf.transform.translation.z = 0.0; + + tf2::Quaternion qt; + qt.setRPY(0.0, 0.0, normalizeAngle(est.theta + inv_yaw)); + tf.transform.rotation.x = qt.x(); + tf.transform.rotation.y = qt.y(); + tf.transform.rotation.z = qt.z(); + tf.transform.rotation.w = qt.w(); + + tf_broadcaster_.sendTransform(tf); + } + + std::string map_frame_, odom_frame_, base_frame_; + double keyframe_distance_ = 0.25, keyframe_angle_ = 0.20; + bool publish_tf_ = true; + + std::shared_ptr graph_; + + bool have_odom_ = false, have_imu_ = false, have_scan_ = false; + double last_kf_x_ = 0.0, last_kf_y_ = 0.0, last_kf_yaw_ = 0.0; + double measured_roll_ = 0.0, measured_pitch_ = 0.0; + sensor_msgs::LaserScan::ConstPtr last_scan_; + + ros::Publisher pose_pub_; + ros::Subscriber odom_sub_, scan_sub_, imu_sub_; + tf2_ros::TransformBroadcaster tf_broadcaster_; +}; + +int main(int argc, char** argv) +{ + ros::init(argc, argv, "slam_core"); + ros::NodeHandle nh; + ros::NodeHandle pnh("~"); + SlamCoreNode node(nh, pnh); + ros::spin(); + return 0; +} diff --git a/src/slam_eval/CMakeLists.txt b/src/slam_eval/CMakeLists.txt new file mode 100644 index 0000000..b65f093 --- /dev/null +++ b/src/slam_eval/CMakeLists.txt @@ -0,0 +1,22 @@ +cmake_minimum_required(VERSION 3.0.2) +project(slam_eval) + +find_package(catkin REQUIRED) + +catkin_package() + +catkin_install_python(PROGRAMS + scripts/eval_ate.py + scripts/repeatability.py + scripts/resource_profile.py + scripts/watch_loc.py + DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +) + +install(PROGRAMS scripts/record_bag.sh + DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +) + +install(DIRECTORY config + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} +) diff --git a/src/slam_eval/config/topics_to_record.yaml b/src/slam_eval/config/topics_to_record.yaml new file mode 100644 index 0000000..3035b32 --- /dev/null +++ b/src/slam_eval/config/topics_to_record.yaml @@ -0,0 +1,38 @@ +# Danh sach topic ghi vao rosbag - tai lieu tham chieu cho record_bag.sh +# +# NGUYEN TAC: chi ghi DU LIEU THO. Bag ton tai de chay lai thuat toan tren +# cung dau vao; ghi ca dau ra chi lam phinh file ma khong so sanh duoc. + +raw_sensors: + - /scan # LiDAR 2D ToF + - /imu/data_raw # ICM-42688-P + - /joint_states # encoder banh xe (giao dien chung sim/that) + - /baro/pressure # BMP390 - phat hien doi tang + - /baro/temperature + +camera: + # Ghi ANH, khong ghi cloud: cloud tai tao duoc bang depth_image_proc + # va nho hon ~10 lan. + - /camera/depth/image_rect_raw + - /camera/depth/camera_info + - /camera/infra1/image_rect_raw + - /camera/infra1/camera_info + - /camera/infra2/image_rect_raw + - /camera/infra2/camera_info + +safety_and_control: + - /bumper + - /cmd_vel + - /cmd_vel_safe + +tf: + - /tf_static # KHONG ghi /tf: se duoc sinh lai khi chay lai + +simulation_only: + # CHI co trong Gazebo. Tren robot that khong ton tai. + # Chi dung cho slam_eval, khong node uoc luong nao duoc subscribe. + - /ground_truth/odom + +# KHONG GHI (deu la dau ra, tai tao duoc): +# /odom /odometry/filtered /perception/cloud_* /map /projected_map +# /octomap_* /slam/pose /tf diff --git a/src/slam_eval/package.xml b/src/slam_eval/package.xml new file mode 100644 index 0000000..efa12f1 --- /dev/null +++ b/src/slam_eval/package.xml @@ -0,0 +1,21 @@ + + + slam_eval + 0.1.0 + + Cong cu danh gia: ATE/RPE bang ground truth cua Gazebo, repeatability, + profile tai nguyen (co che do CPU-only de uoc luong cho IPC), ghi rosbag. + + quangtrung + BSD + + catkin + + rospy + rosbag + rosnode + nav_msgs + geometry_msgs + std_msgs + python3-numpy + diff --git a/src/slam_eval/scripts/eval_ate.py b/src/slam_eval/scripts/eval_ate.py new file mode 100644 index 0000000..db37c9c --- /dev/null +++ b/src/slam_eval/scripts/eval_ate.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +""" +eval_ate - Do ATE/RPE bang ground truth cua Gazebo. + +============ DAY LA LOI ICH LON NHAT CUA MO PHONG ============ +Trong nha hang that ban se KHONG CO motion capture. Ground truth that su +khong ton tai, chi co cac proxy: + - sai so khep vong (chay vong kin, do bang thuoc) + - AprilTag dat o vi tri da do san + - repeatability (den cung mot ban 20 lan, do do phan tan) + +Trong Gazebo, plugin p3d cho pose CHINH XAC TUYET DOI. Nho vay giai doan phat +trien thuat toan co the do ATE/RPE dung nghia - dieu se khong lam duoc sau nay. + +⚠️ /ground_truth/odom CHI duoc dung o day. Tuyet doi khong de bat ky node uoc + luong nao (EKF, slam_core, move_base) subscribe no. + +============ CACH DUNG ============ + # Ghi lai trong luc chay + rosrun slam_eval eval_ate.py --out results/run1 + + # Ket qua: in ATE ra man hinh + xuat 2 file TUM cho evo + evo_ape tum results/run1_gt.tum results/run1_est.tum -va --plot + evo_rpe tum results/run1_gt.tum results/run1_est.tum -r trans_part --delta 1 --delta_unit m +""" + +import argparse +import math +import os +import sys + +import rospy +from nav_msgs.msg import Odometry +from geometry_msgs.msg import PoseWithCovarianceStamped + +try: + import numpy as np +except ImportError: + print('Thieu numpy: sudo apt install python3-numpy') + sys.exit(1) + + +def yaw_from_quat(q): + siny = 2.0 * (q.w * q.z + q.x * q.y) + cosy = 1.0 - 2.0 * (q.y * q.y + q.z * q.z) + return math.atan2(siny, cosy) + + +class Recorder(object): + def __init__(self, gt_topic, est_topic, out_prefix, max_dt): + self.gt = [] # (t, x, y, yaw) + self.est = [] + self.out_prefix = out_prefix + self.max_dt = max_dt + + rospy.Subscriber(gt_topic, Odometry, self.on_gt, queue_size=200) + rospy.Subscriber(est_topic, PoseWithCovarianceStamped, self.on_est, queue_size=200) + + rospy.loginfo('eval_ate: gt=%s est=%s', gt_topic, est_topic) + rospy.loginfo('eval_ate: Ctrl-C de dung va tinh ket qua.') + + def on_gt(self, msg): + p = msg.pose.pose + self.gt.append((msg.header.stamp.to_sec(), p.position.x, p.position.y, + yaw_from_quat(p.orientation))) + + def on_est(self, msg): + p = msg.pose.pose + self.est.append((msg.header.stamp.to_sec(), p.position.x, p.position.y, + yaw_from_quat(p.orientation))) + + # ---------------- Xu ly ---------------- + + def associate(self): + """Ghep cap theo timestamp gan nhat (nearest neighbour).""" + if not self.gt or not self.est: + return [], [] + + gt_t = np.array([g[0] for g in self.gt]) + pairs_gt, pairs_est = [], [] + + for e in self.est: + idx = int(np.argmin(np.abs(gt_t - e[0]))) + if abs(gt_t[idx] - e[0]) <= self.max_dt: + pairs_gt.append(self.gt[idx]) + pairs_est.append(e) + + return pairs_gt, pairs_est + + @staticmethod + def umeyama_2d(src, dst): + """Can chinh SE(2) toi uu (khong scale) dua src ve dst. + + Can thiet vi SLAM va ground truth co goc toa do khac nhau: SLAM lay + vi tri khoi dong lam goc, Gazebo lay goc cua world. + """ + mu_s = src.mean(axis=0) + mu_d = dst.mean(axis=0) + s = src - mu_s + d = dst - mu_d + + H = s.T.dot(d) + U, _, Vt = np.linalg.svd(H) + R = Vt.T.dot(U.T) + if np.linalg.det(R) < 0: + Vt[-1, :] *= -1 + R = Vt.T.dot(U.T) + t = mu_d - R.dot(mu_s) + return R, t + + def report(self): + pairs_gt, pairs_est = self.associate() + + if len(pairs_gt) < 10: + rospy.logerr('eval_ate: chi ghep duoc %d cap - khong du de danh gia.', + len(pairs_gt)) + rospy.logerr('eval_ate: kiem tra ca hai topic co du lieu khong, ' + 'va timestamp co lech qua %.3fs khong.', self.max_dt) + return + + gt_xy = np.array([[g[1], g[2]] for g in pairs_gt]) + est_xy = np.array([[e[1], e[2]] for e in pairs_est]) + + R, t = self.umeyama_2d(est_xy, gt_xy) + aligned = est_xy.dot(R.T) + t + + err = np.linalg.norm(aligned - gt_xy, axis=1) + ate_rmse = float(np.sqrt((err ** 2).mean())) + + # Quang duong that de quy doi sai so ra phan tram + d = np.diff(gt_xy, axis=0) + path_len = float(np.linalg.norm(d, axis=1).sum()) + + print('') + print('=' * 58) + print(' ATE (Absolute Trajectory Error)') + print('=' * 58) + print(' So cap ghep duoc : %d' % len(pairs_gt)) + print(' Quang duong that : %.2f m' % path_len) + print(' ---------------------------------------------') + print(' RMSE : %.4f m' % ate_rmse) + print(' Trung binh : %.4f m' % float(err.mean())) + print(' Trung vi : %.4f m' % float(np.median(err))) + print(' Lon nhat : %.4f m' % float(err.max())) + if path_len > 0.1: + print(' RMSE / quang duong: %.2f %%' % (100.0 * ate_rmse / path_len)) + print('=' * 58) + print('') + + self.write_tum(pairs_gt, pairs_est) + + def write_tum(self, pairs_gt, pairs_est): + """Xuat dinh dang TUM de dung voi evo.""" + if not self.out_prefix: + return + + d = os.path.dirname(self.out_prefix) + if d and not os.path.isdir(d): + os.makedirs(d) + + def dump(path, rows): + with open(path, 'w') as f: + for (t, x, y, yaw) in rows: + qz = math.sin(yaw / 2.0) + qw = math.cos(yaw / 2.0) + f.write('%.9f %.6f %.6f 0.0 0.0 0.0 %.9f %.9f\n' % (t, x, y, qz, qw)) + + gt_path = self.out_prefix + '_gt.tum' + est_path = self.out_prefix + '_est.tum' + dump(gt_path, pairs_gt) + dump(est_path, pairs_est) + + print('Da ghi:') + print(' %s' % gt_path) + print(' %s' % est_path) + print('') + print('Phan tich sau bang evo:') + print(' evo_ape tum %s %s -va --plot' % (gt_path, est_path)) + print(' evo_rpe tum %s %s -r trans_part --delta 1 --delta_unit m' + % (gt_path, est_path)) + print('') + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--gt', default='/ground_truth/odom') + parser.add_argument('--est', default='/slam/pose') + parser.add_argument('--out', default='results/run') + parser.add_argument('--max-dt', type=float, default=0.05, + help='lech timestamp toi da khi ghep cap (s)') + args, _ = parser.parse_known_args() + + rospy.init_node('eval_ate', anonymous=True) + rec = Recorder(args.gt, args.est, args.out, args.max_dt) + rospy.on_shutdown(rec.report) + rospy.spin() + + +if __name__ == '__main__': + main() diff --git a/src/slam_eval/scripts/record_bag.sh b/src/slam_eval/scripts/record_bag.sh new file mode 100644 index 0000000..99d1890 --- /dev/null +++ b/src/slam_eval/scripts/record_bag.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# +# record_bag - Ghi RAW topic de tai lap va so sanh thuat toan. +# +# ============ NGUYEN TAC: CHI GHI DU LIEU THO ============ +# KHONG ghi topic da xu ly (/odom, /perception/cloud_*, /map, /slam/pose). +# Ly do: muc dich cua bag la CHAY LAI thuat toan tren cung du lieu dau vao. +# Neu ghi ca dau ra, bag phinh to ma khong dung duoc de so sanh cong bang. +# +# Bag nay la tai san quan trong nhat cua du an: moi so sanh giua Cartographer, +# RTAB-Map va slam_core PHAI chay tren CUNG mot bag. So sanh giua cac lan chay +# khac nhau la vo nghia - moi lan robot di mot duong khac. +# +# ============ CACH DUNG ============ +# rosrun slam_eval record_bag.sh nha_hang_vang_khach +# rosrun slam_eval record_bag.sh hanh_lang_tang3 +# +set -euo pipefail + +NAME="${1:-run}" +OUTDIR="${BAG_DIR:-$HOME/projects/vSLAM_ws/bags}" +STAMP="$(date +%Y%m%d_%H%M%S)" + +mkdir -p "$OUTDIR" + +TOPICS=( + # ---- Cam bien tho ---- + /scan + /imu/data_raw + /joint_states + /baro/pressure + /baro/temperature + + # ---- Camera: ghi anh + camera_info, KHONG ghi point cloud ---- + # Cloud tai tao duoc tu depth image bang depth_image_proc, ma nho hon ~10 lan. + /camera/depth/image_rect_raw + /camera/depth/camera_info + /camera/infra1/image_rect_raw + /camera/infra1/camera_info + /camera/infra2/image_rect_raw + /camera/infra2/camera_info + + # ---- An toan ---- + /bumper + + # ---- Dieu khien (de tai lap dung quy dao) ---- + /cmd_vel + /cmd_vel_safe + + # ---- TF tinh ---- + /tf_static + + # ---- Ground truth: CHI CO trong mo phong, chi de danh gia ---- + /ground_truth/odom +) + +echo "==============================================" +echo " Ghi bag : ${NAME}_${STAMP}" +echo " Thu muc : $OUTDIR" +echo " Topic : ${#TOPICS[@]}" +echo "==============================================" +echo " Ctrl-C de dung." +echo "" + +exec rosbag record \ + --output-name="$OUTDIR/${NAME}_${STAMP}.bag" \ + --buffsize=1024 \ + --chunksize=1024 \ + "${TOPICS[@]}" diff --git a/src/slam_eval/scripts/repeatability.py b/src/slam_eval/scripts/repeatability.py new file mode 100644 index 0000000..32883f4 --- /dev/null +++ b/src/slam_eval/scripts/repeatability.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +""" +repeatability - Do do phan tan khi robot den cung mot dich nhieu lan. + +============ VI SAO CHI SO NAY QUAN TRONG HON ATE ============ +Khach hang khong quan tam robot NGHI minh dang o toa do nao. Ho quan tam: +"no co dung dung canh ban moi lan khong?" + +Mot he SLAM co ATE 15cm nhung repeatability 2cm thi VAN GIAO DO TOT. +Mot he co ATE 5cm nhung repeatability 20cm thi lam do an roi xuong san. + +Voi robot dich vu, REPEATABILITY la chi so nghiem thu that su. Va no do duoc +ca tren robot that (khong can ground truth) - chi can cho robot chay den cung +mot waypoint nhieu lan roi do do phan tan. + +============ CACH DUNG ============ + rosrun slam_eval repeatability.py --samples 20 + + Moi lan robot den dich, bam Enter (hoac publish /repeatability/mark). + Node ghi lai pose va tinh do phan tan. +""" + +import argparse +import math +import sys +import threading + +import rospy +from nav_msgs.msg import Odometry +from geometry_msgs.msg import PoseWithCovarianceStamped +from std_msgs.msg import Empty + +try: + import numpy as np +except ImportError: + print('Thieu numpy: sudo apt install python3-numpy') + sys.exit(1) + + +def yaw_from_quat(q): + return math.atan2(2.0 * (q.w * q.z + q.x * q.y), + 1.0 - 2.0 * (q.y * q.y + q.z * q.z)) + + +class Repeatability(object): + def __init__(self, pose_topic, gt_topic, n_target): + self.samples = [] + self.gt_samples = [] + self.n_target = n_target + self.pose = None + self.gt = None + self.lock = threading.Lock() + + rospy.Subscriber(pose_topic, PoseWithCovarianceStamped, + self.on_pose, queue_size=10) + if gt_topic: + rospy.Subscriber(gt_topic, Odometry, self.on_gt, queue_size=10) + rospy.Subscriber('/repeatability/mark', Empty, self.on_mark, queue_size=10) + + rospy.loginfo('repeatability: bam Enter (hoac publish /repeatability/mark) ' + 'moi khi robot den dich.') + + def on_pose(self, msg): + p = msg.pose.pose + with self.lock: + self.pose = (p.position.x, p.position.y, yaw_from_quat(p.orientation)) + + def on_gt(self, msg): + p = msg.pose.pose + with self.lock: + self.gt = (p.position.x, p.position.y, yaw_from_quat(p.orientation)) + + def on_mark(self, _msg=None): + with self.lock: + if self.pose is None: + rospy.logwarn('repeatability: chua co pose, bo qua.') + return + self.samples.append(self.pose) + if self.gt is not None: + self.gt_samples.append(self.gt) + n = len(self.samples) + + rospy.loginfo('repeatability: mau %d/%d -> x=%.3f y=%.3f yaw=%.3f', + n, self.n_target, *self.samples[-1]) + + if n >= self.n_target: + self.report() + rospy.signal_shutdown('du mau') + + def report(self): + with self.lock: + samples = list(self.samples) + gt_samples = list(self.gt_samples) + + if len(samples) < 2: + rospy.logerr('repeatability: can it nhat 2 mau.') + return + + def stats(rows, label): + a = np.array([[r[0], r[1]] for r in rows]) + yaws = np.array([r[2] for r in rows]) + centroid = a.mean(axis=0) + d = np.linalg.norm(a - centroid, axis=1) + + # Do lech chuan goc, xu ly wrap bang trung binh vector + mean_yaw = math.atan2(np.sin(yaws).mean(), np.cos(yaws).mean()) + dyaw = np.array([abs(math.atan2(math.sin(y - mean_yaw), + math.cos(y - mean_yaw))) for y in yaws]) + + print('') + print(' %s (%d mau)' % (label, len(rows))) + print(' ' + '-' * 46) + print(' Tam : (%.3f, %.3f)' % (centroid[0], centroid[1])) + print(' Lech tb : %.4f m' % d.mean()) + print(' Lech RMS : %.4f m' % math.sqrt((d ** 2).mean())) + print(' Lech LON NHAT : %.4f m <- chi so quyet dinh' % d.max()) + print(' Lech goc lon nhat: %.4f rad (%.2f do)' + % (dyaw.max(), math.degrees(dyaw.max()))) + + print('') + print('=' * 58) + print(' REPEATABILITY') + print('=' * 58) + stats(samples, 'Theo pose SLAM uoc luong') + if len(gt_samples) == len(samples) and gt_samples: + stats(gt_samples, 'Theo ground truth (vi tri THAT)') + print('') + print(' ⚠️ So sanh hai bang tren:') + print(' - SLAM phan tan NHO ma ground truth phan tan LON') + print(' => robot tuong minh lap lai tot nhung thuc te thi khong.') + print(' Day la truong hop nguy hiem nhat: tu tin nhung sai.') + print('=' * 58) + print('') + + print(' Nguong tham khao cho robot phuc vu:') + print(' < 3cm : tot, dung canh ban chinh xac') + print(' 3-8cm : chap nhan duoc voi ban rong') + print(' > 8cm : khach phai voi tay lay do -> can cai thien') + print('') + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--pose', default='/slam/pose') + parser.add_argument('--gt', default='/ground_truth/odom') + parser.add_argument('--samples', type=int, default=20) + args, _ = parser.parse_known_args() + + rospy.init_node('repeatability', anonymous=True) + node = Repeatability(args.pose, args.gt, args.samples) + rospy.on_shutdown(node.report) + + # Cho Enter tren stdin song song voi topic + def stdin_loop(): + while not rospy.is_shutdown(): + try: + sys.stdin.readline() + except (IOError, ValueError): + return + node.on_mark() + + t = threading.Thread(target=stdin_loop) + t.daemon = True + t.start() + + rospy.spin() + + +if __name__ == '__main__': + main() diff --git a/src/slam_eval/scripts/resource_profile.py b/src/slam_eval/scripts/resource_profile.py new file mode 100644 index 0000000..69ac156 --- /dev/null +++ b/src/slam_eval/scripts/resource_profile.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +""" +resource_profile - Do CPU/RAM tung node va do tre topic. + +============ VI SAO PHAI DO TU BAY GIO ============ +May dang phat trien la i5-14500 (20 luong, 31GB, RTX 4060). Robot that se +chay tren IPC - yeu hon nhieu, va CO THE KHONG CO GPU. + +Neu chi test tren may manh, ban se xay mot he thong chay muot o day roi phat +hien no khong chay noi tren robot. Luc do sua rat dat. + +Node nay doc truc tiep tu /proc (khong can psutil) nen chay duoc o moi noi. + +============ CACH DUNG ============ + # Do 60 giay, ghi ra CSV + rosrun slam_eval resource_profile.py --duration 60 --out results/profile.csv + + # Do o che do CPU-only (mo phong IPC khong GPU) + CUDA_VISIBLE_DEVICES="" rosrun slam_eval resource_profile.py --duration 60 +""" + +import argparse +import collections +import os +import time + +import rospy +import rosnode + + +def read_proc_stat(pid): + """Tra ve (utime+stime tinh theo tick, rss theo KB) hoac None.""" + try: + with open('/proc/%d/stat' % pid, 'r') as f: + parts = f.read().split() + # Ten tien trinh co the chua dau cach -> lay tu sau dau ')' + utime = int(parts[13]) + stime = int(parts[14]) + except (IOError, IndexError, ValueError): + return None + + rss_kb = 0 + try: + with open('/proc/%d/status' % pid, 'r') as f: + for line in f: + if line.startswith('VmRSS:'): + rss_kb = int(line.split()[1]) + break + except (IOError, IndexError, ValueError): + pass + + return (utime + stime, rss_kb) + + +def find_ros_pids(): + """Map ten node ROS -> pid (chi node chay tren may nay).""" + result = {} + try: + names = rosnode.get_node_names() + except Exception: + return result + + for name in names: + try: + uri = rosnode.get_api_uri(rospy.get_master(), name) + if not uri or not isinstance(uri, (list, tuple)): + continue + # rosnode.get_api_uri tra ve (code, msg, uri) + uri = uri[2] if len(uri) > 2 else None + if not uri: + continue + except Exception: + continue + + # Doi chieu qua /proc: tim tien trinh co cmdline chua ten node + short = name.strip('/').split('/')[-1] + for pid_str in os.listdir('/proc'): + if not pid_str.isdigit(): + continue + pid = int(pid_str) + try: + with open('/proc/%d/cmdline' % pid, 'rb') as f: + cmd = f.read().decode('utf-8', errors='ignore') + except IOError: + continue + if ('__name:=' + short) in cmd or ('/' + short) in cmd.split('\x00')[0]: + result[name] = pid + break + return result + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--duration', type=float, default=60.0) + parser.add_argument('--interval', type=float, default=1.0) + parser.add_argument('--out', default='results/profile.csv') + args, _ = parser.parse_known_args() + + rospy.init_node('resource_profile', anonymous=True) + + hz = os.sysconf('SC_CLK_TCK') + ncpu = os.cpu_count() or 1 + + print('resource_profile: do %.0fs, moi %.1fs. %d CPU.' % + (args.duration, args.interval, ncpu)) + print('resource_profile: dang tim node ROS ...') + + pids = find_ros_pids() + if not pids: + print('resource_profile: KHONG tim thay node ROS nao. Da chay roscore chua?') + return + + for n, p in sorted(pids.items()): + print(' %-40s pid %d' % (n, p)) + print('') + + prev = {} + samples = collections.defaultdict(list) + + t_end = time.time() + args.duration + while time.time() < t_end and not rospy.is_shutdown(): + t0 = time.time() + for name, pid in pids.items(): + st = read_proc_stat(pid) + if st is None: + continue + ticks, rss_kb = st + if name in prev: + d_ticks = ticks - prev[name][0] + dt = t0 - prev[name][1] + if dt > 0: + cpu_pct = 100.0 * (d_ticks / float(hz)) / dt + samples[name].append((cpu_pct, rss_kb / 1024.0)) + prev[name] = (ticks, t0) + time.sleep(args.interval) + + # ---- Bao cao ---- + print('') + print('=' * 74) + print(' %-32s %10s %10s %10s' % ('NODE', 'CPU tb%', 'CPU p99%', 'RAM MB')) + print('=' * 74) + + rows = [] + total_cpu = 0.0 + total_ram = 0.0 + for name in sorted(samples): + vals = samples[name] + if not vals: + continue + cpus = sorted(v[0] for v in vals) + rams = [v[1] for v in vals] + avg = sum(cpus) / len(cpus) + p99 = cpus[min(len(cpus) - 1, int(0.99 * len(cpus)))] + ram = max(rams) + total_cpu += avg + total_ram += ram + rows.append((name, avg, p99, ram)) + print(' %-32s %10.1f %10.1f %10.1f' % (name, avg, p99, ram)) + + print('-' * 74) + print(' %-32s %10.1f %10s %10.1f' % ('TONG', total_cpu, '', total_ram)) + print(' Tuong duong %.1f loi CPU (may nay co %d)' % (total_cpu / 100.0, ncpu)) + print('=' * 74) + print('') + print(' ⚠️ IPC tren robot se yeu hon may nay nhieu.') + print(' Neu tong da vuot ~2 loi o day, can toi uu truoc khi chuyen.') + print('') + + if args.out: + d = os.path.dirname(args.out) + if d and not os.path.isdir(d): + os.makedirs(d) + with open(args.out, 'w') as f: + f.write('node,cpu_avg_pct,cpu_p99_pct,ram_mb\n') + for r in rows: + f.write('%s,%.2f,%.2f,%.2f\n' % r) + print('Da ghi %s' % args.out) + + +if __name__ == '__main__': + main() diff --git a/src/slam_eval/scripts/watch_loc.py b/src/slam_eval/scripts/watch_loc.py new file mode 100755 index 0000000..bfa5593 --- /dev/null +++ b/src/slam_eval/scripts/watch_loc.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +""" +watch_loc.py - Theo doi ve LOCALIZATION theo thoi gian thuc TRONG LUC MAPPING. + +============ Y TUONG ============ +SLAM = Simultaneous Localization And Mapping. Phan "Localization" khong phai +buoc sau - no chay dong thoi, va co the nhin thay truc tiep qua hai thu: + + 1. TF map -> odom + Day CHINH LA dau ra cua localization, theo dinh nghia: + odom -> base_footprint = suy doan chet tu encoder (troi dan) + map -> odom = phan SLAM SUA vao cho cai troi do + Neu map->odom dung yen o goc => localization khong lam gi ca. + No lon dan va nhay => SLAM dang sua drift. + + 2. Su kien loop closure (/rtabmap/info) + loopClosureId > 0 -> nhan ra cho cu bang NGOAI QUAN (can visual word) + proximityDetectionId> 0 -> nhan ra cho cu bang KHONG GIAN (odom + ICP) + He nay chi co loai thu hai, vi Kp/MaxFeatures=-1 nen khong co visual word. + +Dung: chay o terminal RIENG, trong khi mapping.launch dang chay. + python3 watch_loc.py +""" + +import math +import sys + +import rospy +import tf2_ros +from rtabmap_msgs.msg import Info + + +def yaw_of(q): + return math.degrees(math.atan2(2.0 * (q.w * q.z + q.x * q.y), + 1.0 - 2.0 * (q.y * q.y + q.z * q.z))) + + +class Watch(object): + def __init__(self): + self.n_loop = 0 # loop closure bang ngoai quan + self.n_prox = 0 # loop closure bang khong gian + self.last_id = 0 + self.corr = [] # do lon moi lan hieu chinh + rospy.Subscriber('/rtabmap/info', Info, self.cb) + + def cb(self, m): + self.last_id = m.refId + ev = None + if m.loopClosureId > 0: + self.n_loop += 1 + ev = ('NGOAI QUAN', m.loopClosureId) + elif m.proximityDetectionId > 0: + self.n_prox += 1 + ev = ('KHONG GIAN', m.proximityDetectionId) + if not ev: + return + t = m.loopClosureTransform.translation + d = math.sqrt(t.x ** 2 + t.y ** 2 + t.z ** 2) + self.corr.append(d) + rospy.loginfo('LOOP CLOSURE %-11s node %4d <-> %4d sua %.3f m', + ev[0], m.refId, ev[1], d) + + +def main(): + rospy.init_node('watch_loc', anonymous=True, disable_signals=True) + w = Watch() + buf = tf2_ros.Buffer() + tf2_ros.TransformListener(buf) + + print(__doc__.split('Dung:')[0]) + print('%-7s %10s %10s %9s | %7s %7s | %s' + % ('t(s)', 'map->odom', 'yaw(deg)', 'node', 'ngoai', 'kh.gian', 'ghi chu')) + print('-' * 88) + + t0 = rospy.Time.now() + prev = None + quiet = 0 + while not rospy.is_shutdown(): + try: + tr = buf.lookup_transform('map', 'odom', rospy.Time(0), + rospy.Duration(1.0)).transform + d = math.sqrt(tr.translation.x ** 2 + tr.translation.y ** 2) + y = yaw_of(tr.rotation) + note = '' + if prev is not None: + jump = abs(d - prev) + if jump > 0.02: + note = '<- map->odom NHAY %.3f m (SLAM vua sua drift)' % jump + prev = d + if d < 1e-4 and w.n_loop + w.n_prox == 0: + quiet += 1 + if quiet > 5: + note = '<- van o goc, chua co hieu chinh nao' + print('%7.1f %10.4f %10.3f %9d | %7d %7d | %s' + % ((rospy.Time.now() - t0).to_sec(), d, y, w.last_id, + w.n_loop, w.n_prox, note)) + except (tf2_ros.LookupException, tf2_ros.ExtrapolationException, + tf2_ros.ConnectivityException) as e: + print(' cho TF map->odom ... (%s)' % type(e).__name__) + rospy.sleep(2.0) + + +if __name__ == '__main__': + try: + main() + except (rospy.ROSInterruptException, KeyboardInterrupt): + pass + finally: + print('\nket thuc.') diff --git a/src/third_party/.rosinstall b/src/third_party/.rosinstall new file mode 100644 index 0000000..fe02ff9 --- /dev/null +++ b/src/third_party/.rosinstall @@ -0,0 +1,36 @@ +# vcstool / wstool manifest cho ma nguon ben ngoai. +# +# sudo apt install python3-vcstool +# cd ~/projects/vSLAM_ws/src/third_party && vcs import < .rosinstall +# +# LUON pin version cu the (version:) - khong dung nhanh mac dinh. +# Mot lan `git pull` cua thu vien ngoai lam hong build la du de mat mot ngay. + +# ============================================================ +# realsense2_camera - build tu source de khop librealsense 2.58.3 dang cai +# Xem README.md muc "Xung dot librealsense". +# ============================================================ +# - git: +# local-name: realsense-ros +# uri: https://github.com/IntelRealSense/realsense-ros.git +# version: ros1-legacy + +# ============================================================ +# allan_variance_ros - hieu chuan nhieu IMU (chay >= 3 gio) +# Ket qua nap vao slam_core/config/slam_core.yaml +# ============================================================ +# - git: +# local-name: allan_variance_ros +# uri: https://github.com/ori-drs/allan_variance_ros.git +# version: master + +# ============================================================ +# Driver LiDAR RICHBEAM - lay tu hang. +# Dong LakiBeam co repo lakibeam1_scan. +# ⚠️ Xem robot_drivers/launch/richbeam.launch: co 4 dieu phai xac minh +# (interface, nguon timestamp, FOV, scan rate) truoc khi tin vao du lieu. +# ============================================================ +# - git: +# local-name: richbeam_driver +# uri: +# version: diff --git a/src/third_party/CATKIN_IGNORE b/src/third_party/CATKIN_IGNORE new file mode 100644 index 0000000..e69de29 diff --git a/src/third_party/README.md b/src/third_party/README.md new file mode 100644 index 0000000..008728f --- /dev/null +++ b/src/third_party/README.md @@ -0,0 +1,59 @@ +# third_party/ — Mã nguồn bên ngoài + +**Thư mục này có `CATKIN_IGNORE`** cho tới khi bạn thực sự clone gì vào đây +(xoá file đó đi khi đã có package thật). + +Quản lý bằng `.rosinstall` + `vcstool`, **không commit source trực tiếp** — +để pin đúng version và không làm phình repo. + +```bash +sudo apt install python3-vcstool +cd ~/projects/vSLAM_ws/src/third_party +vcs import < .rosinstall +``` + +## Cần lấy về + +| Package | Vì sao | Khi nào | +|---|---|---| +| `realsense2_camera` | ⚠️ **Bắt buộc build từ source** — xem bên dưới | Khi chuyển sang phần cứng thật | +| Driver RICHBEAM | Không có trên apt, phải lấy từ hãng | Khi có LiDAR | +| `allan_variance_ros` | Hiệu chuẩn nhiễu IMU | Khi có IMU | + +## ⚠️ Xung đột librealsense — chặn việc chạy phần cứng thật + +Máy hiện có **hai bản librealsense cùng lúc**: + +``` +librealsense2 2.58.3 (Intel repo) +ros-noetic-librealsense2 2.50.0 (ROS repo) +ros-noetic-realsense2-camera 2.3.2 <- build theo 2.50.0 +``` + +Wrapper 2.3.2 được build theo 2.50.0 nhưng runtime có thể nạp 2.58.3 → **lỗi ABI**. + +**Hướng chính:** gỡ `ros-noetic-realsense2-camera` và `ros-noetic-librealsense2`, +giữ Intel `2.58.3`, build `realsense2_camera` từ source ở đây. + +**Dự phòng** (nếu wrapper 2.3.2 không compile với LRS 2.58 do API đổi): pin về +cặp đã được kiểm thử — Intel LRS `2.50.x` + apt wrapper `2.3.2`. + +Việc này **không cản mô phỏng** — chỉ cần xử lý trước khi cắm camera thật. + +## Không thuộc thư mục này + +**GTSAM** là thư viện CMake thuần, **không phải catkin package**. Đặt vào `src/` +sẽ khiến catkin cố build nó như package ROS và báo lỗi khó hiểu. + +Build ngoài workspace: + +```bash +git clone https://github.com/borglab/gtsam.git ~/libs/gtsam +cd ~/libs/gtsam && mkdir build && cd build +cmake -DGTSAM_USE_SYSTEM_EIGEN=ON -DGTSAM_BUILD_TESTS=OFF \ + -DGTSAM_BUILD_EXAMPLES_ALWAYS=OFF .. +make -j$(nproc) && sudo make install && sudo ldconfig +``` + +`slam_core/CMakeLists.txt` dùng `find_package(GTSAM QUIET)` nên workspace vẫn +build xanh khi chưa cài.