From f9a187375364b81a470961670bafab7f4880dd97 Mon Sep 17 00:00:00 2001 From: trung09122002 Date: Sat, 12 Sep 2026 15:38:10 +0700 Subject: [PATCH] upload --- .claude/skills/humanizer/LICENSE | 21 + .claude/skills/humanizer/SKILL.md | 464 ++++++++++ PROJECT_CONTEXT.md | 4 +- ROS_TOPIC_MAP.md | 9 +- agent_skills_claude_code | 1 + docs/ARCHITECTURE.md | 2 +- docs/HARDWARE.md | 130 ++- docs/ROADMAP.md | 2 +- docs/SIM_VS_REAL.md | 79 +- reloc_hosp.sh | 97 +++ src/localization_ops/CMakeLists.txt | 20 +- .../launch/localization_ops.launch | 58 ++ src/localization_ops/package.xml | 8 + .../scripts/global_scan_init.py | 823 ++++++++++++++++++ src/localization_ops/scripts/reloc_active.py | 325 +++++++ src/localization_ops/src/reloc_gicp_node.cpp | 409 +++++++++ src/perception_3d/CMakeLists.txt | 5 +- src/perception_3d/config/depth_filter.yaml | 95 +- .../launch/perception_nodelets.launch | 154 +++- src/perception_3d/nodelet_plugins.xml | 20 +- src/perception_3d/package.xml | 8 + .../src/cliff_detect_nodelet.cpp | 689 +++++++++++++++ .../src/depth_filter_nodelet.cpp | 43 +- .../src/gravity_align_nodelet.cpp | 30 +- .../src/scan_to_cloud_nodelet.cpp | 26 +- src/robot_bringup/CMakeLists.txt | 3 - src/robot_bringup/config/costmap_common.yaml | 86 +- src/robot_bringup/config/costmap_global.yaml | 3 +- .../config/costmap_global_static.yaml | 12 + src/robot_bringup/config/costmap_local.yaml | 18 +- src/robot_bringup/config/robot.yaml | 25 +- src/robot_bringup/launch/localization.launch | 50 +- src/robot_bringup/launch/mapping.launch | 39 +- src/robot_bringup/launch/odom.launch | 181 +++- src/robot_bringup/launch/perception.launch | 20 +- src/robot_bringup/launch/rtabmap.launch | 57 +- src/robot_bringup/launch/sim.launch | 17 + .../launch/teleop_joystick.launch | 14 +- src/robot_bringup/rviz/map_view.rviz | 7 +- src/robot_bringup/rviz/slam.rviz | 483 ++++++++-- src/robot_bringup/scripts/teleop.py | 183 ---- src/robot_bringup/scripts/virtual_joystick.py | 19 + src/robot_bringup/urdf/sensors.xacro | 13 +- src/robot_drivers/CMakeLists.txt | 27 +- src/robot_drivers/config/scan_filter.yaml | 81 ++ .../robot_drivers/scan_header_fix_filter.h | 151 ++++ src/robot_drivers/launch/drivers.launch | 8 +- src/robot_drivers/launch/scan_filter.launch | 47 + src/robot_drivers/package.xml | 9 + src/robot_drivers/scan_filters_plugins.xml | 11 + .../src/scan_filters_plugins.cpp | 13 + src/robot_drivers/src/wheel_odom_node.cpp | 37 +- src/robot_safety/config/safety.yaml | 54 +- src/robot_safety/src/safety_monitor_node.cpp | 122 ++- src/robot_sim/launch/gazebo.launch | 12 +- src/robot_sim/urdf/gazebo_sensors.xacro | 64 +- src/robot_sim/worlds/cliff_test.world | 168 ++++ src/slam_eval/CMakeLists.txt | 4 + src/slam_eval/config/topics_to_record.yaml | 3 +- src/slam_eval/scripts/ate_table.py | 150 ++++ src/slam_eval/scripts/check_initpose.py | 154 ++++ src/slam_eval/scripts/check_scan.py | 366 ++++++++ src/slam_eval/scripts/check_stereo.py | 48 + src/slam_eval/scripts/check_yaw_drift.py | 167 ++++ src/slam_eval/scripts/record_bag.sh | 9 + 65 files changed, 6043 insertions(+), 414 deletions(-) create mode 100644 .claude/skills/humanizer/LICENSE create mode 100644 .claude/skills/humanizer/SKILL.md create mode 160000 agent_skills_claude_code create mode 100755 reloc_hosp.sh create mode 100755 src/localization_ops/scripts/global_scan_init.py create mode 100755 src/localization_ops/scripts/reloc_active.py create mode 100644 src/localization_ops/src/reloc_gicp_node.cpp create mode 100644 src/perception_3d/src/cliff_detect_nodelet.cpp delete mode 100755 src/robot_bringup/scripts/teleop.py create mode 100644 src/robot_drivers/config/scan_filter.yaml create mode 100644 src/robot_drivers/include/robot_drivers/scan_header_fix_filter.h create mode 100644 src/robot_drivers/launch/scan_filter.launch create mode 100644 src/robot_drivers/scan_filters_plugins.xml create mode 100644 src/robot_drivers/src/scan_filters_plugins.cpp create mode 100644 src/robot_sim/worlds/cliff_test.world create mode 100755 src/slam_eval/scripts/ate_table.py create mode 100755 src/slam_eval/scripts/check_initpose.py create mode 100755 src/slam_eval/scripts/check_scan.py create mode 100755 src/slam_eval/scripts/check_yaw_drift.py diff --git a/.claude/skills/humanizer/LICENSE b/.claude/skills/humanizer/LICENSE new file mode 100644 index 0000000..625297f --- /dev/null +++ b/.claude/skills/humanizer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Siqi Chen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.claude/skills/humanizer/SKILL.md b/.claude/skills/humanizer/SKILL.md new file mode 100644 index 0000000..e3d5bbe --- /dev/null +++ b/.claude/skills/humanizer/SKILL.md @@ -0,0 +1,464 @@ +--- +name: humanizer +description: | + Rewrite AI-sounding text so it reads naturally without changing what it says. + Use when editing or reviewing prose for inflated claims, + sales language, vague sources, repetitive structure, stock AI words, passive + voice, filler, or chatbot artifacts. Based on Wikipedia's "Signs of AI writing." + Dùng khi người dùng nói "viết lại cho tự nhiên", "bỏ giọng AI", "humanize + văn bản này", "làm mượt README/docs/commit/PR description", hoặc yêu cầu + review prose trước khi publish. +license: MIT +metadata: + version: "2.11.2" + upstream: "https://github.com/blader/humanizer" +--- + +> Vendored from [blader/humanizer](https://github.com/blader/humanizer) v2.11.2 (MIT). Body kept verbatim; only the description was extended with Vietnamese trigger phrases for this pack. +> +> **Caveman mode does not apply to this skill's output.** The rewritten text is the deliverable — return full prose. Compression applies only to the surrounding commentary. + +# Humanizer: remove AI writing patterns + +Rewrite AI-sounding text so it reads like the writer, not a chatbot. Do not change what it says or make up details. + +The patterns below come from Wikipedia's ["Signs of AI writing"](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing), maintained by WikiProject AI Cleanup. + +## What to do + +When given text to humanize: + +1. **Find AI patterns.** Check the text against the patterns below. +2. **Keep every claim.** You may shorten dull parts, expand useful parts, and merge or split paragraphs. Keep the information even when you change the structure. +3. **Do not invent facts.** Do not add a fact, name, number, date, quote, or citation unless it comes from the source or the user. If a sentence needs a missing detail, ask for it or use a simpler sentence. You may add an opinion or reaction when the writer's voice calls for one, but you may not add a factual claim. Fiction is exempt because invented details are part of the task. +4. **Match the voice.** Use the right tone for the text, such as formal, casual, or technical. Add personality only when the text and the writer call for it. + +The input type controls what you return. See [How to return the result](#how-to-return-the-result). Use the same rewrite process in every mode. + +## Match the writer's voice + +If the user provides a writing sample (their own previous writing), analyze it before rewriting: + +1. Read the sample first. Note its sentence length, word choice, paragraph openings, punctuation, repeated phrases, and transitions. +2. Match those habits. Do not replace casual words with formal ones or remove deliberate quirks. +3. If there is no sample, use the guidance below. + +A writing sample takes priority over these style rules. If the sample uses em dashes, keep them at about the same rate. Do not apply §14 as a ban. + +## Add personality only when it fits + +Removing AI patterns is only half the job. The result should still sound like a person. + +Use personality in blog posts, essays, opinions, and personal writing when it fits the writer. Keep reference, technical, legal, and factual text neutral. Do not add opinions or first-person language where they do not belong. + +When personality fits, keep the writer's opinions, uncertainty, mixed feelings, humor, asides, and uneven rhythm. Never invent facts to make the text feel personal. + +## Content patterns + +### 1. Inflated claims about importance and legacy + +**Words to watch:** stands/serves as, is a testament/reminder, a vital/significant/crucial/pivotal/key role/moment, underscores/highlights its importance/significance, reflects broader, symbolizing its ongoing/enduring/lasting, contributing to the, setting the stage for, marking/shaping the, represents/marks a shift, key turning point, evolving landscape, focal point, indelible mark, deeply rooted +**Problem:** AI writing often claims that ordinary details mark a major change, prove a legacy, or reflect a broad trend. +**Before:** +> The Statistical Institute of Catalonia was officially established in 1989, marking a pivotal moment in the evolution of regional statistics in Spain. This initiative was part of a broader movement across Spain to decentralize administrative functions and enhance regional governance. +**After:** +> The Statistical Institute of Catalonia was established in 1989, part of a wider decentralization of administrative functions in Spain. + +### 2. Name-dropping to prove importance + +**Words to watch:** independent coverage, local/regional/national media outlets, written by a leading expert, active social media presence +**Problem:** AI writing often lists well-known publications or follower counts to prove that a person matters. The list usually gives no useful context. +**Before:** +> Her views have been cited in The New York Times, BBC, Financial Times, and The Hindu. She maintains an active social media presence with over 500,000 followers. +**After:** +> Her views have been cited in The New York Times and the BBC. + +If the source explains what the person said and where, keep that useful citation. Do not invent context for a shorter version. + +### 3. Shallow analysis with -ing phrases + +**Words to watch:** highlighting/underscoring/emphasizing..., ensuring..., reflecting/symbolizing..., contributing to..., cultivating/fostering..., encompassing..., showcasing... +**Problem:** AI writing often adds an -ing phrase to make a simple fact sound deeper than it is. +**Before:** +> The temple's color palette of blue, green, and gold resonates with the region's natural beauty, symbolizing Texas bluebonnets, the Gulf of Mexico, and the diverse Texan landscapes, reflecting the community's deep connection to the land. +**After:** +> The temple is painted blue, green, and gold, colors meant to evoke Texas bluebonnets and the Gulf of Mexico. + +### 4. Sales language + +**Words to watch:** boasts a, vibrant, rich (figurative), profound, enhancing its, showcasing, exemplifies, commitment to, natural beauty, nestled, in the heart of, groundbreaking (figurative), renowned, breathtaking, must-visit, stunning +**Problem:** AI writing often sounds like an advertisement, especially when it describes places, culture, products, or organizations. +**Before:** +> Nestled within the breathtaking region of Gonder in Ethiopia, Alamata Raya Kobo stands as a vibrant town with a rich cultural heritage and stunning natural beauty. +**After:** +> Alamata Raya Kobo is a town in the Gonder region of Ethiopia. + +### 5. Vague sources + +**Words to watch:** Industry reports, Observers have cited, Experts argue, Some critics argue, several sources/publications (when few cited) +**Problem:** AI writing often assigns a claim to unnamed experts, critics, reports, or observers. +**Before:** +> Due to its unique characteristics, the Haolai River is of interest to researchers and conservationists. Experts believe it plays a crucial role in the regional ecosystem. +**After:** +> Researchers and conservationists study the Haolai River for its unusual characteristics. + +Name a real source when the source text provides one. Otherwise, remove the unsupported claim. Never invent a source. + +### 6. Formulaic challenges and outlook sections + +**Words to watch:** Despite its... faces several challenges..., Despite these challenges, Challenges and Legacy, Future Outlook +**Problem:** AI articles often add a stock section about challenges, future prospects, or continued growth. These sections usually repeat vague claims instead of adding facts. +**Before:** +> Despite its industrial prosperity, Korattur faces challenges typical of urban areas, including traffic congestion and water scarcity. Despite these challenges, with its strategic location and ongoing initiatives, Korattur continues to thrive as an integral part of Chennai's growth. +**After:** +> Korattur has recurring traffic congestion and water shortages. + +Add details such as dates or public actions only when they come from the source or the user. + +## Language and grammar patterns + +### 7. Overused AI words + +**High-frequency AI words:** Actually, additionally, align with, crucial, delve, emphasizing, enduring, enhance, fostering, garner, gate/gated/gating (figurative; preserve established technical usage), highlight (verb), interplay, intricate/intricacies, key (adjective), landscape (abstract noun), pivotal, quietly, showcase, tapestry (abstract noun), testament, underscore (verb), valuable, vibrant +**Problem:** AI writing uses these words much more often than most people do, especially in groups. +**Before:** +> Additionally, a distinctive feature of Somali cuisine is the incorporation of camel meat. An enduring testament to Italian colonial influence is the widespread adoption of pasta in the local culinary landscape, showcasing how these dishes have integrated into the traditional diet. +**After:** +> Somali cuisine also includes camel meat, which is considered a delicacy. Pasta dishes, introduced during Italian colonization, remain common, especially in the south. + +### 8. Avoiding is and are + +**Words to watch:** serves as/stands as/marks/represents [a], boasts/features/offers [a] +**Problem:** AI writing often replaces simple verbs such as *is*, *are*, and *has* with longer phrases. +**Before:** +> Gallery 825 serves as LAAA's exhibition space for contemporary art. The gallery features four separate spaces and boasts over 3,000 square feet. +**After:** +> Gallery 825 is LAAA's exhibition space for contemporary art. The gallery has four rooms totaling 3,000 square feet. + +### 9. Not X but Y and clipped negative endings +**Problem:** AI writing overuses forms such as "Not only...but..." and "It's not just X, it's Y." + +It also adds clipped endings such as "no guessing" instead of writing a clear clause. +**Before:** +> It's not just about the beat riding under the vocals; it's part of the aggression and atmosphere. It's not merely a song, it's a statement. +**After:** +> The heavy beat adds to the aggressive tone. +**Before (tailing negation):** +> The options come from the selected item, no guessing. +**After:** +> The options come from the selected item without forcing the user to guess. + +### 10. Forced groups of three +**Problem:** AI writing often forces ideas into groups of three to sound complete. +**Before:** +> The event features keynote sessions, panel discussions, and networking opportunities. Attendees can expect innovation, inspiration, and industry insights. +**After:** +> The event includes talks and panels. There's also time for informal networking between sessions. + +### 11. Changing names and repeating sentence openings +**Problem:** AI writing handles repetition by rule instead of by ear. It may keep renaming the same person or thing. It may also start several sentences with the same subject, often *she* or *he*. + +Use one clear name for the same subject. For repeated openings, merge sentences, change the subject when that helps, or begin with the action. +**Before (synonym cycling):** +> The protagonist faces many challenges. The main character must overcome obstacles. The central figure eventually triumphs. The hero returns home. +**After:** +> The protagonist faces many challenges but eventually triumphs and returns home. +**Before (repeated openings):** +> She noted the door. She noted the lock on it. She filed both away. +**After:** +> She noted the door and its lock, then filed both away. + +Do not ban the repeated word. Fix the repeated sentence pattern. The remaining sentence may still start with "She." + +### 12. False from X to Y ranges +**Problem:** AI writing often uses "from X to Y" when X and Y do not form a real range. +**Before:** +> Our journey through the universe has taken us from the singularity of the Big Bang to the grand cosmic web, from the birth and death of stars to the enigmatic dance of dark matter. +**After:** +> The book covers the Big Bang, star formation, and current theories about dark matter. + +### 13. Passive voice and missing subjects +**Problem:** AI writing often hides who acts or drops the subject. Use active voice when it makes the actor and action clearer. +**Before:** +> No configuration file needed. The results are preserved automatically. +**After:** +> You do not need a configuration file. The system preserves the results automatically. + +## Style patterns + +### 14. Em and en dashes + +**Rule:** The final rewrite must not contain em dashes (—) or en dashes (–), unless the writer's sample uses them. Replace a dash with a period, comma, colon, or parentheses, or rewrite the sentence. Also check for spaced dashes (` — `) and double hyphens (` -- `) used as dashes. +**Before:** +> The term is primarily promoted by Dutch institutions—not by the people themselves. You don't say "Netherlands, Europe" as an address—yet this mislabeling continues—even in official documents. +**After:** +> The term is primarily promoted by Dutch institutions, not by the people themselves. You don't say "Netherlands, Europe" as an address, yet this mislabeling continues in official documents. +**Before:** +> The new policy — announced without warning — affects thousands of workers. The changes -- long overdue according to critics -- will take effect immediately. +**After:** +> The new policy, announced without warning, affects thousands of workers. The changes, long overdue according to critics, will take effect immediately. + +Before returning the rewrite, search for `—` and `–`. Remove each one unless the writer's sample uses that mark. In that case, match the sample's rate. + +### 15. Too much bold text +**Problem:** AI chatbots often bold words and phrases without a clear reason. +**Before:** +> It blends **OKRs (Objectives and Key Results)**, **KPIs (Key Performance Indicators)**, and visual strategy tools such as the **Business Model Canvas (BMC)** and **Balanced Scorecard (BSC)**. +**After:** +> It blends OKRs, KPIs, and visual strategy tools like the Business Model Canvas and Balanced Scorecard. + +### 16. Lists with bold mini-headings +**Problem:** AI writing often uses vertical lists in which every item starts with a bold label and a colon. +**Before:** +> - **User Experience:** The user experience has been significantly improved with a new interface. +> - **Performance:** Performance has been enhanced through optimized algorithms. +> - **Security:** Security has been strengthened with end-to-end encryption. +**After:** +> The update improves the interface, speeds up load times through optimized algorithms, and adds end-to-end encryption. + +### 17. Title case in headings +**Problem:** AI chatbots often capitalize every main word in a heading. +**Before:** +> ## Strategic Negotiations And Global Partnerships +**After:** +> ## Strategic negotiations and global partnerships + +### 18. Emojis +**Problem:** AI chatbots often add emojis to headings and list items as decoration. +**Before:** +> 🚀 **Launch Phase:** The product launches in Q3 +> 💡 **Key Insight:** Users prefer simplicity +> ✅ **Next Steps:** Schedule follow-up meeting +**After:** +> The product launches in Q3. User research showed a preference for simplicity. Next step: schedule a follow-up meeting. + +### 19. Curly quotation marks +**Problem:** ChatGPT often uses curly quotes (“...”) where the writer or target format uses straight quotes ("..."). +**Before:** +> He said “the project is on track” but others disagreed. +**After:** +> He said "the project is on track" but others disagreed. + +## Chatbot patterns + +### 20. Chatbot text left in the answer + +**Words to watch:** I hope this helps, Of course!, Certainly!, You're absolutely right!, Would you like..., Want me to...?, Want me to give examples?, Should I continue?, let me know, here is a... +**Problem:** A chatbot's greeting, offer, or closing sometimes remains in text that should stand on its own. +**Before:** +> Here is an overview of the French Revolution. I hope this helps! Let me know if you'd like me to expand on any section. +**After:** +> The French Revolution began in 1789 when financial crisis and food shortages led to widespread unrest. + +### 21. Knowledge-limit disclaimers and guesses + +**Words to watch:** as of [date], Up to my last training update, While specific details are limited/scarce..., based on available information, not publicly available, maintains a low profile, keeps personal details private, prefers to stay out of the spotlight, likely [grew up/studied/began], it is believed that +**Problem:** Older models may mention the date when their knowledge ends. A model may also explain that it could not find a source, then fill the gap with a plausible guess. State what the source does not show, or remove the sentence. Do not present a guess as a fact. +**Before (cutoff disclaimer):** +> While specific details about the company's founding are not extensively documented in readily available sources, it appears to have been established sometime in the 1990s. +**After:** +> The company's founding date is not documented in the available sources. (Or cut the sentence. State a date only if a source provides one.) +**Before (speculative gap-fill):** +> Information about her early life is not publicly available, suggesting she maintains a low profile and keeps personal details private. She likely grew up in a middle-class household, which shaped her later interest in education reform. +**After:** +> Her early life is not documented in the available sources. (Or omit the section.) + +### 22. Overly agreeable tone +**Problem:** AI assistants often praise the user or agree before giving the answer. +**Before:** +> Great question! You're absolutely right that this is a complex topic. That's an excellent point about the economic factors. +**After:** +> The economic factors you mentioned are relevant here. + +## Filler and hedging + +### 23. Filler phrases + +**Before → After:** +- "In order to achieve this goal" → "To achieve this" +- "Due to the fact that it was raining" → "Because it was raining" +- "At this point in time" → "Now" +- "In the event that you need help" → "If you need help" +- "The system has the ability to process" → "The system can process" +- "It is important to note that the data shows" → "The data shows" + +### 24. Too many qualifiers + +**Phrases to watch:** to be fair, it's also possible, could potentially, might arguably, in some cases it may, this is an inference +**Problem:** Repeated editing can add one qualifier after another until every claim sounds uncertain. Keep a qualifier only when the source supports it and the meaning needs it. Remove caveats that only repair an earlier overstatement. +**Before:** +> It could potentially possibly be argued that the policy might have some effect on outcomes. +**After:** +> The policy may affect outcomes. + +### 25. Generic positive endings +**Problem:** AI writing often ends with vague optimism instead of the last useful fact. +**Before:** +> The future looks bright for the company. Exciting times lie ahead as they continue their journey toward excellence. This represents a major step in the right direction. +**After:** +> (Cut the paragraph. End on the last concrete fact instead of a send-off. If the source states real plans, use those.) + +### 26. Too many hyphenated word pairs + +**Words to watch:** third-party, cross-functional, client-facing, data-driven, decision-making, well-known, high-quality, real-time, long-term, end-to-end +**Problem:** AI writing often hyphenates these pairs everywhere. Keep the hyphen before a noun when grammar needs it, as in `a high-quality report`. Drop it after the noun, as in `the report is high quality`. +**Before:** +> The cross-functional team delivered a high-quality, data-driven report. The team is cross-functional, the report is high-quality, and the methodology is data-driven. +**After:** +> The cross-functional team delivered a high-quality, data-driven report. The team is cross functional, the report is high quality, and the methodology is data driven. + +### 27. Pretending to reveal a deeper truth + +**Phrases to watch:** The real question is, at its core, in reality, what really matters, fundamentally, the deeper issue, the heart of the matter +**Problem:** AI writing uses these phrases to make an ordinary point sound like a hidden truth. +**Before:** +> The real question is whether teams can adapt. At its core, what really matters is organizational readiness. +**After:** +> The question is whether teams can adapt. That mostly depends on whether the organization is ready to change its habits. + +### 28. Announcing the next point + +**Phrases to watch:** Let's dive in, let's explore, let's break this down, here's what you need to know, now let's look at, without further ado, heads up, quick note, before I forget +**Problem:** AI writing often announces the next point instead of stating it. A casual phrase such as "one thing that bit me" can have the same problem. Remove the announcement, not just its formal tone. +**Before:** +> Let's dive into how caching works in Next.js. Here's what you need to know. +**After:** +> Next.js caches data at multiple layers, including request memoization, the data cache, and the router cache. +**Before (casual register):** +> One thing that bit me hard, so pay attention to this part: the webpack dev server doesn't send the CORS header by default. +**After:** +> The webpack dev server doesn't send the CORS header by default. + +### 29. A heading repeated in the first sentence + +**Signs to watch:** A heading followed by a one-line paragraph that simply restates the heading before the real content begins. +**Problem:** AI writing often follows a heading with a sentence that only repeats the heading. Remove the repeated sentence. +**Before:** +> ## Performance +> +> Speed matters. +> +> When users hit a slow page, they leave. +**After:** +> ## Performance +> +> When users hit a slow page, they leave. + +### 30. Writing about the previous version +**Problem:** Documentation and comments should describe the current behavior. Mention the previous version only in change logs, release notes, migration guides, and other documents about change. +**Before:** +> This function was added to replace the previous approach of iterating through all items, which caused O(n²) performance. +**After:** +> This function uses a hash map for O(1) lookups, avoiding the O(n²) cost of naive iteration. + +### 31. Forced punchlines and dramatic fragments +**Problem:** AI writing often turns each sentence into a dramatic closing line. One short sentence can add emphasis. A row of short fragments usually feels forced. +**Before:** +> Then AlphaEvolve arrived. It had no preference for symmetry. No aesthetic prior. No nostalgia for human taste. The old rules were gone. +**After:** +> AlphaEvolve changed the search because it did not favor symmetry or human-looking designs. That made some of the older assumptions less useful. + +### 32. Formulaic sayings + +**Words to watch:** X is the Y of Z, X becomes a trap, X is not a tool but a mirror, the language of, the currency of, the architecture of +**Problem:** AI writing often turns an ordinary claim into a saying that sounds deep but adds no detail. Replace the saying with the specific claim. +**Before:** +> Symmetry is the language of trust. Efficiency becomes a trap when teams forget the human layer. +**After:** +> Symmetric layouts often feel more predictable to users. Teams can over-optimize workflows and miss how people actually use them. + +### 33. Fake-candid openings + +**Phrases to watch:** Honestly?, Look, Here's the thing, The thing is, Let's be honest, Real talk, when used as standalone hooks or fake-candid pauses before an ordinary point. +**Problem:** AI writing often starts with a staged pause or claim of honesty before making a routine point. State the point directly. +**Before:** +> Is it worth the price? Honestly? It depends on how often you'll use it. +**After:** +> Whether it's worth the price depends on how often you'll use it. + +### 34. Answering objections no one raised + +**Phrases to watch:** This isn't (mainly/really) about, I'm not saying/arguing/trying to, To be clear, Don't get me wrong, This is not to say, You could argue/frame this differently but, Some might say... but +**Problem:** AI writing may answer an objection that does not appear in the text. Watch for an unattributed statement about what the writer does not mean, especially when the topic appears nowhere else. A direct claim such as "the API is not thread-safe" is not this pattern. +**Before:** +> This isn't mainly about prompt length, and I'm not arguing that documentation doesn't matter. You could categorize the problem another way, but the issue is whether the agent can use the instruction when it acts. +**After:** +> The issue is whether the agent can use the instruction when it acts. + +Remove only the unsupported defense. If it contains a real claim, state that claim directly. Keep an objection when the text names its source or answers it in full. + +### 35. Rejecting fake alternatives + +**Phrases to watch:** A tempting option/approach would be, One might be tempted to, An obvious approach would be, You might think... but, It would be easy to just, Some would suggest +**Problem:** AI writing may introduce an option that no reader would consider, reject it in a clause, and never mention it again. This often leaves an old drafting idea in the final text. Remove the fake option and state the real constraint directly. +**Before:** +> Session tokens are rotated every 24 hours. A tempting approach would be to rotate them by restarting the auth service on a cron job, but that would drop every active session. Rotation happens in place, and clients refresh transparently. +**After:** +> Session tokens are rotated every 24 hours, in place, and clients refresh transparently. + +One rejected option may be valid. Several short, unrelated rejections are a stronger sign. Ask what new information each sentence adds. If it only records an earlier edit, rewrite the paragraph around its main point. + +## Check for false positives + +### What not to flag + +A person may use some of these patterns. Do not treat any item below as proof by itself: + +- **Perfect grammar and consistent style.** Many writers are professionals or have been edited. Polish does not equal AI. +- **Mixed casual and formal styles.** This can reflect the writer's field, age, or personal habits. +- **"Bland" or "robotic" prose.** AI prose has *specific* tells. Generic dryness without those tells is just dry writing. +- **Formal or academic words.** §7 lists specific words that AI writing overuses. Do not simplify every formal word. +- **Letter-style opening or closing on a comment.** Salutations and sign-offs predate ChatGPT by centuries. +- **Common transition words in isolation.** *Additionally*, *moreover*, *consequently* are AI-coded only when piled up. One *however* is not a tell. +- **Curly quotes alone.** macOS, Word, Google Docs, and most CMSes auto-curl by default. Curly quotes only count when stacked with other tells. +- **Em dashes alone.** Many editors and journalists use them often. Em dashes are evidence only when paired with formulaic sales-y rhythm. +- **One short sentence for emphasis.** Flag dramatic fragments only when several appear in a row. +- **Deliberate repeated openings.** Writers may repeat an opening to build rhythm or pressure, as in "She came. She saw. She conquered." Change it only when the repetition adds nothing. +- **"Honestly" or "look" mid-sentence.** These are ordinary in casual writing. The tell is the standalone theatrical opener, not the word itself. +- **Useful limits and disclaimers.** Keep scope statements, legal and safety notices, real corrections, named objections, replies, and FAQ answers. +- **Real alternatives.** Keep options that a reader may consider in a design document, tutorial, or argument. Remove only an unlikely option that the text dismisses and never uses again. +- **Unsourced claims.** Most of the web is unsourced. Lack of citations doesn't prove anything. +- **Correct, complex formatting.** Visual editors and templates produce clean output without any AI. +- **Secondhand text.** Do not rewrite watched phrases inside quotations, titles, proper names, or examples where the phrase is being discussed rather than used. + +When unsure, look for several patterns together. One em dash proves nothing. Several stock patterns in the same passage are stronger evidence. + +### Human details to keep + +These details often carry the writer's voice. Keep them unless they hurt the meaning: + +- **Specific, unusual details.** Keep a real address, an odd quote, or a phrase such as "the lawyer who used to work upstairs from my dentist." +- **Mixed feelings and unresolved tension.** Keep lines such as "I think this is mostly good, but it bothers me, and I can't fully explain why." +- **Dated, era-bound references.** Slang, memes, or in-jokes that map to a specific year and subculture. Models lag by a year or more. +- **Deliberate first-person choices.** Keep a cut or word choice when the writer can explain why it belongs. +- **Variety in sentence length.** Real writing alternates short and long. AI writing tends toward an even, mid-length cadence. +- **Genuine asides, parentheticals, or self-corrections.** "(I keep wanting to say 'almost' here, but it really was certain.)" Models rarely interrupt themselves like this. +- **Edits made before November 30, 2022.** ChatGPT's public launch. Anything older than that is, with very rare exceptions, not AI-written. + +--- + +## How to return the result + +**Pasted text (default).** Return the draft, a short list of remaining AI patterns, and the final rewrite. + +**File mode.** When the user names a file, run the full rewrite process but write only the final text to the file. Change prose only. Keep code blocks, YAML metadata, data, and link targets unchanged. Then give the user a short summary. + +**Embedded mode.** When another task uses this skill for a pull request, commit message, or document, return only the final text. + +## Rewrite process + +1. Read the source and mark each AI pattern. +2. Write a draft. Read it aloud. Check the rhythm, details, simple verbs such as *is* and *has*, and the right level of formality. +3. Ask two questions: + - **"What still sounds AI-generated?"** + - **"Did the rewrite add or remove any fact, name, number, date, quote, citation, ranking, or other claim?"** + Treat any unsupported addition or lost claim as an error. +4. Write the final version. State each point naturally instead of patching one flagged phrase at a time. If a sentence stays awkward, rewrite the paragraph around its main point. Apply the dash rule in §14. + +Return the result required by [How to return the result](#how-to-return-the-result). + +## Source + +This skill is based on [Wikipedia: Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing), maintained by WikiProject AI Cleanup. Its patterns come from reviews of AI-generated text on Wikipedia. + +Wikipedia's main point: "LLMs use statistical algorithms to guess what should come next. The result tends toward the most statistically likely result that applies to the widest variety of cases." diff --git a/PROJECT_CONTEXT.md b/PROJECT_CONTEXT.md index 25973dc..7a6e9a8 100644 --- a/PROJECT_CONTEXT.md +++ b/PROJECT_CONTEXT.md @@ -64,7 +64,7 @@ Use this file for verified target-repository facts only. Keep unknown values as ## 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. +- LiDAR: **RICHBEAM LakiBeam 1L** — verified from datasheet (2026-09). FOV 270°, range ≥40 m @70% reflectivity / ≥20 m @10%, ±2 cm, scan freq **only** 10/20/25/30 Hz, angular resolution 0.1° **only** at 10 Hz else 0.25°, 43.2 kHz sampling, **940 nm** Class 1, RJ45 UDP 100 Mbps, 9–36 V ≤2 W, 160 g, 60×60×80 mm, IP65, 100 kLux immunity. Configured at **25 Hz / 0.25° → 1081 samples over 270°**. Device is purchased but has not been powered on yet. Driver is `RichbeamTechnology/Lakibeam_ROS1_Driver` (catkin package name is literally `lidar`, node type `lidar_scan_node`, Noetic supported, manifest license is `TODO`) — it has **three verified bugs**: host-side `ros::Time::now()` stamping, `angle_min/max` hardcoded to ±180° regardless of the true 270° FOV, and `range_min`/`range_max` hardcoded to 0.0/100.0. Therefore the driver publishes `/scan_raw` and a `laser_filters` chain sanitises it into `/scan`. Gazebo stands in with `gpu_ray` at the same honest 270°/1081/25 Hz/0.05–40 m and feeds the same filter chain. Body self-occlusion beyond ±120.5° (laser at x=0.24 vs body front x=0.14, half-width 0.17) is cut at ±118°, leaving ~236° effective. - 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. @@ -102,7 +102,7 @@ Use this file for verified target-repository facts only. Keep unknown values as - 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. + 2. LiDAR specs and driver are now known (see Sensors), but the device has **not been powered on**. Two things remain measurable only on hardware, both via `slam_eval/scripts/check_scan.py`: what fills the ~90° arc the driver fabricates but the device never scans (if it is `inf`, `inf_is_valid: true` in `costmap_common.yaml` would raytrace-clear through walls), and whether host-side timestamp jitter is within budget (5 ms ≈ 4 cm at 10 m is tolerable; 20 ms ≈ 16 cm is not). Also unverified: which physical direction is the driver's 0°, which decides `angle_offset`. 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. diff --git a/ROS_TOPIC_MAP.md b/ROS_TOPIC_MAP.md index d390f05..9759c64 100644 --- a/ROS_TOPIC_MAP.md +++ b/ROS_TOPIC_MAP.md @@ -10,7 +10,8 @@ Parity rule (`docs/ARCHITECTURE.md` §6): simulation and real hardware publish t | 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. | +| `/scan_raw` | ROS 1 | `sensor_msgs/LaserScan` | sim: `richbeam_lidar` gpu_ray plugin (`libgazebo_ros_gpu_laser.so`); real: `lidar_scan_node` (pkg `lidar`, RichbeamTechnology driver) | `scan_filter` only | 25 Hz | 10 | **Raw, untrusted.** Nothing else may subscribe. Sim publishes an honest 270° / 1081 samples; the real driver publishes a scan that *claims* ±180° with `range_min=0.0` / `range_max=100.0` regardless of the device's true 270° / 0.05–40 m. See `docs/HARDWARE.md` §2 for the three driver bugs. | +| `/scan` | ROS 1 | `sensor_msgs/LaserScan` | `scan_filter` (`laser_filters/scan_to_scan_filter_chain`) | `safety_monitor` (1), `slam_core` (10), `move_base` obstacle_layer, RTAB-Map | 25 Hz | sub 1 / 10 | frame `laser_link`. **Sanitised**: header `range_min`/`range_max` corrected to 0.05 / 40.0, zero returns → NaN, body-occluded arc beyond ±118° blanked to `range_max+1`. Effective FOV ~236° of the device's 270°. Identical chain in sim and on hardware. | | `/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. | @@ -23,7 +24,7 @@ Parity rule (`docs/ARCHITECTURE.md` §6): simulation and real hardware publish t | `/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. | +| `/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 (940 nm LiDAR and IR depth both pass through). Empty list = glass is invisible to the robot. | ## Odometry And State Estimation @@ -48,10 +49,10 @@ Parity rule (`docs/ARCHITECTURE.md` §6): simulation and real hardware publish t | 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` | ROS 1 | `nav_msgs/OccupancyGrid` | **three mutually exclusive sources**: `rtabmap` (`grid_map` remapped, mapping + localization), `map_server`, `multi_map_manager` (multi-floor, latched) | `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. ⚠️ `octomap_server` does **not** publish here — its `projected_map` is remapped to `/octomap_grid` (debug only); see `docs/SIM_VS_REAL.md` §5 for why a projected octomap grid is unusable for navigation. | | `/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. | +| `/initialpose` | ROS 1 | `geometry_msgs/PoseWithCovarianceStamped` | `dock_init`, `global_scan_init`, RViz "2D Pose Estimate" | `rtabmap` (via `initialpose` → `/initialpose` remap) | on demand (`delay: 3.0` after start) | — | frame `map`. ⚠️ There is **no `amcl`** in this system — RTAB-Map does localization itself; see `localization.launch` for why. 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`. | diff --git a/agent_skills_claude_code b/agent_skills_claude_code new file mode 160000 index 0000000..7428150 --- /dev/null +++ b/agent_skills_claude_code @@ -0,0 +1 @@ +Subproject commit 74281503912851d6bec3d461de8c8b9e0b17a62d diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 95c18a0..b931055 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -271,7 +271,7 @@ cả nhận dạng hình học lẫn nhận dạng ảnh đều sẽ nhầm. | 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 | +| **Cửa kính** | LiDAR ToF 940nm **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 | diff --git a/docs/HARDWARE.md b/docs/HARDWARE.md index e7394b3..84f7c84 100644 --- a/docs/HARDWARE.md +++ b/docs/HARDWARE.md @@ -59,30 +59,104 @@ xứng rủi ro). --- -## 2. RICHBEAM 2D ToF LiDAR +## 2. RICHBEAM LakiBeam 1L — đã xác minh 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 +### Thông số (datasheet) -| # | Câu hỏi | Ảnh hưởng | +| Mục | Giá trị | +|---|---| +| FOV | **270°** | +| Tầm | **≥40 m @70% reflectivity**, ≥20 m @10% | +| Độ chính xác | ±2 cm | +| Scan frequency | **chỉ 10 / 20 / 25 / 30 Hz** | +| Angular resolution | **0.1° chỉ ở 10 Hz**; 0.25° ở 20/25/30 Hz | +| Sampling rate | 43.2 kHz | +| Bước sóng | **940 nm**, Class 1, <1 mW | +| Interface | RJ45 / Type-C, **UDP/IP 100 Mbps** | +| Nguồn | 9–36 V, ≤2 W | +| Khối lượng / kích thước | 160 g / 60×60×80 mm | +| Nhiệt độ | −25…60 °C | +| Chống sáng | 100 kLux | +| IP | IP65 | + +### Cấu hình chốt: 25 Hz / 0.25° → 1081 mẫu trên 270° + +Angular resolution và scan freq **ràng buộc cứng** với nhau — không chọn được cả +hai. Chọn 25 Hz vì: + +- `Icp/VoxelSize = 0.05` trong `rtabmap.launch` đã nuốt hết lợi thế của 0.1° + (ở 10 m: 0.1° → 1.7 cm, 0.25° → 4.4 cm, voxel 5 cm gộp cả hai) +- Méo do chuyển động: 10 Hz = 100 ms/scan, xoay 1.2 rad/s quét **6.9°** trong một + scan; 25 Hz = 40 ms → **2.75°**. Driver không deskew. + +### 4 câu hỏi cũ — đã trả lời + +| # | Câu hỏi | Trả lời | |---|---|---| -| 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 | +| 1 | Interface? | **Ethernet UDP** (RJ45). Jitter thấp ✅ | +| 2 | Thiết bị tự cấp timestamp? | **KHÔNG** — xem bug 1 dưới ⚠️ | +| 3 | FOV 270° hay 360°? | **270°** | +| 4 | Scan rate / angular res? | 10–30 Hz, ghép cặp với resolution | -Kiểm tra #2: `rostopic echo /scan/header` so với `date +%s.%N`. +### ⚠️ 3 bug trong driver chính hãng -Sau khi có số thật, cập nhật `robot_sim/urdf/gazebo_sensors.xacro` cho khớp. +Driver: [`RichbeamTechnology/Lakibeam_ROS1_Driver`](https://github.com/RichbeamTechnology/Lakibeam_ROS1_Driver) +— package tên là `lidar`, node type `lidar_scan_node`, hỗ trợ Noetic. +License trong manifest là `TODO` → **phải xin license bằng văn bản trước khi +thương mại hoá**. + +1. **Host-side timestamp.** `scan_begin = ros::Time::now()` tại azimuth-zero. + Đúng quy ước LaserScan (stamp = tia đầu), nhưng mang jitter của host. + → Time offset LiDAR↔IMU ở GĐ2 là **bắt buộc**, không phải tuỳ chọn. +2. **Khai 360° cho thiết bị 270°.** `angle_min/max = ±180°` vô điều kiện, kể cả + khi `scan_range_start/stop` thu hẹp. Cái gì lấp vào cung bịa ra thì **chưa + biết, phải đo** — nếu là `inf` thì costmap (`inf_is_valid: true`) sẽ + raytrace-clear xuyên tường mỗi scan. +3. **`range_min = 0.0`, `range_max = 100.0`** hardcoded (thật: 0.05 / 40). + `range_min = 0` vô hiệu hoá bộ lọc chuẩn `r < range_min` ở mọi consumer. + +Phụ: `time_increment = duration / n / 2` — chỗ `/2` sai so với REP. + +→ Driver **không** publish thẳng lên `/scan`. Nó publish `/scan_raw`, và +`robot_drivers/launch/scan_filter.launch` vệ sinh rồi mới ra `/scan`. + +### Tự che thân robot + +LiDAR gắn ở `x = 0.24`, thân trước `x = 0.14`, nửa rộng `y = ±0.17`: + +``` +atan2(0.17, 0.14 - 0.24) = 120.5° +``` + +Tia ngoài **±120.5°** đâm vào thân → 29° trong 270° là rác (10.7%). +Cắt ở `laser_filters` tại **±118°** (chừa 2.5° dung sai gá), không cắt ở driver: +bug 2 khiến `scan_range_start/stop` không sửa được `angle_min/max` nói dối. + +### Mạng + +| | | +|---|---| +| IP LiDAR | `192.168.198.2` (param `sensorip`) | +| IP host | `192.168.198.1`, hoặc `hostip: 0.0.0.0` để bind mọi interface | +| Netmask | `255.255.255.0` | +| Port UDP | `2368` | + +IPC cần **một cổng Ethernet rảnh** cho LiDAR, cộng USB3 cho D410 và serial cho +MCU IMU. Tính vào cấu hình IPC ở GĐ8. + +⚠️ Mọi param của driver khai `type="string"`, **kể cả số**. Bỏ `type` đi thì +roslaunch đặt int, `getParam(std::string&)` thất bại, và driver **âm thầm rơi về +30 Hz** — cũng là tần số hợp lệ nên không có gì báo lỗi. ### ⚠️ 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; +2. **Kính** — bước sóng 940nm **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. --- @@ -96,11 +170,47 @@ Sau khi có số thật, cập nhật `robot_sim/urdf/gazebo_sensors.xacro` cho | **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** | +| **Cảm biến vực** | 2–3 ToF/IR chúc xuống ở mép trước | ~$3/con. **Bắt buộc, ngang hàng bumper** — xem §3.1 | | **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ử. +### 3.1. ⚠️ Cảm biến vực — vì sao camera không thay thế được + +Đã có `perception_3d/CliffDetectNodelet` phát hiện vực từ ảnh depth, **nhưng nó +mù hoàn toàn dưới ~1.1 m**. Đây là giới hạn hình học, không phải lỗi cài đặt: + +``` +camera z = 0.80 m, chúc 15°, nửa FOV dọc 27.3° +→ tia thấp nhất chúc 42.3° +→ chỉ thấy sàn từ x = 0.80/tan(42.3°) + 0.19 ≈ 1.07 m +``` + +Robot phát hiện từ 1.1–2.5 m rồi dừng thì **đủ khi tiến thẳng tới mép**, nhưng +không đủ khi: + +- xoay tại chỗ sát mép +- tiến tiếp sau khi đã dừng sẵn trong vùng mù +- tiếp cận mép theo góc chéo + +Ba trường hợp này chỉ cảm biến chúc xuống ở mép trước mới phủ được. Đây cũng là +cách **mọi robot dịch vụ thương mại và mọi robot hút bụi** đều làm. + +⚠️ **Phân cực ngược với siêu âm.** Siêu âm kích khi `range < ngưỡng` (có vật +chắn); cảm biến vực kích khi `range > ngưỡng` (sàn biến mất). Trong +`robot_safety/config/safety.yaml` chúng là **hai danh sách riêng** +(`ultrasonic_topics` và `cliff_topics`). Cắm nhầm danh sách là đảo ngược logic +một cách âm thầm — robot sẽ lao thẳng xuống cầu thang. + +Ba lý do nữa khiến bản dựa trên depth không thể là lớp an toàn duy nhất: + +| Vấn đề | Số đo | +|---|---| +| Mark **sau** mép thật | mép ở 1.2 m → lệch 0.26 m; ở 4 m → lệch 0.85 m. Đã xử lý bằng cách mark tại giao điểm tia × mặt sàn, nhưng vùng mù thì không xử lý được | +| Cầu thang tối **không trả depth** | trả lỗ (NaN), nên phải chạy trên ảnh depth chứ không trên cloud | +| Sai số pitch chưa hiệu chuẩn | 1° ở 3 m → sàn hiện ra ở −52 mm → báo vực giả. Đang bù bằng ngưỡng nở theo tầm 2° | + ### 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.** diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 471fb9a..70a55f2 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -57,7 +57,7 @@ nặng trên nội thất đen, cần xét lại lựa chọn LiDAR. | 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` | +| **Driver RICHBEAM** | ⚠️ Driver CÓ SẴN, không phải chờ hãng — `RichbeamTechnology/Lakibeam_ROS1_Driver`, hỗ trợ Noetic. 4 câu hỏi cũ đã trả lời, nhưng driver có **3 bug** phải bọc lại: xem `HARDWARE.md` §2 | | **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 diff --git a/docs/SIM_VS_REAL.md b/docs/SIM_VS_REAL.md index a183270..1c5a083 100644 --- a/docs/SIM_VS_REAL.md +++ b/docs/SIM_VS_REAL.md @@ -39,11 +39,22 @@ 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. +**Sửa ban đầu:** lùi thân (`body_offset_x = -0.06`), đẩy LiDAR ra trước (x=0.24), +và giảm FOV sim 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. +**Sửa hiện tại (sau khi có spec thật):** sim publish **FOV THẬT 270°** lên +`/scan_raw`, và `robot_drivers/launch/scan_filter.launch` cắt cung bị thân che +tại ±118° rồi mới ra `/scan`. Cùng một filter, cùng bounds, **sim và thật giống +hệt nhau**. + +Với hình học hiện tại, cung bị che nhỏ hơn con số 71.7% đo ngày đó nhiều: +`atan2(0.17, 0.14 − 0.24) = 120.5°` → chỉ 2×14.5° = **29° (10.7%)**. +Con số 71.7% có trước `body_offset_x = -0.06` và `laser_x = 0.24`. + +⚠️ Sim **KHÔNG** bắt chước chỗ driver thật nói dối (nó khai `angle_min/max = ±180°` +cho thiết bị 270° — xem `HARDWARE.md` §2 bug 2). Sim trung thực 270°, thật nói dối +360°, và filter là nơi hấp thụ bất đối xứng đó. Cả hai hội tụ về cùng cung ~236°. +Đừng "sửa" sim cho khớp driver. ### 3. Độ cứng tiếp xúc đặt ngược → bánh mất lực kéo @@ -180,7 +191,7 @@ Sim thấy mọi vật như nhau. Thực tế: 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 +Thực tế: LiDAR ToF 940nm **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". @@ -203,6 +214,57 @@ xuống ~0.3 để mô phỏng sàn dầu mỡ), nhưng động lực học trư 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. +### 9. Hấp thụ IR của vực tối — `cliff_test.world` chỉ kiểm được một nửa + +`robot_sim/worlds/cliff_test.world` có hai tình huống, và chúng **không ngang +giá trị nhau**: + +| Tình huống | Sim kiểm được? | +|---|---| +| **Mép hở**, có sàn dưới ở −1.0 m → depth xa hơn kỳ vọng | ✅ đúng vật lý | +| **Hố tối**, thành phủ vật liệu đen → depth biến mất | ❌ **không** | + +Gazebo không mô phỏng hấp thụ IR. Vật liệu đen trong world chỉ làm ảnh tối đi, +**không làm depth trả về NaN** như ngoài đời. Mà nhánh "lỗ" mới là trường hợp +thật của cầu thang tối, và chính là lý do `CliffDetectNodelet` phải chạy trên +ảnh depth thay vì trên cloud. + +→ Nhánh "sụt" nghiệm thu được trong sim. Nhánh "lỗ" **chỉ kiểm được trên phần +cứng thật**, và phải kiểm ở đúng cầu thang của toà nhà mục tiêu. + +Thêm nữa: không world nào mô phỏng được vùng mù 0–1.1 m một cách có ý nghĩa, +vì trong sim robot luôn "thấy" mép từ xa rồi dừng. Ngoài đời robot có thể bị +đẩy, bị trượt, hoặc khởi động ngay cạnh mép. + +### 10. `intensities` và `scan_time` của LaserScan — sim trả 0 + +Đo trực tiếp trên `/scan_raw` (2026-09-11, `check_scan.py`): + +``` +scan_time : 0.0 <- libgazebo_ros_gpu_laser.so khong dien +time_increment : 0.0 +intensities : [0.0, 0.0, ...] toan bo 1081 tia +``` + +LakiBeam 1L thật thì **ngược lại**: driver publish RSSI vào `intensities`, và +`scan_time` có giá trị đo được. + +Hai hệ quả, cả hai đều là loại hỏng im lặng: + +1. **Deskew sẽ không làm gì trong sim mà vẫn chạy trên phần cứng.** + `ScanHeaderFixFilter` sửa `time_increment = scan_time / n` (gỡ lỗi chia 2 của + driver). Trong sim `scan_time = 0` nên kết quả vẫn là 0. Nếu sau này bật + deskew, sim sẽ cho kết quả "ổn" vì nó không bù gì cả, còn phần cứng mới thực + sự bù — sai lệch giữa hai bên không ai báo. + +2. **Không test được bất kỳ bộ lọc nào dựa trên cường độ.** + `LaserScanIntensityFilter` và nhánh intensity của speckle filter vô dụng + trong sim. Đáng lưu ý vì **dropout của ToF trên bề mặt đen** (mục 4 ở trên) + là rủi ro chính đã ghi trong `HARDWARE.md`, mà RSSI chính là tín hiệu để + phát hiện nó. Tức công cụ chống rủi ro đó chỉ tune được trên phần cứng thật. + +→ Đã thêm vào checklist bên dưới. + --- ## Checklist: phải test lại trên phần cứng thật @@ -210,6 +272,13 @@ ra, bàn được xếp lại. Đá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) +- [ ] **Hướng 0° thật của LakiBeam sau khi gá** — `check_scan.py --topic /scan_raw`, + xem cung mù có đối xứng quanh 180° không. Lệch thì `angle_offset` sai và + mọi bounds trong `scan_filter.yaml` sai theo +- [ ] **Cái gì lấp vào ~90° driver bịa ra** — nếu là `inf` thì costmap + (`inf_is_valid: true`) sẽ raytrace-clear xuyên tường mỗi scan +- [ ] **`intensities` / RSSI thật** — sim trả 0 hết, nên mọi bộ lọc theo cường + độ (chống dropout trên bề mặt đen) chỉ tune được ở đây - [ ] 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 diff --git a/reloc_hosp.sh b/reloc_hosp.sh new file mode 100755 index 0000000..384be4f --- /dev/null +++ b/reloc_hosp.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash +# +# reloc_hosp.sh - Chay bai kidnapped-robot tren ban do hospital. +# +# ============ VI SAO CAN FILE NAY ============ +# localization.launch GHI pose dinh vi cuoi cung vao database (opt_last_localization), +# ke ca o che do Mem/IncrementalMemory=false. Nen lan chay thu hai tren CUNG file +# se khoi dong voi dap an cua lan truoc -> lech kidnap bang 0 -> phep do vo nghia. +# +# Da dinh that hai lan: +# correction = xyz=-2.009,-18.903 trung khit diem tha (-2.11,-18.91) +# correction = xyz=-1.432, -1.922 sot lai tu lan chay khac +# +# Script nay chep ban do sach TRUOC moi lan chay, khong the quen. +# +# ============ DUNG ============ +# ./reloc_hosp.sh -11.46 13.22 # yaw 3.14, Icp/MaxTranslation 0.3 +# ./reloc_hosp.sh -11.46 13.22 1.57 +# ./reloc_hosp.sh -11.46 13.22 3.14 1.0 # noi Icp/MaxTranslation len 1.0 m +# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 15 # ha Vis/MinInliers xuong 15 +# +# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 20 true # bat global_scan_init +# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 20 true true # + dinh vi CHU DONG +# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 20 true true true # + GICP tren depth +# +# Tham so 4 = Icp/MaxTranslation. Noi len de proximity hoi phuc duoc sau va cham. +# Tham so 5 = Vis/MinInliers. Ha xuong de de nhan ra cho hon. +# Tham so 6 = enable_global_init. Bat node khop scan LiDAR (khuyen dung: true). +# Tham so 7 = enable_active_reloc. Khi bi NHAP NHANG, tinh va NOI RA phai di dau +# de phan biet, thay vi de nguoi van hanh mo. Xem /reloc/suggested_motion. +# Khong publish /initialpose nen khong the lam xau do chinh xac. +# +# ⚠️ Ha tham so 5 co RUI RO NHAN NHAM CHO. Chi danh gia bang check_reloc.py +# (sai so tuyet doi so ground truth), TUYET DOI khong danh gia bang so lan +# dong vong trong log. +# +# ============ KICH BAN DO: CHI XOAY TAI CHO ============ +# Yeu cau van hanh: tha robot xuong, XOAY TAI CHO la phai dinh vi duoc. +# Lai di trong moi truong chua biet minh o dau la khong dung duoc that. +# Nen khi do: dung yen, chi xoay. Cot `da di(m)` phai o gan 0. +# +# Terminal 2: rosrun slam_eval check_reloc.py --map-origin 4.0 14.0 0.0 +# Terminal 3: roslaunch robot_bringup teleop_joystick.launch +# +# ============ KIEM PHEP DO CO HOP LE KHONG ============ +# grep -m1 "correction = xyz" /tmp/reloc_hosp.log +# Phai ra xyz=-6.709041,-28.870140 = pose cuoi phien quet. +# Ra so nao khac -> ban do bi nhiem -> bo ket qua, chay lai. +# Va dong t=0.0 trong check_reloc phai hien sai so ~30 m. + +set -euo pipefail + +WS="$HOME/projects/vSLAM_ws" +SRC="$WS/maps/map_hospital.db" +DST="$WS/maps/reloc_hosp.db" + +if [ $# -lt 2 ]; then + echo "Dung: $0 X Y [YAW]" + echo + echo "Bon diem da chon (xa pose khoi tao nhat, thua nhat):" + echo " -0.62 14.79 lech 29.7 m 22 quan sat/1m" + echo " -11.46 13.22 lech 29.4 m 19 quan sat/1m" + echo " 11.64 10.43 lech 29.1 m 18 quan sat/1m" + echo " -10.43 4.81 lech 21.1 m 31 quan sat/1m" + exit 1 +fi + +X="$1"; Y="$2"; YAW="${3:-3.14}"; ICPT="${4:-0.3}"; MININL="${5:-20}" +GLOBAL="${6:-false}" +ACTIVE="${7:-false}" +GICP="${8:-false}" + +[ -f "$SRC" ] || { echo "KHONG THAY ban do goc: $SRC"; exit 1; } + +cp "$SRC" "$DST" +echo "==================================================================" +echo " da chep ban do SACH : $(du -h "$DST" | cut -f1)" +echo " diem tha (Gazebo) : x=$X y=$Y yaw=$YAW" +echo " goc ban do : 4.0 14.0 0.0" +echo "==================================================================" +echo +echo " Cho ~25 s cho database nap xong (2716 node) roi moi bat T2." +echo " T2: rosrun slam_eval check_reloc.py --map-origin 4.0 14.0 0.0" +echo " T3: roslaunch robot_bringup teleop_joystick.launch" +echo +echo " Kiem sau khi chay:" +echo " grep -m1 'correction = xyz' /tmp/reloc_hosp.log" +echo " -> phai ra xyz=-6.709041,-28.870140" +echo + +exec roslaunch robot_bringup localization.launch world:=hospital \ + database_path:="$DST" \ + visual_loop:=true start_at_origin:=false enable_dock_init:=false \ + x:="$X" y:="$Y" yaw:="$YAW" icp_max_translation:="$ICPT" \ + vis_min_inliers:="$MININL" enable_global_init:="$GLOBAL" \ + enable_active_reloc:="$ACTIVE" \ + enable_gicp:="$GICP" diff --git a/src/localization_ops/CMakeLists.txt b/src/localization_ops/CMakeLists.txt index a1a76b0..198453a 100644 --- a/src/localization_ops/CMakeLists.txt +++ b/src/localization_ops/CMakeLists.txt @@ -1,12 +1,30 @@ cmake_minimum_required(VERSION 3.0.2) project(localization_ops) -find_package(catkin REQUIRED) +find_package(catkin REQUIRED COMPONENTS + roscpp geometry_msgs sensor_msgs std_msgs + tf2_ros tf2_geometry_msgs pcl_ros pcl_conversions +) +find_package(PCL REQUIRED COMPONENTS common filters registration kdtree) +find_package(RTABMap 0.21 REQUIRED COMPONENTS core) catkin_package() +include_directories( + ${catkin_INCLUDE_DIRS} ${PCL_INCLUDE_DIRS} ${RTABMap_INCLUDE_DIRS}) + +add_executable(reloc_gicp_node src/reloc_gicp_node.cpp) +add_dependencies(reloc_gicp_node ${catkin_EXPORTED_TARGETS}) +target_link_libraries(reloc_gicp_node + ${catkin_LIBRARIES} ${PCL_LIBRARIES} ${RTABMap_LIBRARIES}) + +install(TARGETS reloc_gicp_node + RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}) + catkin_install_python(PROGRAMS scripts/dock_init.py + scripts/global_scan_init.py + scripts/reloc_active.py scripts/floor_detector.py scripts/multi_map_manager.py DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} diff --git a/src/localization_ops/launch/localization_ops.launch b/src/localization_ops/launch/localization_ops.launch index 781da27..62786ba 100644 --- a/src/localization_ops/launch/localization_ops.launch +++ b/src/localization_ops/launch/localization_ops.launch @@ -10,11 +10,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/localization_ops/package.xml b/src/localization_ops/package.xml index 7de439c..7b74f06 100644 --- a/src/localization_ops/package.xml +++ b/src/localization_ops/package.xml @@ -11,6 +11,14 @@ catkin + roscpp + tf2_ros + tf2_geometry_msgs + pcl_ros + pcl_conversions + libpcl-all-dev + rtabmap + rospy sensor_msgs nav_msgs diff --git a/src/localization_ops/scripts/global_scan_init.py b/src/localization_ops/scripts/global_scan_init.py new file mode 100755 index 0000000..090aaa1 --- /dev/null +++ b/src/localization_ops/scripts/global_scan_init.py @@ -0,0 +1,823 @@ +#!/usr/bin/env python3 +""" +global_scan_init - Dinh vi toan cuc bang khop scan LiDAR voi luoi chiem dung. + +============ BAI TOAN ============ +Tha robot xuong mot cho bat ky tren ban do da quet, KHONG cho no biet dang o +dau. Robot xoay tai cho mot vong. Phai suy ra duoc pose trong ban do. + +Lai vong quanh trong moi truong chua biet minh o dau la KHONG dung duoc that - +do la yeu cau van hanh, khong phai so thich. + +============ VI SAO KHONG DUNG TUI TU (bag-of-words) ============ +Da do tren ban do hospital (2716 node): + + 194 lan tui tu de xuat ung vien, 0 lan qua duoc kiem chung hinh hoc + matches trung vi 43 <- mo ta ORB khop rat nhieu + inliers trung vi 0, cao nhat 19 tren nguong Vis/MinInliers=20 + 186/194 lan co DUNG 0 inlier + +Thu ca hai huong noi long, deu khong cuu duoc: + Icp/MaxTranslation 0.3 -> 1.0 van phai lai 60 m moi ra + Vis/MinInliers 20 -> 15 van phai lai + +Nguyen nhan: TRUNG LAP TRI GIAC. Hanh lang benh vien giong nhau, mo ta noi +"cho nay toi tung qua", hinh hoc noi "khong, hanh lang khac trong giong het". +Tren ban do house (khong co hanh lang lap) thi cung he do dat 14m -> 0.038m +trong 1.7 giay, dung yen. + +============ VI SAO KHOP SCAN GIAI QUYET DUOC ============ +Tui tu de xuat TUNG ung vien roi de hinh hoc loai tung cai mot - no khong bao +gio SO SANH cac ung vien voi nhau. + +Cho nay tinh diem MOI gia thuyet (x,y,theta) cung mot luc, nen so sanh duoc. +Hai hanh lang giong nhau se cho hai diem gan bang nhau -> phat hien duoc su +nhap nhang va IM LANG, thay vi chon bua. + +Bat bien theo goc quay la do QUET HET moi theta, khong phai do huan luyen. + +============ VI SAO KHONG DUNG VPR HOC SAU ============ + librtabmap_core.so.0.21 KHONG link libpython + chuoi nam san trong .so: + "PyDescriptor cannot be used as rtabmap is not built with Python3 support." + +Phai bien dich lai RTAB-Map tu nguon + PyTorch + CUDA. Tren Orin Nano 8 GB +dung chung CPU/GPU thi rieng CUDA context da ~1 GB. Va mo hinh VPR huan luyen +tren anh RGB trong khi D410 chi co IR. + +Node nay chi can numpy + cv2, chay CPU, duoi 1 giay moi lan truy van. + +============ NODE NAY KHONG DUNG VAO RTAB-MAP ============ +No chi publish /initialpose - dung topic ma dock_init.py dang dung va +rtabmap.launch:252 da remap san. RTAB-Map nhan pose khoi tao roi tinh chinh +cuc bo bang ICP, phan do von da chay tot. + +Quan he voi dock_init: BO SUNG, khong thay the. Khoi dong tu dock thi dung +dock_init (pose da biet chinh xac). Node nay cho truong hop bi be di hoac mat +track giua ca. + +============ DUNG ============ + roslaunch robot_bringup localization.launch enable_global_init:=true + +Goi tay: + rosservice call /global_scan_init/relocalize +""" + +import math +import threading + +import numpy as np +import rospy +import tf2_ros +from geometry_msgs.msg import Pose, PoseArray, PoseWithCovarianceStamped +from nav_msgs.msg import OccupancyGrid, Odometry +from sensor_msgs.msg import LaserScan +from std_srvs.srv import Trigger, TriggerResponse + +try: + import cv2 +except ImportError: + cv2 = None + + +def yaw_of(q): + """Yaw tu quaternion. Chi can thanh phan z vi he la SE(2).""" + 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)) + + +def maxpool(a, k): + """Gop khoi k x k lay gia tri LON NHAT. + + Phai la max chu khong phai trung binh: muc tho dung de SANG LOC, bo sot mot + dinh that o day thi khong con co hoi tinh chinh no nua. Max thi rong rai, + giu lai moi ung vien dang xet.""" + h, w = a.shape + h2, w2 = (h // k) * k, (w // k) * k + if h2 == 0 or w2 == 0: + return a.copy() + return a[:h2, :w2].reshape(h2 // k, k, w2 // k, k).max(axis=(1, 3)) + + +class GlobalScanInit(object): + def __init__(self): + self.map_frame = rospy.get_param('~map_frame', 'map') + self.odom_frame = rospy.get_param('~odom_frame', 'odom') + self.base_frame = rospy.get_param('~base_frame', 'base_footprint') + + # Do rong ham khoang cach. 0.15 m ~ 3 o luoi o CellSize=0.05, du de + # chiu sai so luoi ma khong lam nhoe het dac trung hinh hoc. + self.sigma = rospy.get_param('~sigma', 0.15) + + # ⚠️ Khop den 12 m thoi. Grid/RangeMax=12.0 trong rtabmap.launch, tuc + # ban do CHI duoc dung tu tia <= 12 m. Dung tia xa hon la khop vao vung + # ban do chua tung ghi -> diem thap oan cho dung vi tri. + self.max_range = rospy.get_param('~max_range', 12.0) + + self.coarse_res = rospy.get_param('~coarse_res', 0.80) + self.angle_step = math.radians(rospy.get_param('~angle_step', 5.0)) + self.top_k = rospy.get_param('~top_k', 24) + + # Nguong chong nhan nham: diem cao nhat phai hon diem cao nhat NGOAI + # ban kinh reject_radius bao nhieu lan. + self.min_ratio = rospy.get_param('~min_ratio', 1.30) + self.reject_radius = rospy.get_param('~reject_radius', 2.0) + + # ⚠️ CONG KIEM THEO TRUC GOC. + # + # min_ratio/reject_radius chi loc doi thu theo VI TRI. Mot gia thuyet o + # DUNG vi tri do nhung KHAC HUONG bi loai khoi danh sach doi thu (ca o + # buoc gom ung vien, dong ~356, lan buoc tim doi thu, dong ~386/393), + # nen ty le s1/s2 KHONG BAO GIO do duoc tinh da nghia ve huong. + # + # Da do tren ban do hospital, diem tha (7.47,-29.97) huong 180 do: + # xoay 301 do -> khop ra -139.2 do (sai 40.8 do) ty le 1.66 + # xoay 181 do -> khop ra -20.4 do (sai 159.6 do) ty le 1.59 + # xoay 0 do -> khop ra 180.0 do (sai 0.0 do) ty le 1.57 + # Ca ba deu vuot min_ratio 1.30. Vi tri luon dung 0.17-0.21 m. + # Odometry da duoc loai tru: xoay 3 vong lech tong 0.1 do. + # + # Nguyen nhan: mot scan don la cung 236 do bat doi xung -> huong co mot + # nghiem. Dam may tich luy 360 do doi xung quay hon nhieu -> da cuc tri + # theo goc, dung luc cong kiem khong nhin huong. + self.min_ratio_yaw = rospy.get_param('~min_ratio_yaw', 1.30) + # Doi thu goc phai lech it nhat ngan nay moi tinh la "khac huong". + self.min_angle_sep = math.radians( + rospy.get_param('~min_angle_sep_deg', 25.0)) + + # ============ CHAY LIEN TUC ============ + # Truoc day node la MOT LAN: bi tu choi vi nhap nhang la nam im, phai + # goi tay `rosservice call /global_scan_init/relocalize`. + # Da do tren ban do hospital: 3/4 lan thu bi tu choi (ty le 1.04, 1.18, + # 1.24 < 1.30) - tuc hanh lang lap, node tu choi DUNG. Nhung nguoi van + # hanh khong the ngoi goi service moi lan robot doi cho. + # + # Tu nap lai sau khi bi tu choi. 0 = tat. + self.retry_period = rospy.get_param('~retry_period', 10.0) + + # ⚠️ TU PHAT HIEN DA LAC - BAT BUOC di kem retry_period. + # + # Thieu no thi node se bom /initialpose DE LEN ket qua dung cua RTAB-Map + # moi chu ky, tuc pha hoai dung luc he dang chay tot. + # + # Cach do: lay mot scan, chieu vao ban do bang pose DANG TIN (map->base + # tu TF), roi cham diem tren cung truong likelihood dung de khop. + # Pose dung thi scan chong khit tuong -> diem cao. Bi be di thi diem sut + # ngay. Hoan toan doc lap voi RTAB-Map: no tu hoi "pose toi dang tin co + # giai thich duoc cai toi dang thay khong". + self.watch_lost = rospy.get_param('~watch_lost', True) + # Diem tut duoi ty le nay so voi diem luc khop thanh cong -> nghi lac. + self.lost_score_ratio = rospy.get_param('~lost_score_ratio', 0.55) + # Phai tut LIEN TUC ngan nay giay moi kich hoat. Chong nhieu nhat thoi + # khi co nguoi di ngang qua LiDAR. + self.lost_hold = rospy.get_param('~lost_hold', 3.0) + self.lost_period = rospy.get_param('~lost_period', 1.0) + + # ============ ⚠️ CHO ROBOT CHAM LAI ROI MOI PUBLISH ============ + # T_map_odom tim duoc la TINH va DUNG. Nhung compose() ghep no voi + # odom->base tra o Time(0) - ban moi nhat CO SAN trong bo dem TF, von + # tre ~0.5s so voi thuc tai - roi dong dau ban tin bang now(). + # Ben nhan hieu la "bay gio" -> lech = omega * do_tre. + # + # Da do tren ban do hospital: + # khop luc DUNG YEN (omega=0) -> sai huong 0.07-0.09 do + # khop luc dang quay ~20 do/s -> sai huong 15-22 do + # + # Vi T_map_odom khong doi theo thoi gian, chi can CHO robot cham lai + # roi tra lai odom->base la ra pose chinh xac. Khong phai ngoai suy, + # khong phai doan do tre. + self.settle_omega = rospy.get_param('~settle_omega', 0.05) # rad/s + self.settle_timeout = rospy.get_param('~settle_timeout', 8.0) + self.omega = 0.0 + rospy.Subscriber(rospy.get_param('~odom_topic', '/odometry/filtered'), + Odometry, self.on_odom, queue_size=5) + + self.ref_score = None # diem/diem-do luc khop thanh cong gan nhat + self.lost_since = None + self.last_scan = None + self.pose_stamp = None + + # Goc quet tich luy truoc khi khop. + # + # FOV huu dung la 236 do: thiet bi quet 270 do, va chuoi filter cat cung + # bi than robot che tai +-118 do. + # Nguon: robot_drivers/config/scan_filter.yaml (KHONG con o + # gazebo_sensors.xacro - sim gio publish dung 270 do cua thiet bi va + # cung duoc cat o chuoi filter, giong het duong phan cung that). + # + # Mot scan thieu 360 - 236 = 124 do, nen ve ly thuyet xoay 124 do la du + # phu kin. De 300 do la CHON DU AN TOAN, khong phai con so suy ra: + # bu cho odometry troi trong luc xoay va cho trung lap giua cac scan. + self.yaw_sweep = math.radians(rospy.get_param('~yaw_sweep', 300.0)) + self.timeout = rospy.get_param('~timeout', 30.0) + + self.max_points = rospy.get_param('~max_points', 1500) + self.auto = rospy.get_param('~auto', True) + self.delay = rospy.get_param('~delay', 5.0) + + self.lock = threading.Lock() + self.grid = None # (L_fine, free_fine, res, ox, oy) + self.pts = [] # diem tich luy, he odom + self.yaw_acc = 0.0 + self.yaw_prev = None + self.active = False + self.t_start = 0.0 + + self.buf = tf2_ros.Buffer() + tf2_ros.TransformListener(self.buf) + + self.pub = rospy.Publisher('/initialpose', PoseWithCovarianceStamped, + queue_size=1, latch=True) + + # ⚠️ Lo ra TAP GIA THUYET, ke ca khi khong du tu tin de publish. + # + # Truoc day khi nhap nhang (ty le < min_ratio) node vut het va im lang. + # Nhung chinh luc do no BIET ro co may cho dang canh nhau va o dau - do + # la thong tin quy nhat de mot lop tren tinh xem PHAI DI DAU de phan + # biet. Vut di la bat nguoi van hanh mo lai tu dau. + # + # /initialpose VAN chi ra khi mot gia thuyet ap dao. Topic nay khong + # thay doi hanh vi dinh vi, chi cong bo thu dang co. + self.hyp_pub = rospy.Publisher('/reloc/hypotheses', PoseArray, + queue_size=1, latch=True) + rospy.Subscriber('map', OccupancyGrid, self.on_map, queue_size=1) + rospy.Subscriber('scan', LaserScan, self.on_scan, queue_size=5) + self.srv = rospy.Service('~relocalize', Trigger, self.on_trigger) + + if cv2 is None: + rospy.logerr('global_scan_init: thieu cv2. ' + 'sudo apt install python3-opencv') + + if self.watch_lost: + rospy.Timer(rospy.Duration(self.lost_period), self.on_watch) + + rospy.loginfo('global_scan_init: san sang. Xoay robot tai cho.') + if self.auto: + rospy.Timer(rospy.Duration(self.delay), self.on_timer, oneshot=True) + + # ---------------- ban do ---------------- + + def on_map(self, msg): + if cv2 is None: + return + w, h = msg.info.width, msg.info.height + g = np.asarray(msg.data, dtype=np.int8).reshape(h, w) + + # OccupancyGrid: 0 = trong, 100 = co vat can, -1 = chua biet. + occ = (g >= 50).astype(np.uint8) + free = (g == 0) + + # distanceTransform do khoang cach tu diem KHAC 0 toi diem 0 gan nhat, + # nen phai dao: vung khong co vat can = 255. + inv = np.where(occ > 0, 0, 255).astype(np.uint8) + dist = cv2.distanceTransform(inv, cv2.DIST_L2, 5) * msg.info.resolution + + lf = np.exp(-(dist ** 2) / (2.0 * self.sigma ** 2)).astype(np.float32) + + with self.lock: + self.grid = dict(L=lf, free=free, res=msg.info.resolution, + ox=msg.info.origin.position.x, + oy=msg.info.origin.position.y, + w=w, h=h) + rospy.loginfo_once('global_scan_init: nhan ban do %dx%d @ %.3f m', + w, h, msg.info.resolution) + + # ---------------- gom scan ---------------- + + def on_odom(self, msg): + self.omega = msg.twist.twist.angular.z + + def on_scan(self, msg): + # Luon giu ban moi nhat: bo tu kiem "da lac" can scan ngay ca khi + # khong dang gom. + self.last_scan = msg + with self.lock: + if not self.active or self.grid is None: + return + try: + tr = self.buf.lookup_transform(self.odom_frame, msg.header.frame_id, + msg.header.stamp, + rospy.Duration(0.2)) + except Exception: + return + + t = tr.transform.translation + th = yaw_of(tr.transform.rotation) + + r = np.asarray(msg.ranges, dtype=np.float32) + ok = np.isfinite(r) & (r > msg.range_min) & (r < min(msg.range_max, + self.max_range)) + if not ok.any(): + return + idx = np.nonzero(ok)[0] + ang = msg.angle_min + idx * msg.angle_increment + rr = r[idx] + + # laser_link -> odom + ca, sa = math.cos(th), math.sin(th) + lx, ly = rr * np.cos(ang), rr * np.sin(ang) + ox = t.x + ca * lx - sa * ly + oy = t.y + sa * lx + ca * ly + + with self.lock: + self.pts.append(np.stack([ox, oy], axis=1)) + + # Do goc da quet bang chinh TF cua LiDAR - xoay tai cho thi + # odometry rat chinh xac nen phep gom nay sach. + if self.yaw_prev is not None: + d = math.atan2(math.sin(th - self.yaw_prev), + math.cos(th - self.yaw_prev)) + self.yaw_acc += abs(d) + self.yaw_prev = th + + done = self.yaw_acc >= self.yaw_sweep + late = (rospy.Time.now().to_sec() - self.t_start) > self.timeout + + if done or late: + self.finish(timed_out=late and not done) + + # ---------------- khop ---------------- + + def finish(self, timed_out): + with self.lock: + self.active = False + pts = np.concatenate(self.pts) if self.pts else None + sweep = math.degrees(self.yaw_acc) + g = self.grid + if pts is None or len(pts) < 50 or g is None: + rospy.logwarn('global_scan_init: khong du diem (%s). Bo qua.', + 0 if pts is None else len(pts)) + return + if timed_out: + rospy.logwarn('global_scan_init: het %.0fs ma moi quet %.0f do ' + '(can %.0f). Van thu khop voi nhung gi co.', + self.timeout, sweep, math.degrees(self.yaw_sweep)) + + pts = self.downsample(pts, g['res']) + rospy.loginfo('global_scan_init: khop %d diem, da quet %.0f do...', + len(pts), sweep) + + t0 = rospy.Time.now().to_sec() + res = self.match(pts, g) + dt = rospy.Time.now().to_sec() - t0 + + if res is None: + rospy.logwarn('global_scan_init: THAT BAI - khong tim duoc dinh ' + 'nao du manh (%.2fs).', dt) + self.arm_retry() + return + + x, y, th, s1, s2, s2_yaw, tx, ty, bth, hyps = res + + # Cong bo TRUOC moi cong kiem: du bi tu choi, tap gia thuyet van co gia + # tri cho lop dinh vi chu dong o tren. + self.publish_hypotheses(hyps) + ratio = s1 / max(s2, 1e-6) + + # ⚠️ Cong kiem thu hai: doi thu CUNG vi tri, KHAC huong. + # Xem khoi ghi chu o min_ratio_yaw. Khong co cong nay thi node tra ve + # vi tri dung voi huong sai 40-160 do ma van bao ty le 1.6. + ratio_yaw = s1 / max(s2_yaw, 1e-6) + if ratio_yaw < self.min_ratio_yaw: + rospy.logwarn('global_scan_init: NHAP NHANG VE HUONG - ty le goc ' + '%.2f < %.2f (ty le vi tri %.2f - CHUA xet, cong goc ' + 'chan truoc). KHONG publish. ' + 'Vi tri co the dung nhung huong khong tin duoc.', + ratio_yaw, self.min_ratio_yaw, ratio) + self.arm_retry() + return + + if ratio < self.min_ratio: + # ⚠️ Day la truong hop QUAN TRONG NHAT, khong phai loi. + # Hai cho khac nhau cho diem gan bang nhau -> hanh lang lap. + # Tra loi sai tu tin te hon nhieu so voi im lang: tren robot that + # khong co ground truth de ma biet minh dang sai. + rospy.logwarn('global_scan_init: NHAP NHANG - ty le %.2f < %.2f. ' + 'KHONG publish. Di chuyen vai met roi thu lai.', + ratio, self.min_ratio) + self.arm_retry() + return + + # ⚠️ Cho robot cham lai roi COMPOSE LAI. Xem settle_omega o onInit. + if abs(self.omega) > self.settle_omega: + rospy.loginfo('global_scan_init: dang quay %.1f do/s - cho dung roi ' + 'moi publish (toi da %.0fs).', + math.degrees(self.omega), self.settle_timeout) + t_wait = rospy.Time.now().to_sec() + rate = rospy.Rate(20) + while (not rospy.is_shutdown() + and abs(self.omega) > self.settle_omega + and rospy.Time.now().to_sec() - t_wait < self.settle_timeout): + rate.sleep() + if abs(self.omega) > self.settle_omega: + rospy.logwarn('global_scan_init: van quay %.1f do/s sau %.0fs. ' + 'Publish luon - huong se lech ~%.0f do.', + math.degrees(self.omega), self.settle_timeout, + math.degrees(abs(self.omega)) * 0.5) + # T_map_odom khong doi; chi can odom->base moi hon. + x, y, th = self.compose(tx, ty, bth) + + self.publish(x, y, th, ratio) + + # Moc tham chieu cho bo canh "da lac". Cho TF ngam pose moi roi moi do, + # neu khong se do trung pose CU va tuong la dang lac. + rospy.sleep(0.5) + self.ref_score = self.score_current_pose() + self.lost_since = None + if self.ref_score is not None: + rospy.loginfo('global_scan_init: diem tham chieu %.3f - se tu kich ' + 'hoat lai neu tut duoi %.0f%% trong %.1fs.', + self.ref_score, 100.0 * self.lost_score_ratio, + self.lost_hold) + rospy.loginfo('global_scan_init: TIM DUOC (%.3f, %.3f, %.1f do) ' + 'ty le vi tri %.2f / goc %.2f trong %.2fs', + x, y, math.degrees(th), ratio, ratio_yaw, dt) + + def downsample(self, pts, res): + """Gop diem ve luoi do phan giai ban do. Nhieu tia cung roi vao mot o + thi khong them thong tin, chi lam cham FFT.""" + k = np.round(pts / res).astype(np.int64) + _, keep = np.unique(k, axis=0, return_index=True) + pts = pts[np.sort(keep)] + if len(pts) > self.max_points: + step = int(math.ceil(len(pts) / float(self.max_points))) + pts = pts[::step] + return pts + + def match(self, pts, g): + """Quet tho bang FFT roi tinh chinh cuc bo. + + Meo chinh: voi mot theta co dinh, tinh diem cho TOAN BO cac phep tinh + tien (x,y) = tuong quan cheo giua truong kha nang va mat na diem. Mot + phep FFT lam xong ca luoi, thay vi lap tung o.""" + res = g['res'] + k = max(1, int(round(self.coarse_res / res))) + Lc = maxpool(g['L'], k) + Fc = maxpool(g['free'].astype(np.float32), k) > 0.5 + rc = res * k + H, W = Lc.shape + + # Dem bien bang tam quet: tuong quan vong (circular) se cuon diem tu + # canh nay sang canh kia neu khong dem. + pad = int(math.ceil(self.max_range / rc)) + 1 + Lp = np.zeros((H + 2 * pad, W + 2 * pad), dtype=np.float32) + Lp[pad:pad + H, pad:pad + W] = Lc + Hp, Wp = Lp.shape + FL = np.fft.rfft2(Lp) + + c = pts.mean(axis=0) + P = pts - c # xoay quanh tam cho on dinh so hoc + + best = [] + n_ang = int(round(2.0 * math.pi / self.angle_step)) + for i in range(n_ang): + th = i * self.angle_step + ct, st = math.cos(th), math.sin(th) + qx = ct * P[:, 0] - st * P[:, 1] + qy = st * P[:, 0] + ct * P[:, 1] + + M = np.zeros_like(Lp) + cr = np.round(qy / rc).astype(np.int64) % Hp + cc = np.round(qx / rc).astype(np.int64) % Wp + np.add.at(M, (cr, cc), 1.0) + + sc = np.fft.irfft2(FL * np.conj(np.fft.rfft2(M)), s=(Hp, Wp)) + sc = sc[pad:pad + H, pad:pad + W] + sc[~Fc] = 0.0 # robot phai nam trong vung TRONG + + r, cidx = np.unravel_index(int(np.argmax(sc)), sc.shape) + best.append((float(sc[r, cidx]), r, cidx, th, sc)) + + best.sort(key=lambda t: -t[0]) + if not best or best[0][0] <= 0.0: + return None + + # Gom TOP-K dinh tho, loai trung nhau trong ban kinh reject_radius. + # Phai xet nhieu dinh chu khong chi cai cao nhat: muc tho dung max-pool + # nen rat rong rai, thu tu o day chua chac dung. + rad_c = self.reject_radius / rc + cand = [] + for sv, r0, c0, th0, _ in best[:self.top_k]: + if all((r0 - r) ** 2 + (c0 - cx0) ** 2 > rad_c * rad_c + for _, r, cx0, _ in cand): + cand.append((sv, r0, c0, th0)) + if len(cand) >= 8: + break + if not cand: + return None + + # ⚠️ Tinh chinh TUNG ung vien roi moi so diem voi nhau. + # Ban dau toi so diem o muc tho - do la sai. Muc tho co max-pool nen + # gan nhu moi cho canh tuong deu diem cao, hai gia thuyet tot/xau chi + # cach nhau 1.18 lan -> cong chan nham loai ca truong hop DUNG. + # O muc tinh, khop dung sac net hon han khop sai. + refined = [self.refine(P, g, r0, c0, th0, rc, res) + for _, r0, c0, th0 in cand] + refined = [r for r in refined if r is not None] + if not refined: + return None + refined.sort(key=lambda t: -t[0]) + + bs, bx, by, bth = refined[0] + + # ⚠️ Doi thu phai LUON tim duoc, ke ca khi khong co trong top-K. + # Ban dau toi chi lay s2 tu cac ung vien da tinh chinh. Tren ban do nho + # (house 16x17 m) ca 8 ung vien co the nam gon trong ban kinh 2 m cua + # nhau -> khong co doi thu xa -> s2 = 0 -> ty le no len vo cuc va node + # publish bua. Do duoc: ty le max 201.217.651 va 9.3% duong tinh gia + # voi sai so 9-13 m. Nen phai quet lai truong diem THO o vung xa. + s2 = 0.0 + for sv, x2, y2, _ in refined[1:]: + if math.hypot(x2 - bx, y2 - by) > self.reject_radius: + s2 = max(s2, sv) + + rw = int(round((by - rc / 2.0) / rc)) + cw = int(round((bx - rc / 2.0) / rc)) + rad_f = self.reject_radius / rc + rr, cc = np.ogrid[:H, :W] + far = ((rr - rw) ** 2 + (cc - cw) ** 2) > rad_f * rad_f + fv, fr, fc, fth = -1.0, None, None, 0.0 + for _, _, _, th_, sc in best: + m = np.where(far, sc, 0.0) + v = float(m.max()) + if v > fv: + fv = v + fr, fc = np.unravel_index(int(np.argmax(m)), m.shape) + fth = th_ + if fr is not None: + alt = self.refine(P, g, fr, fc, fth, rc, res) + if alt is not None: + s2 = max(s2, alt[0]) + + # ---- Doi thu theo GOC: CUNG vi tri, KHAC huong ---- + # Cung khuon mau voi doi thu vi tri o tren: tim dinh tho roi TINH CHINH + # truoc khi so diem. So o muc tho la sai - xem ghi chu dong ~364. + near = ~far + gv, gr, gc2, gth = -1.0, None, None, 0.0 + for _, _, _, th_, sc in best: + dth = abs(math.atan2(math.sin(th_ - bth), math.cos(th_ - bth))) + if dth < self.min_angle_sep: + continue + m = np.where(near, sc, 0.0) + v = float(m.max()) + if v > gv: + gv = v + gr, gc2 = np.unravel_index(int(np.argmax(m)), m.shape) + gth = th_ + s2_yaw = 0.0 + if gr is not None: + alt2 = self.refine(P, g, gr, gc2, gth, rc, res) + if alt2 is not None: + s2_yaw = alt2[0] + + # Ket qua (bx,by,bth) dat TAM c cua dam diem vao cho nao tren ban do. + # Doi sang T_map_odom: p_map = R(th)*p_odom + t, voi + # t = (bx,by) + goc_ban_do - R(th)*c + def to_map(sx, sy, sth): + """(bx,by,bth) o luoi -> T_map_odom roi ghep odom->base.""" + cc_, ss_ = math.cos(sth), math.sin(sth) + mx = sx + g['ox'] - (cc_ * c[0] - ss_ * c[1]) + my = sy + g['oy'] - (ss_ * c[0] + cc_ * c[1]) + return self.compose(mx, my, sth) + + # Toan bo ung vien da tinh chinh, doi sang he ban do. refined[0] la + # nguoi thang; phan con lai la doi thu that su - chung da duoc khu + # trung theo reject_radius nen moi cai la MOT CHO khac nhau. + hyps = [to_map(hx, hy, hth) + (hs,) for hs, hx, hy, hth in refined] + + ct, st = math.cos(bth), math.sin(bth) + tx = bx + g['ox'] - (ct * c[0] - st * c[1]) + ty = by + g['oy'] - (st * c[0] + ct * c[1]) + + return self.compose(tx, ty, bth) + (bs, s2, s2_yaw, tx, ty, bth, hyps) + + def refine(self, P, g, r0, c0, th0, rc, res): + """Tinh chinh mot ung vien o do phan giai ban do. + + Quet +-nua o tho quanh dinh (du phu kin o do) va +-mot buoc goc. + Tinh truc tiep, khong FFT - vung nho nen re hon FFT.""" + x0, y0 = c0 * rc + rc / 2.0, r0 * rc + rc / 2.0 + span = rc / 2.0 + bs, bx, by, bth = -1.0, None, None, None + for dth in np.arange(-self.angle_step, self.angle_step + 1e-9, + self.angle_step / 5.0): + th = th0 + dth + ct, st = math.cos(th), math.sin(th) + qx = ct * P[:, 0] - st * P[:, 1] + qy = st * P[:, 0] + ct * P[:, 1] + for dx in np.arange(-span, span + 1e-9, res * 2): + cix = np.round((qx + x0 + dx) / res).astype(np.int64) + okx = (cix >= 0) & (cix < g['w']) + for dy in np.arange(-span, span + 1e-9, res * 2): + ri = np.round((qy + y0 + dy) / res).astype(np.int64) + m = okx & (ri >= 0) & (ri < g['h']) + if not m.any(): + continue + v = float(g['L'][ri[m], cix[m]].sum()) + if v > bs: + bs, bx, by, bth = v, x0 + dx, y0 + dy, th + if bx is None: + return None + return (bs, bx, by, bth) + + def compose(self, tx, ty, th): + """T_map_odom vua tim duoc, ghep voi odom->base HIEN TAI. + + Robot da xoay trong luc gom scan nen pose bay gio khac luc bat dau. + Gom o he odom (co dinh) roi ghep o day la cach duy nhat khong bi lech.""" + try: + tr = self.buf.lookup_transform(self.odom_frame, self.base_frame, + rospy.Time(0), rospy.Duration(0.5)) + except Exception as e: + rospy.logwarn('global_scan_init: khong lay duoc %s->%s: %s', + self.odom_frame, self.base_frame, e) + return (tx, ty, th) + self.pose_stamp = tr.header.stamp + p = tr.transform.translation + b = yaw_of(tr.transform.rotation) + ct, st = math.cos(th), math.sin(th) + return (tx + ct * p.x - st * p.y, + ty + st * p.x + ct * p.y, + math.atan2(math.sin(th + b), math.cos(th + b))) + + # ---------------- publish ---------------- + + def publish_hypotheses(self, hyps): + """Cong bo tap gia thuyet len /reloc/hypotheses. + + Thu tu = diem giam dan, nen phan tu [0] la nguoi thang. Diem so KHONG + goi kem duoc (PoseArray khong co cho) - lop tren can diem thi doc + /reloc/hypotheses cung luc voi log, hoac ta doi sang msg rieng sau. + """ + if not hyps: + return + msg = PoseArray() + msg.header.stamp = rospy.Time.now() + msg.header.frame_id = self.map_frame + for hx, hy, hth, _score in hyps: + p = Pose() + p.position.x = hx + p.position.y = hy + p.orientation.z = math.sin(hth / 2.0) + p.orientation.w = math.cos(hth / 2.0) + msg.poses.append(p) + self.hyp_pub.publish(msg) + if len(hyps) > 1: + rospy.loginfo('global_scan_init: %d gia thuyet -> /reloc/hypotheses ' + '(cach nhau >= %.1f m)', len(hyps), self.reject_radius) + + def publish(self, x, y, th, ratio): + m = PoseWithCovarianceStamped() + # Dong dau bang moc TF that su da dung, khong phai now(): + # noi that ve thoi diem pose nay co gia tri. + m.header.stamp = self.pose_stamp or rospy.Time.now() + m.header.frame_id = self.map_frame + m.pose.pose.position.x = x + m.pose.pose.position.y = y + m.pose.pose.orientation.z = math.sin(th / 2.0) + m.pose.pose.orientation.w = math.cos(th / 2.0) + + # Cang dut khoat thi cang tin. Khong lay duoi 0.05 m / 0.03 rad: ICP + # cua RTAB-Map van phai duoc phep tinh chinh tiep. + s_xy = max(0.05, 0.30 / ratio) + s_th = max(0.03, 0.15 / ratio) + m.pose.covariance[0] = s_xy ** 2 + m.pose.covariance[7] = s_xy ** 2 + m.pose.covariance[35] = s_th ** 2 + self.pub.publish(m) + + # ---------------- kich hoat ---------------- + + def start(self): + with self.lock: + if self.grid is None: + return False, 'chua nhan duoc ban do tren topic map' + self.pts = [] + self.yaw_acc = 0.0 + self.yaw_prev = None + self.t_start = rospy.Time.now().to_sec() + self.active = True + rospy.loginfo('global_scan_init: bat dau gom scan. ' + 'XOAY ROBOT TAI CHO %.0f do.', + math.degrees(self.yaw_sweep)) + return True, 'dang gom scan, xoay robot tai cho' + + def on_timer(self, _evt): + # ⚠️ Phai thu lai, khong duoc bo cuoc. + # Ban do hospital 1.76 GB mat ~19 s de RTAB-Map nap het vao bo nho lam + # viec (Mem/InitWMWithAllNodes=true). Bat mot lan sau `delay` giay roi + # thoi thi /map chua ve, node nam im vinh vien. + if self.start()[0]: + return + rospy.loginfo_throttle(10.0, 'global_scan_init: cho /map...') + rospy.Timer(rospy.Duration(2.0), self.on_timer, oneshot=True) + + # ---------------- tu kiem "da lac" ---------------- + + def score_current_pose(self): + """Cham diem scan moi nhat tai pose DANG TIN (map->base tu TF). + + Tra ve diem trung binh moi diem, hoac None neu chua du dieu kien. + Dung CHINH truong likelihood da dung de khop, nen thang do nhat quan + voi diem luc khop thanh cong.""" + msg = self.last_scan + with self.lock: + g = self.grid + if msg is None or g is None: + return None + try: + tr = self.buf.lookup_transform(self.map_frame, msg.header.frame_id, + rospy.Time(0), rospy.Duration(0.2)) + except Exception: + return None + + r = np.asarray(msg.ranges, dtype=np.float32) + ok = np.isfinite(r) & (r > msg.range_min) & (r < min(msg.range_max, + self.max_range)) + if ok.sum() < 50: + return None + idx = np.nonzero(ok)[0] + ang = msg.angle_min + idx * msg.angle_increment + rr = r[idx] + + t = tr.transform.translation + th = yaw_of(tr.transform.rotation) + ct, st = math.cos(th), math.sin(th) + lx, ly = rr * np.cos(ang), rr * np.sin(ang) + mx = ct * lx - st * ly + t.x + my = st * lx + ct * ly + t.y + + ci = np.round((mx - g['ox']) / g['res']).astype(np.int64) + ri = np.round((my - g['oy']) / g['res']).astype(np.int64) + m = (ci >= 0) & (ci < g['w']) & (ri >= 0) & (ri < g['h']) + if m.sum() < 50: + return None + return float(g['L'][ri[m], ci[m]].mean()) + + def on_watch(self, _evt): + """Dinh ky kiem pose dang tin co con giai thich duoc scan khong.""" + if not self.watch_lost or self.ref_score is None: + return + with self.lock: + if self.active: # dang gom scan roi, khoi kiem + self.lost_since = None + return + + sc = self.score_current_pose() + if sc is None: + # ⚠️ Im lang o day la diem mu: khong phan biet duoc "chua do duoc" + # voi "do duoc va thay on". Phai noi ro. + rospy.logwarn_throttle(5.0, + 'global_scan_init[watch]: chua cham duoc diem (thieu scan/ban ' + 'do, hoac tra TF %s->laser that bai).', self.map_frame) + return + + thr = self.ref_score * self.lost_score_ratio + rospy.loginfo_throttle(2.0, + 'global_scan_init[watch]: diem %.4f | nguong %.4f | tham chieu ' + '%.4f | %s', sc, thr, self.ref_score, + 'ON' if sc >= thr else 'DUOI NGUONG') + + if sc >= thr: + self.lost_since = None + return + + now = rospy.Time.now().to_sec() + if self.lost_since is None: + self.lost_since = now + return + if now - self.lost_since < self.lost_hold: + return + + rospy.logwarn('global_scan_init: NGHI DA LAC - diem %.3f < %.0f%% cua ' + '%.3f trong %.1fs. Tu kich hoat lai.', + sc, 100.0 * self.lost_score_ratio, self.ref_score, + self.lost_hold) + self.lost_since = None + self.ref_score = None + self.start() + + def arm_retry(self): + """Tu nap lai sau khi bi tu choi. Xem retry_period o onInit.""" + if self.retry_period <= 0.0: + rospy.loginfo('global_scan_init: retry_period=0 -> dung. Goi tay: ' + 'rosservice call /global_scan_init/relocalize') + return + rospy.loginfo('global_scan_init: thu lai sau %.0fs. Di chuyen robot vai ' + 'met de doi goc nhin - dung yen thi lan sau cung nhap ' + 'nhang y het.', self.retry_period) + rospy.Timer(rospy.Duration(self.retry_period), self.on_timer, + oneshot=True) + + def on_trigger(self, _req): + ok, msg = self.start() + return TriggerResponse(success=ok, message=msg) + + +if __name__ == '__main__': + rospy.init_node('global_scan_init') + try: + GlobalScanInit() + rospy.spin() + except rospy.ROSInterruptException: + pass diff --git a/src/localization_ops/scripts/reloc_active.py b/src/localization_ops/scripts/reloc_active.py new file mode 100755 index 0000000..b327fb8 --- /dev/null +++ b/src/localization_ops/scripts/reloc_active.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python3 +""" +reloc_active - DINH VI CHU DONG: tinh xem phai DI DAU de het nhap nhang. + +============ VAN DE ============ +global_scan_init khop rat chinh xac khi khong nhap nhang (da do: 0.155-0.21 m, +0.07-0.09 do). Nhung o nhieu cho trong benh vien no TU CHOI: + + NHAP NHANG - ty le 1.04 < 1.30. KHONG publish. + Di chuyen vai met roi thu lai. + +Tu choi la DUNG - hai cho cho diem gan bang nhau thi tra loi bua nguy hiem hon +im lang. Nhung "di chuyen vai met" bat nguoi van hanh MO: len, xuong, thu lai, +cho toi khi trung. Da do tren ban do hospital: 3/4 lan thu bi tu choi. + +============ Y TUONG ============ +Luc tu choi, he KHONG mu. No biet ro: + - co may gia thuyet, o dau (/reloc/hypotheses) + - ban do trong nhu the nao (/map) + +Tu hai thu do tinh duoc: CHUYEN DONG NAO TACH CAC GIA THUYET NHANH NHAT. + +Voi moi chuyen dong ung vien, mo phong scan LiDAR ma TUNG gia thuyet se thay +sau khi thuc hien. Neu hai gia thuyet du doan hai canh hoan toan khac nhau thi +chi can di mot lan la biet minh o dau. Chon chuyen dong co do phan ky lon nhat. + + Nhap nhang giua 2 cho. Di THANG 1.8 m se phan biet duoc. + +Doi mo hinh tuong tac: tu "doan va thu lai" sang "he chi duong, di mot lan". + +============ ⚠️ GIOI HAN ============ +Phu thuoc hoan toan vao chat luong tap gia thuyet. Neu cho DUNG khong nam trong +/reloc/hypotheses thi chuyen dong de xuat cung vo nghia - no chi phan biet duoc +cac gia thuyet SAI voi nhau. + +=> Node nay KHONG thay the viec kiem tra. Sau khi di, van phai de + global_scan_init khop lai va di qua day du cong kiem cua no. + +============ CACH DUNG ============ + roslaunch robot_bringup localization.launch enable_global_init:=true \\ + enable_active_reloc:=true + + rostopic echo /reloc/suggested_motion +""" + +import math + +import numpy as np +import rospy +from geometry_msgs.msg import PoseArray, PoseStamped +from nav_msgs.msg import OccupancyGrid +from sensor_msgs.msg import LaserScan + + +def yaw_of(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 ActiveReloc(object): + def __init__(self): + self.map_frame = rospy.get_param('~map_frame', 'map') + self.base_frame = rospy.get_param('~base_frame', 'base_footprint') + + # ---- Tap chuyen dong ung vien ---- + # Robot vi sai: khong truot ngang duoc. Nen moi chuyen dong la + # "quay tai cho goc phi, roi di thang d met". + self.turns = [math.radians(a) for a in + rospy.get_param('~turn_options_deg', + [0, 45, -45, 90, -90, 135, -135, 180])] + self.dists = rospy.get_param('~dist_options', [0.5, 1.0, 1.5, 2.0, 3.0]) + + # ⚠️ CHI XET TOP-N GIA THUYET. + # + # PoseArray den theo thu tu diem giam dan, [0] la nguoi thang. + # Da do: o mot diem tha co 7 gia thuyet, va KHONG chuyen dong nao an + # toan o ca 7 -> node tu vo hieu hoa dung luc nhap nhang nhat. + # + # Nhung cac gia thuyet hang duoi co diem thap han; tach chung ra khong + # dang de danh mat mot chuyen dong tot. Chi can phan biet nguoi thang + # voi vai doi thu SAT NUT. + self.max_hyps = rospy.get_param('~max_hyps', 3) + + # ---- Mo phong scan ---- + # Lay mau thua tia: khong can 1081 tia de biet hai canh co khac nhau + # khong, va do phan ky bao hoa rat nhanh theo so tia. + self.n_rays = rospy.get_param('~n_rays', 72) + self.fov = math.radians(rospy.get_param('~fov_deg', 236.0)) + self.sim_max_range = rospy.get_param('~sim_max_range', 12.0) + self.ray_step = rospy.get_param('~ray_step', 0.10) # m + + # Hai tia coi la KHAC NHAU khi lech qua nguong nay. + self.diff_thresh = rospy.get_param('~diff_thresh', 0.5) # m + + # ⚠️ Chuyen dong de xuat phai DI DUOC o MOI gia thuyet. + # Neu no dam tuong trong mot gia thuyet thi khong the bao nguoi van hanh + # thuc hien - ta chua biet minh dang o gia thuyet nao. + self.clearance = rospy.get_param('~clearance', 0.35) # m + + # Duoi muc TANG THEM nay thi di chuyen khong giup gi -> noi that thay + # vi de xuat bua mot chuyen dong vo ich. + self.min_gain = rospy.get_param('~min_gain', 0.05) + + self.grid = None + self.pub = rospy.Publisher('/reloc/suggested_motion', PoseStamped, + queue_size=1, latch=True) + rospy.Subscriber('map', OccupancyGrid, self.on_map, queue_size=1) + rospy.Subscriber('/reloc/hypotheses', PoseArray, self.on_hyps, + queue_size=1) + rospy.Subscriber('scan', LaserScan, self.on_scan, queue_size=1) + + self._scan_seen = False + rospy.loginfo('reloc_active: san sang. Cho /reloc/hypotheses.') + + # ---------------- dau vao ---------------- + + def on_scan(self, msg): + """Lay thong so LiDAR THAT thay vi doan - chi can mot ban tin.""" + if self._scan_seen: + return + self._scan_seen = True + span = msg.angle_max - msg.angle_min + if 0.1 < span < 2.0 * math.pi + 0.1: + self.fov = span + if 0.5 < msg.range_max < 100.0: + self.sim_max_range = min(self.sim_max_range, msg.range_max) + rospy.loginfo('reloc_active: LiDAR that -> FOV %.1f do, mo phong toi %.1f m', + math.degrees(self.fov), self.sim_max_range) + + def on_map(self, msg): + w, h = msg.info.width, msg.info.height + g = np.asarray(msg.data, dtype=np.int8).reshape(h, w) + self.grid = dict(occ=(g >= 50), free=(g == 0), + res=msg.info.resolution, + ox=msg.info.origin.position.x, + oy=msg.info.origin.position.y, w=w, h=h) + rospy.loginfo_once('reloc_active: nhan ban do %dx%d @ %.3f m', w, h, + msg.info.resolution) + + # ---------------- mo phong ---------------- + + def cast(self, x, y, th): + """Mo phong scan LiDAR tai pose (x,y,th). Tra ve vector tam tia. + + Ray-cast vector hoa: lay mau TAT CA tia o TAT CA buoc cung luc, roi tim + buoc dau tien cham vat can tren tung tia. Nhanh hon vong lap tung tia + vai chuc lan, va so tia * so buoc o day chi vai nghin.""" + g = self.grid + n_step = int(self.sim_max_range / self.ray_step) + ang = th + np.linspace(-self.fov / 2.0, self.fov / 2.0, self.n_rays) + d = (np.arange(1, n_step + 1) * self.ray_step)[None, :] # (1,S) + + px = x + np.cos(ang)[:, None] * d # (R,S) + py = y + np.sin(ang)[:, None] * d + + ci = np.round((px - g['ox']) / g['res']).astype(np.int64) + ri = np.round((py - g['oy']) / g['res']).astype(np.int64) + inside = (ci >= 0) & (ci < g['w']) & (ri >= 0) & (ri < g['h']) + + hit = np.zeros(ci.shape, dtype=bool) + hit[inside] = g['occ'][ri[inside], ci[inside]] + # Ra ngoai ban do cung coi la "het thong tin" -> dung tia o do. + hit |= ~inside + + any_hit = hit.any(axis=1) + first = np.argmax(hit, axis=1) + rng = np.where(any_hit, (first + 1) * self.ray_step, self.sim_max_range) + return rng + + def path_clear(self, x, y, th, turn, dist): + """Duong di thang sau khi quay co trong khong? Kiem ca le an toan.""" + g = self.grid + a = th + turn + n = max(2, int(dist / (g['res'] * 0.5))) + t = np.linspace(0.0, dist, n) + px = x + math.cos(a) * t + py = y + math.sin(a) * t + # No rong theo clearance: lay mau them hai ben duong di. + offs = np.linspace(-self.clearance, self.clearance, 3) + ox_ = -math.sin(a) * offs + oy_ = math.cos(a) * offs + qx = (px[:, None] + ox_[None, :]).ravel() + qy = (py[:, None] + oy_[None, :]).ravel() + ci = np.round((qx - g['ox']) / g['res']).astype(np.int64) + ri = np.round((qy - g['oy']) / g['res']).astype(np.int64) + ok = (ci >= 0) & (ci < g['w']) & (ri >= 0) & (ri < g['h']) + if not ok.all(): + return False + return not g['occ'][ri[ok], ci[ok]].any() + + # ---------------- lua chon ---------------- + + def on_hyps(self, msg): + if self.grid is None: + rospy.logwarn_throttle(5.0, 'reloc_active: chua co /map.') + return + all_hyps = [(p.position.x, p.position.y, yaw_of(p.orientation)) + for p in msg.poses] + if len(all_hyps) < 2: + # Mot gia thuyet = khong nhap nhang. global_scan_init tu lo. + return + n_all = len(all_hyps) + hyps = all_hyps[:self.max_hyps] # da sap theo diem giam dan + + t0 = rospy.Time.now().to_sec() + + # ⚠️ NOI LONG DAN, khong phai tat ca-hoac-khong. + # + # Doi an toan o ca N gia thuyet la ly tuong, nhung neu khong co thi + # tha de xuat mot chuyen dong an toan o vai gia thuyet DAU BANG con hon + # im lang bat nguoi van hanh mo. Lop an toan vat ly (safety_monitor + + # costmap) van la chan cuoi. + best, used = None, 0 + for need in range(len(hyps), 0, -1): + best = self.search(hyps[:need]) + if best is not None: + used = need + break + if best is not None and used < len(hyps): + rospy.logwarn('reloc_active: khong co chuyen dong an toan o ca %d ' + 'gia thuyet dau -> chi bao dam o %d gia thuyet manh ' + 'nhat. Lop an toan vat ly van chan.', len(hyps), used) + + dt = rospy.Time.now().to_sec() - t0 + if best is None: + rospy.logwarn('reloc_active: %d gia thuyet (xet %d), nhung khong ' + 'chuyen dong nao an toan ke ca chi voi gia thuyet ' + 'manh nhat. Can nguoi can thiep.', n_all, len(hyps)) + return + + gain, turn, dist, sep = best + if gain < self.min_gain: + rospy.logwarn('reloc_active: %d gia thuyet. Chuyen dong tot nhat chi ' + 'TANG THEM %.0f%% so tia tach duoc (< %.0f%%) - di quanh ' + 'day khong giup gi, cac cho nay giong nhau tren ca vung ' + 'lan can. Can di XA hon %.1f m.', + n_all, 100 * gain, 100 * self.min_gain, max(self.dists)) + return + + self.publish(turn, dist) + rospy.logwarn('reloc_active: NHAP NHANG giua %d cho (xet %d manh nhat). ' + '%s -> tach %.0f%% so tia (tang %+.0f%% so voi dung yen). ' + '(tinh trong %.2fs)', + n_all, used, self.describe(turn, dist), + 100 * sep, 100 * gain, dt) + + def separation(self, hyps, turn, dist): + """Ty le tia khac nhau giua CAP GIA THUYET TE NHAT, sau chuyen dong.""" + scans = [] + for hx, hy, hth in hyps: + a = hth + turn + scans.append(self.cast(hx + math.cos(a) * dist, + hy + math.sin(a) * dist, a)) + worst = 1.0 + for i in range(len(scans)): + for j in range(i + 1, len(scans)): + frac = float(np.mean(np.abs(scans[i] - scans[j]) + > self.diff_thresh)) + worst = min(worst, frac) + return worst + + def search(self, hyps): + """Tim chuyen dong LAM TANG do tach nhieu nhat, an toan o TAT CA hyps. + + ⚠️ Toi da hoa MUC TANG THEM, khong phai do tach tuyet doi. + + Cac gia thuyet von nam o nhung cho KHAC NHAU tren ban do, nen scan cua + chung DA khac nhau san truoc khi di chuyen met nao. Cham diem tuyet doi + se cho 50-58% ngay ca voi chuyen dong 0.5 m - do la con so cua HIEN + TRANG, khong phai loi ich cua viec di. + Da do: chon dung 0.5 m (quang ngan nhat) ca ba lan lien tiep. + + Tru di muc tach khi DUNG YEN thi moi do duoc chuyen dong dong gop gi. + """ + if len(hyps) < 2: + return None + base = self.separation(hyps, 0.0, 0.0) + best = None + for turn in self.turns: + for dist in self.dists: + if not all(self.path_clear(hx, hy, hth, turn, dist) + for hx, hy, hth in hyps): + continue + + # Dung CAP TE NHAT chu khong trung binh: chi can MOT cap khong + # tach duoc la van con nhap nhang. + sep = self.separation(hyps, turn, dist) + gain = sep - base + if best is None or gain > best[0]: + best = (gain, turn, dist, sep) + return best + + @staticmethod + def describe(turn, dist): + d = math.degrees(turn) + if abs(d) < 1.0: + return 'Di THANG %.1f m' % dist + if abs(abs(d) - 180.0) < 1.0: + return 'QUAY DAU roi di %.1f m' % dist + return 'Quay %s %.0f do roi di %.1f m' % ( + 'TRAI' if d > 0 else 'PHAI', abs(d), dist) + + def publish(self, turn, dist): + """Muc tieu trong he base_footprint: quay `turn` roi tien `dist`.""" + m = PoseStamped() + m.header.stamp = rospy.Time.now() + m.header.frame_id = self.base_frame + m.pose.position.x = math.cos(turn) * dist + m.pose.position.y = math.sin(turn) * dist + m.pose.orientation.z = math.sin(turn / 2.0) + m.pose.orientation.w = math.cos(turn / 2.0) + self.pub.publish(m) + + +def main(): + rospy.init_node('reloc_active') + ActiveReloc() + rospy.spin() + + +if __name__ == '__main__': + try: + main() + except rospy.ROSInterruptException: + pass diff --git a/src/localization_ops/src/reloc_gicp_node.cpp b/src/localization_ops/src/reloc_gicp_node.cpp new file mode 100644 index 0000000..d7d6e7d --- /dev/null +++ b/src/localization_ops/src/reloc_gicp_node.cpp @@ -0,0 +1,409 @@ +/** + * reloc_gicp_node - GD3: tinh chinh gia thuyet dinh vi bang GICP tren may depth. + * + * ============ VI SAO CAN ============ + * Reg/Strategy=1 nghia la RTAB-Map dang ky CHI bang ICP tren LiDAR - depth cua + * D410 khong bao gio duoc dung vao viec chot pose. Node nay bit dung cho do: + * global_scan_init cho tap gia thuyet SE(2) tu LiDAR, con day dung cau truc 3D + * that (khung cua, ban ghe, thiet bi tuong) de XEP HANG LAI va siet sai so. + * + * ============ KY VONG DUNG MUC ============ + * Khop LiDAR da cho 0.155-0.21 m, ma Icp/MaxTranslation = 0.3 nen RTAB-Map con + * tu tinh chinh tiep. GICP o day siet xuong vai cm - GIA TRI GIA TANG NHO. + * Lam vi no dung kien truc 2.5D, KHONG phai vi no cuu duoc nhap nhang. Nhap + * nhang la gioi han THONG TIN, chi chuyen dong moi giai duoc - xem reloc_active. + * + * ⚠️ MAC DINH KHONG publish /initialpose (~publish_initialpose = false). + * global_scan_init van la noi DUY NHAT chot pose. Bat node nay o mac dinh + * KHONG THE lam xau do chinh xac - no chi in ra va publish /reloc/gicp_pose. + * + * ⚠️ TEN FILE NOI "GICP" NHUNG NO CHAY ICP + TransformationEstimation2D. + * Giu ten cu vi doi thi phai sua lan sang 3 launch file, khong dang. + * + * Duong di toi day, ghi lai de khong ai quay lai: + * 1. Plan ban dau: GICP + TransformationEstimation2D. Doc pcl/registration/ + * gicp.h:118 -> GICP gan cung rigid_transformation_estimation_ vao BFGS + * rieng ngay trong constructor va override computeTransformation, nen + * setTransformationEstimation() BI BO QUA IM LANG. Bien dich tron nhung + * cho ra nghiem 6-DoF. + * 2. Nen thu: de GICP chay du 3D roi CHIEU nghiem ve SE(2). DA DO va HONG: + * may depth song chi 211-429 diem tu mot goc nhin 69 do -> bai toan SUY + * BIEN, nghiem troi dz toi 1.03 m va nghieng toi 47.9 do, ca 4 gia thuyet + * deu bi cong kiem lech-ngoai-mat-phang loai sach. + * 3. Hien tai: ICP + TransformationEstimation2D. ICP CO goi + * transformation_estimation_, nen nghiem bi ep ve SE(2) that su. + * + * Cong kiem lech ngoai mat phang van giu du gio khong con kich hoat duoc: + * no la luoi an toan, bat duoc ngay neu ai doi lai sang 6-DoF. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +typedef pcl::PointCloud Cloud; + +namespace +{ +Eigen::Matrix4f poseToEigen(const geometry_msgs::Pose & p) +{ + const double s = 2.0 * (p.orientation.w * p.orientation.z + + p.orientation.x * p.orientation.y); + const double c = 1.0 - 2.0 * (p.orientation.y * p.orientation.y + + p.orientation.z * p.orientation.z); + const double yaw = std::atan2(s, c); + Eigen::Matrix4f T = Eigen::Matrix4f::Identity(); + T(0, 0) = std::cos(yaw); T(0, 1) = -std::sin(yaw); + T(1, 0) = std::sin(yaw); T(1, 1) = std::cos(yaw); + T(0, 3) = p.position.x; T(1, 3) = p.position.y; + return T; // gia thuyet vao la SE(2) thuan +} +} // namespace + +class RelocGicp +{ +public: + RelocGicp(ros::NodeHandle & nh, ros::NodeHandle & pnh) + : tf_listener_(tf_buffer_) + { + pnh.param("database_path", db_path_, ""); + pnh.param("base_frame", base_frame_, "base_footprint"); + pnh.param("map_frame", map_frame_, "map"); + pnh.param("node_radius", node_radius_, 4.0); + pnh.param("max_nodes", max_nodes_, 12); + pnh.param("max_hyps", max_hyps_, 5); + pnh.param("voxel", voxel_, 0.05); + pnh.param("max_depth", max_depth_, 4.0); + pnh.param("max_corr_dist", max_corr_dist_, 0.5); + pnh.param("max_correction", max_correction_, 1.0); + pnh.param("max_out_of_plane", max_out_of_plane_, 0.15); + pnh.param("max_tilt_deg", max_tilt_deg_, 10.0); + pnh.param("max_fitness", max_fitness_, 0.10); + pnh.param("min_ratio", min_ratio_, 1.30); + // Da do: may depth song sau loc chi 211-429 diem. Nguong 500 chan sach + // moi luot. 150 la san thuc te, khong phai con so chon bua. + pnh.param("min_points", min_points_, 150); + pnh.param("cloud_timeout", cloud_timeout_, 2.0); + pnh.param("publish_initialpose", publish_initialpose_, false); + + if (db_path_.empty()) + { + ROS_FATAL("reloc_gicp: thieu ~database_path"); + ros::shutdown(); + return; + } + + db_ = rtabmap::DBDriver::create(); + if (!db_->openConnection(db_path_, false)) + { + ROS_FATAL("reloc_gicp: khong mo duoc %s", db_path_.c_str()); + ros::shutdown(); + return; + } + // ⚠️ PHAI dung opt_poses, KHONG dung Node.pose. Da do tren map_hospital.db: + // |opt - Node.pose| trung vi 0.386 m, p90 5.23 m, 39.4% lech > 1 m. Lay + // nham thi may ban do dat sai cho va GICP tinh chinh vao hu khong. + opt_poses_ = db_->loadOptimizedPoses(); + ROS_INFO("reloc_gicp: %s, %zu pose toi uu", + db_path_.c_str(), opt_poses_.size()); + + pub_pose_ = nh.advertise( + "/reloc/gicp_pose", 1, true); + if (publish_initialpose_) + { + ROS_WARN("reloc_gicp: ~publish_initialpose=true - node NAY se ghi de " + "/initialpose cua global_scan_init. Chi bat khi dang do doi chung."); + pub_init_ = nh.advertise( + "/initialpose", 1); + } + + sub_cloud_ = nh.subscribe( + pnh.param("cloud_topic", "/perception/cloud_aligned"), + 1, &RelocGicp::onCloud, this); + sub_hyps_ = nh.subscribe("/reloc/hypotheses", 1, &RelocGicp::onHyps, this); + ROS_INFO("reloc_gicp: cho /reloc/hypotheses"); + } + + ~RelocGicp() { delete db_; } + +private: + void onCloud(const sensor_msgs::PointCloud2::ConstPtr & msg) + { + last_cloud_ = msg; + } + + // Gom may depth cua cac node ban do quanh mot gia thuyet, da dua ve he map. + Cloud::Ptr mapCloudNear(double x, double y) + { + std::vector > near; + for (std::map::const_iterator it = opt_poses_.begin(); + it != opt_poses_.end(); ++it) + { + if (it->second.isNull()) continue; + const double dx = it->second.x() - x; + const double dy = it->second.y() - y; + const double d2 = dx * dx + dy * dy; + if (d2 <= node_radius_ * node_radius_) + near.push_back(std::make_pair(d2, it->first)); + } + std::sort(near.begin(), near.end()); + if ((int)near.size() > max_nodes_) near.resize(max_nodes_); + + Cloud::Ptr out(new Cloud); + for (size_t i = 0; i < near.size(); ++i) + { + const int id = near[i].second; + std::map::iterator hit = cache_.find(id); + if (hit == cache_.end()) + { + rtabmap::SensorData data; + db_->getNodeData(id, data, true, false, false, false); + data.uncompressData(); + Cloud::Ptr c = rtabmap::util3d::cloudFromSensorData( + data, 2 /*decimation*/, (float)max_depth_, 0.0f); + if (!c || c->empty()) + { + cache_[id] = Cloud::Ptr(new Cloud); // nho de khong nap lai + continue; + } + // cloudFromSensorData da ap localTransform (camera -> base) nen c dang + // o he base cua node do; dua ve map bang chinh pose toi uu. + Cloud::Ptr m(new Cloud); + pcl::transformPointCloud(*c, *m, opt_poses_[id].toEigen4f()); + cache_[id] = m; + hit = cache_.find(id); + } + *out += *hit->second; + } + if (out->empty()) return out; + + Cloud::Ptr ds(new Cloud); + pcl::VoxelGrid vg; + vg.setInputCloud(out); + vg.setLeafSize(voxel_, voxel_, voxel_); + vg.filter(*ds); + return ds; + } + + void onHyps(const geometry_msgs::PoseArray::ConstPtr & msg) + { + // ---- XAC THUC TRUOC khi tinh chinh (ROADMAP GD6) ---- + if (msg->poses.empty()) return; + if (!last_cloud_) + { + ROS_WARN_THROTTLE(5.0, "reloc_gicp: chua co may depth nao"); + return; + } + const double age = (ros::Time::now() - last_cloud_->header.stamp).toSec(); + if (age > cloud_timeout_) + { + ROS_WARN("reloc_gicp: may depth cu %.1f s > %.1f - BO LUOT. " + "Camera chet thi khong tinh chinh bua.", age, cloud_timeout_); + return; + } + + Cloud::Ptr live(new Cloud); + pcl::fromROSMsg(*last_cloud_, *live); + if (last_cloud_->header.frame_id != base_frame_) + { + geometry_msgs::TransformStamped tf; + try + { + tf = tf_buffer_.lookupTransform(base_frame_, + last_cloud_->header.frame_id, + last_cloud_->header.stamp, + ros::Duration(0.2)); + } + catch (const tf2::TransformException & ex) + { + ROS_WARN("reloc_gicp: thieu TF %s <- %s: %s", base_frame_.c_str(), + last_cloud_->header.frame_id.c_str(), ex.what()); + return; + } + Eigen::Matrix4f T = Eigen::Matrix4f::Identity(); + const Eigen::Quaternionf q(tf.transform.rotation.w, tf.transform.rotation.x, + tf.transform.rotation.y, tf.transform.rotation.z); + T.block<3, 3>(0, 0) = q.toRotationMatrix(); + T(0, 3) = tf.transform.translation.x; + T(1, 3) = tf.transform.translation.y; + T(2, 3) = tf.transform.translation.z; + pcl::transformPointCloud(*live, *live, T); + } + + Cloud::Ptr src(new Cloud); + pcl::VoxelGrid vg; + vg.setInputCloud(live); + vg.setLeafSize(voxel_, voxel_, voxel_); + vg.filter(*src); + if ((int)src->size() < min_points_) + { + ROS_WARN("reloc_gicp: may song chi %zu diem < %d - BO LUOT", + src->size(), min_points_); + return; + } + + // ---- tinh chinh tung gia thuyet ---- + struct Res { double fit; double x, y, yaw; int idx; }; + std::vector ok; + const int n = std::min((int)msg->poses.size(), max_hyps_); + for (int i = 0; i < n; ++i) + { + const Eigen::Matrix4f guess = poseToEigen(msg->poses[i]); + Cloud::Ptr tgt = mapCloudNear(guess(0, 3), guess(1, 3)); + if ((int)tgt->size() < min_points_) + { + ROS_INFO("reloc_gicp: gt%d (%.2f,%.2f) chi %zu diem ban do - bo", + i, guess(0, 3), guess(1, 3), tgt->size()); + continue; + } + + // ⚠️ ICP chu KHONG phai GICP. Da do o lan chay dau: GICP tu do 6 bac + // tu do tren may 211-429 diem tu mot goc nhin 69 do la bai toan SUY + // BIEN - nghiem troi dz toi 1.03 m, nghieng toi 47.9 do, moi gia thuyet + // deu bi cong kiem loai. ICP thi CO goi transformation_estimation_, + // nen TransformationEstimation2D ep nghiem ve SE(2) that su va no + // khong the troi ra ngoai mat phang nua. + pcl::IterativeClosestPoint icp; + pcl::registration::TransformationEstimation2D::Ptr + te(new pcl::registration::TransformationEstimation2D); + icp.setTransformationEstimation(te); + icp.setInputSource(src); + icp.setInputTarget(tgt); + icp.setMaxCorrespondenceDistance(max_corr_dist_); + icp.setMaximumIterations(50); + icp.setTransformationEpsilon(1e-6); + Cloud aligned; + icp.align(aligned, guess); + if (!icp.hasConverged()) + { + ROS_INFO("reloc_gicp: gt%d khong hoi tu", i); + continue; + } + + const Eigen::Matrix4f T = icp.getFinalTransformation(); + + // Phan lech NGOAI mat phang = phep kiem mien phi. Robot chay tren san, + // may da can bang trong luc; GICP doi day len 30 cm nghia la no khop + // nham tang/vat the khac, khong phai tinh chinh. + const double dz = std::fabs(T(2, 3)); + const double tilt = std::acos(std::max(-1.0f, std::min(1.0f, T(2, 2)))); + if (dz > max_out_of_plane_ || tilt > max_tilt_deg_ * M_PI / 180.0) + { + ROS_WARN("reloc_gicp: gt%d LOAI - lech ngoai mat phang dz=%.3f m " + "nghieng=%.1f do", i, dz, tilt * 180.0 / M_PI); + continue; + } + + const double dx = T(0, 3) - guess(0, 3); + const double dy = T(1, 3) - guess(1, 3); + const double corr = std::sqrt(dx * dx + dy * dy); + if (corr > max_correction_) + { + ROS_WARN("reloc_gicp: gt%d LOAI - keo %.2f m > %.2f", i, corr, + max_correction_); + continue; + } + + Res r; + r.fit = icp.getFitnessScore(max_corr_dist_); + r.x = T(0, 3); + r.y = T(1, 3); + r.yaw = std::atan2(T(1, 0), T(0, 0)); // chieu ve SE(2) + r.idx = i; + ok.push_back(r); + ROS_INFO("reloc_gicp: gt%d -> (%.3f, %.3f, %.1f do) keo %.3f m, " + "khop %.4f", i, r.x, r.y, r.yaw * 180.0 / M_PI, corr, r.fit); + } + + if (ok.empty()) + { + ROS_WARN("reloc_gicp: khong gia thuyet nao qua duoc cong kiem"); + return; + } + std::sort(ok.begin(), ok.end(), + [](const Res & a, const Res & b) { return a.fit < b.fit; }); + + const Res & best = ok[0]; + if (best.fit > max_fitness_) + { + ROS_WARN("reloc_gicp: khop tot nhat %.4f > %.4f - KHONG DU TIN", + best.fit, max_fitness_); + return; + } + // khop cang nho cang tot, nen ty le = nhi/nhat + if (ok.size() >= 2) + { + const double ratio = ok[1].fit / std::max(best.fit, 1e-9); + if (ratio < min_ratio_) + { + ROS_WARN("reloc_gicp: NHAP NHANG - ty le %.2f < %.2f (%.4f vs %.4f). " + "Depth KHONG tach duoc hai cho nay; can chuyen dong.", + ratio, min_ratio_, best.fit, ok[1].fit); + return; + } + } + + geometry_msgs::PoseWithCovarianceStamped out; + out.header.stamp = ros::Time::now(); + out.header.frame_id = map_frame_; + out.pose.pose.position.x = best.x; + out.pose.pose.position.y = best.y; + out.pose.pose.orientation.z = std::sin(best.yaw / 2.0); + out.pose.pose.orientation.w = std::cos(best.yaw / 2.0); + out.pose.covariance[0] = out.pose.covariance[7] = 0.05 * 0.05; + out.pose.covariance[35] = (2.0 * M_PI / 180.0) * (2.0 * M_PI / 180.0); + pub_pose_.publish(out); + ROS_INFO("reloc_gicp: CHOT gt%d (%.3f, %.3f, %.2f do) khop %.4f", + best.idx, best.x, best.y, best.yaw * 180.0 / M_PI, best.fit); + if (publish_initialpose_) pub_init_.publish(out); + } + + tf2_ros::Buffer tf_buffer_; + tf2_ros::TransformListener tf_listener_; + ros::Subscriber sub_cloud_, sub_hyps_; + ros::Publisher pub_pose_, pub_init_; + sensor_msgs::PointCloud2::ConstPtr last_cloud_; + + rtabmap::DBDriver * db_ = 0; + std::map opt_poses_; + std::map cache_; + + std::string db_path_, base_frame_, map_frame_; + double node_radius_, voxel_, max_depth_, max_corr_dist_, max_correction_; + double max_out_of_plane_, max_tilt_deg_, max_fitness_, min_ratio_, cloud_timeout_; + int max_nodes_, max_hyps_, min_points_; + bool publish_initialpose_; +}; + +int main(int argc, char ** argv) +{ + ros::init(argc, argv, "reloc_gicp"); + ros::NodeHandle nh, pnh("~"); + RelocGicp node(nh, pnh); + ros::spin(); + return 0; +} diff --git a/src/perception_3d/CMakeLists.txt b/src/perception_3d/CMakeLists.txt index e962780..28567dd 100644 --- a/src/perception_3d/CMakeLists.txt +++ b/src/perception_3d/CMakeLists.txt @@ -14,6 +14,8 @@ find_package(catkin REQUIRED COMPONENTS tf2_ros pcl_ros pcl_conversions + message_filters + image_geometry ) find_package(PCL REQUIRED COMPONENTS common filters) @@ -21,7 +23,7 @@ find_package(Eigen3 REQUIRED) catkin_package( CATKIN_DEPENDS roscpp nodelet pluginlib sensor_msgs std_msgs geometry_msgs - tf2 tf2_ros pcl_ros pcl_conversions + tf2 tf2_ros pcl_ros pcl_conversions message_filters image_geometry ) include_directories( @@ -39,6 +41,7 @@ add_library(${PROJECT_NAME}_nodelets src/depth_filter_nodelet.cpp src/gravity_align_nodelet.cpp src/scan_to_cloud_nodelet.cpp + src/cliff_detect_nodelet.cpp ) target_link_libraries(${PROJECT_NAME}_nodelets ${catkin_LIBRARIES} diff --git a/src/perception_3d/config/depth_filter.yaml b/src/perception_3d/config/depth_filter.yaml index 15b855e..c607f19 100644 --- a/src/perception_3d/config/depth_filter.yaml +++ b/src/perception_3d/config/depth_filter.yaml @@ -13,12 +13,24 @@ depth_filter: voxel_size: 0.03 # 3cm - du chi tiet cho vat can, du nhe cho IPC + # ============ GIOI HAN TAN SO ============ + # Camera 30 Hz, nhung local costmap chi update 5 Hz va global 2 Hz -> chuoi + # dang lam thua ~6 lan. Bo frame o day chan duoc ca gravity_align lan + # bufferCloud cua costmap. + # Da do truoc khi bat: perception_manager 55.6% CPU tb (results/). + # 0 = tat gioi han. + max_rate: 10.0 + # ⚠️ 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. + # + # ⚠️ Luan cu cu ("octomap_server da tich phan xac suat trong frame map roi") + # KHONG con dung: octomap gio mac dinh TAT (khong ai doc dau ra cua no). + # Bo loc ben vung duy nhat con lai la raytrace-clear cua costmap. + # Nhung ly do KHONG duoc bat cai nay van nguyen ven - do la van de frame di + # dong o tren, khong lien quan gi den octomap. enable_temporal: false min_hits: 3 temporal_window: 0.5 @@ -29,6 +41,85 @@ depth_filter: sor_mean_k: 20 sor_stddev: 1.0 +# ============================================================= +# Phat hien vuc / bac thang di xuong. Chay tren ANH DEPTH. +# Xem dau perception_3d/src/cliff_detect_nodelet.cpp de biet vi sao KHONG lam +# tren point cloud (cau thang toi tra LO, ma PassThrough da vut NaN). +# ============================================================= +cliff_detect: + # ⚠️ 1.10 la GIOI HAN HINH HOC, khong phai tinh chinh. + # Camera z=0.80 chuc 15 do, nua FOV doc 27.3 do -> tia thap nhat chuc 42.3 do + # -> chi thay san tu x = 0.80/tan(42.3) + 0.19 ~ 1.07 m. + # Gan hon the node nay MU. Chi cam bien ToF/IR chuc xuong o mep truoc moi + # phu duoc 0-1.1m - xem robot_safety/config/safety.yaml `cliff_topics`. + min_dist: 1.10 + # Xa hon 2.5m nguong thich nghi no ra rong hon ca chieu cao mot bac thang + # (0.17m) nen khong con phan biet duoc gi. + max_dist: 2.50 + + # Thap hon san bao nhieu thi tinh la sut. + cliff_margin: 0.05 + + # ⚠️ Extrinsic camera<->base CHUA hieu chuan (ROADMAP GD2), va sai so pitch + # bien thanh do sau gia: e do o tam d -> -d*tan(e). + # e=1 do, d=3m -> -52mm -> vuot nguong 50mm -> BAO GIA + # Nen nguong phai no ra theo tam. Ha xuong sau khi hieu chuan xong. + pitch_uncertainty_deg: 2.0 + + pixel_step: 4 # lay mau thua tren anh 320x240 -> luoi 80x60 + min_neighbors: 3 # chong pixel nhieu le + min_cluster: 12 # so ung vien toi thieu de bao dong + imu_timeout: 0.5 + enabled: true + + # ============ ⚠️ HAI CO CHONG BAO GIA - DA DO LA BAT BUOC ============ + # Da do tren world restaurant (san phang): detector bao vuc lien tuc, co luc + # 1625/1832 mau. Sai so pitch khuech dai theo tam: z_gia = -r*tan(e). + # e=2.0 do @2.5m -> -0.087m | e=5.2 do @2.5m -> -0.227m + # 5.2 do la muc gyro drift DA DO trong repo khi accel bi gate. + + # Bo qua frame khi gravity_align khong neo duoc vao trong luc (accel_gate tu + # choi mau luc tang/giam toc) -> pitch la gyro thuan va dang troi. + require_accel_ok: true + + # Lay muc san tham chieu tu chinh dai gan nhat thay vi gia dinh z=0. + # Phep do thanh VI SAI -> sai so pitch/chieu cao camera/lun caster deu la + # common-mode va bi triet. + self_level: true + near_band: 0.40 # m - dai [min_dist, min_dist+near_band] lam tham chieu + min_level_samples: 40 # it hon thi khong do duoc muc san -> bo qua frame + # ⚠️ Chi diem |z| < nguong nay moi duoc tinh vao muc san tham chieu. + # Khong co no thi trong restaurant, dai gan thuong la MAT BAN (0.7m) chu + # khong phai san -> trung vi bi keo len -> san that bi coi la vuc. + # 0.25 du rong cho sai so pitch (5.2 do @2.5m = 0.227m), du hep de loai mat + # ban 0.7m, mat ghe 0.45m, va vuc that >= 1m. + level_gate: 0.25 + + # ⚠️ Khop CA DO DOC cua mat san, khong chi do lech. + # Da do: tu hieu chuan chi bang do lech van con bao gia. `tz` dao dong + # 0.775-0.817 (le ra co dinh 0.800) -> pitch that dao dong +-8.5 do, va sai so + # con lai sau khi tru do lech la -(2.5-1.3)*tan(8.5) = -0.179 m, vuot nguong + # 0.137 m. Phai khop ca doc moi triet duoc. + # + # An toan vi level_gate da loai vuc that (z ~ -1m) khoi phep khop, nen khop + # tren toan cua so khong nuot mat chinh cai dang can tim. + # 0.20 ~ 11.3 do - lon hon sai so pitch da do, du chan phep khop bi keo lech. + max_level_slope: 0.20 + + # ⚠️ Duong khop co THUC SU ta duoc mat san khong? Do bang do lech tuyet doi + # trung vi (MAD) cua phan du. + # Khong co cong nay thi node tin phep khop vo dieu kien. Da do mot frame: + # doc = 0.2000 (cham dung tran = dau hieu khop hong) va z0 = -0.4592 + # -> 461 diem bao vuc tren san phang. + # San that phang cho MAD ~ nhieu depth (vai mm). Lon hon nguong nay nghia la + # khung nhin khong phai mat phang san -> khong du can cu -> bo qua frame. + max_level_residual: 0.05 + + # In thong ke tung chang moi 2s. Bat khi detector im lang ma khong ro vi sao - + # no chi ra chang nao dang loai het pixel (tia len, ngoai dai, khong qua + # nguong, hay bi loc cum). + debug: true + gravity_align: base_frame: base_link output_frame: base_footprint diff --git a/src/perception_3d/launch/perception_nodelets.launch b/src/perception_3d/launch/perception_nodelets.launch index 046a4bf..b61638e 100644 --- a/src/perception_3d/launch/perception_nodelets.launch +++ b/src/perception_3d/launch/perception_nodelets.launch @@ -25,7 +25,27 @@ - + + + + + + @@ -33,12 +53,48 @@ + + + + + + + + + + + + - - + + @@ -74,35 +130,83 @@ + - - - + + + + + - + + + - + + message_filters + + image_geometry depth_image_proc + + image_proc + octomap_server diff --git a/src/perception_3d/src/cliff_detect_nodelet.cpp b/src/perception_3d/src/cliff_detect_nodelet.cpp new file mode 100644 index 0000000..041714d --- /dev/null +++ b/src/perception_3d/src/cliff_detect_nodelet.cpp @@ -0,0 +1,689 @@ +/** + * cliff_detect_nodelet - Phat hien VUC / BAC THANG DI XUONG tu anh depth. + * + * ================== ⚠️ VI SAO KHONG LAM TREN POINT CLOUD ================== + * Cach hien nhien - "diem nao co z < -0.05 thi la vuc" - DA BI LOAI sau khi + * tinh lai hinh hoc. Ba ly do, ly do 2 la ly do giet: + * + * 1. MARK SAI CHO. Camera o z=0.80 chuc 15 do. Diem duoi san DAU TIEN cua mot + * bac 0.17m khong nam o mep, ma nam SAU mep mot doan: + * mep cach 1.2m -> 0.26m sau mep + * mep cach 2.0m -> 0.43m + * mep cach 3.0m -> 0.64m + * mep cach 4.0m -> 0.85m + * Mark o do la CHO PHEP robot chay qua mep roi moi dung. + * + * 2. CAU THANG TOI KHONG TRA DEPTH. No tra LO (NaN), khong tra diem duoi san. + * Ma depth_filter chay pcl::PassThrough, von VUT BO NaN. Den luc cloud toi + * day thi tin hieu that - cai lo - da bi xoa sach. Bo phat hien chi hoat + * dong khi cam bien tinh co tra ve mot diem hop le trong ho, tuc hong dung + * luc can nhat. + * + * 3. NGUONG DUOI SAN NHIEU. Sai so pitch e lam san o tam d hien ra o + * z = -d*tan(e): e=1 do, d=3m -> -52mm. Nguong -50mm bao vuc gia ngay. + * Ma extrinsic camera<->base CHUA hieu chuan (ROADMAP GD2). + * + * ================== CACH LAM O DAY ================== + * Chay trên ANH DEPTH, nen cai LO cung la du lieu: + * + * voi moi pixel (lay mau thua): + * 1. dung tia tu mo hinh pinhole + * 2. cat tia voi MAT SAN z=0 trong base_footprint -> P_floor, z_exp + * 3. so depth quan sat d_obs voi z_exp: + * d_obs khong hop le -> LO: le ra phai thay san ma khong thay + * diem quan sat thap hon san qua nguong -> SUT + * 4. MARK TAI P_floor - giao diem tia x san, tuc DUNG MEP, + * KHONG mark tai diem tra ve + * 5. chi xet P_floor trong [min_dist, max_dist] + * 6. doi cum: mot pixel le khong duoc kich + * + * Nguong thich nghi theo tam: margin(d) = cliff_margin + d*tan(pitch_unc), + * de sai so pitch chua hieu chuan khong sinh bao dong gia o xa. + * + * ================== ⚠️ VUNG MU 0 - 1.1 m ================== + * Camera chuc 15 do o z=0.80, nua FOV doc 27.3 do -> tia thap nhat chuc + * 42.3 do -> chi THAY SAN tu x ~ 1.07m tro ra. + * + * Gan hon 1.07m node nay MU HOAN TOAN. Robot phat hien tu 1.1-2.5m va dung + * thi du khi TIEN THANG, nhung KHONG du khi xoay tai cho sat mep, hoac khi + * tien sau luc da dung trong vung mu. + * + * => Day KHONG phai lop bao ve day du. Chi cam bien ToF/IR chuc xuong o mep + * truoc moi phu duoc 0-1.1m. Xem safety.yaml `cliff_topics` va + * docs/HARDWARE.md muc 3. + * + * ================== PHAN CONG ================== + * /perception/cloud_cliff -> costmap tranh ne khi dieu huong (best effort) + * /perception/cliff_detected -> safety_monitor DUNG ROBOT. Day moi la chan. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace perception_3d +{ + +class CliffDetectNodelet : public nodelet::Nodelet +{ +public: + CliffDetectNodelet() = default; + +private: + typedef message_filters::sync_policies::ApproximateTime< + sensor_msgs::Image, sensor_msgs::CameraInfo> SyncPolicy; + + void onInit() override + { + nh_ = getNodeHandle(); + pnh_ = getPrivateNodeHandle(); + + pnh_.param("output_frame", output_frame_, "base_footprint"); + + // Chi tin trong dai nay. Duoi min_dist camera khong thay san (vung mu + // hinh hoc ~1.07m); tren max_dist nguong thich nghi no ra rong hon ca + // chieu cao bac thang nen vo nghia. + pnh_.param("min_dist", min_dist_, 1.10); + pnh_.param("max_dist", max_dist_, 2.50); + + // Bao nhieu met duoi mat san thi coi la sut. + pnh_.param("cliff_margin", cliff_margin_, 0.05); + + // ⚠️ Sai so pitch CHUA HIEU CHUAN. Nguong no ra theo tam de khong bao gia: + // e=2 do o 3m -> 105mm. Khong co no thi san phang cung bao vuc. + // Ha xuong sau khi lam xong extrinsic camera<->base (ROADMAP GD2). + pnh_.param("pitch_uncertainty_deg", pitch_unc_deg_, 2.0); + + // Lay mau thua tren anh - khong can tung pixel, va giam CPU manh. + pnh_.param("pixel_step", pixel_step_, 4); + + // Chong nhieu: mot pixel le khong duoc kich. Moi ung vien phai co it nhat + // ngan nay ung vien khac trong cua so 3x3 (theo luoi da lay mau thua). + pnh_.param("min_neighbors", min_neighbors_, 3); + + // So ung vien toi thieu de bao dong. + pnh_.param("min_cluster", min_cluster_, 12); + + pnh_.param("imu_timeout", imu_timeout_, 0.5); + + // ============ ⚠️ HAI CO CHE CHONG BAO GIA - BAT BUOC ============ + // + // Da do tren world restaurant (san phang tuyet doi): detector bao vuc lien + // tuc, co luc 1625/1832 mau trong cua so. Nguyen nhan la sai so pitch, va + // no khuech dai theo tam: z_gia = -r*tan(e). + // e = 2.0 do, r = 2.5 m -> -0.087 m + // e = 5.2 do, r = 2.5 m -> -0.227 m (5.2 do la muc gyro drift DA DO) + // Nguong tinh la 0.137 m nen 3.2 do tro len la bao gia. + // + // Noi pitch_uncertainty_deg KHONG cuu duoc: de chiu 5.2 do thi nguong o + // 2.5m thanh 0.28m, tuc bac thang 0.17m bi BO SOT hoan toan. Doi mot loi + // lay mot loi te hon. + // + // 1. require_accel_ok: bo qua frame khi gravity_align dang KHONG neo duoc + // vao trong luc (accel_gate tu choi mau luc robot tang/giam toc). Luc do + // pitch chi la tich phan gyro va dang troi - hinh hoc khong dung tin. + pnh_.param("require_accel_ok", require_accel_ok_, true); + + // 2. TU HIEU CHUAN MUC SAN. + // Thay vi gia dinh san o dung z=0, lay MUC SAN THAM CHIEU tu chinh dai + // gan nhat (r trong [min_dist, min_dist+near_band]) - vung gan robot + // nhat, gan nhu chac chan van la san that (neu no da la vuc thi robot + // dang roi roi). Trung vi cua z quan sat o dai do la muc 0 thuc te. + // Phep do tro thanh VI SAI, nen sai so pitch dang common-mode bi triet. + pnh_.param("self_level", self_level_, true); + pnh_.param("near_band", near_band_, 0.40); // m + // Can it nhat ngan nay mau trong dai gan thi muc tham chieu moi dang tin. + pnh_.param("min_level_samples", min_level_samples_, 40); + + // ⚠️ Chi diem KHA DI LA SAN moi duoc tinh vao muc tham chieu. + // + // Khong co cong nay thi trong restaurant, dai gan [1.10, 1.50] m thuong la + // MAT BAN chu khong phai san. Trung vi bi keo len ~0.7 m, va sàn that o 2 m + // thanh ra thap hon tham chieu 0.7 m -> BAO VUC TREN SAN PHANG. + // + // 0.25 m du rong de chua sai so pitch (5.2 do @2.5m = 0.227 m) nhung loai + // duoc mat ban (0.7 m), mat ghe (0.45 m), va vuc that (>= 1 m). + pnh_.param("level_gate", level_gate_, 0.25); + + // Chan doc vo ly cho mat san khop duoc. 0.20 ~ 11.3 do - lon hon moi sai + // so pitch thuc te da do (8.5 do), nhung van chan duoc truong hop phep + // khop bi mot be mat nghieng that (doc len) keo di. + pnh_.param("max_level_slope", max_level_slope_, 0.20); + + // ⚠️ KIEM CHAT LUONG PHEP KHOP. Khong co no thi node tin duong thang khop + // duoc VO DIEU KIEN, ke ca khi no bay. + // Da do mot frame: doc = 0.2000 (CHAM DUNG TRAN, dau hieu khop hong) va + // z0 = -0.4592 -> 461 diem bao vuc tren san phang. + // Xay ra khi khung nhin khong con la mat phang san: robot dang quay va + // nhin toan ban ghe, tap mau con lai vua it vua chum. + // + // Do do lech tuyet doi trung vi (MAD) cua phan du so voi duong khop. San + // that phang thi MAD ~ nhieu depth (vai mm). Lon hon nguong nay nghia la + // "cai dang nhin khong phai mot mat phang" -> KHONG DU CAN CU de phan xet. + pnh_.param("max_level_residual", max_level_residual_, 0.05); + + // Tat han de A/B test hoac khi chua hieu chuan. + pnh_.param("enabled", enabled_, true); + + // In thong ke tung chang moi 2s. Bat khi detector im lang ma khong ro vi sao: + // no chi ra chinh xac chang nao dang loai het pixel. + pnh_.param("debug", debug_, false); + + tf_buffer_ = std::make_shared(); + tf_listener_ = std::make_shared(*tf_buffer_); + + cloud_pub_ = nh_.advertise("cloud_cliff", 5); + // latch=false, publish LIEN TUC (ca khi false) de safety_monitor phat hien + // duoc node nay chet, thay vi tuong "khong co vuc". + flag_pub_ = nh_.advertise("cliff_detected", 5); + + rp_sub_ = nh_.subscribe("gravity_align/roll_pitch", 10, + &CliffDetectNodelet::onRollPitch, this); + + image_sub_.subscribe(nh_, "depth/image", 5); + info_sub_.subscribe(nh_, "depth/camera_info", 5); + sync_ = std::make_shared>( + SyncPolicy(10), image_sub_, info_sub_); + sync_->registerCallback( + boost::bind(&CliffDetectNodelet::onDepth, this, _1, _2)); + + NODELET_INFO("cliff_detect: dai [%.2f, %.2f] m, margin %.3f m + tam*tan(%.1f do), " + "step %d px, cum >= %d", + min_dist_, max_dist_, cliff_margin_, pitch_unc_deg_, + pixel_step_, min_cluster_); + NODELET_WARN("cliff_detect: ⚠️ MU HOAN TOAN duoi %.2f m (hinh hoc camera). " + "Khong thay the duoc cam bien vuc chuc xuong o mep truoc.", + min_dist_); + } + + void onRollPitch(const std_msgs::Float64MultiArray::ConstPtr& msg) + { + if (msg->data.size() < 2) + return; + roll_ = msg->data[0]; + pitch_ = msg->data[1]; + // data[2] = accel_ok: gravity_align co dang neo duoc vao huong trong luc + // khong, hay chi dang tich phan gyro. Xem require_accel_ok o onInit. + accel_ok_ = (msg->data.size() >= 3) ? (msg->data[2] > 0.5) : true; + last_rp_time_ = ros::Time::now(); + have_rp_ = true; + } + + // Doc mot pixel depth ra met. Ho tro ca 32FC1 (Gazebo) lan 16UC1 (RealSense). + static inline double depthAt(const sensor_msgs::Image& img, int u, int v, bool is_float) + { + if (is_float) + { + const float d = *reinterpret_cast( + &img.data[v * img.step + u * sizeof(float)]); + return static_cast(d); + } + const uint16_t d = *reinterpret_cast( + &img.data[v * img.step + u * sizeof(uint16_t)]); + return d == 0 ? std::numeric_limits::quiet_NaN() : d * 0.001; + } + + void onDepth(const sensor_msgs::Image::ConstPtr& img, + const sensor_msgs::CameraInfo::ConstPtr& info) + { + if (!enabled_) + return; + + const bool is_float = (img->encoding == "32FC1"); + if (!is_float && img->encoding != "16UC1") + { + NODELET_WARN_THROTTLE(10.0, "cliff_detect: encoding '%s' khong ho tro " + "(can 32FC1 hoac 16UC1)", img->encoding.c_str()); + return; + } + + // --- Phep bien doi base_footprint <- frame quang hoc camera --- + // Giong gravity_align: canh TF phang, nen tu ap Lift*Tilt bang roll/pitch DO. + geometry_msgs::TransformStamped tf_msg; + try + { + tf_msg = tf_buffer_->lookupTransform(base_frame_, img->header.frame_id, + img->header.stamp, ros::Duration(0.1)); + } + catch (const tf2::TransformException& ex) + { + NODELET_WARN_THROTTLE(5.0, "cliff_detect: khong lookup duoc TF %s <- %s: %s", + base_frame_.c_str(), img->header.frame_id.c_str(), ex.what()); + return; + } + + double roll = 0.0, pitch = 0.0; + const bool rp_fresh = + have_rp_ && ((ros::Time::now() - last_rp_time_).toSec() < imu_timeout_); + if (rp_fresh) + { + roll = roll_; + pitch = pitch_; + } + else + { + NODELET_WARN_THROTTLE(10.0, "cliff_detect: khong co roll/pitch moi -> " + "gia dinh phang. Ket qua KHONG dang tin khi robot nghieng."); + } + + // ⚠️ Gravity_align dang khong neo duoc vao trong luc -> pitch la gyro thuan + // va dang troi. Hinh hoc cat tia x san khong dung tin o trang thai nay. + // Publish False va di tiep, thay vi bao vuc gia. + if (require_accel_ok_ && rp_fresh && !accel_ok_) + { + std_msgs::Bool f; f.data = false; flag_pub_.publish(f); + NODELET_WARN_THROTTLE(5.0, "cliff_detect: accel bi gate (robot dang tang/giam toc) " + "-> pitch khong dang tin, BO QUA frame."); + return; + } + + Eigen::Affine3d t_bl_cam = Eigen::Affine3d::Identity(); + t_bl_cam.translation() << tf_msg.transform.translation.x, + tf_msg.transform.translation.y, + tf_msg.transform.translation.z; + t_bl_cam.linear() = Eigen::Quaterniond(tf_msg.transform.rotation.w, + tf_msg.transform.rotation.x, + tf_msg.transform.rotation.y, + tf_msg.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::Affine3d T = lift * tilt * t_bl_cam; + const Eigen::Matrix3d R = T.linear(); + const double tz = T.translation().z(); + + // Tia chi co the cham san khi no chuc XUONG trong base_footprint. + // Va camera phai o TREN san. + if (tz <= 0.0) + return; + + // ⚠️ KHONG duoc doc thang info->K. + // + // depth_decimate (image_proc/crop_decimate) giao anh 320x240 NHUNG + // CameraInfo van mang K cua 640x480 va bao muc gop qua binning_x/y = 2. + // Do la dung quy uoc sensor_msgs/CameraInfo: width/height/K la cua do phan + // giai LUC HIEU CHUAN, con binning noi anh that nho hon bao nhieu lan. + // + // Doc thang K thi pixel day anh (v=239) cho b = (239-240.5)/465.7 ~ -0.003, + // tuc MOI tia bi coi nhu nam ngang. Da do hau qua: r_floor [3.53, 134.55] m + // thay vi [1.07, 3.18] m -> khong tia nao roi vao cua so -> detector im + // lang hoan toan ma khong bao loi gi. + // + // image_geometry::PinholeCameraModel::fromCameraInfo() bu ca binning LAN + // ROI, va fx()/cy() doc tu P_ da hieu chinh. depth_image_proc cung dung + // dung thu nay - do la ly do duong cloud khong dinh loi con duong nay dinh. + model_.fromCameraInfo(info); + const double fx = model_.fx(), cx = model_.cx(); + const double fy = model_.fy(), cy = model_.cy(); + if (fx <= 0.0 || fy <= 0.0) + return; + + const double tan_unc = std::tan(pitch_unc_deg_ * M_PI / 180.0); + + const int W = static_cast(img->width); + const int H = static_cast(img->height); + const int step = std::max(1, pixel_step_); + const int gw = (W + step - 1) / step; + const int gh = (H + step - 1) / step; + + // Luoi ung vien theo do phan giai da lay mau thua + std::vector cand(static_cast(gw) * gh, 0); + std::vector pos(static_cast(gw) * gh, + Eigen::Vector3d::Zero()); + + // Bo dem chan doan + long n_total = 0, n_up = 0, n_zneg = 0, n_range = 0, n_inwin = 0; + long n_hole = 0, n_drop = 0; + double r_min = 1e9, r_max = -1e9, z_lowest = 1e9; + + // ============ LUOT 1: DO MUC SAN THAM CHIEU ============ + // Lay trung vi z quan sat trong DAI GAN NHAT. Vung do gan robot nhat nen + // gan nhu chac chan van la san that; neu no da la vuc thi robot dang roi. + // Trung vi chiu duoc ca nhieu lan vat can le trong dai. + // + // Tru di muc nay bien phep do thanh VI SAI -> sai so pitch, sai so chieu + // cao camera, va lun caster deu la common-mode va bi triet. + // Mat san tham chieu: z_ref(r) = lvl_z0 + lvl_slope * r + double lvl_z0 = 0.0, lvl_slope = 0.0, lvl_mad = 0.0; + bool leveled = false; + if (self_level_) + { + std::vector> rz; // (r_floor, z quan sat) + rz.reserve(2048); + + for (int gy = 0; gy < gh; ++gy) + { + const int v = gy * step; + if (v >= H) break; + for (int gx = 0; gx < gw; ++gx) + { + const int u = gx * step; + if (u >= W) break; + const double a = (u - cx) / fx; + const double b = (v - cy) / fy; + const double denom = R(2, 0) * a + R(2, 1) * b + R(2, 2); + if (denom > -1e-6) continue; + const double z_exp = -tz / denom; + if (z_exp <= 0.0) continue; + const Eigen::Vector3d pf = T * Eigen::Vector3d(z_exp * a, z_exp * b, z_exp); + const double rf = std::hypot(pf.x(), pf.y()); + if (rf < min_dist_ || rf > max_dist_) continue; + const double d = depthAt(*img, u, v, is_float); + if (!std::isfinite(d) || d <= 0.0) continue; + const Eigen::Vector3d po = T * Eigen::Vector3d(d * a, d * b, d); + // ⚠️ Cong nay lam CA HAI viec: + // - loai vat the (mat ban 0.7m, mat ghe 0.45m) khoi phep khop + // - loai VUC THAT (z ~ -1m) khoi phep khop + // Nho ve thu hai ma khop duoc tren TOAN cua so ma khong so nuot mat + // chinh cai vuc dang can tim. Xem level_gate o onInit. + if (std::fabs(po.z()) > level_gate_) continue; + rz.emplace_back(rf, po.z()); + } + } + + if (static_cast(rz.size()) >= min_level_samples_) + { + // Khop BEN VUNG bang hai trung vi, khong dung binh phuong toi thieu: + // mot vet vat can sot lai khong duoc phep keo ca duong thang. + std::sort(rz.begin(), rz.end(), + [](const std::pair& p, const std::pair& q) + { return p.first < q.first; }); + const size_t n = rz.size(), h = n / 2; + + auto med = [](std::vector>::iterator b, + std::vector>::iterator e, + double& r_out, double& z_out) + { + const size_t m = static_cast(std::distance(b, e)); + std::vector zs; zs.reserve(m); + for (auto it = b; it != e; ++it) zs.push_back(it->second); + std::nth_element(zs.begin(), zs.begin() + m / 2, zs.end()); + z_out = zs[m / 2]; + r_out = (b + m / 2)->first; // da sap xep theo r + }; + + double r1, z1, r2, z2; + med(rz.begin(), rz.begin() + h, r1, z1); + med(rz.begin() + h, rz.end(), r2, z2); + + bool slope_clamped = false; + if (r2 - r1 > 0.15) // du duong day de uoc luong doc + { + double sl = (z2 - z1) / (r2 - r1); + // Doc vuot tran = dau hieu phep khop hong, KHONG phai san doc that. + if (std::fabs(sl) > max_level_slope_) + { + slope_clamped = true; + sl = (sl > 0 ? max_level_slope_ : -max_level_slope_); + } + lvl_slope = sl; + lvl_z0 = z1 - lvl_slope * r1; + } + else + { + lvl_slope = 0.0; + lvl_z0 = z1; + } + + // Do MAD cua phan du: duong khop co THUC SU ta duoc mat san khong? + std::vector resid; resid.reserve(rz.size()); + for (const auto& pr : rz) + resid.push_back(std::fabs(pr.second - (lvl_z0 + lvl_slope * pr.first))); + std::nth_element(resid.begin(), resid.begin() + resid.size() / 2, resid.end()); + lvl_mad = resid[resid.size() / 2]; + + if (slope_clamped || lvl_mad > max_level_residual_) + { + // Khung nhin khong phai mot mat phang san -> khong co goc quy chieu + // dang tin -> KHONG phan xet. Im lang an toan hon bao gia: bao gia se + // chan duong robot giua nha hang va nguoi van hanh se tat han node di. + std_msgs::Bool f; f.data = false; flag_pub_.publish(f); + NODELET_WARN_THROTTLE(5.0, + "cliff_detect: khop mat san KHONG dat (%s, MAD %.3f m > %.3f) -> " + "BO QUA frame.", + slope_clamped ? "doc cham tran" : "phan du lon", + lvl_mad, max_level_residual_); + return; + } + leveled = true; + } + else + { + // Khong du mau -> khong biet san o dau -> KHONG phan xet. + // Im lang con hon bao gia, vi bao gia se chan duong robot giua nha hang. + std_msgs::Bool f; f.data = false; flag_pub_.publish(f); + NODELET_WARN_THROTTLE(5.0, + "cliff_detect: chi %zu mau san hop le trong [%.2f, %.2f] m (can >= %d) -> " + "khong khop duoc mat san, BO QUA frame.", + rz.size(), min_dist_, max_dist_, min_level_samples_); + return; + } + } + + for (int gy = 0; gy < gh; ++gy) + { + const int v = gy * step; + if (v >= H) break; + for (int gx = 0; gx < gw; ++gx) + { + const int u = gx * step; + if (u >= W) break; + + ++n_total; + + const double a = (u - cx) / fx; + const double b = (v - cy) / fy; + + // z cua diem trong base_footprint = z_cam*(R20*a + R21*b + R22) + tz + const double denom = R(2, 0) * a + R(2, 1) * b + R(2, 2); + if (denom > -1e-6) + { + ++n_up; // tia khong chuc xuong -> khong cham san + continue; + } + + const double z_exp = -tz / denom; // depth ma san LE RA phai o do + if (z_exp <= 0.0) + { + ++n_zneg; + continue; + } + + const Eigen::Vector3d p_floor = T * Eigen::Vector3d(z_exp * a, z_exp * b, z_exp); + const double r_floor = std::hypot(p_floor.x(), p_floor.y()); + r_min = std::min(r_min, r_floor); + r_max = std::max(r_max, r_floor); + if (r_floor < min_dist_ || r_floor > max_dist_) + { + ++n_range; + continue; + } + ++n_inwin; + + const double d_obs = depthAt(*img, u, v, is_float); + + // Nguong no ra theo tam: bu sai so pitch con lai sau khi tu hieu chuan. + // Mat san tham chieu tai dung tam nay, roi moi tru le an toan. + const double z_ref = lvl_z0 + lvl_slope * r_floor; + const double thr = z_ref - (cliff_margin_ + r_floor * tan_unc); + + bool is_cand = false; + if (!std::isfinite(d_obs) || d_obs <= 0.0) + { + // LO: le ra phai thay san o day ma khong co so do nao. + // Day la ca cau thang toi, va la ly do phai chay tren anh depth. + is_cand = true; + ++n_hole; + } + else + { + const Eigen::Vector3d p_obs = T * Eigen::Vector3d(d_obs * a, d_obs * b, d_obs); + z_lowest = std::min(z_lowest, p_obs.z()); + if (p_obs.z() < thr) + { + is_cand = true; // SUT: be mat thap hon san qua nguong + ++n_drop; + } + } + + if (is_cand) + { + const size_t idx = static_cast(gy) * gw + gx; + cand[idx] = 1; + pos[idx] = p_floor; // ⚠️ MARK TAI MEP, khong tai diem tra ve + } + } + } + + // --- Doi cum: loai pixel le --- + pcl::PointCloud out; + out.reserve(256); + int n_cliff = 0; + + for (int gy = 0; gy < gh; ++gy) + { + for (int gx = 0; gx < gw; ++gx) + { + const size_t idx = static_cast(gy) * gw + gx; + if (!cand[idx]) + continue; + + int neigh = 0; + for (int dy = -1; dy <= 1; ++dy) + { + const int ny = gy + dy; + if (ny < 0 || ny >= gh) continue; + for (int dx = -1; dx <= 1; ++dx) + { + const int nx = gx + dx; + if (nx < 0 || nx >= gw) continue; + if (dx == 0 && dy == 0) continue; + neigh += cand[static_cast(ny) * gw + nx]; + } + } + if (neigh < min_neighbors_) + continue; + + pcl::PointXYZ p; + p.x = static_cast(pos[idx].x()); + p.y = static_cast(pos[idx].y()); + // ⚠️ GIU z AM, khong nang len. Vat can ao dat o z duong se bi chinh tia + // clearing cua camera (huong toi tuong xa) xoa ngay frame sau. + // costmap_2d::VoxelLayer kep diem duoi origin_z vao voxel 0 va mark, + // con raytraceFreespace cat moi tia tai z = origin_z -> khong tia nao + // voi toi de xoa. Xem costmap_common.yaml nguon cliff_cloud. + p.z = static_cast(-(cliff_margin_ + 0.05)); + out.push_back(p); + ++n_cliff; + } + } + + const bool detected = (n_cliff >= min_cluster_); + + if (debug_) + { + NODELET_INFO_THROTTLE(2.0, + "cliff_detect[dbg] anh %dx%d enc=%s | mau %ld: tia-len %ld, z<=0 %ld, " + "ngoai-dai %ld, TRONG-DAI %ld | lo %ld, sut %ld | sau-cum %d | " + "r_floor [%.2f, %.2f] m | z thap nhat %.3f m | " + "san: z0 %.4f doc %.4f MAD %.4f (%s) | " + "accel_ok %d | tz %.3f fx %.1f cy %.1f", + W, H, img->encoding.c_str(), n_total, n_up, n_zneg, n_range, n_inwin, + n_hole, n_drop, n_cliff, + (r_min > 1e8 ? 0.0 : r_min), (r_max < -1e8 ? 0.0 : r_max), + (z_lowest > 1e8 ? 0.0 : z_lowest), lvl_z0, lvl_slope, lvl_mad, + leveled ? "khop duoc" : "mac dinh", + accel_ok_ ? 1 : 0, tz, fx, cy); + } + + if (!out.empty()) + { + sensor_msgs::PointCloud2 msg_out; + pcl::toROSMsg(out, msg_out); + msg_out.header.stamp = img->header.stamp; + msg_out.header.frame_id = output_frame_; + cloud_pub_.publish(msg_out); + } + + std_msgs::Bool flag; + flag.data = detected; + flag_pub_.publish(flag); + + if (detected) + NODELET_WARN_THROTTLE(2.0, "cliff_detect: VUC phia truoc - %d diem trong " + "[%.2f, %.2f] m", n_cliff, min_dist_, max_dist_); + } + + ros::NodeHandle nh_, pnh_; + ros::Publisher cloud_pub_, flag_pub_; + ros::Subscriber rp_sub_; + + message_filters::Subscriber image_sub_; + message_filters::Subscriber info_sub_; + std::shared_ptr> sync_; + + image_geometry::PinholeCameraModel model_; + + std::shared_ptr tf_buffer_; + std::shared_ptr tf_listener_; + + std::string output_frame_; + const std::string base_frame_ = "base_link"; + double wheel_radius_ = 0.075; + + double min_dist_ = 1.10, max_dist_ = 2.50; + double cliff_margin_ = 0.05; + double pitch_unc_deg_ = 2.0; + int pixel_step_ = 4; + int min_neighbors_ = 3; + int min_cluster_ = 12; + double imu_timeout_ = 0.5; + bool enabled_ = true; + bool debug_ = false; + bool require_accel_ok_ = true; + bool self_level_ = true; + double near_band_ = 0.40; + int min_level_samples_ = 40; + double level_gate_ = 0.25; + double max_level_slope_ = 0.20; + double max_level_residual_ = 0.05; + + double roll_ = 0.0, pitch_ = 0.0; + bool have_rp_ = false, accel_ok_ = true; + ros::Time last_rp_time_; +}; + +} // namespace perception_3d + +PLUGINLIB_EXPORT_CLASS(perception_3d::CliffDetectNodelet, nodelet::Nodelet) diff --git a/src/perception_3d/src/depth_filter_nodelet.cpp b/src/perception_3d/src/depth_filter_nodelet.cpp index 681e1e5..f1ec72a 100644 --- a/src/perception_3d/src/depth_filter_nodelet.cpp +++ b/src/perception_3d/src/depth_filter_nodelet.cpp @@ -64,6 +64,20 @@ private: pnh_.param("voxel_size", voxel_size_, 0.03); + // ============ GIOI HAN TAN SO - CAT PHAN THUA ============ + // Camera chay 30 Hz, nhung phia sau khong ai can 30 Hz: + // local costmap update_frequency 5 Hz + // global costmap update_frequency 2 Hz + // Tuc chuoi dang lam viec THUA ~6 lan. + // + // Da do (world restaurant, 20 loi): perception_manager 55.6% CPU trung + // binh, la muc lon nhat trong he sau octomap. Bo frame o DAY chan duoc ca + // phan con lai cua chuoi - gravity_align, va ca bufferCloud cua costmap. + // + // Khong co rui ro hinh hoc: chi bo bot frame, khong dong vao toa do diem. + // 0 = tat gioi han. + pnh_.param("max_rate", max_rate_, 10.0); + // ⚠️ Xac nhan theo thoi gian - MAC DINH TAT. // // Node nay chay o FRAME QUANG HOC CAMERA, ma frame do di chuyen cung robot. @@ -89,8 +103,8 @@ private: 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_); + NODELET_INFO("depth_filter: range [%.2f, %.2f] m, voxel %.3f m, max_rate %.1f Hz", + min_range_, max_range_, voxel_size_, max_rate_); if (enable_temporal_) NODELET_INFO("depth_filter: xac nhan thoi gian - can %d hit trong %.2fs", min_hits_, temporal_window_); @@ -109,6 +123,28 @@ private: void onCloud(const sensor_msgs::PointCloud2::ConstPtr& msg) { + // --- 0. Gioi han tan so (xem max_rate o onInit) --- + if (max_rate_ > 0.0) + { + const ros::Time now = msg->header.stamp; + if (!rate_init_) + { + rate_init_ = true; + last_processed_ = now; + } + else + { + const double dt = (now - last_processed_).toSec(); + // dt < 0 : nhay thoi gian (reset sim / phat lai bag) -> nhan lai moc + if (dt < 0.0) + last_processed_ = now; + else if (dt < 1.0 / max_rate_) + return; + else + last_processed_ = now; + } + } + pcl::PointCloud::Ptr cloud(new pcl::PointCloud); pcl::fromROSMsg(*msg, *cloud); if (cloud->empty()) @@ -203,6 +239,9 @@ private: ros::Publisher pub_; double min_range_ = 0.22, max_range_ = 4.0, voxel_size_ = 0.03; + double max_rate_ = 10.0; + bool rate_init_ = false; + ros::Time last_processed_; bool enable_temporal_ = true; int min_hits_ = 3; double temporal_window_ = 0.5; diff --git a/src/perception_3d/src/gravity_align_nodelet.cpp b/src/perception_3d/src/gravity_align_nodelet.cpp index 0ddfa9c..9b3e2b6 100644 --- a/src/perception_3d/src/gravity_align_nodelet.cpp +++ b/src/perception_3d/src/gravity_align_nodelet.cpp @@ -232,17 +232,39 @@ private: // Lift va Tilt do base_tilt_tf.py phat. const std::string& target = tilt_from_tf_ ? output_frame_ : base_frame_; + // ⚠️ Tra TF tai DUNG THOI DIEM cua cloud, khong phai ros::Time(0). + // + // Time(0) = "ban moi nhat co san". Vo hai khi chuoi TF tinh, nhung voi + // tilt_from_tf_=true (duong phan cung that) thi canh + // base_footprint -> base_link la DONG, do base_tilt_tf.py phat. Luc do + // Time(0) lay do nghieng cua thoi diem KHAC voi luc chup cloud -> cloud + // duoc bu bang goc sai khi robot dang quay hoac qua go cua. + // + // Fallback ve Time(0) neu khong extrapolate duoc, vi mat mot chut chinh + // xac van hon la vut ca cloud di (luc do costmap khong con gi de clear). geometry_msgs::TransformStamped tf_bl_cam; try { tf_bl_cam = tf_buffer_->lookupTransform(target, msg->header.frame_id, - ros::Time(0), ros::Duration(0.1)); + msg->header.stamp, ros::Duration(0.1)); } catch (const tf2::TransformException& ex) { - NODELET_WARN_THROTTLE(5.0, "gravity_align: khong lookup duoc TF %s <- %s: %s", - target.c_str(), msg->header.frame_id.c_str(), ex.what()); - return; + try + { + tf_bl_cam = tf_buffer_->lookupTransform(target, msg->header.frame_id, + ros::Time(0), ros::Duration(0.1)); + NODELET_WARN_THROTTLE(5.0, + "gravity_align: khong co TF %s <- %s tai stamp (%s) -> dung ban moi nhat. " + "Cloud se bu nghieng hoi lech neu robot dang quay.", + target.c_str(), msg->header.frame_id.c_str(), ex.what()); + } + catch (const tf2::TransformException& ex2) + { + NODELET_WARN_THROTTLE(5.0, "gravity_align: khong lookup duoc TF %s <- %s: %s", + target.c_str(), msg->header.frame_id.c_str(), ex2.what()); + return; + } } // --- Roll/pitch hien tai --- diff --git a/src/perception_3d/src/scan_to_cloud_nodelet.cpp b/src/perception_3d/src/scan_to_cloud_nodelet.cpp index 5aafcaf..4430bf6 100644 --- a/src/perception_3d/src/scan_to_cloud_nodelet.cpp +++ b/src/perception_3d/src/scan_to_cloud_nodelet.cpp @@ -1,13 +1,29 @@ /** * scan_to_cloud_nodelet - Chieu LaserScan 2D thanh PointCloud2 trong base_footprint. * - * ================== VI SAO CAN NODE NAY ================== + * ================== ⚠️ KHONG CON DUOC INSTANTIATE ================== + * Da bo khoi perception_nodelets.launch. File giu lai vi code dung va day la + * tien ich LaserScan -> PointCloud2 duy nhat trong repo; se can lai neu sau + * nay lam mot lop 3D nuoi bang LiDAR. + * + * Ly do ton tai (ghi ben duoi) DA HET HIEU LUC tren hai diem: + * - Ban do dieu huong /map gio den tu RTAB-Map, khong tu octomap. + * Xem docs/SIM_VS_REAL.md muc 5. + * - octomap_server gio mac dinh TAT (khong ai doc dau ra cua no). + * + * Va viec bo no MO KHOA mot thu quan trong hon: /perception/cloud_aligned gio + * chi con MOT nguon (camera), nen costmap dat duoc sensor_frame dung la + * camera_depth_optical_frame. Truoc day topic co hai publisher voi hai goc + * cam bien khac nhau (camera z=0.80, LiDAR z=0.20) nen goc tia raycast KHONG + * THE dung cho ca hai. Xem robot_bringup/config/costmap_common.yaml. + * + * ================== VI SAO TUNG 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 + * LiDAR ToF : FOV 270 do (236 do sau khi cat cung bi than che), tam 40m * * 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". @@ -64,7 +80,9 @@ private: // 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); + // 40.0 = tam that cua LakiBeam 1L. Truoc day de 25.0 - mot con so khong + // ung voi thiet bi nao, no cat bot du lieu ma khong co ly do. + pnh_.param("max_range", max_range_, 40.0); pub_ = nh_.advertise("cloud_out", 5); sub_ = nh_.subscribe("scan", 10, &ScanToCloudNodelet::onScan, this); @@ -141,7 +159,7 @@ private: std::shared_ptr tf_listener_; std::string output_frame_; - double min_range_ = 0.10, max_range_ = 25.0; + double min_range_ = 0.10, max_range_ = 40.0; }; } // namespace perception_3d diff --git a/src/robot_bringup/CMakeLists.txt b/src/robot_bringup/CMakeLists.txt index 8c4e7b0..9a60161 100644 --- a/src/robot_bringup/CMakeLists.txt +++ b/src/robot_bringup/CMakeLists.txt @@ -5,10 +5,7 @@ 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 scripts/base_tilt_tf.py scripts/virtual_joystick.py # teleop_model.py la MODULE, khong phai node. Phai cai vao CUNG thu muc voi diff --git a/src/robot_bringup/config/costmap_common.yaml b/src/robot_bringup/config/costmap_common.yaml index c087d1d..0985653 100644 --- a/src/robot_bringup/config/costmap_common.yaml +++ b/src/robot_bringup/config/costmap_common.yaml @@ -20,9 +20,30 @@ transform_tolerance: 0.5 # ============================================================= obstacle_layer: enabled: true - observation_sources: laser_scan camera_cloud + observation_sources: laser_scan camera_cloud cliff_cloud combination_method: 1 + # =========================================================== + # ⚠️ KHOI 3D DUOI DAY CHI CO TAC DUNG O LOCAL COSTMAP + # costmap_local.yaml dung costmap_2d::VoxelLayer; + # costmap_global*.yaml van dung ObstacleLayer va BO QUA cac khoa nay + # mot cach vo hai. Ly do tach ra nam trong costmap_global_static.yaml. + # + # ⚠️ RANG BUOC PHAI GIU: origin_z + z_voxels*z_resolution PHAI > camera_z. + # 0.0 + 12*0.10 = 1.20 > 0.80 (camera) OK + # Vi pham thi VoxelLayer::raytraceFreespace TAT TOAN BO viec clear va chi + # ROS_WARN throttle - vat can ao se dong lai mai ma khong co gi bao loi. + # + # z_voxels toi da 16: cot voxel la uint32 voi 16 bit mark + 16 bit unknown + # (voxel_grid/voxel_grid.h:54). + # =========================================================== + origin_z: 0.0 + z_resolution: 0.10 + z_voxels: 12 + mark_threshold: 0 + unknown_threshold: 15 + publish_voxel_map: false + # ---- 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. @@ -34,18 +55,40 @@ obstacle_layer: clearing: true obstacle_range: 6.0 raytrace_range: 8.0 + # 25 Hz -> het han sau 5 chu ky. Khong dat thi mac dinh la 0.0 = KHONG BAO + # GIO cu, tuc LiDAR chet ma costmap van bao `current` va move_base van lap + # ke hoach tren du lieu dong bang. + expected_update_rate: 0.2 + # ⚠️ inf_is_valid: true AN TOAN CHI VI robot_drivers/launch/scan_filter.launch + # dam bao cung bi than robot che mang gia tri range_max+1 (bi loai), + # KHONG BAO GIO mang inf. + # Driver that BIA RA ~90 do no khong he quet (docs/HARDWARE.md muc 2, + # bug 2). Neu cung do ve inf thi costmap se raytrace-clear XUYEN TUONG + # suot cung do, MOI SCAN. Doi bat cu thu gi trong chuoi filter -> doc + # lai cho nay truoc. 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 + # obstacle_range 3.5 : xa hon ~4m depth stereo baseline 55mm nhieu manh camera_cloud: - sensor_frame: base_footprint + # ⚠️ sensor_frame la GOC TIA RAYCAST, DOC LAP voi frame_id cua cloud. + # Nguon: costmap_2d/observation_buffer.h:72 - "The frame of the origin + # of the sensor, can be left blank to be read from the messages". + # ObservationBuffer dung diem (0,0,0) trong frame NAY lam goc tia, con + # du lieu cloud van duoc bien doi tu header.frame_id cua no. + # + # Truoc day dat base_footprint -> goc tia nam o z=0 TREN SAN, trong khi + # camera thuc te o z=0.80. Tia di tu san CHEO LEN toi diem cao se xuyen + # qua voxel cua vat thap va XOA chung - dung cai tui xach duoi san ma + # tieu chi nghiem thu L3 doi phai thay. + # + # Dat duoc gia tri dung la nho scan_to_cloud da bo: topic nay gio chi + # con MOT nguon (camera). Truoc do no co hai publisher voi hai goc cam + # bien khac nhau nen khong the khai bao dung mot frame nao. + sensor_frame: camera_depth_optical_frame data_type: PointCloud2 topic: /perception/cloud_aligned marking: true @@ -56,6 +99,37 @@ obstacle_layer: max_obstacle_height: 1.10 obstacle_range: 3.5 raytrace_range: 4.0 + # depth_filter gioi han 10 Hz -> het han sau 5 chu ky. + # Khong dat thi camera chet van duoc coi la du lieu tuoi mai mai. + expected_update_rate: 0.5 + + # ---- VUC / BAC THANG DI XUONG ---- + # perception_3d/CliffDetectNodelet phat hien tren ANH DEPTH va mark tai + # GIAO DIEM tia x mat san (dung mep), khong tai diem tra ve. + # + # ⚠️ chieu cao AM, va KHONG duoc nang len z duong. + # Vat can ao dat o z=0.30 nam giua khong khi se bi chinh tia clearing cua + # camera (huong toi tuong o 3m) xoa ngay frame sau - no di xuyen qua do. + # Giu z am thi: VoxelLayer kep diem duoi origin_z (=0.0) vao voxel 0 roi + # mark, con raytraceFreespace CAT moi tia tai z = origin_z nen khong tia + # nao voi toi duoc. Tuc mark nay MIEN NHIEM voi clearing. + # + # ⚠️ clearing: false. Nguon nay chi danh dau, khong bao gio xoa - no khong + # quan sat khong gian trong, no quan sat su VANG MAT cua san. + # + # ⚠️ Day la lop TRANH NE khi dieu huong, KHONG phai lop an toan. + # Lop an toan la /perception/cliff_detected -> safety_monitor. + # Va ca hai deu MU duoi ~1.1m. + cliff_cloud: + sensor_frame: camera_depth_optical_frame + data_type: PointCloud2 + topic: /perception/cloud_cliff + marking: true + clearing: false + min_obstacle_height: -2.0 + max_obstacle_height: -0.01 + obstacle_range: 2.5 + raytrace_range: 2.5 inflation_layer: enabled: true diff --git a/src/robot_bringup/config/costmap_global.yaml b/src/robot_bringup/config/costmap_global.yaml index 035b2b1..8a610e5 100644 --- a/src/robot_bringup/config/costmap_global.yaml +++ b/src/robot_bringup/config/costmap_global.yaml @@ -38,7 +38,8 @@ global_costmap: 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. + # LiDAR ToF tam 40m (LakiBeam 1L) nhung obstacle_range da cat o 6m - + # co y: tam thiet bi khong lien quan den kich thuoc costmap. width: 16.0 height: 16.0 resolution: 0.05 diff --git a/src/robot_bringup/config/costmap_global_static.yaml b/src/robot_bringup/config/costmap_global_static.yaml index 0359e4b..d7a5b8d 100644 --- a/src/robot_bringup/config/costmap_global_static.yaml +++ b/src/robot_bringup/config/costmap_global_static.yaml @@ -24,6 +24,18 @@ global_costmap: rolling_window: false resolution: 0.05 + # ⚠️ ObstacleLayer o day, KHONG phai VoxelLayer (local costmap moi dung Voxel). + # + # Duoi VoxelLayer, mot o 2D chi tro lai FREE khi CA COT voxel sach. Tia LiDAR + # o z=0.20 khong xoa duoc mot vet camera sai o z=0.9; chi mot tia camera khac + # di qua dung voxel do moi xoa duoc, ma camera chi co FOV 69 do va tam 4m. + # + # Costmap nay co rolling_window: false - khong co gi troi ra ngoai. Nen mot + # vet sai se ket LAI VINH VIEN va chan duong that. Local costmap la cua so + # truot 6m nen khong bi. + # + # Danh doi da chap nhan: o day vat can 3D bi lam phang ve 2D. Chap nhan duoc + # vi tranh va cham la viec cua LOCAL costmap; global chi de lap ke hoach dai. plugins: - {name: static_layer, type: "costmap_2d::StaticLayer"} - {name: obstacle_layer, type: "costmap_2d::ObstacleLayer"} diff --git a/src/robot_bringup/config/costmap_local.yaml b/src/robot_bringup/config/costmap_local.yaml index 132353c..7b09c10 100644 --- a/src/robot_bringup/config/costmap_local.yaml +++ b/src/robot_bringup/config/costmap_local.yaml @@ -11,6 +11,22 @@ local_costmap: height: 6.0 resolution: 0.05 + # ⚠️ VoxelLayer o day, ObstacleLayer o global. KHONG phai tuy tien. + # + # ObstacleLayer raytrace trong 2D: mot tia toi mat ban o z=1.0m cach 2m se + # CLEAR moi o 2D nam giua - ke ca o dang co tui xach o z=0.1m. Dung hai vat + # ma tieu chi nghiem thu L3 doi phai thay. + # VoxelLayer clear theo 3D roi moi chieu xuong 2D, nen tia cao khong xoa + # duoc vat thap. + # + # Vi sao KHONG dung o global costmap: duoi VoxelLayer, mot o 2D chi tro lai + # FREE khi CA COT voxel sach. Tia LiDAR o z=0.20 khong con xoa duoc mot vet + # camera sai o z=0.9 - chi mot tia camera khac qua dung voxel do moi xoa + # duoc, ma camera chi co FOV 69 do. Trong cua so truot 6m o day thi vet troi + # ra ngoai; trong costmap_global_static.yaml (rolling_window: false) no ket + # VINH VIEN. Xem ghi chu trong file do. + # + # Tham so 3D (origin_z/z_resolution/z_voxels/...) nam trong costmap_common.yaml. plugins: - - {name: obstacle_layer, type: "costmap_2d::ObstacleLayer"} + - {name: obstacle_layer, type: "costmap_2d::VoxelLayer"} - {name: inflation_layer, type: "costmap_2d::InflationLayer"} diff --git a/src/robot_bringup/config/robot.yaml b/src/robot_bringup/config/robot.yaml index 0bde8fb..39ce6bf 100644 --- a/src/robot_bringup/config/robot.yaml +++ b/src/robot_bringup/config/robot.yaml @@ -19,10 +19,31 @@ wheel_odom: # 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) + slip_cov_multiplier: 100.0 # CHI con ap cho POSE covariance (sai so tich luy + # theo quang duong). Yaw-rate dung cach khac -> imu_timeout: 0.5 + # ---- ⚠️ DO BAT DINH YAW-RATE: KHAI BAO CAI DA DO ---- + # twist.covariance[35] KHONG dung slip_cov_multiplier nua. Thay vao do lay + # sigma = slip_metric = |omega_encoder - gyro_z|, tuc chinh sai so cua phep + # do banh xe, do duoc tung chu ky. + # + # Vi sao doi: he so co dinh 100 THIEU ~2 BAC. Da do khi robot xoay tai cho: + # sai so that : omega encoder -3.635 vs gyro -1.377 = 2.26 rad/s + # sigma khai bao : (0.02*0.02)^2 * 100 / 0.02^2 = 0.04 -> 0.2 rad/s + # EKF nhan mot diem 11-sigma ma van tin -> yaw troi. + # + # Hau qua da do o tang tren: global_scan_init ghep scan bang odom, nen sau + # khi xoay 301 do no khop ra HUONG SAI 40.8 do (vi tri van dung 0.17 m). + # Khong xoay thi huong DUNG - khong tich luy sai so odom nao. + # + # San khi banh va gyro dong y. Khong de 0 vi banh con sai so he thong + # (ban kinh / wheelbase chua hieu chuan UMBmark). + yaw_rate_sigma_floor: 0.02 # rad/s + # Khong co gyro de doi chieu -> khong do duoc truot -> phai khai rong. + # Dat qua nho o day la bao EKF tin banh xe mu quang. + yaw_rate_sigma_no_imu: 0.50 # rad/s + # ---- 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. diff --git a/src/robot_bringup/launch/localization.launch b/src/robot_bringup/launch/localization.launch index 41c66f2..cfb3e78 100644 --- a/src/robot_bringup/launch/localization.launch +++ b/src/robot_bringup/launch/localization.launch @@ -25,6 +25,10 @@ --> + + + @@ -84,10 +88,44 @@ + + + + + + + + + + + + + + + + + ⚠️ Ghi chu cu o day noi "enable_octomap van bat: no lo VAT CAN 3D cho + costmap". DIEU DO CHUA BAO GIO DUNG - khong co VoxelLayer nao doc + /octomap_full, va no khong co subscriber nao trong ca repo. + + Vat can 3D den costmap qua obstacle_layer doc thang + /perception/cloud_aligned, va gio local costmap dung + costmap_2d::VoxelLayer nen clear theo 3D that. + octomap gio mac dinh TAT (34% CPU cho dau ra khong ai dung); bat len + bang enable_octomap:=true khi can NHIN khoi 3D trong rviz. --> + @@ -109,6 +147,8 @@ Ha xuong false cho bai kiem relocalization. --> + + + + + @@ -65,9 +76,30 @@ Dang ky VAN bang ICP LiDAR. Xem rtabmap.launch. --> + + + + @@ -83,6 +115,9 @@ + + + + + + + - + @@ -71,10 +127,123 @@ - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/robot_bringup/launch/perception.launch b/src/robot_bringup/launch/perception.launch index 29bc013..8e94bdf 100644 --- a/src/robot_bringup/launch/perception.launch +++ b/src/robot_bringup/launch/perception.launch @@ -10,7 +10,12 @@ 2. Phai thay MAT BAN - world restaurant co ban voi mat NHO RA 15cm khoi chan. LiDAR o z=0.20 chi thay chan ban. Neu chi dung LiDAR, robot se dam canh ban. 3. Phai thay VAT THAP - hop do o (0, -3.5) cao 12cm - 4. Bat /octomap_full: ban do vat can 3D hinh thanh + 4. Kiem TY LE cloud sau khi giam mau: dat mot hop o khoang cach da biet, + do trong rviz. depth_decimate chay 2x va image_geometry phai tu bu + binning - sai o day la cloud co dung hinh nhung SAI KICH THUOC. + 5. (tuy chon) enable_octomap:=true roi bat MarkerArray tren + /occupied_cells_vis_array de nhin khoi 3D tich luy. Mac dinh TAT vi + khong ai doc dau ra cua octomap va no an 34% CPU. (/map la viec cua RTAB-Map, chi co trong mapping.launch / localization.launch) Kiem tra bu nghieng: @@ -19,6 +24,10 @@ --> + + + @@ -35,7 +44,13 @@ - + + + + + + + + - + + @@ -241,6 +276,8 @@ --> + + @@ -249,8 +286,9 @@ + - - + + @@ -283,10 +321,13 @@ - + + @@ -344,7 +385,7 @@ - + diff --git a/src/robot_bringup/launch/sim.launch b/src/robot_bringup/launch/sim.launch index 11a714d..00b94fb 100644 --- a/src/robot_bringup/launch/sim.launch +++ b/src/robot_bringup/launch/sim.launch @@ -7,6 +7,10 @@ roslaunch robot_bringup sim.launch world:=restaurant rostopic hz /scan /imu/data_raw /joint_states /ground_truth/odom rostopic hz /camera/depth/image_rect_raw + rosrun slam_eval check_scan.py # kiem header + cung mu + + /scan phai la 25 Hz. Neu thay /scan_raw ma khong thay /scan thi chuoi + laser_filters chua len - xem robot_drivers/launch/scan_filter.launch. Kiem tra them trong rviz: - LaserScan hien dung hinh dang phong @@ -66,4 +70,17 @@ + + + diff --git a/src/robot_bringup/launch/teleop_joystick.launch b/src/robot_bringup/launch/teleop_joystick.launch index 0db123d..0147c8f 100644 --- a/src/robot_bringup/launch/teleop_joystick.launch +++ b/src/robot_bringup/launch/teleop_joystick.launch @@ -14,8 +14,11 @@ Nguon: package `virtual_joystick_teleop`, BSD-3-Clause, tac gia duongtd https://git.pnkr.asia/DuongTD/virtual_joystick_teleop.git - ============ SO LIEU: GIONG HET launch GOC ============ - linear_speed 0.30 max_linear_speed 2.00 linear_limit_ceiling 5.00 + ============ SO LIEU ============ + linear_speed 1.50 <- DA DOI khoi ban goc (0.30). Cac so khac giu nguyen. + ⚠️ Thanh truot mo o 1.50 nhung robot van chay 0.70 + vi safety_monitor chan. Xem khoi ben duoi. + max_linear_speed 2.00 linear_limit_ceiling 5.00 angular_speed 0.70 max_angular_speed 2.00 angular_limit_ceiling 8.00 linear_step 0.05 min_linear_speed 0.05 angular_step 0.10 min_angular_speed 0.10 @@ -45,8 +48,9 @@ mapping.launch NGHIEM TRONG. Odometry sai lam BAN DO MEO vinh vien, vi RTAB-Map dung odometry lam gia tri khoi tao cho ICP. - Quet map thi lai cham, hoac dung teleop co ramp: - python3 src/robot_bringup/scripts/teleop.py + Ban teleop co ramp (scripts/teleop.py) DA BI XOA, nen + KHONG con cach nao tu dong gioi han gia toc. Quet map + thi phai tu lai cham tay, dac biet luc khoi hanh. localization.launch NHE HON. Ban do co dinh, RTAB-Map sua drift bang ICP moi giay. Nhung co mot nguong phai biet: @@ -76,7 +80,7 @@ - + diff --git a/src/robot_bringup/rviz/map_view.rviz b/src/robot_bringup/rviz/map_view.rviz index 2cd84cd..f77cf84 100644 --- a/src/robot_bringup/rviz/map_view.rviz +++ b/src/robot_bringup/rviz/map_view.rviz @@ -38,11 +38,12 @@ Visualization Manager: Alpha: 0.9 # Do thi pose: node + LOOP CLOSURE. Cho nay dang nhin nhat. - - Class: rviz/MarkerArray + # ⚠️ Xem ghi chu trong slam.rviz: /rtabmap/mapGraph la rtabmap_msgs/MapGraph, + # khong phai visualization_msgs/MarkerArray. + - Class: rtabmap_rviz_plugins/MapGraph Name: PoseGraph Enabled: true - Marker Topic: /rtabmap/mapGraph - Queue Size: 10 + Topic: /rtabmap/mapGraph # Voxel 3D tu octomap (camera D410). Day la 3D duy nhat trong he thong - # KHONG nam trong file .db cua RTAB-Map. diff --git a/src/robot_bringup/rviz/slam.rviz b/src/robot_bringup/rviz/slam.rviz index 9ccdaea..4766187 100644 --- a/src/robot_bringup/rviz/slam.rviz +++ b/src/robot_bringup/rviz/slam.rviz @@ -1,5 +1,6 @@ Panels: - Class: rviz/Displays + Help Height: 70 Name: Displays Property Tree Widget: Expanded: @@ -7,148 +8,454 @@ Panels: - /LaserScan1 - /CloudAligned1 Splitter Ratio: 0.5 - Tree Height: 700 + Tree Height: 283 - Class: rviz/Tool Properties + Expanded: ~ Name: Tool Properties + Splitter Ratio: 0.5 - Class: rviz/Views + Expanded: + - /Current View1 Name: Views - + Splitter Ratio: 0.5 +Preferences: + PromptSaveOnExit: true +Toolbars: + toolButtonStyle: 2 Visualization Manager: Class: "" - Global Options: - Background Color: 48; 48; 48 - Fixed Frame: map - Frame Rate: 30 Displays: - - Class: rviz/Grid - Name: Grid - Enabled: true + - Alpha: 0.5 Cell Size: 1 - Plane Cell Count: 20 + Class: rviz/Grid Color: 100; 100; 100 - - - Class: rviz/RobotModel - Name: RobotModel Enabled: true + Line Style: + Line Width: 0.029999999329447746 + Value: Lines + Name: Grid + Normal Cell Count: 0 + Offset: + X: 0 + Y: 0 + Z: 0 + Plane: XY + Plane Cell Count: 20 + Reference Frame: + Value: true + - Alpha: 1 + Class: rviz/RobotModel + Collision Enabled: false + Enabled: true + Links: + All Links Enabled: true + Expand Joint Details: false + Expand Link Details: false + Expand Tree: false + Link Tree Style: Links in Alphabetic Order + base_footprint: + Alpha: 1 + Show Axes: false + Show Trail: false + base_link: + Alpha: 1 + Show Axes: false + Show Trail: false + Value: true + camera_depth_optical_frame: + Alpha: 1 + Show Axes: false + Show Trail: false + camera_infra1_optical_frame: + Alpha: 1 + Show Axes: false + Show Trail: false + camera_infra2_optical_frame: + Alpha: 1 + Show Axes: false + Show Trail: false + camera_link: + Alpha: 1 + Show Axes: false + Show Trail: false + Value: true + front_caster_link: + Alpha: 1 + Show Axes: false + Show Trail: false + Value: true + imu_link: + Alpha: 1 + Show Axes: false + Show Trail: false + laser_link: + Alpha: 1 + Show Axes: false + Show Trail: false + Value: true + left_wheel_link: + Alpha: 1 + Show Axes: false + Show Trail: false + Value: true + rear_caster_link: + Alpha: 1 + Show Axes: false + Show Trail: false + Value: true + right_wheel_link: + Alpha: 1 + Show Axes: false + Show Trail: false + Value: true + Name: RobotModel Robot Description: robot_description TF Prefix: "" - + Update Interval: 0 + Value: true + Visual Enabled: true - Class: rviz/TF + Enabled: true + Filter (blacklist): "" + Filter (whitelist): "" + Frame Timeout: 15 + Frames: + All Enabled: true + base_footprint: + Value: true + base_link: + Value: true + camera_depth_optical_frame: + Value: true + camera_infra1_optical_frame: + Value: true + camera_infra2_optical_frame: + Value: true + camera_link: + Value: true + front_caster_link: + Value: true + imu_link: + Value: true + laser_link: + Value: true + left_wheel_link: + Value: true + map: + Value: true + odom: + Value: true + rear_caster_link: + Value: true + right_wheel_link: + Value: true + Marker Alpha: 1 + Marker Scale: 0.30000001192092896 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 + Show Axes: true + Show Names: true + Tree: + map: + odom: + base_footprint: + base_link: + camera_link: + camera_depth_optical_frame: + camera_infra1_optical_frame: + {} + camera_infra2_optical_frame: + {} + front_caster_link: + {} + imu_link: + {} + laser_link: + {} + left_wheel_link: + {} + rear_caster_link: + {} + right_wheel_link: + {} + Update Interval: 0 + Value: true + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz/LaserScan 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 + Invert Rainbow: false + Max Color: 255; 255; 255 + Min Color: 0; 0; 0 + Name: LaserScan + Position Transformer: XYZ + Queue Size: 10 + Selectable: true + Size (Pixels): 3 + Size (m): 0.029999999329447746 Style: Points - Color Transformer: AxisColor + Topic: /scan + Unreliable: false + Use Fixed Frame: true + Use rainbow: true + Value: true + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 0.20000000298023224 + Min Value: 0.20000000298023224 + Value: true Axis: Z + Channel Name: intensity + Class: rviz/PointCloud2 + Color: 255; 255; 255 + Color Transformer: AxisColor Decay Time: 0 - - - Class: rviz/Map - Name: Map Enabled: true - Topic: /map + Invert Rainbow: false + Max Color: 255; 255; 255 + Min Color: 0; 0; 0 + Name: CloudAligned + Position Transformer: XYZ + Queue Size: 10 + Selectable: true + Size (Pixels): 3 + Size (m): 0.019999999552965164 + Style: Points + Topic: /perception/cloud_aligned + Unreliable: false + Use Fixed Frame: true + Use rainbow: true + Value: true + - Alpha: 0.699999988079071 + Class: rviz/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 + Name: Map + Topic: /map + Unreliable: false + Use Timestamp: false + Value: true + - Alpha: 1 + Class: rtabmap_rviz_plugins/MapGraph + Enabled: true + Global loop closure: 255; 0; 0 + Landmark: 0; 128; 0 + Local loop closure: 255; 255; 0 + Merged neighbor: 255; 170; 0 + Name: PoseGraph + Neighbor: 0; 0; 255 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 + Topic: /rtabmap/mapGraph + Unreliable: false + User: 255; 0; 0 + Value: true + Virtual: 255; 0; 255 + - Alpha: 1 + Buffer Length: 1 + Class: rviz/Path + Color: 255; 200; 0 Enabled: false - Topic: /rtabmap/cloud_map - Size (m): 0.03 - Style: Points - Color Transformer: FlatColor + Head Diameter: 0.30000001192092896 + Head Length: 0.20000000298023224 + Length: 0.30000001192092896 + Line Style: Lines + Line Width: 0.029999999329447746 + Name: MapPath + Offset: + X: 0 + Y: 0 + Z: 0 + Pose Color: 255; 85; 255 + Pose Style: None + Queue Size: 10 + Radius: 0.029999999329447746 + Shaft Diameter: 0.10000000149011612 + Shaft Length: 0.10000000149011612 + Topic: /rtabmap/mapPath + Unreliable: false + Value: false + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz/PointCloud2 Color: 90; 200; 220 + Color Transformer: FlatColor Decay Time: 0 - + Enabled: false + Invert Rainbow: false + Max Color: 255; 255; 255 + Min Color: 0; 0; 0 + Name: RtabmapCloud + Position Transformer: "" + Queue Size: 10 + Selectable: true + Size (Pixels): 3 + Size (m): 0.029999999329447746 + Style: Points + Topic: /rtabmap/cloud_map + Unreliable: false + Use Fixed Frame: true + Use rainbow: true + Value: false - 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 + Name: OctoMap + Namespaces: + {} + Queue Size: 100 + Value: false + - Angle Tolerance: 0.10000000149011612 + Class: rviz/Odometry Covariance: + Orientation: + Alpha: 0.5 + Color: 255; 255; 127 + Color Style: Unique + Frame: Local + Offset: 1 + Scale: 1 + Value: true + Position: + Alpha: 0.30000001192092896 + Color: 204; 51; 204 + Scale: 1 + Value: true Value: false - - - Class: rviz/Path - Name: GlobalPlan - Enabled: true - Topic: /move_base/NavfnROS/plan + Enabled: false + Keep: 1000 + Name: GroundTruth + Position Tolerance: 0.10000000149011612 + Queue Size: 10 + Shape: + Alpha: 1 + Axes Length: 1 + Axes Radius: 0.10000000149011612 + Color: 60; 255; 60 + Head Length: 0.30000001192092896 + Head Radius: 0.10000000149011612 + Shaft Length: 1 + Shaft Radius: 0.05000000074505806 + Value: Arrow + Topic: /ground_truth/odom + Unreliable: false + Value: false + - Alpha: 1 + Buffer Length: 1 + Class: rviz/Path Color: 60; 160; 255 - - - Class: rviz/Path - Name: LocalPlan Enabled: true - Topic: /move_base/TrajectoryPlannerROS/local_plan + Head Diameter: 0.30000001192092896 + Head Length: 0.20000000298023224 + Length: 0.30000001192092896 + Line Style: Lines + Line Width: 0.029999999329447746 + Name: GlobalPlan + Offset: + X: 0 + Y: 0 + Z: 0 + Pose Color: 255; 85; 255 + Pose Style: None + Queue Size: 10 + Radius: 0.029999999329447746 + Shaft Diameter: 0.10000000149011612 + Shaft Length: 0.10000000149011612 + Topic: /move_base/NavfnROS/plan + Unreliable: false + Value: true + - Alpha: 1 + Buffer Length: 1 + Class: rviz/Path Color: 255; 255; 60 - + Enabled: true + Head Diameter: 0.30000001192092896 + Head Length: 0.20000000298023224 + Length: 0.30000001192092896 + Line Style: Lines + Line Width: 0.029999999329447746 + Name: LocalPlan + Offset: + X: 0 + Y: 0 + Z: 0 + Pose Color: 255; 85; 255 + Pose Style: None + Queue Size: 10 + Radius: 0.029999999329447746 + Shaft Diameter: 0.10000000149011612 + Shaft Length: 0.10000000149011612 + Topic: /move_base/TrajectoryPlannerROS/local_plan + Unreliable: false + Value: true + Enabled: true + Global Options: + Background Color: 48; 48; 48 + Default Light: true + Fixed Frame: map + Frame Rate: 30 + Name: root Tools: - Class: rviz/MoveCamera - Class: rviz/Select - Class: rviz/SetInitialPose + Theta std deviation: 0.2617993950843811 Topic: /initialpose + X std deviation: 0.5 + Y std deviation: 0.5 - Class: rviz/SetGoal Topic: /move_base_simple/goal - + Value: true Views: Current: Class: rviz/Orbit - Name: Current View Distance: 14 + Enable Stereo Rendering: + Stereo Eye Separation: 0.05999999865889549 + Stereo Focal Distance: 1 + Swap Stereo Eyes: false + Value: false + Field of View: 0.7853981852531433 Focal Point: X: 0 Y: 0 Z: 0 - Pitch: 0.9 - Yaw: 1.6 + Focal Shape Fixed Size: true + Focal Shape Size: 0.05000000074505806 + Invert Z Axis: false + Name: Current View + Near Clip Distance: 0.009999999776482582 + Pitch: 0.8999999761581421 + Target Frame: + Yaw: 1.600000023841858 Saved: ~ - Window Geometry: - Height: 900 - Width: 1500 Displays: collapsed: false + Height: 974 + Hide Left Dock: false + Hide Right Dock: false + QMainWindow State: 000000ff00000000fd00000001000000000000018000000378fc0200000003fb000000100044006900730070006c006100790073010000003b0000019c000000c700fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007301000001dd000000c80000005c00fffffffb0000000a0056006900650077007301000002ab00000108000000a000ffffff0000023a0000037800000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 + Tool Properties: + collapsed: false + Views: + collapsed: false + Width: 960 + X: 960 + Y: 27 diff --git a/src/robot_bringup/scripts/teleop.py b/src/robot_bringup/scripts/teleop.py deleted file mode 100755 index d09b724..0000000 --- a/src/robot_bringup/scripts/teleop.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/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/scripts/virtual_joystick.py b/src/robot_bringup/scripts/virtual_joystick.py index 1e92739..d70f505 100755 --- a/src/robot_bringup/scripts/virtual_joystick.py +++ b/src/robot_bringup/scripts/virtual_joystick.py @@ -8,6 +8,25 @@ from tkinter import ttk import rospy from geometry_msgs.msg import Twist +# ⚠️ teleop_model la MODULE anh em, va catkin_install_python sinh ra RELAY chu +# khong copy file. Relay exec file nguon vao mot dict RIENG: +# +# context = {'__builtins__':…, '__file__': python_script, …} +# exec(compile(fh.read(), python_script, 'exec'), context) +# +# nen cac ten (TeleopModel) nam trong `context`, KHONG nam trong namespace cua +# module. Relay chay dung khi bi EXECUTE, hong khi bi IMPORT: +# ImportError: cannot import name 'TeleopModel' from 'teleop_model' +# +# Dat thu muc chua chinh file nay len DAU sys.path de import trung file THAT: +# devel : relay set __file__ = duong dan NGUON -> tro vao src/.../scripts, +# dat truoc devel nen file that thang relay +# install : __file__ = script da cai, va teleop_model.py duoc copy that +# nam ngay canh -> cung dung +import os +import sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + from teleop_model import TeleopModel diff --git a/src/robot_bringup/urdf/sensors.xacro b/src/robot_bringup/urdf/sensors.xacro index d2fc596..8dfcb3c 100644 --- a/src/robot_bringup/urdf/sensors.xacro +++ b/src/robot_bringup/urdf/sensors.xacro @@ -9,17 +9,24 @@ --> - + + - + - + diff --git a/src/robot_drivers/CMakeLists.txt b/src/robot_drivers/CMakeLists.txt index 9e71714..b0b0f80 100644 --- a/src/robot_drivers/CMakeLists.txt +++ b/src/robot_drivers/CMakeLists.txt @@ -11,18 +11,30 @@ find_package(catkin REQUIRED COMPONENTS std_msgs tf2 tf2_ros + filters + pluginlib ) catkin_package( + INCLUDE_DIRS include + LIBRARIES robot_drivers_scan_filters CATKIN_DEPENDS roscpp rospy sensor_msgs nav_msgs std_msgs tf2 tf2_ros + filters pluginlib ) -include_directories(${catkin_INCLUDE_DIRS}) +include_directories(include ${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}) +# Filter LaserScan rieng - sua header sai cua driver LakiBeam. +# Ten thu vien PHAI khop path trong scan_filters_plugins.xml: +# +add_library(robot_drivers_scan_filters src/scan_filters_plugins.cpp) +target_link_libraries(robot_drivers_scan_filters ${catkin_LIBRARIES}) +add_dependencies(robot_drivers_scan_filters ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + catkin_install_python(PROGRAMS scripts/imu_bridge_node.py DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} @@ -32,6 +44,19 @@ install(TARGETS wheel_odom_node RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) +install(TARGETS robot_drivers_scan_filters + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} +) + +install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} +) + +install(FILES scan_filters_plugins.xml + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} +) + install(DIRECTORY launch config DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} ) diff --git a/src/robot_drivers/config/scan_filter.yaml b/src/robot_drivers/config/scan_filter.yaml new file mode 100644 index 0000000..f36f721 --- /dev/null +++ b/src/robot_drivers/config/scan_filter.yaml @@ -0,0 +1,81 @@ +# ============================================================= +# Chuoi ve sinh LaserScan: /scan_raw -> /scan +# +# Chay GIONG HET NHAU o mo phong va tren phan cung that. Day la co y: +# moi thu tu lop odometry tro len khong duoc biet minh dang chay o dau. +# +# ⚠️ THU TU QUAN TRONG. header_fix PHAI dung dau: +# LaserScanAngularBoundsFilterInPlace blank tia bang `range_max + 1.0`. +# Neu no chay truoc header_fix thi sentinel la 101.0 (range_max doi cua +# driver) thay vi 41.0, va safety_monitor doc sai so tia bi blank. +# ============================================================= +scan_filter_chain: + + # ---- 1. Sua header sai cua driver ---- + # Xem robot_drivers/include/robot_drivers/scan_header_fix_filter.h + # va docs/HARDWARE.md muc 2 (3 bug cua driver). + # + # Trong mo phong cac gia tri nay VON DA dung (Gazebo khai that), nen filter + # chi la phep dong nhat. Van chay de chuoi hai ben giong nhau tuyet doi. + - name: header_fix + type: robot_drivers/ScanHeaderFixFilter + params: + range_min: 0.05 # datasheet LakiBeam 1L + range_max: 40.0 # >=40m @70% reflectivity + zero_is: "nan" # 0.0 = khong do duoc. Xem giai thich trong header. + fix_time_increment: true # go phep chia 2 thua cua driver + + # ---- 2 & 3. Cat cung bi THAN ROBOT che ---- + # + # LiDAR gan o x=0.24, than truoc x=0.14, nua rong y=+-0.17: + # atan2(0.17, 0.14 - 0.24) = 120.5 do + # Tia ngoai +-120.5 do dam vao chinh than robot. FOV that +-135 do + # => 14.5 do moi ben la rac, tong 29 do tren 270 (10.7%). + # + # Cat o 118 do, khong phai 120.5: chua 2.5 do dung sai ga. + # Con lai FOV huu dung ~236 do. + # + # ⚠️ Vi sao cat o day chu khong dat scan_range_start/stop cua driver: + # driver khai angle_min/max = +-180 do VO DIEU KIEN, ke ca khi + # scan_range_* da thu hep. Thu hep o driver khong sua duoc loi khai bao + # do, nen van phai cat o day. Xem docs/HARDWARE.md muc 2 bug 2. + # + # ⚠️ Filter nay blank tia NAM TRONG khoang [lower_angle, upper_angle]. + # Can HAI instance vi no chi cat duoc mot khoang lien tuc, ma vung can + # cat la hai nem o hai ben phia sau. + # + # ⚠️ Sau khi ga LiDAR that, PHAI kiem lai huong 0 do bang + # slam_eval/scripts/check_scan.py truoc khi tin hai con so nay. + # Cat nham quat truoc -> safety_monitor bao SCAN_SPARSE va robot dung. + - name: body_occlusion_left + type: laser_filters/LaserScanAngularBoundsFilterInPlace + params: + lower_angle: 2.0595 # +118 do + upper_angle: 3.2 # qua +180 do de chac chan het bien + + - name: body_occlusion_right + type: laser_filters/LaserScanAngularBoundsFilterInPlace + params: + lower_angle: -3.2 + upper_angle: -2.0595 # -118 do + + # ---- 4. (TAT) Loc speckle cho dropout cua ToF ---- + # + # ToF rot diem tren be mat den/bong (docs/HARDWARE.md muc 2), va speckle + # filter dung de don thu do. CHUA BAT vi hai ly do: + # + # 1. Chua doc duoc `update()` cua no ghi GIA TRI GI cho tia bi loai + # (nam trong .cpp cua lib, khong co trong header). Neu no ghi + # `range_max + 1.0` thi safety_monitor se dem nham thanh "bi blank" + # va co the bao SCAN_SPARSE oan. + # 2. max_range_difference phai tune theo thong ke dropout THAT, ma chua + # co du lieu phan cung nao. + # + # Bat sau khi da chay check_scan.py tren LiDAR that va xac minh ca hai diem. + # - name: speckle + # type: laser_filters/LaserScanSpeckleFilter + # params: + # filter_type: 0 + # max_range: 40.0 + # max_range_difference: 0.10 + # filter_window: 2 diff --git a/src/robot_drivers/include/robot_drivers/scan_header_fix_filter.h b/src/robot_drivers/include/robot_drivers/scan_header_fix_filter.h new file mode 100644 index 0000000..c2262d8 --- /dev/null +++ b/src/robot_drivers/include/robot_drivers/scan_header_fix_filter.h @@ -0,0 +1,151 @@ +/** + * scan_header_fix_filter - Sua header LaserScan cua driver LakiBeam chinh hang. + * + * ================== VI SAO PHAI CO FILE NAY ================== + * Driver RichbeamTechnology/Lakibeam_ROS1_Driver (package `lidar`) khai bao + * SAI ba thu trong moi ban tin. Da doc source de xac nhan: + * + * scan.range_min = 0.0; <- thiet bi that: 0.05 + * scan.range_max = 100.0; <- thiet bi that: 40.0 + * scan.time_increment = duration / num_readings / 2; <- thua phep chia 2 + * + * `range_min = 0.0` la cai nguy hiem nhat. Phep loc chuan cua MOI consumer la: + * + * if (r < msg->range_min) continue; // bo tia khong hop le + * + * Voi range_min = 0.0 thi `0.0 < 0.0` la SAI, nen mot tia bao 0.0 - von nghia + * la "khong do duoc" - duoc CHAP NHAN thanh mot vat can o ngay goc LiDAR. + * Hau qua: safety_monitor thay vat can 0.0m -> dung vinh vien; costmap ghi mot + * o LETHAL ngay duoi bung robot. + * + * Khong co plugin nao cua laser_filters lam duoc viec nay. laser_filters/ + * LaserScanRangeFilter chi ghi lai ranges[i], KHONG dung toi header (da doc + * /opt/ros/noetic/include/laser_filters/range_filter.h). + * + * ================== NGU NGHIA CUA TUNG LOAI TIA ================== + * Phan biet ba thu KHAC NHAU, dung gop lam mot: + * + * NaN = "khong do duoc" -> consumer bo qua, KHONG clear free space + * inf = "khong co gi trong tam" -> costmap voi inf_is_valid=true SE clear + * free space toi raytrace_range. Dung. + * so = khoang cach that + * + * ⚠️ Vi sao `zero_is` mac dinh la "nan" chu khong phai "inf": + * LiDAR UDP tra 0.0 cho CA HAI truong hop "khong co vat trong tam" VA "be mat + * den nuot het xung". Map 0.0 -> inf thi robot se clear free space XUYEN QUA + * ghe da den - dung cai ma docs/HARDWARE.md muc 2 canh bao la che do hong that + * cua ToF. Map -> NaN thi hong ve phia "coi nhu co vat", tuc an toan. + * raytrace_range chi 8m va trong nha gan nhu luon co vat trong 8m, nen mat mat + * gan nhu bang khong. + * + * ⚠️ KHONG dung phep chia 2 cua driver cho time_increment: bat ky ai deskew + * theo truong nay se chi bu duoc mot nua. + * + * ================== THU TU TRONG CHUOI ================== + * Filter nay PHAI dung DAU TIEN. LaserScanAngularBoundsFilterInPlace blank tia + * bang `input_scan.range_max + 1.0`; neu no chay truoc thi sentinel se la 101.0 + * thay vi 41.0, va safety_monitor (min_front_rays) doc sai. + */ + +#ifndef ROBOT_DRIVERS_SCAN_HEADER_FIX_FILTER_H +#define ROBOT_DRIVERS_SCAN_HEADER_FIX_FILTER_H + +#include +#include + +#include +#include +#include + +namespace robot_drivers +{ + +class ScanHeaderFixFilter : public filters::FilterBase +{ +public: + bool configure() override + { + getParam("range_min", range_min_); + getParam("range_max", range_max_); + getParam("fix_time_increment", fix_time_increment_); + + std::string zero_is = "nan"; + getParam("zero_is", zero_is); + zero_to_inf_ = (zero_is == "inf"); + + if (range_min_ <= 0.0 || range_max_ <= range_min_) + { + ROS_ERROR("scan_header_fix: range_min=%.3f range_max=%.3f khong hop le.", + range_min_, range_max_); + return false; + } + + ROS_INFO("scan_header_fix: ep header ve [%.3f, %.2f] m, 0.0 -> %s%s", + range_min_, range_max_, zero_to_inf_ ? "inf" : "NaN", + fix_time_increment_ ? ", sua time_increment" : ""); + return true; + } + + virtual ~ScanHeaderFixFilter() {} + + bool update(const sensor_msgs::LaserScan& input_scan, + sensor_msgs::LaserScan& filtered_scan) override + { + filtered_scan = input_scan; // giu nguyen stamp, angle_*, kich thuoc mang + + filtered_scan.range_min = static_cast(range_min_); + filtered_scan.range_max = static_cast(range_max_); + + if (fix_time_increment_ && !input_scan.ranges.empty()) + { + filtered_scan.time_increment = + input_scan.scan_time / static_cast(input_scan.ranges.size()); + } + + const float nan_v = std::numeric_limits::quiet_NaN(); + const float inf_v = std::numeric_limits::infinity(); + const float zero_v = zero_to_inf_ ? inf_v : nan_v; + + for (size_t i = 0; i < filtered_scan.ranges.size(); ++i) + { + const float r = filtered_scan.ranges[i]; + + if (std::isnan(r)) + continue; // da la "khong do duoc" + + if (r <= 0.0f) + { + filtered_scan.ranges[i] = zero_v; // 0.0 = khong do duoc / be mat den + continue; + } + + if (r < filtered_scan.range_min) + { + // Gan hon nguong tin cay cua thiet bi -> khong dung de do khoang cach. + // KHONG map sang inf: cho nay co the dang co vat that, chi la qua gan. + filtered_scan.ranges[i] = nan_v; + continue; + } + + if (r > filtered_scan.range_max) + { + // Ke ca inf san co. Nghia la "khong co gi trong tam" -> giu inf de + // costmap (inf_is_valid=true) clear free space nhu binh thuong. + filtered_scan.ranges[i] = inf_v; + continue; + } + } + + return true; + } + +private: + double range_min_ = 0.05; + double range_max_ = 40.0; + bool fix_time_increment_ = true; + bool zero_to_inf_ = false; +}; + +} // namespace robot_drivers + +#endif // ROBOT_DRIVERS_SCAN_HEADER_FIX_FILTER_H diff --git a/src/robot_drivers/launch/drivers.launch b/src/robot_drivers/launch/drivers.launch index f5bb316..e0a922b 100644 --- a/src/robot_drivers/launch/drivers.launch +++ b/src/robot_drivers/launch/drivers.launch @@ -17,9 +17,15 @@ - + + + diff --git a/src/robot_drivers/launch/scan_filter.launch b/src/robot_drivers/launch/scan_filter.launch new file mode 100644 index 0000000..794c918 --- /dev/null +++ b/src/robot_drivers/launch/scan_filter.launch @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + diff --git a/src/robot_drivers/package.xml b/src/robot_drivers/package.xml index c0ec4f8..745e4ba 100644 --- a/src/robot_drivers/package.xml +++ b/src/robot_drivers/package.xml @@ -19,5 +19,14 @@ tf2 tf2_ros + + filters + pluginlib + laser_filters + python3-serial + + + + diff --git a/src/robot_drivers/scan_filters_plugins.xml b/src/robot_drivers/scan_filters_plugins.xml new file mode 100644 index 0000000..5282084 --- /dev/null +++ b/src/robot_drivers/scan_filters_plugins.xml @@ -0,0 +1,11 @@ + + + + Sua range_min / range_max / time_increment ma driver LakiBeam chinh hang + khai sai, va chuan hoa ngu nghia tia: 0.0 -> NaN (khong do duoc), + qua tam -> inf (khong co gi trong tam). PHAI dung dau tien trong chuoi. + + + diff --git a/src/robot_drivers/src/scan_filters_plugins.cpp b/src/robot_drivers/src/scan_filters_plugins.cpp new file mode 100644 index 0000000..4df715e --- /dev/null +++ b/src/robot_drivers/src/scan_filters_plugins.cpp @@ -0,0 +1,13 @@ +/** + * Dang ky cac filter LaserScan rieng cua robot nay voi pluginlib. + * Xem include/robot_drivers/scan_header_fix_filter.h de biet vi sao can. + */ + +#include +#include +#include + +#include "robot_drivers/scan_header_fix_filter.h" + +PLUGINLIB_EXPORT_CLASS(robot_drivers::ScanHeaderFixFilter, + filters::FilterBase) diff --git a/src/robot_drivers/src/wheel_odom_node.cpp b/src/robot_drivers/src/wheel_odom_node.cpp index 4c06242..921b24a 100644 --- a/src/robot_drivers/src/wheel_odom_node.cpp +++ b/src/robot_drivers/src/wheel_odom_node.cpp @@ -66,7 +66,17 @@ public: // Slip detection pnh.param("slip_omega_threshold", slip_omega_threshold_, 0.15); // rad/s + // Chi con ap cho POSE covariance (sai so tich luy theo quang duong). + // Yaw-rate cua TWIST khong dung he so nay nua - xem khoi ghi chu o cho + // dat odom.twist.covariance[35]. pnh.param("slip_cov_multiplier", slip_cov_multiplier_, 100.0); + + // San do bat dinh yaw-rate khi banh va gyro dong y. Khong de 0 vi banh xe + // con sai so he thong (ban kinh / wheelbase chua hieu chuan UMBmark). + pnh.param("yaw_rate_sigma_floor", yaw_rate_sigma_floor_, 0.02); // rad/s + // Khong co gyro de doi chieu -> khong do duoc truot -> phai khai bao rong. + // Dat qua nho o day la bao EKF tin banh xe mu quang. + pnh.param("yaw_rate_sigma_no_imu", yaw_rate_sigma_no_imu_, 0.50); // rad/s pnh.param("imu_timeout", imu_timeout_, 0.5); // s // Covariance co ban. Cap nhat sau khi hieu chuan UMBmark. @@ -224,7 +234,31 @@ private: odom.twist.covariance[14] = 1e6; odom.twist.covariance[21] = 1e6; odom.twist.covariance[28] = 1e6; - odom.twist.covariance[35] = cov_yaw / (dt * dt); + + // ============ ⚠️ YAW-RATE: KHAI BAO DO BAT DINH DA DO ============ + // Khac cac thanh phan khac o tren: chung dung cov ty le quang duong roi + // nhan mot he so co dinh khi truot. Yaw-rate thi KHONG. + // + // Ly do: slip_metric = |omega_encoder - gyro_z| CHINH LA sai so cua phep + // do banh xe, do duoc tung chu ky. Lay no lam sigma la khai bao do bat + // dinh DA DO, thay vi mot he so doan truoc. + // + // Cach cu (cov_yaw/dt^2 voi he so co dinh 100) THIEU ~2 BAC. Da do khi + // robot xoay tai cho: + // sai so that : omega encoder -3.635 vs gyro -1.377 = 2.26 rad/s + // sigma khai bao: (0.02*0.02)^2 * 100 / 0.02^2 = 0.04 -> 0.2 rad/s + // EKF nhan mot diem 11-sigma ma van tin -> yaw troi. + // + // Hau qua da do o tang tren: global_scan_init ghep scan bang odom, nen sau + // khi xoay 301 do no khop ra HUONG SAI 40.8 do (vi tri van dung 0.17m). + // Khong xoay thi huong DUNG - vi khong tich luy sai so odom nao. + // + // ⚠️ San khi KHONG co gyro: luc do slip_metric = 0, va neu dung thang thi + // sigma = 0 -> EKF tin banh xe TUYET DOI, te hon ca truoc khi sua. + const double sigma_wr = imu_fresh + ? std::max(slip_metric, yaw_rate_sigma_floor_) + : yaw_rate_sigma_no_imu_; + odom.twist.covariance[35] = sigma_wr * sigma_wr; odom_pub_.publish(odom); @@ -237,6 +271,7 @@ private: 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 yaw_rate_sigma_floor_ = 0.02, yaw_rate_sigma_no_imu_ = 0.50; double sigma_x_, sigma_y_, sigma_yaw_; // Trang thai diff --git a/src/robot_safety/config/safety.yaml b/src/robot_safety/config/safety.yaml index 3a7dd4c..0384a90 100644 --- a/src/robot_safety/config/safety.yaml +++ b/src/robot_safety/config/safety.yaml @@ -15,8 +15,29 @@ safety_monitor: # Vat can hai ben khong can dung khan cap - de local planner lo. front_angle: 0.6 + # ============ KHONG TIN HEADER CUA DRIVER LiDAR ============ + # Driver LakiBeam chinh hang hardcode range_min = 0.0 (docs/HARDWARE.md muc 2, + # bug 3). Voi range_min = 0 thi phep loc `r < range_min` thanh `0.0 < 0.0` = + # SAI -> tia bao 0.0 duoc chap nhan -> SCAN_STOP vinh vien. + # scan_filter.launch da sua header, nhung lop an toan khong duoc phu thuoc + # vao mot node khac chay dung. + min_valid_range: 0.05 + + # ============ CHONG "QUAT TRUOC BI CAT MAT" ============ + # So tia toi thieu phai DUNG DUOC trong quat truoc. Duoi nguong nay -> dung + # va bao SCAN_SPARSE. + # + # "Dung duoc" = phu song va KHONG mang sentinel blank cua laser_filters + # (range_max + 1.0). Tia inf/NaN VAN tinh la dung duoc - sanh trong khong co + # phan xa la binh thuong, khong phai loi. + # + # Bat duoc: scan_filter cat nham bounds, hoac goc 0 do that cua driver khong + # nhu gia dinh -> quat truoc bi blank -> min_front = inf -> node se bao OK + # va cho robot chay het toc do vao tuong neu khong co check nay. + min_front_rays: 3 + # ============ SIEU AM: PHAT HIEN KINH ============ - # ⚠️ QUAN TRONG: LiDAR ToF 905nm XUYEN QUA kinh. Depth IR cung vay. + # ⚠️ QUAN TRONG: LiDAR ToF 940nm 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. @@ -31,6 +52,37 @@ safety_monitor: # - /ultrasonic/front_right ultrasonic_stop_distance: 0.30 + # ============ VUC / BAC THANG DI XUONG ============ + # Nguon: /perception/cliff_detected tu perception_3d/CliffDetectNodelet + # (chay tren anh depth - xem dau file nodelet do). + # + # Chan TIEN, van cho LUI va XOAY: vuc la thu robot tu thoat duoc, khac bumper + # (va cham da xay ra -> phai chot, phai co nguoi xac nhan). + # + # ⚠️⚠️ MU HOAN TOAN DUOI ~1.1 m. + # Camera z=0.80 chuc 15 do chi thay san tu 1.07 m tro ra. Phat hien tu + # 1.1-2.5m va dung thi DU khi robot tien thang toi mep, nhung KHONG DU khi: + # - robot xoay tai cho sat mep + # - robot tien sau khi da dung san trong vung mu + # Day KHONG phai lop bao ve day du. + enable_cliff_stop: true + cliff_timeout: 1.0 # s - khong co tin hieu moi thi coi nhu khong biet + + # ============ CAM BIEN VUC PHAN CUNG - CHUA MUA ============ + # 2-3 ToF/IR chuc xuong o mep truoc (~$3/con). Day la thu DUY NHAT phu duoc + # vung mu 0-1.1m cua camera. Xem docs/HARDWARE.md muc 3. + # + # ⚠️ PHAN CUC NGUOC VOI SIEU AM - dung tron hai danh sach: + # sieu am : kich khi range < nguong (co vat chan) + # vuc : kich khi range > nguong (san BIEN MAT) + # Nham cho la dao nguoc logic am tham, robot se lao thang xuong cau thang. + cliff_topics: [] + # Vi du khi da lap: + # cliff_topics: + # - /cliff/front_left + # - /cliff/front_right + cliff_expected_range: 0.85 # m - khoang cach toi san khi binh thuong + # Watchdog sensor_timeout: 1.0 # s - mat du lieu cam bien thi dung cmd_timeout: 0.5 # s - khong co lenh moi thi dung diff --git a/src/robot_safety/src/safety_monitor_node.cpp b/src/robot_safety/src/safety_monitor_node.cpp index 8395dd8..9d3ea30 100644 --- a/src/robot_safety/src/safety_monitor_node.cpp +++ b/src/robot_safety/src/safety_monitor_node.cpp @@ -16,7 +16,7 @@ * 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. + * 1. Sieu am -> KINH va GUONG. LiDAR ToF 940nm 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 @@ -56,6 +56,38 @@ public: pnh.param("front_angle", front_angle_, 0.6); // rad, +- pnh.param("ultrasonic_stop_distance", us_stop_distance_, 0.30); + + // ============ ⚠️ KHONG TIN HEADER CUA DRIVER ============ + // Driver LakiBeam chinh hang hardcode range_min = 0.0 (xem docs/HARDWARE.md + // muc 2, bug 3). Voi range_min = 0, phep loc chuan `r < msg->range_min` + // thanh `0.0 < 0.0` = SAI, nen mot tia bao 0.0 (nghia la "khong co so do") + // duoc CHAP NHAN -> scan_min_front_ = 0.0 -> SCAN_STOP vinh vien. + // + // scan_filter.launch da sua header roi, nhung node nay la lop an toan: + // no khong duoc phu thuoc vao viec mot node khac chay dung. + pnh.param("min_valid_range", min_valid_range_, 0.05); + + // ============ ⚠️ CHONG "QUAT TRUOC BI BLANK" ============ + // Chuoi laser_filters cat cung bi than robot che. Neu cau hinh sai bounds, + // hoac driver that doi goc 0 do, no co the blank NHAM quat phia truoc. + // Khi do min_front = +inf, node bao OK, va robot chay het toc vao tuong. + // + // Dem tia hop le trong quat truoc. Qua it = KHONG TIN DUOC, phai dung. + // Day la fail-safe cho mot loi fail-dangerous. + pnh.param("min_front_rays", min_front_rays_, 3); + + // ============ VUC / BAC THANG DI XUONG ============ + // Nguon: perception_3d/CliffDetectNodelet, chay tren anh depth. + // + // ⚠️ Node do MU HOAN TOAN duoi ~1.1m (hinh hoc camera: z=0.80 chuc 15 do + // chi thay san tu 1.07m). Phat hien tu 1.1-2.5m va dung thi DU khi tien + // thang, KHONG DU khi xoay tai cho sat mep hoac tien sau khi da dung + // trong vung mu. + // Chi cam bien ToF/IR chuc xuong o mep truoc moi phu duoc 0-1.1m - + // xem `cliff_topics` trong safety.yaml. + pnh.param("enable_cliff_stop", enable_cliff_stop_, true); + pnh.param("cliff_timeout", cliff_timeout_, 1.0); + pnh.param("sensor_timeout", sensor_timeout_, 1.0); pnh.param("cmd_timeout", cmd_timeout_, 0.5); pnh.param("max_linear", max_linear_, 0.7); @@ -70,6 +102,8 @@ public: 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); + cliff_sub_ = nh.subscribe("perception/cliff_detected", 1, + &SafetyMonitor::onCliff, this); for (const auto& t : us_topics) { @@ -105,18 +139,44 @@ private: void onScan(const sensor_msgs::LaserScan::ConstPtr& msg) { double min_front = std::numeric_limits::infinity(); + int front_rays = 0; // so tia PHU song quat truoc, bat ke do duoc gi + int front_blanked = 0; // so tia mang sentinel cua bo loc goc + + // Nguong duoi lay MAX cua hai nguon: cai driver khai, va cai ta biet la + // dung. Driver khai 0.0 thi ta van dung 0.05. Xem min_valid_range o onInit. + const double rmin = std::max(min_valid_range_, static_cast(msg->range_min)); 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; + + ++front_rays; const double r = msg->ranges[i]; - if (!std::isfinite(r) || r < msg->range_min || r > msg->range_max) + + // ⚠️ PHAN BIET "BI BLANK" VOI "KHONG CO GI TRONG TAM". + // laser_filters/LaserScanAngularBoundsFilterInPlace blank tia bang + // range_max + 1.0 - tuc HUU HAN va LON HON range_max. + // Tia khong co phan xa that thi la inf (Gazebo) hoac NaN (bo loc cua ta + // map 0.0 -> NaN). + // + // Neu dem nham hai thu nay lam mot thi robot dung giua sanh trong: + // khong vat nao trong 40 m -> moi tia inf -> "khong tia nao hop le". + if (std::isfinite(r) && r > msg->range_max) + { + ++front_blanked; continue; + } + + if (!std::isfinite(r) || r < rmin) + continue; // khong co phan xa, hoac qua gan -> khong dung de do + min_front = std::min(min_front, static_cast(r)); } + front_ray_count_ = front_rays; + front_blanked_count_ = front_blanked; scan_min_front_ = min_front; last_scan_time_ = ros::Time::now(); have_scan_ = true; @@ -134,6 +194,13 @@ private: have_bumper_ = true; } + void onCliff(const std_msgs::Bool::ConstPtr& msg) + { + cliff_ = msg->data; + last_cliff_time_ = ros::Time::now(); + have_cliff_ = true; + } + void onRange(const sensor_msgs::Range::ConstPtr& msg, const std::string& topic) { if (std::isfinite(msg->range) && msg->range >= msg->min_range) @@ -216,6 +283,27 @@ private: return; } + // --- VUC / BAC THANG --- + // ⚠️ KHONG chot (khong latch) nhu bumper: bumper la va cham DA XAY RA nen + // phai co nguoi xac nhan; vuc la thu robot co the tu lui ra khoi. Chot lai + // se lam robot ket cung truoc mep ma khong ai cuu. + // + // Chi chan TIEN, cho phep LUI va XOAY - do la duong thoat duy nhat. + if (enable_cliff_stop_ && have_cliff_ && cliff_ && + (now - last_cliff_time_).toSec() <= cliff_timeout_ && + last_cmd_.linear.x > 0.0) + { + out = last_cmd_; + out.linear.x = 0.0; // chan tien, giu angular de con xoay ra + out.angular.z = std::max(-max_angular_, std::min(max_angular_, out.angular.z)); + cmd_pub_.publish(out); + publishStatus("CLIFF_STOP"); + ROS_ERROR_THROTTLE(1.0, + "safety_monitor: VUC phia truoc - chan tien. Lui hoac xoay de thoat. " + "⚠️ Cam bien nay MU duoi ~1.1m."); + return; + } + // --- LiDAR --- if (have_scan_ && (now - last_scan_time_).toSec() > sensor_timeout_) { @@ -225,6 +313,27 @@ private: return; } + // --- Scan den deu nhung QUAT TRUOC BI CAT MAT --- + // Khac han SCAN_TIMEOUT: ban tin van toi dung nhip, chi la quat truoc + // khong con tia dung duoc. Hai nguyen nhan: + // front_ray_count_ thap -> angle_min/max khong phu quat truoc + // blanked ~ toan bo -> laser_filters cat nham bounds + // + // ⚠️ Sanh trong (moi tia inf) KHONG duoc tinh la loi: tia van phu song, + // chi la khong co phan xa. Do la ly do phai tru rieng phan bi blank. + const int front_usable = front_ray_count_ - front_blanked_count_; + if (have_scan_ && front_usable < min_front_rays_) + { + cmd_pub_.publish(out); + publishStatus("SCAN_SPARSE"); + ROS_ERROR_THROTTLE(2.0, + "safety_monitor: quat truoc chi con %d tia dung duoc (%d tia phu song, " + "%d bi blank; can >= %d) - KHONG TIN DUOC, dung. " + "Kiem tra scan_filter bounds va angle_offset.", + front_usable, front_ray_count_, front_blanked_count_, min_front_rays_); + return; + } + out = last_cmd_; std::string status = "OK"; @@ -255,12 +364,19 @@ private: double stop_distance_, slow_distance_, slow_factor_, front_angle_; double us_stop_distance_, sensor_timeout_, cmd_timeout_; double max_linear_, max_angular_; + double min_valid_range_ = 0.05; + int min_front_rays_ = 3; + bool enable_cliff_stop_ = true; + double cliff_timeout_ = 1.0; geometry_msgs::Twist last_cmd_; ros::Time last_cmd_time_, last_scan_time_, last_bumper_time_, last_us_time_; + ros::Time last_cliff_time_; bool have_cmd_ = false, have_scan_ = false, have_bumper_ = false; + bool have_cliff_ = false, cliff_ = false; double scan_min_front_ = std::numeric_limits::infinity(); + int front_ray_count_ = 0, front_blanked_count_ = 0; std::map us_ranges_; bool bumper_latched_ = false; @@ -268,7 +384,7 @@ private: std::string last_status_; ros::Publisher cmd_pub_, status_pub_; - ros::Subscriber cmd_sub_, scan_sub_, bumper_sub_; + ros::Subscriber cmd_sub_, scan_sub_, bumper_sub_, cliff_sub_; std::vector us_subs_; ros::ServiceServer reset_srv_, estop_srv_; ros::Timer timer_; diff --git a/src/robot_sim/launch/gazebo.launch b/src/robot_sim/launch/gazebo.launch index a807959..da1a36d 100644 --- a/src/robot_sim/launch/gazebo.launch +++ b/src/robot_sim/launch/gazebo.launch @@ -56,9 +56,15 @@ -> no nam NGOAI NHA. Do thoang khong phan biet duoc "giua phong" voi "ngoai troi"; phai dem huong co vat can moi biet. --> - - - + + + + diff --git a/src/robot_sim/urdf/gazebo_sensors.xacro b/src/robot_sim/urdf/gazebo_sensors.xacro index b4d9d12..1470a73 100644 --- a/src/robot_sim/urdf/gazebo_sensors.xacro +++ b/src/robot_sim/urdf/gazebo_sensors.xacro @@ -164,51 +164,73 @@ - + 0 0 0 0 0 0 false - 15 + 25 - 960 + 1081 1 - - -2.0944 - 2.0944 + + -2.356194 + 2.356194 0.05 - 30.0 + 40.0 0.01 gaussian 0.0 + 0.01 - /scan + /scan_raw laser_link diff --git a/src/robot_sim/worlds/cliff_test.world b/src/robot_sim/worlds/cliff_test.world new file mode 100644 index 0000000..8c07608 --- /dev/null +++ b/src/robot_sim/worlds/cliff_test.world @@ -0,0 +1,168 @@ + + + + + + model://sun + + + 0.001 + 1.0 + 1000 + + + + 0.6 0.6 0.6 1 + 0.8 0.8 0.85 1 + false + + + + + + true + + 0 0 -1.05 0 0 0 + + 60 60 0.1 + + + 60 60 0.1 + + 0.25 0.25 0.28 1 + 0.3 0.3 0.33 1 + + + + + + + + true + + -2 0 -0.5 0 0 0 + + 10 8 1.0 + + + 10 8 1.0 + + 0.7 0.7 0.68 1 + 0.8 0.8 0.78 1 + + + + + + + + + true + + 3.2 2.0 -0.5 0 0 0 + + 0.4 4 1.0 + + + 0.4 4 1.0 + + 0.02 0.02 0.02 1 + 0.03 0.03 0.03 1 + 0 0 0 1 + + + + + + + + + true + + -2 4.0 0.6 0 0 0 + + 10 0.2 1.2 + + + 10 0.2 1.2 + 0.6 0.6 0.65 1 + + + + + + true + + -2 -4.0 0.6 0 0 0 + + 10 0.2 1.2 + + + 10 0.2 1.2 + 0.6 0.6 0.65 1 + + + + + + true + + -7.0 0 0.6 0 0 0 + + 0.2 8 1.2 + + + 0.2 8 1.2 + 0.6 0.6 0.65 1 + + + + + + diff --git a/src/slam_eval/CMakeLists.txt b/src/slam_eval/CMakeLists.txt index 1978d09..4ac72d7 100644 --- a/src/slam_eval/CMakeLists.txt +++ b/src/slam_eval/CMakeLists.txt @@ -13,6 +13,10 @@ catkin_install_python(PROGRAMS scripts/check_tilt_tf.py scripts/check_reloc.py scripts/check_stereo.py + scripts/ate_table.py + scripts/check_scan.py + scripts/check_yaw_drift.py + scripts/check_initpose.py DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) diff --git a/src/slam_eval/config/topics_to_record.yaml b/src/slam_eval/config/topics_to_record.yaml index 3035b32..2b389b1 100644 --- a/src/slam_eval/config/topics_to_record.yaml +++ b/src/slam_eval/config/topics_to_record.yaml @@ -4,7 +4,8 @@ # cung dau vao; ghi ca dau ra chi lam phinh file ma khong so sanh duoc. raw_sensors: - - /scan # LiDAR 2D ToF + - /scan_raw # LiDAR 2D ToF - THO, truoc laser_filters + - /scan # sau chuoi ve sinh; ghi ca hai (xem record_bag.sh) - /imu/data_raw # ICM-42688-P - /joint_states # encoder banh xe (giao dien chung sim/that) - /baro/pressure # BMP390 - phat hien doi tang diff --git a/src/slam_eval/scripts/ate_table.py b/src/slam_eval/scripts/ate_table.py new file mode 100755 index 0000000..6b81e56 --- /dev/null +++ b/src/slam_eval/scripts/ate_table.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +""" +ate_table - Dung bang so sanh ATE tu cac file TUM da ghi. + +============ HAI COT, HAI CAU HOI KHAC NHAU ============ + odom_ do TF odom -> base_footprint = ODOMETRY THO + slam_ do TF map -> base_footprint = DAU RA SLAM + +Cot `slam` cua moi nguon se gan bang nhau, vi RTAB-Map khop ICP LiDAR moi giay +va keo tat ca ve cung mot cho. Cot `odom` moi la thu PHAN BIET duoc cac nguon. + +⚠️ RMSE tuyet doi chi so sanh duoc khi QUANG DUONG bang nhau. Bang nay in ca + quang duong va ty le RMSE/quang duong de doi chieu cho dung. + +Dung: + rosrun slam_eval ate_table.py + rosrun slam_eval ate_table.py --dir ~/projects/vSLAM_ws/results +""" + +import argparse +import glob +import math +import os +import sys + +try: + import numpy as np +except ImportError: + print('Thieu numpy: sudo apt install python3-numpy') + sys.exit(1) + + +def load(path): + D = [] + for ln in open(path): + v = ln.split() + if len(v) >= 8: + D.append((float(v[0]), float(v[1]), float(v[2]))) + return D + + +def umeyama(src, dst): + """Can chinh SE(2) toi uu (khong scale). Can vi goc toa do cua SLAM va cua + Gazebo khac nhau.""" + ms, md = src.mean(0), dst.mean(0) + H = (src - ms).T.dot(dst - md) + 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) + return R, md - R.dot(ms) + + +def ate(prefix, max_dt=0.05): + gp, ep = prefix + '_gt.tum', prefix + '_est.tum' + if not (os.path.exists(gp) and os.path.exists(ep)): + return None + gt, est = load(gp), load(ep) + if not gt or not est: + return None + + gt_t = np.array([g[0] for g in gt]) + pg, pe = [], [] + for e in est: + i = int(np.argmin(np.abs(gt_t - e[0]))) + if abs(gt_t[i] - e[0]) <= max_dt: + pg.append(gt[i]) + pe.append(e) + if len(pg) < 10: + return None + + G = np.array([[p[1], p[2]] for p in pg]) + E = np.array([[p[1], p[2]] for p in pe]) + R, t = umeyama(E, G) + err = np.linalg.norm(E.dot(R.T) + t - G, axis=1) + path = float(np.linalg.norm(np.diff(G, axis=0), axis=1).sum()) + return dict(n=len(pg), path=path, dur=est[-1][0] - est[0][0], + rmse=math.sqrt((err ** 2).mean()), + med=float(np.median(err)), + p95=float(np.percentile(err, 95)), + mx=float(err.max())) + + +# Ghi chu ve kha nang chuyen sang phan cung that. Xem docs/SIM_VS_REAL.md. +NOTE = { + 'wheel': 'moc so sanh', + 'icp': 'LiDAR thuan - KHONG dinh bay IR, so nay suy ra duoc cho doi that', + 'stereo': 'duong phan cung (emitter Off). Sim BI QUAN vi infra2 rot khung', + 'rgbd': 'CHI TRONG SIM - emitter Bat hong anh, emitter Tat hong depth', + 'rgbdicp': 'CHI TRONG SIM - phan rgbd da be tac', +} +ORDER = ['wheel', 'icp', 'stereo', 'rgbd', 'rgbdicp'] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--dir', default=os.path.expanduser( + '~/projects/vSLAM_ws/results')) + a, _ = ap.parse_known_args() + + found = sorted({os.path.basename(f).split('_', 1)[1].rsplit('_', 1)[0] + for f in glob.glob(os.path.join(a.dir, 'odom_*_gt.tum'))} | + {os.path.basename(f).split('_', 1)[1].rsplit('_', 1)[0] + for f in glob.glob(os.path.join(a.dir, 'slam_*_gt.tum'))}, + key=lambda s: ORDER.index(s) if s in ORDER else 99) + if not found: + print('Khong tim thay file nao trong %s' % a.dir) + print('Ky vong: odom__{gt,est}.tum va slam__{gt,est}.tum') + return 1 + + for title, pre in (('ODOMETRY THO (TF odom -> base_footprint)', 'odom'), + ('DAU RA SLAM (TF map -> base_footprint)', 'slam')): + print('') + print('=' * 88) + print(' ' + title) + print('=' * 88) + print('%-10s %6s %8s %9s %9s %9s %9s %9s' + % ('nguon', 'cap', 'duong(m)', 'RMSE', 'trung vi', 'P95', 'max', 'RMSE/duong')) + print('-' * 88) + rows = [] + for s in found: + r = ate(os.path.join(a.dir, '%s_%s' % (pre, s))) + if not r: + print('%-10s %s' % (s, '(chua co du lieu)')) + continue + rows.append((s, r)) + print('%-10s %6d %8.2f %9.4f %9.4f %9.4f %9.4f %8.3f%%' + % (s, r['n'], r['path'], r['rmse'], r['med'], r['p95'], r['mx'], + 100.0 * r['rmse'] / r['path'] if r['path'] > 0.1 else 0)) + # canh bao khi quang duong lech nhieu -> RMSE tuyet doi khong so duoc + if len(rows) > 1: + ps = [r['path'] for _, r in rows] + if max(ps) > 0 and (max(ps) - min(ps)) / max(ps) > 0.20: + print('') + print(' ⚠️ Quang duong lech qua 20%% (%.1f .. %.1f m).' % (min(ps), max(ps))) + print(' Doc cot RMSE/duong, DUNG doc cot RMSE.') + + print('') + print('GHI CHU VE KHA NANG DUNG TREN PHAN CUNG THAT') + print('-' * 88) + for s in found: + if s in NOTE: + print(' %-10s %s' % (s, NOTE[s])) + print('') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/src/slam_eval/scripts/check_initpose.py b/src/slam_eval/scripts/check_initpose.py new file mode 100755 index 0000000..63398fa --- /dev/null +++ b/src/slam_eval/scripts/check_initpose.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +""" +check_initpose - Cham diem /initialpose NGAY TAI THOI DIEM no duoc publish. + +============ VI SAO CAN ============ +check_reloc.py chi do SAI SO VI TRI. Da gap ca: vi tri dung 0.17-0.25 m nhung +HUONG lech hang chuc do, va check_reloc van bao "DA TIM LAI DUOC". + +Va suy yaw that tu "goc da quet" la de sai: robot dang xoay nen yaw that thay +doi lien tuc, phai lay dung yaw tai dung khoanh khac publish. Bo kiem nay lam +chinh xac viec do - khong suy dien, khong tinh tay. + +============ CACH DUNG ============ + PYTHONUNBUFFERED=1 rosrun slam_eval check_initpose.py --map-origin 4.0 14.0 0.0 + +In mot dong moi khi co /initialpose. Chay song song voi bai reloc. + +============ DOC KET QUA ============ + sai_yaw nho (< 5 do) -> huong dung, van de nam o cho khac + sai_yaw ~ hang chuc do, va |omega| lon luc do -> DO TRE (pose ghep voi mot + moc thoi gian sai khi robot dang quay) + sai_yaw ~ hang chuc do, nhung |omega| ~ 0 -> KHONG phai do tre, ma la + bo khop that su chon sai huong + +⚠️ /ground_truth/odom CHI de danh gia. Khong uoc luong nao duoc subscribe no. +""" + +import argparse +import math +import sys + +import rospy +from geometry_msgs.msg import PoseWithCovarianceStamped +from nav_msgs.msg import Odometry + + +def yaw_of(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)) + + +def wrap(a): + return math.atan2(math.sin(a), math.cos(a)) + + +class Checker(object): + def __init__(self, ox, oy, oyaw): + self.ox, self.oy, self.oyaw = ox, oy, oyaw + self.gt = None # (x, y, yaw) trong Gazebo + self.omega = 0.0 # toc do quay hien tai, rad/s + self.n = 0 + # ---- GD4: dem SO LAN DI CHUYEN ---- + # Mot "lan di chuyen" = robot roi trang thai dung yen, di duoc > move_min + # met, roi dung lai. Xoay tai cho KHONG tinh - do la ca muc tieu van + # hanh: tha xuong, xoay, phai dinh vi duoc ma khong phai lai di. + self.moving = False + self.move_acc = 0.0 # quang duong cua lan di hien tai + self.path = 0.0 # tong quang duong tu lan chot truoc + self.moves = 0 + self.prev = None + self.move_min = 0.15 # m, nho hon coi nhu run/truot + self.v_go, self.v_stop = 0.05, 0.02 # tre nguong, tranh dem nhay + rospy.Subscriber('/ground_truth/odom', Odometry, self.on_gt, queue_size=20) + rospy.Subscriber('/initialpose', PoseWithCovarianceStamped, + self.on_init, queue_size=10) + + def on_gt(self, m): + self.gt = (m.pose.pose.position.x, m.pose.pose.position.y, + yaw_of(m.pose.pose.orientation)) + self.omega = m.twist.twist.angular.z + + p = (m.pose.pose.position.x, m.pose.pose.position.y) + if self.prev is not None: + d = math.hypot(p[0] - self.prev[0], p[1] - self.prev[1]) + self.path += d + v = math.hypot(m.twist.twist.linear.x, m.twist.twist.linear.y) + if not self.moving and v > self.v_go: + self.moving, self.move_acc = True, 0.0 + elif self.moving: + self.move_acc += d + if v < self.v_stop: + self.moving = False + if self.move_acc > self.move_min: + self.moves += 1 + print(' [di chuyen lan %d: %.2f m]' + % (self.moves, self.move_acc)) + self.prev = p + + def on_init(self, m): + if self.gt is None: + rospy.logwarn('check_initpose: chua co /ground_truth/odom') + return + gx, gy, gyaw = self.gt + w = self.omega + + # Gazebo -> he ban do + c, s = math.cos(-self.oyaw), math.sin(-self.oyaw) + dx, dy = gx - self.ox, gy - self.oy + tx = c * dx - s * dy + ty = s * dx + c * dy + tyaw = wrap(gyaw - self.oyaw) + + px = m.pose.pose.position.x + py = m.pose.pose.position.y + pyaw = yaw_of(m.pose.pose.orientation) + + e_pos = math.hypot(px - tx, py - ty) + e_yaw = math.degrees(wrap(pyaw - tyaw)) + + self.n += 1 + print('') + print('--- /initialpose #%d ---' % self.n) + print(' publish : x=%8.3f y=%8.3f yaw=%8.2f do' % + (px, py, math.degrees(pyaw))) + print(' that : x=%8.3f y=%8.3f yaw=%8.2f do' % + (tx, ty, math.degrees(tyaw))) + print(' SAI : vi tri %.3f m | HUONG %+.2f do' % (e_pos, e_yaw)) + print(' omega luc do: %+.3f rad/s (%+.1f do/s)' % (w, math.degrees(w))) + print(' SO LAN DI CHUYEN toi khi chot: %d (tong duong di %.2f m)' + % (self.moves, self.path)) + if self.moves == 0: + print(' => chot duoc CHI BANG XOAY TAI CHO.') + self.moves, self.path = 0, 0.0 # dem lai cho lan chot sau + + if abs(e_yaw) < 5.0: + print(' => huong DUNG.') + elif abs(w) > 0.05: + print(' => huong sai VA robot dang quay %.1f do/s.' % math.degrees(w)) + print(' Do tre tuong duong: %.2f s. Nghi DO TRE.' + % (math.radians(abs(e_yaw)) / abs(w))) + else: + print(' => huong sai NHUNG robot DUNG YEN (omega ~ 0).') + print(' KHONG phai do tre - bo khop that su chon sai huong.') + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--map-origin', nargs=3, type=float, required=True, + metavar=('X', 'Y', 'YAW'), + help='pose trong Gazebo noi da BAT DAU QUET ban do') + args, _ = ap.parse_known_args() + + rospy.init_node('check_initpose', anonymous=True) + Checker(*args.map_origin) + print('check_initpose: dang cho /initialpose ... (Ctrl-C de thoat)') + rospy.spin() + return 0 + + +if __name__ == '__main__': + try: + sys.exit(main()) + except rospy.ROSInterruptException: + pass diff --git a/src/slam_eval/scripts/check_scan.py b/src/slam_eval/scripts/check_scan.py new file mode 100755 index 0000000..51fae21 --- /dev/null +++ b/src/slam_eval/scripts/check_scan.py @@ -0,0 +1,366 @@ +#!/usr/bin/env python3 +""" +check_scan.py - Soi mot topic LaserScan: header, cung mu, jitter timestamp. + +================== VI SAO CAN ================== +Driver LakiBeam chinh hang khai SAI header (xem docs/HARDWARE.md muc 2): + + 1. stamp = ros::Time::now() cua host, khong phai cua thiet bi + 2. angle_min/max = +-180 do VO DIEU KIEN, cho thiet bi chi quet 270 do + -> co ~90 do trong ban tin ma thiet bi KHONG HE quet. + CHUA BIET cai gi lap vao do, va dieu do quyet dinh cau hinh costmap. + 3. range_min = 0.0, range_max = 100.0 (that: 0.05 / 40) + +Script nay tra loi ba cau, va khong doan gi. + +================== DUNG NHU THE NAO ================== +Trong mo phong: + rosrun slam_eval check_scan.py # doc /scan + rosrun slam_eval check_scan.py --topic /scan_raw # truoc khi loc + +Tren phan cung that, CHAY TRUOC KHI TIN BAT KY DU LIEU NAO: + rosrun slam_eval check_scan.py --topic /scan_raw --samples 200 + +Robot phai DUNG YEN, va nen dat o giua phong de moi huong deu co tuong. + +================== DOC KET QUA ================== +Cung mu: tim bucket co ty le inf/nan/zero ~100%%. Neu no KHONG nam doi xung +phia sau thi `angle_offset` cua driver sai, va moi bounds trong +robot_drivers/config/scan_filter.yaml deu sai theo. + +⚠️ Neu cung mu day INF thi PHAI xu ly truoc khi chay nav: costmap_common.yaml +dat inf_is_valid: true, tuc costmap se raytrace-clear XUYEN TUONG suot cung do. + +Jitter stamp: nguong o max_vel_theta = 0.8 rad/s + 5 ms -> 0.23 do -> 4 cm sai o 10 m : chap nhan duoc + 20 ms -> 0.92 do -> 16 cm sai o 10 m : khong chap nhan, phai bu time offset +""" + +import argparse +import math +import sys +import time +from collections import defaultdict + +import rospy +from sensor_msgs.msg import LaserScan + + +class ScanChecker(object): + def __init__(self, topic, n_samples, bucket_deg): + self.topic = topic + self.n_samples = n_samples + self.bucket_deg = bucket_deg + + self.count = 0 + self.first = None + self.last_stamp = None + + # jitter giua cac ban tin lien tiep (chu ky den) + self.periods = [] + # lech giua stamp trong header va thoi diem nhan + self.stamp_lag = [] + + # thong ke theo bucket goc + self.bk_total = defaultdict(int) + self.bk_finite = defaultdict(int) + self.bk_zero = defaultdict(int) + self.bk_inf = defaultdict(int) + self.bk_nan = defaultdict(int) + self.bk_over = defaultdict(int) # huu han nhung > range_max + self.bk_ranges = defaultdict(list) + self.bk_intens = defaultdict(list) + + self.sub = rospy.Subscriber(topic, LaserScan, self.cb, queue_size=50) + + def bucket(self, angle_rad): + d = math.degrees(angle_rad) + return int(math.floor(d / self.bucket_deg)) * self.bucket_deg + + def cb(self, msg): + if self.count >= self.n_samples: + return + + now = rospy.Time.now() + if self.first is None: + self.first = msg + if self.last_stamp is not None: + self.periods.append((msg.header.stamp - self.last_stamp).to_sec()) + self.last_stamp = msg.header.stamp + # Bo qua khi thoi gian he thong dang la 0 (use_sim_time bat ma /clock + # chua toi) - luc do hieu so la rac. + if not now.is_zero(): + self.stamp_lag.append((now - msg.header.stamp).to_sec()) + + has_int = len(msg.intensities) == len(msg.ranges) + + for i, r in enumerate(msg.ranges): + a = msg.angle_min + i * msg.angle_increment + b = self.bucket(a) + self.bk_total[b] += 1 + + if r != r: # NaN + self.bk_nan[b] += 1 + elif math.isinf(r): + self.bk_inf[b] += 1 + elif r <= 0.0: + self.bk_zero[b] += 1 + elif r > msg.range_max: + self.bk_over[b] += 1 + else: + self.bk_finite[b] += 1 + self.bk_ranges[b].append(r) + if has_int: + self.bk_intens[b].append(msg.intensities[i]) + + self.count += 1 + + def done(self): + return self.count >= self.n_samples + + # ---------- in ket qua ---------- + + def report(self): + m = self.first + if m is None: + print("KHONG nhan duoc ban tin nao tren %s" % self.topic) + print("Kiem tra: rostopic list | grep scan") + return 1 + + n = len(m.ranges) + span = math.degrees(m.angle_max - m.angle_min) + inc = math.degrees(m.angle_increment) + + print("") + print("=" * 68) + print(" %s (%d ban tin)" % (self.topic, self.count)) + print("=" * 68) + print("") + print("--- HEADER ---") + print(" frame_id : %s" % m.header.frame_id) + print(" so tia : %d" % n) + print(" angle_min / max : %+8.3f / %+8.3f do" % + (math.degrees(m.angle_min), math.degrees(m.angle_max))) + print(" span : %8.3f do" % span) + print(" angle_increment : %8.4f do" % inc) + print(" range_min / max : %8.3f / %8.2f m" % (m.range_min, m.range_max)) + + # Doi chieu voi thiet bi that + print("") + print("--- DOI CHIEU LakiBeam 1L (270 do, 0.05-40 m, 0.25 do @25Hz) ---") + self._flag("span", span, 270.0, 1.0, + "driver khai 360 do cho thiet bi 270 -> co cung BIA RA") + self._flag("angle_increment", inc, 0.25, 0.01, "khong khop 0.25 do") + self._flag("range_min", m.range_min, 0.05, 0.001, + "range_min=0 lam vo hieu phep loc `r < range_min` o MOI consumer") + self._flag("range_max", m.range_max, 40.0, 0.1, "khong khop 40 m") + + # time_increment + print("") + print("--- THOI GIAN TRONG BAN TIN ---") + print(" scan_time : %.6f s" % m.scan_time) + print(" time_increment : %.9f s" % m.time_increment) + if n > 0: + expect = m.scan_time / float(n) + print(" scan_time / n_tia : %.9f s <- dung theo REP" % expect) + if m.time_increment > 0 and expect > 0: + ratio = expect / m.time_increment + if abs(ratio - 2.0) < 0.1: + print(" ⚠️ time_increment nho gap DOI muc dung - dung bug `/2`") + print(" cua driver. Ai deskew theo truong nay chi bu duoc mot nua.") + elif abs(ratio - 1.0) > 0.1: + print(" ⚠️ lech he so %.2f so voi muc dung" % ratio) + else: + print(" OK") + + # timestamp + print("") + print("--- TIMESTAMP ---") + if self.periods: + ps = sorted(self.periods) + mean = sum(ps) / len(ps) + p99 = ps[min(len(ps) - 1, int(0.99 * len(ps)))] + jit = [abs(p - mean) for p in ps] + jmean = sum(jit) / len(jit) + jp99 = sorted(jit)[min(len(jit) - 1, int(0.99 * len(jit)))] + print(" chu ky trung binh : %.4f s (%.2f Hz)" % + (mean, 1.0 / mean if mean > 0 else 0.0)) + print(" chu ky p99 : %.4f s" % p99) + print(" jitter mean / p99 : %.2f ms / %.2f ms" % (jmean * 1e3, jp99 * 1e3)) + self._jitter_verdict(jp99) + if self.stamp_lag: + ls = sorted(self.stamp_lag) + print(" now - stamp (p50) : %.2f ms" % (ls[len(ls) // 2] * 1e3)) + print(" (chi co nghia tren phan cung that; trong sim dung /clock)") + + # bucket + print("") + print("--- THEO BUCKET %d DO (0 do = huong TRUOC robot) ---" % self.bucket_deg) + print(" %8s %7s %6s %6s %6s %6s %6s %8s %8s %8s" % + ("goc", "tia", "do%", "zero%", "inf%", "nan%", "over%", + "min_m", "med_m", "med_int")) + blind = [] + for b in sorted(self.bk_total.keys()): + t = self.bk_total[b] + if t == 0: + continue + f, z, i_, na, ov = (self.bk_finite[b], self.bk_zero[b], self.bk_inf[b], + self.bk_nan[b], self.bk_over[b]) + rs = self.bk_ranges[b] + ints = self.bk_intens[b] + rmin = min(rs) if rs else float('nan') + rmed = sorted(rs)[len(rs) // 2] if rs else float('nan') + imed = sorted(ints)[len(ints) // 2] if ints else float('nan') + print(" %+4d..%+3d %7d %5.1f%% %5.1f%% %5.1f%% %5.1f%% %5.1f%% %8.2f %8.2f %8.1f" % + (b, b + self.bucket_deg, t, + 100.0 * f / t, 100.0 * z / t, 100.0 * i_ / t, + 100.0 * na / t, 100.0 * ov / t, rmin, rmed, imed)) + if f == 0: + blind.append((b, z, i_, na, ov, t)) + + self._blind_verdict(blind, span) + return 0 + + def _flag(self, name, got, want, tol, why): + ok = abs(got - want) <= tol + print(" %-16s %10.4f %s" % + (name, got, "OK" if ok else ("⚠️ mong doi %.4f - %s" % (want, why)))) + + def _jitter_verdict(self, jp99): + ms = jp99 * 1e3 + print("") + if ms < 5.0: + print(" => jitter p99 %.1f ms: CHAP NHAN DUOC" % ms) + print(" (0.8 rad/s x %.1f ms = %.2f do = %.1f cm o 10 m)" % + (ms, math.degrees(0.8 * jp99), 0.8 * jp99 * 10.0 * 100)) + elif ms < 20.0: + print(" => jitter p99 %.1f ms: RANH GIOI. Do lai khi robot DANG CHAY." % ms) + else: + print(" => ⚠️ jitter p99 %.1f ms: QUA LON." % ms) + print(" 0.8 rad/s x %.1f ms = %.2f do = %.1f cm sai o 10 m." % + (ms, math.degrees(0.8 * jp99), 0.8 * jp99 * 10.0 * 100)) + print(" Phai bu time offset (ROADMAP GD2) truoc khi tin scan matching.") + + def _blind_verdict(self, blind, span): + print("") + print("--- KET LUAN ---") + if span > 300.0: + print(" ⚠️ span %.1f do > FOV that 270 do." % span) + print(" Driver dang khai mot cung MA THIET BI KHONG QUET.") + if not blind: + print(" Khong co bucket nao trong hoan toan.") + print(" (Dat robot giua phong de moi huong deu co tuong thi ket qua ro hon.)") + return + + print(" Bucket KHONG co tia do duoc nao:") + for b, z, i_, na, ov, t in blind: + parts = [] + if z: + parts.append("zero %.0f%%" % (100.0 * z / t)) + if i_: + parts.append("inf %.0f%%" % (100.0 * i_ / t)) + if na: + parts.append("nan %.0f%%" % (100.0 * na / t)) + if ov: + parts.append("over-range %.0f%%" % (100.0 * ov / t)) + print(" %+4d..%+3d do : %s" % (b, b + self.bucket_deg, ", ".join(parts))) + + tot_inf = sum(x[2] for x in blind) + tot_zero = sum(x[1] for x in blind) + tot_over = sum(x[4] for x in blind) + + print("") + if tot_inf > 0: + print(" ⚠️⚠️ CUNG MU DAY `inf`.") + print(" costmap_common.yaml dat inf_is_valid: true -> costmap se") + print(" RAYTRACE-CLEAR XUYEN TUONG suot cung nay, moi scan.") + print(" PHAI cat cung do trong robot_drivers/config/scan_filter.yaml") + print(" truoc khi chay nav.") + if tot_zero > 0: + print(" Cung mu day `0.0`. ScanHeaderFixFilter se doi thanh NaN") + print(" (zero_is: nan) - an toan. Kiem lai tren /scan sau khi loc.") + if tot_over > 0: + print(" Cung mu day gia tri > range_max - day la sentinel cua") + print(" LaserScanAngularBoundsFilterInPlace. Dung nhu mong doi tren /scan.") + + print("") + print(" ⚠️ Kiem cung mu co DOI XUNG QUANH 180 do khong (tuc phia sau).") + print(" Neu no lech - vi du nam quanh 0 do - thi `angle_offset` cua") + print(" driver sai, va moi bounds trong scan_filter.yaml sai theo.") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument('--topic', default='/scan') + ap.add_argument('--samples', type=int, default=50) + ap.add_argument('--bucket', type=int, default=30, help='do rong bucket goc, do') + ap.add_argument('--timeout', type=float, default=30.0) + args, _ = ap.parse_known_args() + + rospy.init_node('check_scan', anonymous=True) + ck = ScanChecker(args.topic, args.samples, args.bucket) + + print("Dang doc %s ... (%d ban tin, toi da %.0f s)" % + (args.topic, args.samples, args.timeout)) + print("Robot nen DUNG YEN, dat o giua phong.") + sys.stdout.flush() + + # ⚠️ DUNG WALL CLOCK, KHONG dung rospy.Time.now(). + # + # Voi use_sim_time=true ma /clock khong publish (gazebo chet, hoac con mot + # gzserver mo coi khong chay world), rospy.Time.now() DONG BANG o 0: + # - (now - t0).to_sec() luon = 0 -> timeout khong bao gio kich + # - rospy.Rate.sleep() -> chan VINH VIEN + # Script se treo im thay vi bao loi. Cong cu chan doan khong duoc phep + # phu thuoc vao chinh thu no dang di chan doan. + t0 = time.monotonic() + last_tick = 0 + while not rospy.is_shutdown() and not ck.done(): + elapsed = time.monotonic() - t0 + if elapsed > args.timeout: + print("\nHet gio sau %d ban tin." % ck.count) + break + # Dau hieu song, de phan biet "dang cho" voi "treo" + if int(elapsed) > last_tick: + last_tick = int(elapsed) + if ck.count == 0 and last_tick % 5 == 0: + print(" ... %ds, chua nhan duoc ban tin nao tren %s" + % (last_tick, args.topic)) + sys.stdout.flush() + time.sleep(0.1) + + if ck.count == 0: + diagnose_silence(args.topic) + + return ck.report() + + +def diagnose_silence(topic): + """Khong nhan duoc gi - chi ro cho hong thay vi de nguoi dung tu doan.""" + print("") + print("--- VI SAO KHONG CO DU LIEU ---") + try: + import rosgraph + master = rosgraph.Master('/check_scan') + pubs = dict(master.getPublishedTopics('')) + if topic not in pubs: + print(" %s KHONG co trong danh sach topic." % topic) + sim = rospy.get_param('/use_sim_time', False) + if sim and '/clock' not in pubs: + print(" ⚠️ /use_sim_time = true NHUNG /clock khong co publisher.") + print(" Gazebo da chet, hoac con mot gzserver MO COI khong chay world.") + print(" Sua: pkill -f gzserver; pkill -f gzclient") + print(" roslaunch robot_bringup sim.launch world:=") + elif topic == '/scan': + print(" Co /scan_raw khong? Neu co ma khong co /scan thi chuoi") + print(" laser_filters chua len - xem node scan_filter.") + except Exception as e: + print(" (khong chan doan them duoc: %s)" % e) + + +if __name__ == '__main__': + try: + sys.exit(main()) + except rospy.ROSInterruptException: + pass diff --git a/src/slam_eval/scripts/check_stereo.py b/src/slam_eval/scripts/check_stereo.py index 3928532..8934d18 100755 --- a/src/slam_eval/scripts/check_stereo.py +++ b/src/slam_eval/scripts/check_stereo.py @@ -42,6 +42,7 @@ class Side(object): self.info = None self.n_img = 0 self.stamps = [] + self.last = None # (stamp, bytes) de so noi dung hai anh rospy.Subscriber(ns + '/camera_info', CameraInfo, self._on_info, queue_size=5) rospy.Subscriber(ns + '/image_rect_raw', Image, @@ -53,6 +54,8 @@ class Side(object): def _on_img(self, m): self.n_img += 1 self.stamps.append(m.header.stamp.to_sec()) + self.last = (m.header.stamp.to_sec(), m.width, m.height, m.step, + m.encoding, m.data) def main(): @@ -200,6 +203,51 @@ def main(): print(' khong du mau') fail += 1 + # ---- 5. HAI ANH CO THAT SU KHAC NHAU KHONG ---- + # ⚠️ Day la phep kiem quan trong nhat va de bo sot nhat. + # camera_info co the hoan toan dung (P[3] chuan, baseline chuan) trong khi + # HAI ANH LA MOT - vi du khi cua sensor bi Gazebo bo qua. Khi do + # disparity = 0 o moi diem -> do sau vo cuc -> stereo_odometry bao + # "Not enough inliers 0/20 (matches=28)" + # tuc van khop duoc dac trung nhung khong cai nao qua kiem tra hinh hoc. + print('\n5. HAI ANH CO KHAC NHAU KHONG <- de bo sot nhat') + if L.last and R.last: + ls, lw, lh, lstep, lenc, ldata = L.last + rs, rw, rh, rstep, renc, rdata = R.last + print(' trai %dx%d %s %d byte' % (lw, lh, lenc, len(ldata))) + print(' phai %dx%d %s %d byte' % (rw, rh, renc, len(rdata))) + if bytes(ldata) == bytes(rdata): + print(' ❌ HAI ANH GIONG HET TUNG BYTE -> khong phai cap stereo.') + print(' disparity = 0 khap noi -> do sau vo cuc -> 0 inlier.') + print(' Nghi cua sensor infra2 khong duoc ap dung.') + fail += 1 + else: + # Uoc luong disparity tho: truot hang giua cua anh trai tren anh phai, + # tim do dich cho tong sai lech tuyet doi nho nhat. + row = lh // 2 + n = min(lw, rw) + lrow = bytes(ldata)[row * lstep: row * lstep + n] + rrow = bytes(rdata)[row * rstep: row * rstep + n] + best, bd = None, 0 + for d in range(0, 64): + m = n - d + if m < 32: + break + s = sum(abs(lrow[i + d] - rrow[i]) for i in range(0, m, 4)) + if best is None or s < best: + best, bd = s, d + print(' khac nhau. Disparity uoc luong o hang giua: %d px' % bd) + if bd == 0: + print(' ⚠️ disparity 0 -> hai goc nhin gan nhu trung nhau.') + fail += 1 + else: + fx = L.info.P[0] + z = fx * a.baseline / bd if bd else float('inf') + print(' -> ung voi do sau ~%.2f m. Hop ly thi cap stereo dung.' % z) + else: + print(' khong nhan du anh de so') + fail += 1 + print('=' * 70) print('KET LUAN:', 'DAT - chay stereo_odometry duoc' if fail == 0 else 'CHUA DAT - %d van de' % fail) diff --git a/src/slam_eval/scripts/check_yaw_drift.py b/src/slam_eval/scripts/check_yaw_drift.py new file mode 100755 index 0000000..99583c9 --- /dev/null +++ b/src/slam_eval/scripts/check_yaw_drift.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +""" +check_yaw_drift - Do sai so YAW cua odometry so voi ground truth. + +============ VI SAO CAN ============ +global_scan_init gom scan trong he `odom` roi khop dam may do vao ban do. +Cach do gia dinh odom yaw CHINH XAC suot ca qua trinh gom +(global_scan_init.py:231 ghi thang: "odometry rat chinh xac nen phep gom nay sach"). + +Da do: xoay tai cho roi khop cho ra HUONG SAI 40.8 do (xoay 301) va 159.6 do +(xoay 181). Xoay 0 do thi huong DUNG chinh xac. + +Hai kha nang, can hai cach sua khac han: + 1. odom yaw TROI -> dam may bi boi nhoe -> phai sua tang uoc luong + 2. odom yaw ON -> ban than bo khop chon sai huong tren dam may 360 do + (xoay du vong thi dam may gan doi xung quay -> da cuc tri) + +Bo kiem nay tra loi dut khoat cau hoi do: neu sau khi xoay 180 do ma sai so yaw +chi vai do thi odom KHONG PHAI thu phai sua. + +============ CACH DUNG ============ + 1. Chay sim (bat ky world nao co /ground_truth/odom): + roslaunch robot_bringup perception.launch world:=restaurant + 2. Bo kiem: + PYTHONUNBUFFERED=1 rosrun slam_eval check_yaw_drift.py + 3. XOAY ROBOT TAI CHO mot huong, lien tuc, it nhat 2 vong. + 4. Ctrl-C de xem tong ket. + +⚠️ /ground_truth/odom CHI de danh gia. Khong uoc luong nao duoc subscribe no. +""" + +import argparse +import math +import sys + +import rospy +from nav_msgs.msg import Odometry + + +def yaw_of(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)) + + +def unwrap(prev, cur): + """Go goc de dem duoc tong goc da quay vuot qua +-180 do.""" + d = cur - prev + while d > math.pi: + d -= 2.0 * math.pi + while d < -math.pi: + d += 2.0 * math.pi + return d + + +class YawDrift(object): + def __init__(self, odom_topic, gt_topic): + self.o_yaw = None + self.g_yaw = None + self.o_acc = 0.0 # tong goc odom da quay (khong goi) + self.g_acc = 0.0 # tong goc that da quay + self.o_prev = None + self.g_prev = None + self.off = None # lech ban dau, tru di de chi con TROI + self.rows = [] + rospy.Subscriber(odom_topic, Odometry, self.on_odom, queue_size=20) + rospy.Subscriber(gt_topic, Odometry, self.on_gt, queue_size=20) + + def on_odom(self, m): + y = yaw_of(m.pose.pose.orientation) + if self.o_prev is not None: + self.o_acc += unwrap(self.o_prev, y) + self.o_prev = y + self.o_yaw = y + + def on_gt(self, m): + y = yaw_of(m.pose.pose.orientation) + if self.g_prev is not None: + self.g_acc += unwrap(self.g_prev, y) + self.g_prev = y + self.g_yaw = y + + def ready(self): + return self.o_yaw is not None and self.g_yaw is not None + + def sample(self, t): + if not self.ready(): + return + if self.off is None: + # Odom bat dau tu 0, ground truth bat dau tu yaw spawn. Tru lech + # ban dau di de chi con lai phan TROI. + self.off = self.g_yaw - self.o_yaw + err = self.g_yaw - (self.o_yaw + self.off) + err = math.atan2(math.sin(err), math.cos(err)) + self.rows.append((t, math.degrees(self.g_acc), math.degrees(self.o_acc), + math.degrees(err))) + print('%7.1f %12.1f %12.1f %11.2f' % + (t, math.degrees(self.g_acc), math.degrees(self.o_acc), + math.degrees(err))) + + def report(self): + print('') + print('=' * 64) + print(' SAI SO YAW CUA ODOMETRY') + print('=' * 64) + if not self.rows: + print(' Khong co du lieu. Sim da chay chua?') + print(' Can CA HAI: /odometry/filtered va /ground_truth/odom') + return 1 + errs = [abs(r[3]) for r in self.rows] + errs_s = sorted(errs) + gt_total = self.rows[-1][1] + od_total = self.rows[-1][2] + print(' Goc that da quay : %8.1f do' % gt_total) + print(' Goc odom bao da quay : %8.1f do' % od_total) + print(' Lech tong goc : %8.1f do' % (od_total - gt_total)) + print(' ---------------------------------------------') + print(' Sai so yaw | trung vi : %8.2f do' % errs_s[len(errs_s) // 2]) + print(' | p95 : %8.2f do' % errs_s[int(0.95 * (len(errs_s) - 1))]) + print(' | max : %8.2f do' % errs_s[-1]) + print('=' * 64) + print('') + if errs_s[-1] < 5.0: + print(' => Odom yaw TOT (max < 5 do).') + print(' Neu global_scan_init van khop ra huong sai thi loi KHONG') + print(' nam o odometry - no nam o chinh bo khop.') + elif errs_s[-1] < 20.0: + print(' => Odom yaw troi VUA (max %.1f do).' % errs_s[-1]) + print(' Du gay lech dam may nhung chua giai thich duoc sai so') + print(' 40-160 do da quan sat. Kha nang ca hai nguyen nhan.') + else: + print(' => Odom yaw TROI NANG (max %.1f do).' % errs_s[-1]) + print(' Day la nguyen nhan: dam may gom trong he odom bi boi') + print(' nhoe theo goc, bo khop an phai du lieu meo.') + return 0 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--odom', default='/odometry/filtered') + ap.add_argument('--gt', default='/ground_truth/odom') + ap.add_argument('--rate', type=float, default=2.0) + args, _ = ap.parse_known_args() + + rospy.init_node('check_yaw_drift', anonymous=True) + ck = YawDrift(args.odom, args.gt) + + print('Dang doi %s va %s ...' % (args.odom, args.gt)) + print('XOAY ROBOT TAI CHO mot huong, it nhat 2 vong. Ctrl-C de tong ket.') + print('') + print('%7s %12s %12s %11s' % ('t(s)', 'that(do)', 'odom(do)', 'sai so(do)')) + + t0 = rospy.Time.now() + r = rospy.Rate(args.rate) + try: + while not rospy.is_shutdown(): + ck.sample((rospy.Time.now() - t0).to_sec()) + r.sleep() + except rospy.ROSInterruptException: + pass + return ck.report() + + +if __name__ == '__main__': + try: + sys.exit(main()) + except rospy.ROSInterruptException: + pass diff --git a/src/slam_eval/scripts/record_bag.sh b/src/slam_eval/scripts/record_bag.sh index 99d1890..56a2f42 100644 --- a/src/slam_eval/scripts/record_bag.sh +++ b/src/slam_eval/scripts/record_bag.sh @@ -25,6 +25,15 @@ mkdir -p "$OUTDIR" TOPICS=( # ---- Cam bien tho ---- + # /scan_raw la DU LIEU THO that su. /scan la dau ra da qua chuoi + # laser_filters (robot_drivers/launch/scan_filter.launch). + # + # Ghi CA HAI, co y: + # /scan_raw -> chay lai duoc voi bounds/nguong filter KHAC, va la thu duy + # nhat cho phep chan doan mot cai cat goc sai sau su co + # /scan -> tai tao duoc dung canh ma SLAM da thuc su nhin thay + # LaserScan nho (~9 kB/ban tin) nen ghi ca hai khong dang ke. + /scan_raw /scan /imu/data_raw /joint_states