ros2机器开发人员必看,如何配置环境让人工智能全程参与开发第一部分,初始化环境

我们在开发机器人的时候,如果全程让人工智能与,我们第一步是环境要给大模型初始化好,避免进程在等待,或因权限原因ai 不能办到换一个方法实现现,无数次
偿试浪费token ,所以我们得在环境上就规范起来,这样才有更好的开发环境,

!/bin/bash

set -e

echo ""
echo " ROS2 Humble 完整安装脚本 (Ubuntu 22.04)"
echo "
"

设置 locale

echo "[1/8] 配置 locale..."
sudo apt update
sudo apt install -y locales
sudo locale-gen en_US en_US.UTF-8
sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
export LANG=en_US.UTF-8

确保 universe 仓库已启用

echo "[2/8] 启用 universe 仓库..."
sudo apt install -y software-properties-common
sudo add-apt-repository universe -y

添加 ROS2 GPG 密钥

echo "[3/8] 添加 ROS2 GPG 密钥..."
sudo apt install -y curl gnupg lsb-release
sudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpg

添加 ROS2 源

echo "[4/8] 添加 ROS2 apt 源..."
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/ros-archive-keyring.gpg] http://packages.ros.org/ros2/ubuntu $(. /etc/os-release && echo $UBUNTU_CODENAME) main" | sudo tee /etc/apt/sources.list.d/ros2.list > /dev/null

更新包索引

echo "[5/8] 更新 apt 包索引..."
sudo apt update

安装 ROS2 Humble 完整桌面版(desktop-full)

echo "[6/8] 安装 ROS2 Humble Desktop Full(完整安装,这可能需要较长时间)..."
sudo apt install -y ros-humble-desktop-full

安装开发工具

echo "[7/8] 安装 ROS2 开发工具(colcon、rosdep 等)..."
sudo apt install -y ros-dev-tools
sudo apt install -y python3-colcon-common-extensions

初始化 rosdep

echo "[8/8] 初始化 rosdep..."
sudo rosdep init 2>/dev/null || true
rosdep update

配置环境变量到 .bashrc

echo "" >> ~/.bashrc
echo "# ROS2 Humble 环境配置" >> ~/.bashrc
echo "source /opt/ros/humble/setup.bash" >> ~/.bashrc
echo "export LANG=en_US.UTF-8" >> ~/.bashrc

立即加载环境

source /opt/ros/humble/setup.bash

echo ""
echo ""
echo " ROS2 Humble 安装完成!"
echo "
"
echo ""
echo "已安装内容:"
echo " - ros-humble-desktop-full(完整桌面版)"
echo " - ros-dev-tools(开发工具)"
echo " - python3-colcon-common-extensions(colcon 构建工具)"
echo " - rosdep(依赖管理工具)"
echo ""
echo "环境已自动配置到 ~/.bashrc"
echo "新终端会自动加载 ROS2 环境"
echo ""
echo "验证安装:"
ros2 --version 2>/dev/null || echo "(需要新开终端或执行: source ~/.bashrc)"
echo ""
echo "常用命令:"
echo " ros2 run 运行节点"
echo " ros2 launch 启动 launch 文件"
echo " ros2 topic list 查看话题列表"
echo " colcon build 编译工作空间"

New System Setup Guide

Rule: First configure the development environment, then write code.


详细初始化空间

New System Setup Guide

Core Rule: First configure the environment, then write code.

Why this matters: When the environment is not properly configured, AI coding assistants
waste massive amounts of tokens on retry loops. A task that should take 3 commands
turns into 30 failed attempts. This guide eliminates ALL common environment issues
so that every command succeeds on the first try.

Do this FIRST after every fresh OS install. No exceptions.


Problem Statement

When the development environment is misconfigured, these symptoms appear:

Symptom Root Cause Token Waste
AI retries the same command 5+ times sudo waits for password silently (non-interactive SSH cannot prompt) Huge
Chinese output is garbled ??? or ?? PowerShell not set to UTF-8 Medium
Every SSH command fails with "forbidden" PowerShell execution policy is Restricted Huge
SSH hangs forever during apt install Connection killed by firewall/NAT timeout Huge
SSH refuses to connect after VM reinstall Host key changed, strict checking blocks it Medium
AI tries pip install but wrong Python No conda/venv configured, system Python conflicts Medium
git clone asks for credentials every time Git credential helper not configured Medium
AI cannot read error messages Encoding mismatch hides real errors Huge

The pattern is always the same: environment issue -> command fails -> AI retries -> user confused -> more retries -> tokens wasted.

This guide fixes ALL of these in one shot.


Phase 1: Windows PowerShell Environment

1.1 Script Execution Policy

Problem: Windows defaults to Restricted, blocking ALL .ps1 scripts including your own profile. Every PowerShell window shows red errors before you even start.

Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -Force

