diff --git a/.dockerignore b/.dockerignore index 0df9811..e40daea 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,6 @@ **/.git .env +.env.* **/build **/install **/log diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..138b9e9 --- /dev/null +++ b/.env.example @@ -0,0 +1,12 @@ +# Copy to .env in the repository root for Docker Compose. +COMPOSE_FILE=modules/docker-compose.yaml:modules/docker-compose.dev.yaml + +# Optional ROS settings. Match the domain and middleware of any peer nodes. +# ROS_DOMAIN_ID=0 +# ROS_AUTOMATIC_DISCOVERY_RANGE=LOCALHOST +# RMW_IMPLEMENTATION=rmw_fastrtps_cpp +# FASTDDS_BUILTIN_TRANSPORTS=UDPv4 + +# Optional image settings. Export AP1_REGISTRY in your shell for Bake as well. +# AP1_REGISTRY=ghcr.io/we-autopilot/ap1 +# AP1_TAG_SUFFIX= diff --git a/.github/workflows/control-images.yml b/.github/workflows/control-images.yml index 29eacab..9f1a0df 100644 --- a/.github/workflows/control-images.yml +++ b/.github/workflows/control-images.yml @@ -55,14 +55,13 @@ jobs: targets: control load: true - # Runs control_node with the config installed in the image, as the deploy - # service does. timeout exits with 124 when the node is still running - # after 10 s; anything else means it crashed or exited. + # Check that the node stays up for 10 seconds with its installed ROS parameters. + # timeout returns 124 if the node was still running at the deadline. - name: Smoke test run: | docker run --rm "$IMAGE:cpu" bash -c ' timeout 10 ros2 run ap1_control control_node \ - /opt/ap1/share/ap1_control/config/control_node_cfg.csv + --ros-args --params-file /opt/ap1/share/ap1_control/config/control.yaml test $? -eq 124' - name: Log in to GHCR diff --git a/.github/workflows/planning-images.yml b/.github/workflows/planning-images.yml new file mode 100644 index 0000000..cfc09a4 --- /dev/null +++ b/.github/workflows/planning-images.yml @@ -0,0 +1,77 @@ +# Builds the planning image (CPU only), smoke-tests it, and on main pushes it to +# ghcr.io/we-autopilot/ap1/planning. See docker/README.md. +name: Planning images + +on: + pull_request: + paths: + - "docker/**" + - "src/planning/**" + - ".dockerignore" + - "src/msgs/**" + - ".github/workflows/planning-images.yml" + # Builds on development too, without pushing images: PRs can only read the + # build cache of their own branch and their base branch, so this gives every + # new PR into development a warm cache. + push: + branches: [main, development] + paths: + - "docker/**" + - "src/planning/**" + - ".dockerignore" + - "src/msgs/**" + - ".github/workflows/planning-images.yml" + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + packages: write + +env: + IMAGE: ghcr.io/we-autopilot/ap1/planning + PUSH: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + +jobs: + build: + name: planning (cpu) + runs-on: ubuntu-24.04 + + steps: + - uses: actions/checkout@v7 + + - uses: docker/setup-buildx-action@v4 + + - name: Build image + uses: docker/bake-action@v7 + env: + GIT_SHA: ${{ github.sha }} + with: + source: . + files: docker/docker-bake.hcl + targets: planning + load: true + + # Check that the node stays up for 10 seconds with its installed ROS parameters. + # timeout returns 124 if the node was still running at the deadline. + - name: Smoke test + run: | + docker run --rm "$IMAGE:cpu" bash -c ' + timeout 10 ros2 run ap1_planning planner_node \ + --ros-args --params-file /opt/ap1/share/ap1_planning/config/planner.yaml + test $? -eq 124' + + - name: Log in to GHCR + if: env.PUSH == 'true' + uses: docker/login-action@v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Push + if: env.PUSH == 'true' + run: docker push --all-tags "$IMAGE" diff --git a/.gitignore b/.gitignore index 8af5a1e..181547d 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,5 @@ __pycache__/ # Per-user docker compose settings (see docker/README.md, Setup) /.env +/.env.* +!/.env.example diff --git a/README.md b/README.md index ca08f4e..d8645fc 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ This is WE Autopilot's master workspace for development of the self-driving car ## Setup - **Native (all subsystems):** see [SETUP.md](SETUP.md). -- **Docker (perception and control for now):** see [docker/README.md](docker/README.md). Images are built with `docker buildx bake` and run with `docker compose`. +- **Docker:** see [docker/README.md](docker/README.md). Images are built with `docker buildx bake` and run with `docker compose`. ## Repo Structure diff --git a/docker/README.md b/docker/README.md index bd6a090..ba0cc21 100644 --- a/docker/README.md +++ b/docker/README.md @@ -2,7 +2,7 @@ Containerized build and dev environment for AP1 modules, modelled on [WATonomous' wato_monorepo](https://github.com/WATonomous/wato_monorepo). -Perception and control run on it. Other modules still use `ap1_setup.sh`. +Modules with Docker services are defined in `modules/`. Use `ap1_setup.sh` for native setup. Perception images come in two variants built from the same files: @@ -11,9 +11,9 @@ Perception images come in two variants built from the same files: | `cpu` | `ubuntu:24.04` | `onnxruntime` | anyone, no GPU needed (image ~2.9 GB) | | `gpu` | `nvidia/cuda:13.0.3-cudnn-runtime-ubuntu24.04` | `onnxruntime-gpu` | NVIDIA GPU machines (image ~8.3 GB) | -The code is identical in both. Only the installed packages differ, and the -YOLO node's `device` parameter picks the hardware. Control has no GPU code, so -it only has a CPU image (see [Control](#control)). +Both variants run the same perception code with different dependencies. The +YOLO node's `device` parameter selects the hardware. See +[Control and planning](#control-and-planning) for the CPU-only services. ## Setup @@ -29,20 +29,21 @@ it only has a CPU image (see [Control](#control)). 2. GPU machines only (Linux and WSL): NVIDIA driver 580 or newer (needed for CUDA 13) and the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html), then `sudo nvidia-ctk runtime configure --runtime=docker && sudo systemctl restart docker`. -3. [Git LFS](https://git-lfs.com), then `git lfs pull` in the repo. Models live in +3. For perception, install [Git LFS](https://git-lfs.com), then `git lfs pull` in the repo. Models live in `src/perception/models/` (LFS) and the folder is mounted read-only at `/opt/ap1/models`, so a model can be swapped without rebuilding. If `yolo26n.onnx` is a small text pointer instead of ~10 MB, run `git lfs pull`. -4. Create a `.env` file in the repo root (it's gitignored) with this content: - ```bash - # Required: the compose files, so commands need no -f flags - COMPOSE_FILE=modules/docker-compose.yaml:modules/docker-compose.dev.yaml +4. From the repo root, copy the Compose settings template if you do not have + a local `.env` yet: - # Optional, see Settings - # ROS_DOMAIN_ID=0 - # ROS_AUTOMATIC_DISCOVERY_RANGE=LOCALHOST + ```bash + test -f .env || cp .env.example .env ``` - Run `docker compose` from the repo root, since that's the only place it reads `.env` from. + + An existing `.env` should contain + `COMPOSE_FILE=modules/docker-compose.yaml:modules/docker-compose.dev.yaml`. + Run Compose commands from the repo root. Run ROS and colcon commands from + the container shell. The template lists optional image and ROS settings. ### Windows (WSL 2) @@ -196,49 +197,73 @@ The GPU image sets `AP1_GPU=1`, which makes `yolo.launch.py` default to `device:=cuda` (failing at startup if the GPU isn't usable, rather than silently running on CPU). `device:=auto` uses the GPU when available. -### Control +### Control and planning + +Both modules have CPU deploy and dev images. Each node loads one ROS parameter +file at startup: + +| Service | ROS node | Parameter file | +|---|---|---| +| `control` | `/ap1_control` | `src/control/config/control.yaml` | +| `planning` | `/ap1_planning` | `src/planning/config/planner.yaml` | + +Control's file contains the controller settings. Planning's file contains the +topics, debug setting, and ordered state-machine transitions. -Control is CPU only, so its targets and services have no `-cpu`/`-gpu` suffix: -`control` (deploy) and `control-dev`. The dev container mounts `src/msgs` and -`src/control`: +Build and launch the deploy services from the repo root: ```bash -docker buildx bake -f docker/docker-bake.hcl --load control-dev -docker compose up -d control-dev -docker compose exec control-dev bash +docker buildx bake -f docker/docker-bake.hcl --load control planning +docker compose up -d control planning +docker compose logs -f control planning ``` -Inside, build from `/ws` and run the node. `ros2 run` takes the package name -(`ap1_control`) and the executable name (`control_node`), then the path to the -config CSV: +Deploy services load their parameter files from +`/opt/ap1/share//config/` inside the image. Rebuild the corresponding +image after editing its YAML. Both nodes log when initialized. They report +missing inputs while upstream ROS topics are idle. + +Both dev services start idle, mount their module and shared message sources, +and keep colcon output in named volumes. Start the containers from the repo +root: + +```bash +docker buildx bake -f docker/docker-bake.hcl --load control-dev planning-dev +docker compose up -d control-dev planning-dev +``` + +Open a ROS shell with `docker compose exec control-dev bash` or +`docker compose exec planning-dev bash`. Build and source the workspace in +each shell: ```bash cd /ws colcon build --symlink-install source install/setup.bash -ros2 run ap1_control control_node /ws/src/control/config/control_node_cfg.csv ``` -The deploy service runs the node with the CSV installed in the image -(`/opt/ap1/share/ap1_control/config/control_node_cfg.csv`), so rebuild the -`control` image after changing the config: +Before starting a dev node, stop any running deploy instance for that module +from the host. Run the corresponding command in the dev shell to start the +node and see its logs there: ```bash -docker buildx bake -f docker/docker-bake.hcl --load control -docker compose up -d control -docker compose logs -f control +# In control-dev +ros2 run ap1_control control_node --ros-args --params-file /ws/src/control/config/control.yaml + +# In planning-dev +ros2 run ap1_planning planner_node --ros-args --params-file /ws/src/planning/config/planner.yaml ``` -It logs `Velocity is null or nan. Skipping update.` every 2 seconds until -something publishes `/ap1/actuation/speed`. That's expected. +Press Ctrl+C to stop the foreground node. From the host, use +`docker compose stop control-dev planning-dev` to stop the dev containers. ### All modules -The `all` images hold every Docker module (perception and control for now) in -one image, built from the same commit with one shared `ap1_msgs`. +The `all` images bundle the containerized modules from the same commit with one +shared build of `ap1_msgs`. For development, `all-dev-cpu` and `all-dev-gpu` are single containers with the -sources of `src/msgs`, `src/perception` and `src/control` mounted at `/ws/src`. +module sources and shared messages mounted at `/ws/src`. Build and run everything from one shell: ```bash @@ -247,13 +272,12 @@ docker compose up -d all-dev-cpu docker compose exec all-dev-cpu bash ``` -Inside, `colcon build` from `/ws` builds all three packages, then any `ros2` -command works as in the module dev containers. +Inside, `colcon build` from `/ws` builds the mounted packages. Source +`install/setup.bash` to use them with `ros2`. For deployment, `all-deploy` is a GPU image (`ap1/all:gpu`), like the car. The -`all-deploy` profile runs one container per module from it, `all-perception` and -`all-control`, with the same commands and mounts as the module services. Each -restarts and logs on its own: +`all-deploy` profile runs one container per module with the same commands and +mounts as the standalone services. Each restarts and logs on its own: ```bash docker buildx bake -f docker/docker-bake.hcl --load all-deploy @@ -261,8 +285,8 @@ docker compose --profile all-deploy up -d docker compose logs -f all-perception ``` -Don't run the `all-deploy` profile alongside the module deploy services -(`perception-gpu`, `control`): every node would run twice. +Stop standalone deploy services for the same modules before starting +`all-deploy` to avoid duplicate ROS nodes. ### Settings @@ -318,17 +342,16 @@ Never pip-install `numpy`: ROS's `cv_bridge` is built against Ubuntu's numpy ## Layout ``` -.env yours, not tracked: points docker compose at modules/ (Setup step 4) +.env.example template for local Compose settings (Setup step 4) .dockerignore keeps bags and build output out of images bags/ recordings, mounted at /ws/bags (contents gitignored) -modules/ how modules run (CPU and GPU services per module, CPU only for control) +modules/ how modules run and which hardware variants they support docker-compose.yaml deploy services: mounts, networking, launch commands - docker-compose.dev.yaml dev services: extend deploy, mount source, idle + docker-compose.dev.yaml dev services: extend deploy and mount source docker/ how images are built base.Dockerfile ROS Jazzy base, plus the shared pipeline: rosdep scan -> install -> build -> deploy/develop - perception.Dockerfile perception's sources and extra dependencies - control.Dockerfile control's sources and extra dependencies + .Dockerfile module sources and extra dependencies all.Dockerfile merges every module's sources for the all-modules images docker-bake.hcl build graph: variants x targets (used locally and by CI) config/ entrypoint, shell env, pip version pins, pyproject mask @@ -363,7 +386,7 @@ stage, after the install. Dev build output lives in named volumes, one set per variant (`ap1_perception-build-cpu`, `...-gpu`, and the same for `install` and `log`), so CPU and GPU dev containers never reuse a build compiled against the other -image. Control has one set (`ap1_control-build` and so on), and the all-modules +image. Control and planning each have one set (e.g. `ap1_planning-build`), and the all-modules dev containers one per variant (`ap1_all-build-cpu`, ...). `docker compose --profile '*' down` keeps them; delete them with `docker volume rm` to start clean. @@ -396,8 +419,8 @@ include a module in the all-modules images, also add a `COPY` line in ## CI -Two workflows build the deploy images on every PR that touches their module, -`docker/` or `src/msgs/`: +Module image workflows build and test deploy images on PRs that touch their +module, `docker/`, or `src/msgs/`: - `.github/workflows/perception-images.yml` builds both perception variants and runs the deploy tests in each. The runners have no GPU, so the GPU @@ -405,14 +428,16 @@ Two workflows build the deploy images on every PR that touches their module, CUDA support. - `.github/workflows/control-images.yml` builds the control image and checks that `control_node` starts with its installed config and stays up. +- `.github/workflows/planning-images.yml` builds the planning image and checks + that `planner_node` starts with its installed parameter file and stays up. -On `main` they push `ghcr.io/we-autopilot/ap1/{perception,control}` images plus -a per-commit tag. They also run on pushes to `development`, without pushing +On `main` they push module images to `ghcr.io/we-autopilot/ap1/` +with a per-commit tag alongside the regular tag. They also run on pushes to `development`, without pushing images, so PRs into `development` start from a warm build cache. -The build cache lives in the GitHub Actions cache, one scope per image -(`perception-cpu`, `perception-gpu`, `control`; see `cache_from` and `cache_to` -in `docker-bake.hcl`). A PR can read its own cache and its base branch's. A +Each image uses its own GitHub Actions cache scope. See `cache_from` and +`cache_to` in `docker-bake.hcl`. A PR can read its own cache and its base +branch's. A build only reinstalls packages when a `package.xml` or `pip-constraints.txt` changes, as long as the rule in [How the build works](#how-the-build-works) holds. The all-modules images aren't built in CI. diff --git a/docker/all.Dockerfile b/docker/all.Dockerfile index 108f13a..b6954c8 100644 --- a/docker/all.Dockerfile +++ b/docker/all.Dockerfile @@ -7,3 +7,4 @@ FROM base AS source COPY --from=perception-source ${AP1_WS}/src ${AP1_WS}/src COPY --from=control-source ${AP1_WS}/src ${AP1_WS}/src +COPY --from=planning-source ${AP1_WS}/src ${AP1_WS}/src diff --git a/docker/base.Dockerfile b/docker/base.Dockerfile index f4a8cea..e894687 100644 --- a/docker/base.Dockerfile +++ b/docker/base.Dockerfile @@ -2,7 +2,7 @@ # Dependencies from the .Dockerfile file(s) that base is paired with are handled by rosdep # and pip respectively. # -# We define 6 build stages: +# Shared build stages: # base ROS 2 and AP1 tooling on top of any Ubuntu 24.04 image # rosdep_scan resolve a .Dockerfile's package.xml into apt and pip package lists # dependencies install those lists (cached until the lists change) diff --git a/docker/control.Dockerfile b/docker/control.Dockerfile index c908d6a..c48b89a 100644 --- a/docker/control.Dockerfile +++ b/docker/control.Dockerfile @@ -1,5 +1,5 @@ -# Control module. Copies over source code built by colcon and relevant to control. -# Also present as an intermediary for dependency management in build stages. +# Provide module sources and a stage for extra dependencies. + ########################## source ########################## FROM base AS source @@ -8,4 +8,4 @@ COPY src/msgs msgs COPY src/control control ####################### dependencies ####################### -FROM base AS dependencies \ No newline at end of file +FROM base AS dependencies diff --git a/docker/docker-bake.hcl b/docker/docker-bake.hcl index ad53f67..f388af4 100644 --- a/docker/docker-bake.hcl +++ b/docker/docker-bake.hcl @@ -5,7 +5,7 @@ // docker buildx bake -f docker/docker-bake.hcl --load perception-cpu // docker buildx bake -f docker/docker-bake.hcl --print perception-gpu # show resolved config // -// Two Dockerfiles, chained through named contexts: +// Dockerfiles are connected through named contexts: // docker/.Dockerfile module sources and extra deps // (-source-, -deps-) // docker/base.Dockerfile base- (stage `base`), and the shared pipeline @@ -39,8 +39,7 @@ variable "VARIANTS" { ] } -// One cache scope per image: perception-cpu, perception-gpu, control, all-gpu. -// Only the image's own target exports it. mode=max includes every stage the +// Each image target exports its own cache scope. mode=max includes every stage the // image was built from, so the base and module stages are stored once per // image instead of once per target (the repo's cache is capped at 10 GB). // Every target imports the scopes of the images built on it. @@ -60,7 +59,7 @@ group "default" { // Every per-module deploy image in one command, to check each module builds on its own group "modules" { - targets = ["perception-cpu", "control"] + targets = ["perception-cpu", "control", "planning"] } ############################ base ############################ @@ -78,7 +77,7 @@ target "base" { ROS_DISTRO = ROS_DISTRO } tags = ["${AP1_REGISTRY}/base:${ROS_DISTRO}-${v.name}"] - cache-from = cache_from(v.name == "cpu" ? ["perception-cpu", "control"] : ["perception-gpu", "all-gpu"]) + cache-from = cache_from(v.name == "cpu" ? ["perception-cpu", "control", "planning"] : ["perception-gpu", "all-gpu"]) } ######################### perception ######################### @@ -137,7 +136,7 @@ target "perception-dev" { } ######################### control ######################### -// CPU only: control has no GPU dependencies, so no matrix +// CPU only. target "control-source" { context = "." @@ -184,6 +183,54 @@ target "control-dev" { tags = ["${AP1_REGISTRY}/control:cpu-dev"] } +######################### planning ######################### +// CPU only. + +target "planning-source" { + context = "." + dockerfile = "docker/planning.Dockerfile" + target = "source" + contexts = { base = "target:base-cpu" } + cache-from = cache_from(["planning", "all-gpu"]) +} + +target "planning-deps" { + context = "." + dockerfile = "docker/planning.Dockerfile" + target = "dependencies" + contexts = { base = "target:base-cpu" } + cache-from = cache_from(["planning"]) +} + +// Deploy image: what runs on the car / in integration tests +target "planning" { + context = "." + dockerfile = "docker/base.Dockerfile" + target = "deploy" + contexts = { + "module-source" = "target:planning-source" + "module-deps" = "target:planning-deps" + } + tags = compact([ + "${AP1_REGISTRY}/planning:cpu", + notequal(GIT_SHA, "") ? "${AP1_REGISTRY}/planning:cpu-${GIT_SHA}" : "", + ]) + cache-from = cache_from(["planning"]) + cache-to = cache_to("planning") +} + +// Dev image: dependencies + dev tools; source is mounted and built at runtime +target "planning-dev" { + context = "." + dockerfile = "docker/base.Dockerfile" + target = "develop" + contexts = { + "module-source" = "target:planning-source" + "module-deps" = "target:planning-deps" + } + tags = ["${AP1_REGISTRY}/planning:cpu-dev"] +} + ######################### all modules ######################### // Every module in one image. all.Dockerfile merges the module source stages. // The module dependencies stages are stacked instead: each one is built with @@ -202,14 +249,15 @@ target "all-source" { contexts = { base = "target:base-${v.name}" "perception-source" = "target:perception-source-${v.name}" - // control has no variants: its source files are the same for both - "control-source" = "target:control-source" + // CPU-only source targets can be reused across hardware variants. + "control-source" = "target:control-source" + "planning-source" = "target:planning-source" } cache-from = cache_from(["all-${v.name}"]) } -target "all-deps" { - name = "all-deps-${v.name}" +target "all-control-deps" { + name = "all-control-deps-${v.name}" matrix = { v = VARIANTS } context = "." dockerfile = "docker/control.Dockerfile" @@ -218,6 +266,16 @@ target "all-deps" { cache-from = cache_from(["all-${v.name}"]) } +target "all-deps" { + name = "all-deps-${v.name}" + matrix = { v = VARIANTS } + context = "." + dockerfile = "docker/planning.Dockerfile" + target = "dependencies" + contexts = { base = "target:all-control-deps-${v.name}" } + cache-from = cache_from(["all-${v.name}"]) +} + // Deploy image: GPU only, like the car. Compose runs one container per module from it target "all-deploy" { context = "." diff --git a/docker/planning.Dockerfile b/docker/planning.Dockerfile new file mode 100644 index 0000000..9355126 --- /dev/null +++ b/docker/planning.Dockerfile @@ -0,0 +1,11 @@ +# Provide module sources and a stage for extra dependencies. + + +########################## source ########################## +FROM base AS source +WORKDIR ${AP1_WS}/src +COPY src/msgs msgs +COPY src/planning planning + +####################### dependencies ####################### +FROM base AS dependencies diff --git a/modules/docker-compose.dev.yaml b/modules/docker-compose.dev.yaml index 329aa96..0d32a84 100644 --- a/modules/docker-compose.dev.yaml +++ b/modules/docker-compose.dev.yaml @@ -1,5 +1,5 @@ # Dev containers: each extends its module's service, swaps in the dev image, -# mounts the module's source and idles so you can shell in and build. +# mounts the module's source. Each service's command defines its startup behavior. # Dev images have no prebuilt workspace: everything in /ws/src is built in the # container with colcon, including ap1_msgs. # @@ -61,6 +61,22 @@ services: - control-log:/ws/log command: sleep infinity + #################### PLANNING #################### + planning-dev: + extends: + file: docker-compose.yaml + service: planning + profiles: !override [planning-dev] + image: ${AP1_REGISTRY:-ghcr.io/we-autopilot/ap1}/planning:cpu-dev + restart: "no" + volumes: + - ../src/msgs:/ws/src/msgs + - ../src/planning:/ws/src/planning + - planning-build:/ws/build + - planning-install:/ws/install + - planning-log:/ws/log + command: sleep infinity + #################### ALL MODULES #################### # One container with every module's source. Extends perception's service for # the ROS settings and the model and bags mounts. @@ -75,6 +91,7 @@ services: - ../src/msgs:/ws/src/msgs - ../src/perception:/ws/src/perception - ../src/control:/ws/src/control + - ../src/planning:/ws/src/planning - ../docker/config/pyproject-mask.toml:/ws/src/perception/pyproject.toml:ro - all-build-cpu:/ws/build - all-install-cpu:/ws/install @@ -92,6 +109,7 @@ services: - ../src/msgs:/ws/src/msgs - ../src/perception:/ws/src/perception - ../src/control:/ws/src/control + - ../src/planning:/ws/src/planning - ../docker/config/pyproject-mask.toml:/ws/src/perception/pyproject.toml:ro - all-build-gpu:/ws/build - all-install-gpu:/ws/install @@ -110,6 +128,9 @@ volumes: control-build: control-install: control-log: + planning-build: + planning-install: + planning-log: all-build-cpu: all-install-cpu: all-log-cpu: diff --git a/modules/docker-compose.yaml b/modules/docker-compose.yaml index ef085ab..0e0c847 100644 --- a/modules/docker-compose.yaml +++ b/modules/docker-compose.yaml @@ -1,6 +1,6 @@ # AP1 module services: how each module runs on the car and in integration tests. # Service names match the targets in docker/docker-bake.hcl (e.g. perception-cpu, -# perception-gpu). Each user creates a root .env file that sets COMPOSE_FILE +# perception-gpu). Copy the root .env.example to .env to set COMPOSE_FILE # (docker/README.md, Setup), so you can run from the repo root without -f flags: # docker compose up -d perception-cpu # See docker/README.md for the everyday commands. @@ -51,17 +51,24 @@ services: gpus: all #################### CONTROL #################### - # only one base control service, no variants as they do not require GPUs - control: &control + control: <<: *ros profiles: [control] image: ${AP1_REGISTRY:-ghcr.io/we-autopilot/ap1}/control:cpu${AP1_TAG_SUFFIX:-} restart: unless-stopped - # control_node takes the config CSV path as its first argument (not a ROS params file). - # The CSV is installed into the image by CMake command: > ros2 run ap1_control control_node - /opt/ap1/share/ap1_control/config/control_node_cfg.csv + --ros-args --params-file /opt/ap1/share/ap1_control/config/control.yaml + + #################### PLANNING #################### + planning: + <<: *ros + profiles: [planning] + image: ${AP1_REGISTRY:-ghcr.io/we-autopilot/ap1}/planning:cpu${AP1_TAG_SUFFIX:-} + restart: unless-stopped + command: > + ros2 run ap1_planning planner_node + --ros-args --params-file /opt/ap1/share/ap1_planning/config/planner.yaml #################### ALL MODULES #################### # Every module from one image (all-deploy in docker-bake.hcl), one container @@ -80,3 +87,9 @@ services: service: control profiles: !override [all-deploy] image: ${AP1_REGISTRY:-ghcr.io/we-autopilot/ap1}/all:gpu${AP1_TAG_SUFFIX:-} + + all-planning: + extends: + service: planning + profiles: !override [all-deploy] + image: ${AP1_REGISTRY:-ghcr.io/we-autopilot/ap1}/all:gpu${AP1_TAG_SUFFIX:-} diff --git a/src/bringup/launch/full_system.launch.py b/src/bringup/launch/full_system.launch.py index dcd4d77..2cf09ad 100644 --- a/src/bringup/launch/full_system.launch.py +++ b/src/bringup/launch/full_system.launch.py @@ -61,29 +61,24 @@ def CriticalNode(**kwargs): ) # == CONTROL NODE == - # needs a path to control cfg.csv pkg_share = get_package_share_directory('ap1_control') - csv_file_path = os.path.join(pkg_share, 'config', 'control_node_cfg.csv') + control_yaml_path = os.path.join(pkg_share, 'config', 'control.yaml') control = CriticalNode( package='ap1_control', executable='control_node', name='ap1_control', output='log', - arguments=[ - csv_file_path - ], + parameters=[control_yaml_path], ) # == PLANNER NODE == pkg_share = get_package_share_directory('ap1_planning') - transitions_file_path = os.path.join(pkg_share, 'config', 'stop_sign_transitions.yaml') planner_yaml_path = os.path.join(pkg_share, 'config', 'planner.yaml') planner = CriticalNode( package='ap1_planning', executable='planner_node', name='ap1_planning', output='log', - arguments=[transitions_file_path], parameters=[planner_yaml_path] ) diff --git a/src/bringup/launch/pnc_backend.launch.py b/src/bringup/launch/pnc_backend.launch.py index 8eb110d..bdddc24 100644 --- a/src/bringup/launch/pnc_backend.launch.py +++ b/src/bringup/launch/pnc_backend.launch.py @@ -16,8 +16,8 @@ def generate_launch_description(): executable='control_node', name='ap1_control', output='screen', - arguments=[ - os.path.join(get_package_share_directory('ap1_control'), 'config', 'control_node_cfg.csv'), + parameters=[ + os.path.join(get_package_share_directory('ap1_control'), 'config', 'control.yaml'), ], ) @@ -26,8 +26,8 @@ def generate_launch_description(): executable='planner_node', name='ap1_planning', output='screen', - arguments=[ - os.path.join(get_package_share_directory('ap1_planning'), 'config', 'stop_sign_transitions.yaml'), + parameters=[ + os.path.join(get_package_share_directory('ap1_planning'), 'config', 'planner.yaml'), ], ) diff --git a/src/control/config/control.yaml b/src/control/config/control.yaml new file mode 100644 index 0000000..c192fdc --- /dev/null +++ b/src/control/config/control.yaml @@ -0,0 +1,7 @@ +ap1_control: + ros__parameters: + wheelbase: 2.5 + a_max: 3.0 + delta_max: 0.5 + throttle_gain: 1.0 + brake_gain: 1.0 diff --git a/src/control/config/control_node_cfg.csv b/src/control/config/control_node_cfg.csv deleted file mode 100644 index a3aa583..0000000 --- a/src/control/config/control_node_cfg.csv +++ /dev/null @@ -1,5 +0,0 @@ -wheelbase,2.5 -a_max,3.0 -delta_max,0.5 -throttle_gain,1.0 -brake_gain,1.0 diff --git a/src/control/include/ap1/control/ackermann_controller.hpp b/src/control/include/ap1/control/ackermann_controller.hpp index a770f04..c806e39 100644 --- a/src/control/include/ap1/control/ackermann_controller.hpp +++ b/src/control/include/ap1/control/ackermann_controller.hpp @@ -8,7 +8,6 @@ #ifndef AP1_ACKERMANN_CONTROLLER_HPP #define AP1_ACKERMANN_CONTROLLER_HPP -#include #include "vectors.hpp" namespace ap1::control @@ -36,8 +35,6 @@ class AckermannController Command compute_command(const vec3f& acc, const vec3f& vel); - static Config load_config(const std::string &path); - private: Config cfg_; }; diff --git a/src/control/include/ap1/control/control_node.hpp b/src/control/include/ap1/control/control_node.hpp index 900083d..31a65ec 100644 --- a/src/control/include/ap1/control/control_node.hpp +++ b/src/control/include/ap1/control/control_node.hpp @@ -58,7 +58,7 @@ class ControlNode : public rclcpp::Node void control_loop_callback(); public: - ControlNode(const std::string& cfg_path, float rate_hz = 60); + explicit ControlNode(double rate_hz = 60); }; } // namespace ap1::control diff --git a/src/control/src/ackermann_controller.cpp b/src/control/src/ackermann_controller.cpp index 75491e8..58a6deb 100644 --- a/src/control/src/ackermann_controller.cpp +++ b/src/control/src/ackermann_controller.cpp @@ -6,12 +6,7 @@ #include #include -#include -#include -#include -#include -#include -#include +#include #include "vectors.hpp" #include "ap1/control/ackermann_controller.hpp" @@ -20,38 +15,6 @@ namespace ap1::control { -// also this should be moved to a csv/config loader -std::unordered_map load_csv_config(const std::string& path) -{ - std::ifstream file(path); - if (!file.is_open()) - { - throw std::runtime_error("Failed to open config file: " + path); - } - - std::unordered_map config; - std::string line; - while (std::getline(file, line)) - { - std::istringstream ss(line); - std::string key, value_str; - if (std::getline(ss, key, ',') && std::getline(ss, value_str)) - { - try - { - double value = std::stod(value_str); - config[key] = value; - } - catch (const std::exception& e) - { - throw std::runtime_error("Invalid vlaue for key " + key + ": " + value_str); - } - } - } - - return config; -} - AckermannController::AckermannController(const Config& cfg) : cfg_(cfg) { printf("Created Ackermann Controller with config: a_max=%f, delta_max=%f, L=%f, throttle_gain=%f, brake_gain=%f\n", @@ -81,18 +44,4 @@ AckermannController::Command AckermannController::compute_command(const vec3f& a return cmd; } -AckermannController::Config AckermannController::load_config(const std::string& path) -{ - Config cfg; - - auto map = load_csv_config(path); - - cfg.L = map["wheelbase"]; - cfg.a_max = map["a_max"]; - cfg.delta_max = map["delta_max"]; - cfg.throttle_gain = map["throttle_gain"]; - cfg.brake_gain = map["brake_gain"]; - - return cfg; -} } // namespace ap1::control diff --git a/src/control/src/control_node.cpp b/src/control/src/control_node.cpp index bfa873e..799455f 100644 --- a/src/control/src/control_node.cpp +++ b/src/control/src/control_node.cpp @@ -100,9 +100,15 @@ void ControlNode::control_loop_callback() brake_pub_->publish(brake_msg); } -ControlNode::ControlNode(const std::string& cfg_path, float rate_hz) - : Node("control_node"), rate_hz_(rate_hz), controller_(new PDController()), - ackermann_controller_(AckermannController(AckermannController::load_config(cfg_path))) +ControlNode::ControlNode(double rate_hz) + : Node("ap1_control"), rate_hz_(rate_hz), controller_(new PDController()), + ackermann_controller_(AckermannController::Config{ + declare_parameter("wheelbase"), + declare_parameter("a_max"), + declare_parameter("delta_max"), + declare_parameter("throttle_gain"), + declare_parameter("brake_gain"), + }) { // Subs speed_profile_sub_ = this->create_subscription( diff --git a/src/control/src/main.cpp b/src/control/src/main.cpp index 596b78e..9560ef1 100644 --- a/src/control/src/main.cpp +++ b/src/control/src/main.cpp @@ -1,28 +1,10 @@ -#include -#include - #include "ap1/control/control_node.hpp" - -const char* LOGGER_NAME = "main"; +#include "rclcpp/rclcpp.hpp" int main(int argc, char** argv) { - // init ros & ros logger rclcpp::init(argc, argv); - - // get control node config path from args - std::string config_path = ""; - if (argc > 1) - { - config_path = argv[1]; - } - else - { - RCLCPP_ERROR(rclcpp::get_logger(LOGGER_NAME), "Usage: control_node "); - return 1; - } - - auto node = std::make_shared(config_path); + auto node = std::make_shared(); rclcpp::spin(node); rclcpp::shutdown(); return 0; diff --git a/src/planning/CMakeLists.txt b/src/planning/CMakeLists.txt index 762c864..c99d9fc 100644 --- a/src/planning/CMakeLists.txt +++ b/src/planning/CMakeLists.txt @@ -11,7 +11,6 @@ find_package(rclcpp REQUIRED) find_package(std_msgs REQUIRED) find_package(geometry_msgs REQUIRED) find_package(ap1_msgs REQUIRED) -find_package(yaml-cpp REQUIRED) add_executable(planner_node src/behaviours.cpp @@ -35,9 +34,6 @@ ament_target_dependencies( geometry_msgs ap1_msgs ) -target_link_libraries(planner_node - yaml-cpp -) install(TARGETS planner_node diff --git a/src/planning/config/planner.yaml b/src/planning/config/planner.yaml index 2f7bd68..76d6449 100644 --- a/src/planning/config/planner.yaml +++ b/src/planning/config/planner.yaml @@ -10,3 +10,9 @@ ap1_planning: target_path: /ap1/planning/target_path speed_profile: /ap1/planning/speed_profile target_speed: /ap1/control/target_speed + # Ordered rules in the form " ". + transitions: + - "Driving SignDetected Stopping" + - "Stopping HasStopped Stopped" + - "Stopped StopTimeElapsed DrivingThrough" + - "DrivingThrough DriveThruDistanceCovered Driving" diff --git a/src/planning/config/stop_sign_transitions.yaml b/src/planning/config/stop_sign_transitions.yaml deleted file mode 100644 index 069124a..0000000 --- a/src/planning/config/stop_sign_transitions.yaml +++ /dev/null @@ -1,13 +0,0 @@ -transitions: - - from: Driving - event: SignDetected - to: Stopping - - from: Stopping - event: HasStopped - to: Stopped - - from: Stopped - event: StopTimeElapsed - to: DrivingThrough - - from: DrivingThrough - event: DriveThruDistanceCovered - to: Driving diff --git a/src/planning/include/ap1/planning/fsm.hpp b/src/planning/include/ap1/planning/fsm.hpp index 6cbfb34..fa87cbf 100644 --- a/src/planning/include/ap1/planning/fsm.hpp +++ b/src/planning/include/ap1/planning/fsm.hpp @@ -42,7 +42,7 @@ struct FSM VehicleState current_state; // the state of the vehicle std::vector transitions; // transitions between states - FSM(rclcpp::Time now, VehicleState default_state, std::string transitions_path); + FSM(rclcpp::Time now, VehicleState default_state, std::vector transitions); }; // Lookup tables @@ -58,13 +58,8 @@ constexpr std::array, 4> event_table{ {"StopTimeElapsed", Event::StopTimeElapsed}, {"DriveThruDistanceCovered", Event::DriveThruDistanceCovered}}}; -/** - * @brief Loads a transition table from a yaml file. - * - * @param path - * @return std::vector - */ -std::vector load_transitions_from_file(std::string path); +// Entries are ordered triples of source state, event, and destination state. +std::vector parse_transitions(const std::vector& entries); /** * @brief Transitions to the next state based on a transition table and current state. diff --git a/src/planning/include/ap1/planning/planner_node.hpp b/src/planning/include/ap1/planning/planner_node.hpp index 739d4ab..3192258 100644 --- a/src/planning/include/ap1/planning/planner_node.hpp +++ b/src/planning/include/ap1/planning/planner_node.hpp @@ -44,7 +44,7 @@ class PlannerNode : public rclcpp::Node * * @param rate_hz Primary loop update frequency. */ - PlannerNode(double rate_hz, std::string transitions_path); + explicit PlannerNode(double rate_hz = 60); private: const double rate_hz_; bool debug_; diff --git a/src/planning/src/fsm.cpp b/src/planning/src/fsm.cpp index 0b85e1e..5c55857 100644 --- a/src/planning/src/fsm.cpp +++ b/src/planning/src/fsm.cpp @@ -1,11 +1,9 @@ -#include +#include #include #include #include -#include - #include "ap1/planning/fsm.hpp" #include "ap1/planning/state_context.hpp" @@ -16,14 +14,8 @@ using ap1::planning::fsm::VehicleState; using namespace ap1::planning; -// Helper funcs -VehicleState state_from_string(const std::string& s); -Event event_from_string(const std::string& s); - -// Beef and potatoes -fsm::FSM::FSM(rclcpp::Time now, VehicleState default_state, std::string transitions_path) - : context(now), current_state(default_state), - transitions(load_transitions_from_file(transitions_path)) +fsm::FSM::FSM(rclcpp::Time now, VehicleState default_state, std::vector transitions) + : context(now), current_state(default_state), transitions(std::move(transitions)) { } @@ -83,63 +75,32 @@ void fsm::on_state_change(const VehicleState from, const VehicleState to, const } } -std::vector fsm::load_transitions_from_file(std::string path) +std::vector fsm::parse_transitions(const std::vector& entries) { - // 1. Check extension - std::filesystem::path fs_path(path); - if (fs_path.extension() != ".yaml") - { - throw std::runtime_error("Invalid file extension. Expected .yaml"); - } - - // Load that bomboclaat file - YAML::Node root; - try - { - root = YAML::LoadFile(path); - } - catch (const std::exception& e) - { - throw std::runtime_error(std::string("Failed to load YAML file: ") + e.what()); - } - - // Make sure we have a root - if (!root["transitions"]) + if (entries.empty()) { - throw std::runtime_error("Missing 'transitions' in config."); + throw std::runtime_error("The transitions parameter must contain at least one transition"); } - // Build transitions vector std::vector transitions; - - for (const auto& node : root["transitions"]) + for (const auto& entry : entries) { - if (!node.IsMap()) + std::istringstream fields(entry); + std::string from_name, event_name, to_name, extra; + if (!(fields >> from_name >> event_name >> to_name) || (fields >> extra)) { - throw std::runtime_error("Each transition must be a map"); + throw std::runtime_error("Expected ' ' in transition: " + entry); } - if (!node["from"] || !node["event"] || !node["to"]) + const auto from = to_state(from_name); + const auto event = to_event(event_name); + const auto to = to_state(to_name); + if (!from || !event || !to) { - throw std::runtime_error( - "Transntion is missing fields. Must have 'from', 'event', to'"); + throw std::runtime_error("Unknown state or event in transition: " + entry); } - std::string from_str = node["from"].as(); - std::string event_str = node["event"].as(); - std::string to_str = node["to"].as(); - - // validate against enum options - VehicleState from = to_state(from_str).value(); - Event event = to_event(event_str).value(); - VehicleState to = to_state(to_str).value(); - - transitions.push_back({from, event, to}); - } - - if (transitions.empty()) - { - throw std::runtime_error("No transitions defined in file"); + transitions.push_back({*from, *event, *to}); } return transitions; diff --git a/src/planning/src/main.cpp b/src/planning/src/main.cpp index b50f01b..4c807af 100644 --- a/src/planning/src/main.cpp +++ b/src/planning/src/main.cpp @@ -1,31 +1,11 @@ #include "ap1/planning/planner_node.hpp" #include "rclcpp/rclcpp.hpp" -const char* LOGGER_NAME = "main"; - -// should ideally provide rate_hz parsed from config file -// leaving this for when launch files are created -const float RATE_HZ = 60; - int main(int argc, char** argv) { rclcpp::init(argc, argv); - - // get planning node config path from args - std::string config_path = ""; - if (argc > 1) - { - config_path = argv[1]; - } - else - { - RCLCPP_ERROR(rclcpp::get_logger(LOGGER_NAME), "Usage: planner_node "); - return 1; - } - auto node = std::make_shared(RATE_HZ, argv[1]); - + auto node = std::make_shared(); rclcpp::spin(node); rclcpp::shutdown(); - return 0; } diff --git a/src/planning/src/planner_node.cpp b/src/planning/src/planner_node.cpp index 159dea9..f6d0f1e 100644 --- a/src/planning/src/planner_node.cpp +++ b/src/planning/src/planner_node.cpp @@ -34,9 +34,11 @@ using ap1_msgs::msg::TargetPathStamped; namespace ap1::planning { -PlannerNode::PlannerNode(double rate_hz, std::string transitions_path) - : Node("planner_node"), rate_hz_(rate_hz), - fsm(this->now(), fsm::VehicleState::Driving, transitions_path), event_generator() +PlannerNode::PlannerNode(double rate_hz) + : Node("ap1_planning"), rate_hz_(rate_hz), + fsm(this->now(), fsm::VehicleState::Driving, + fsm::parse_transitions(declare_parameter>("transitions"))), + event_generator() { // Read and validate DEBUG once at startup. this->debug_ = this->declare_parameter("DEBUG");