Verify:

Get-ExecutionPolicy -Scope CurrentUser
# Should output: RemoteSigned

1.2 UTF-8 Encoding (Fix Chinese Garbled Output)

Problem: PowerShell defaults to the system locale encoding (e.g., GBK on Chinese Windows). When AI tools output UTF-8 text (which is the standard), Chinese characters appear as ??? or garbled symbols. The AI cannot read its own error messages and keeps retrying blindly.

Step 1: Enable system-wide UTF-8 (requires reboot):

# Enable UTF-8 system-wide in Windows Region settings
# This sets the system locale code page to 65001 (UTF-8)
Set-WinSystemLocale -SystemLocale en-US
# Or for Chinese locale with UTF-8:
# Control Panel -> Region -> Administrative -> Change system locale -> Beta: Use Unicode UTF-8

Note: The GUI method is more reliable:
Control Panel -> Region -> Administrative tab -> Change system locale... -> Check Beta: Use Unicode UTF-8 for worldwide language support -> Reboot.

Step 2: Create PowerShell profile with UTF-8 config:

# Create profile directory if it doesn't exist
New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\Documents\WindowsPowerShell" | Out-Null

# Create/edit the profile file
notepad "$env:USERPROFILE\Documents\WindowsPowerShell\profile.ps1"

Paste this content (comments MUST be in English - Chinese comments in profile.ps1 cause garbled output even with UTF-8 enabled):

# === UTF-8 Encoding ===
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

# === Fix chcp code page ===
chcp 65001 | Out-Null

# === Conda Initialize (adjust path to your installation) ===
#region conda initialize
$condaPath = "D:\ProgramData\anaconda3\Scripts\conda.exe"
If (Test-Path $condaPath) {
    (& $condaPath "shell.powershell" "hook") | Out-String | Where-Object { $_ } | Invoke-Expression
}
#endregion

Verify: Close and reopen PowerShell, then:

[Console]::OutputEncoding
# Should show: System.Text.UTF8Encoding
echo "Test Chinese: depth camera test"
# Chinese should display correctly, no garbled characters

1.3 Install OpenSSH Client (If Not Present)

Problem: Some fresh Windows installs don't have the OpenSSH client. Without it, ssh and ssh-copy-id commands don't exist.

# Check if ssh is available
ssh -V
# If not found, install it:
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

1.4 Git Configuration

Problem: Without git config, every git commit fails. Without credential helper, every git clone from private repos asks for password (which hangs non-interactive sessions).

git config --global user.name "Your Name"
git config --global user.email "your@email.com"
git config --global credential.helper manager
git config --global core.autocrlf true

Problem: Default PowerShell font may not render all Unicode characters (e.g., box-drawing characters from build tools, emoji from some CLI tools).

Install a Nerd Font and set it as default:

  1. Download MesloLGS NF or similar
  2. In Windows Terminal settings -> PowerShell -> Appearance -> Font face: MesloLGS NF

Phase 2: Windows SSH Config

2.1 SSH Config File

Create or edit C:\Users\fgxwa\.ssh\config:

Host ubuntu-vm
    HostName 192.168.241.138
    User xsy
    IdentityFile ~/.ssh/id_rsa
    ServerAliveInterval 30
    ServerAliveCountMax 5
    TCPKeepAlive yes
    ConnectTimeout 10
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null

Host *
    ServerAliveInterval 30
    ServerAliveCountMax 5
    TCPKeepAlive yes
    StrictHostKeyChecking accept-new

Why each setting matters:

Setting Purpose
ServerAliveInterval 30 Send heartbeat every 30s. Without this, SSH silently disconnects during long operations (apt install, colcon build). The terminal appears frozen with no output, no error - AI thinks it's still running and waits forever.
ServerAliveCountMax 5 Disconnect after 5 missed heartbeats (150s). Prevents zombie connections.
TCPKeepAlive yes OS-level keepalive as backup.
ConnectTimeout 10 Fail fast if VM is unreachable. Without this, SSH hangs for 2+ minutes before timing out.
StrictHostKeyChecking no (per-host) After VM reinstall, the host key changes. Without this, SSH refuses to connect and blocks the entire session.
UserKnownHostsFile /dev/null (per-host) Don't cache host keys for a VM that gets reinstalled frequently.
StrictHostKeyChecking accept-new (global) For other hosts, accept new keys but reject changed keys (security balance).

2.2 Generate SSH Key (If Not Exists)

# Check if key exists
Test-Path "$env:USERPROFILE\.ssh\id_rsa"
# If False, generate:
ssh-keygen -t rsa -b 4096 -f "$env:USERPROFILE\.ssh\id_rsa" -N '""'

2.3 Verify SSH Connection

ssh ubuntu-vm "echo OK"
# Should connect immediately without password prompt

Phase 3: Ubuntu Remote Server

3.1 SSH Server

sudo apt install -y openssh-server
sudo systemctl enable --now ssh

3.2 Passwordless Sudo (CRITICAL - #1 Cause of AI Retry Loops)

This is the single most important step. Without it, every sudo command via SSH hangs forever because the terminal waits for password input that will never come (non-interactive SSH cannot prompt for passwords).

echo "$(whoami) ALL=NOPASSWD:ALL" | sudo tee /etc/sudoers.d/$(whoami)
sudo chmod 440 /etc/sudoers.d/$(whoami)

Verify:

sudo whoami
# Must output "root" immediately, NO password prompt

3.3 SSH Key Login (From Windows)

# From Windows PowerShell:
type $env:USERPROFILE\.ssh\id_rsa.pub | ssh ubuntu-vm "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

Verify:

ssh ubuntu-vm "echo OK"
# Must output "OK" immediately, NO password prompt

3.4 SSH Keepalive (Server Side)

sudo bash -c 'echo -e "ClientAliveInterval 60\nClientAliveCountMax 3\nMaxSessions 20" > /etc/ssh/sshd_config.d/keepalive.conf'
sudo systemctl restart ssh

3.5 Disable System Version Upgrade

sudo sed -i 's/Prompt=lts/Prompt=never/' /etc/update-manager/release-upgrades

Why: Ubuntu periodically prompts "Upgrade to 24.04 LTS?". Accidentally accepting this will break ROS2 Humble (tied to Ubuntu 22.04). This disables the prompt while keeping security updates.

3.6 Set UTF-8 Locale

Problem: If Ubuntu's locale is not UTF-8, Chinese characters in SSH output become garbled.

sudo apt install -y locales
sudo locale-gen en_US.UTF-8 zh_CN.UTF-8
sudo update-locale LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8

Verify:

locale
# LANG=en_US.UTF-8

3.7 Install Common Dev Tools

sudo apt install -y \
    build-essential \
    cmake \
    git \
    curl \
    wget \
    htop \
    tree \
    net-tools \
    usbutils \
    python3-pip \
    python3-venv

Why pre-install: When AI needs to run cmake or pip and they're not installed, it wastes tokens trying to install them, often hitting the password prompt issue again.


Phase 4: Full Verification Checklist

Run ALL of these. Every single one must pass before you start any real development.

Windows Side

# 1. Execution policy
Get-ExecutionPolicy -Scope CurrentUser
# Expected: RemoteSigned

# 2. UTF-8 encoding
[Console]::OutputEncoding.EncodingName
# Expected: Unicode (UTF-8)

# 3. SSH client
ssh -V
# Expected: OpenSSH for Windows version...

# 4. SSH connection
ssh ubuntu-vm "echo OK"
# Expected: OK (no password prompt)

# 5. Chinese display
echo "Chinese test: depth camera"
# Expected: Chinese displays correctly, no garbled characters

Ubuntu Side (via SSH)

ssh ubuntu-vm "sudo whoami && locale | head -1 && which cmake && which git && echo ALL_OK"

Expected output:

root
LANG=en_US.UTF-8
/usr/bin/cmake
/usr/bin/git
ALL_OK

If ANY check fails, fix it before proceeding. A failing check means future commands will fail and waste tokens.


Phase 5: AI Coding Assistant Configuration

5.1 Set AI Thinking Language to Chinese

If your AI coding assistant supports configurable thinking/reasoning language, set it to Chinese. This lets you review the AI's thought process and catch mistakes early.

5.2 Project Rules File

Create a project-level rules file so the AI always knows the environment:

For Trae IDE: Create .trae/rules.md in your project root:

# Project Rules

## Environment
- Local: Windows 11, PowerShell (UTF-8, RemoteSigned)
- Remote: Ubuntu 22.04 via SSH (alias: ubuntu-vm)
- Remote user has passwordless sudo
- All commands should be UTF-8 compatible

## Guidelines
- Always use Chinese for thinking/reasoning
- When running remote commands, use: ssh ubuntu-vm "command"
- Never use interactive prompts (no password input, no yes/no questions)
- Use non-interactive flags: apt-get -y, DEBIAN_FRONTEND=noninteractive
- If a command fails, analyze the error BEFORE retrying

5.3 Key Principle for AI-Assisted Development

When a command fails:

  1. Read the error message carefully - don't just retry
  2. Check if it's an environment issue - 90% of retry loops are environment problems
  3. Fix the root cause - don't work around symptoms
  4. Verify the fix - run the verification checklist

Quick Reference: Common Issues & Fixes

Symptom Root Cause Fix
profile.ps1 forbidden Execution policy Restricted Set-ExecutionPolicy RemoteSigned
Chinese shows as ??? or ?? PowerShell not UTF-8 System locale UTF-8 + profile.ps1 UTF-8 config
SSH hangs with no output sudo waiting for password Configure NOPASSWD sudo
SSH password prompt every time No SSH key configured Set up SSH key login
SSH hangs during long build Connection timeout ServerAliveInterval 30 in SSH config
Host key changed after VM reinstall Old host key cached StrictHostKeyChecking no for VM host
Connection refused SSH server not running sudo systemctl start ssh
cmake: command not found Dev tools not installed apt install build-essential cmake
Upgrade to 24.04 popup Default Prompt=lts Prompt=never
AI retries same command 10 times One of the above issues Fix environment FIRST

One-Script Setup

Windows (Run as Administrator in PowerShell)

# === Windows Environment Setup ===
# 1. Execution policy
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -Force

# 2. SSH client
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0 -ErrorAction SilentlyContinue

# 3. Git config (edit name/email first)
git config --global user.name "Your Name"
git config --global user.email "your@email.com"
git config --global credential.helper manager
git config --global core.autocrlf true

# 4. Create PowerShell profile with UTF-8
$profileDir = "$env:USERPROFILE\Documents\WindowsPowerShell"
New-Item -ItemType Directory -Force -Path $profileDir | Out-Null
$profileContent = @'
# UTF-8 encoding
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
chcp 65001 | Out-Null

# Conda initialize (adjust path)
#region conda initialize
$condaPath = "D:\ProgramData\anaconda3\Scripts\conda.exe"
If (Test-Path $condaPath) {
    (& $condaPath "shell.powershell" "hook") | Out-String | Where-Object { $_ } | Invoke-Expression
}
#endregion
'@
Set-Content -Path "$profileDir\profile.ps1" -Value $profileContent -Encoding UTF8

Write-Host "`n=== Windows Setup Complete ===" -ForegroundColor Green
Write-Host "IMPORTANT: Manually enable UTF-8 system locale:" -ForegroundColor Yellow
Write-Host "  Control Panel -> Region -> Administrative -> Change system locale" -ForegroundColor Yellow
Write-Host "  -> Check 'Beta: Use Unicode UTF-8 for worldwide language support' -> Reboot" -ForegroundColor Yellow
Write-Host "Then reopen PowerShell and run: ssh ubuntu-vm 'echo OK'" -ForegroundColor Yellow

Ubuntu (Save as setup-env.sh and run)

#!/bin/bash
set -e

echo "=== Ubuntu Environment Setup ==="

# 1. Passwordless sudo (CRITICAL)
echo "$(whoami) ALL=NOPASSWD:ALL" | sudo tee /etc/sudoers.d/$(whoami)
sudo chmod 440 /etc/sudoers.d/$(whoami)
echo "[OK] Passwordless sudo configured"

# 2. SSH keepalive
sudo bash -c 'echo -e "ClientAliveInterval 60\nClientAliveCountMax 3\nMaxSessions 20" > /etc/ssh/sshd_config.d/keepalive.conf'
sudo systemctl restart ssh
echo "[OK] SSH keepalive configured"

# 3. Disable version upgrade
sudo sed -i 's/Prompt=lts/Prompt=never/' /etc/update-manager/release-upgrades
echo "[OK] Version upgrade disabled"

# 4. UTF-8 locale
sudo apt install -y locales
sudo locale-gen en_US.UTF-8 zh_CN.UTF-8
sudo update-locale LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8
echo "[OK] UTF-8 locale configured"

# 5. Common dev tools
sudo apt install -y build-essential cmake git curl wget htop tree net-tools usbutils python3-pip python3-venv
echo "[OK] Dev tools installed"

# 6. Verify
echo ""
echo "=== Verification ==="
echo "Sudo:      $(sudo whoami)"
echo "SSH:       $(systemctl is-active ssh)"
echo "Locale:    $(locale | grep LANG=)"
echo "CMake:     $(cmake --version | head -1)"
echo "Git:       $(git --version)"
echo "Python:    $(python3 --version)"
echo "Upgrade:   $(grep Prompt /etc/update-manager/release-upgrades)"
echo ""
echo "ALL DONE. Now run from Windows:"
echo "  ssh-copy-id $(whoami)@$(hostname -I | awk '{print $1}')"
echo "  ssh ubuntu-vm 'echo OK'"

After Every Fresh OS Install

  1. Run Windows setup script (Phase 1-2)
  2. Reboot for UTF-8 system locale
  3. Install Ubuntu VM / or connect to remote Ubuntu
  4. Run Ubuntu setup script (Phase 3)
  5. Copy SSH key from Windows to Ubuntu
  6. Run full verification checklist (Phase 4)
  7. Only then start writing code

Skipping any step = guaranteed token waste later.

posted @ 2026-06-18 22:59  鬼门元歌  阅读(22)  评论(0)    收藏  举报