Compare commits
211 Commits
sl-mechani
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b353a2ba29 | |||
| 329797d43c | |||
| 1ae600ead4 | |||
| e73674f161 | |||
| 972db16635 | |||
| 5250ce67ad | |||
| d2175bf7d0 | |||
| 2a13c3e18b | |||
| 3f0508815d | |||
| d9e7acfa0d | |||
| c02faf3ac2 | |||
| 61f241ae1d | |||
| 26e71d7a14 | |||
| 2fa097e3d6 | |||
| b830420efc | |||
| 9d6c72bd24 | |||
| 9b460e34db | |||
| c297d24a48 | |||
| 885a66f24b | |||
| fbc88f5c2a | |||
| 0122957b6b | |||
| 759277a7e0 | |||
| b1e8da4403 | |||
| dd8afb480f | |||
| 43fb3f1147 | |||
| 416a393134 | |||
| 60f500c206 | |||
| b1cd15327f | |||
| b72e435bf3 | |||
| 9cf98830c6 | |||
| a1233dbd04 | |||
| fa75c442a7 | |||
| fe84ff6039 | |||
| fda6ab99ff | |||
| 308be74330 | |||
| 19be6bbe11 | |||
| 5ef1f7e365 | |||
| bfca6d1d92 | |||
| f71dad5344 | |||
| 5e97676703 | |||
| 30b0f245e1 | |||
| 7db6158ada | |||
| f0d9fead74 | |||
| 811a2ccc5c | |||
| bb354336c3 | |||
| 6d047ca50c | |||
| f384cc4810 | |||
| 2560718b39 | |||
| e220797c07 | |||
| b5354e1ac0 | |||
| f59bc9931e | |||
| de4d1bbe3a | |||
| d235c414e0 | |||
| 62d7525df7 | |||
| 2b3f3584a9 | |||
| 7a100b2d14 | |||
| 37b646780d | |||
| 2d60aab79c | |||
| af982bb575 | |||
| 6d59baa30e | |||
| 1ec4d3fc58 | |||
|
|
c6cf64217d | ||
| 5906af542b | |||
| 4318589496 | |||
| 441c56b1d9 | |||
| 334ab9249c | |||
| 4affd6d0cb | |||
| fe979fdd1f | |||
| 9e8ea3c411 | |||
| d57c0bd51d | |||
| fdda6fe5ee | |||
| 3457919c7a | |||
| cfdd74a9dc | |||
| 4f3a30d871 | |||
| 7eb3f187e2 | |||
|
|
a50dbe7e56 | ||
| 6561e35fd6 | |||
| 4dc75c8a70 | |||
| 4d0a377cee | |||
| 06101371ff | |||
| cf0ceb4641 | |||
| ee16bae9fb | |||
| 70fa404437 | |||
| c11cbaf3e6 | |||
| d132b74df0 | |||
| 8985934f29 | |||
| 9ed678ca35 | |||
| 06db56103f | |||
| 05ba557dca | |||
| 0a2f336eb8 | |||
| 5e82878083 | |||
| 92c0628c62 | |||
| 56c59f60fe | |||
| 7f67fc6abe | |||
| ea5203b67d | |||
| 14c80dc33c | |||
| 7d2d41ba9f | |||
| b74307c58a | |||
|
|
9d2b19104f | ||
| 89f892e5ef | |||
|
|
289185e6cf | ||
| 4f81571dd3 | |||
|
|
d9b4b10b90 | ||
|
|
a96fd91ed7 | ||
|
|
bf8df6af8f | ||
| d8b25bad77 | |||
| b2c9f368f6 | |||
| a506989af6 | |||
| 1d87899270 | |||
| 0fcad75cb4 | |||
| 5aadf4b5c8 | |||
| 5f0affcd79 | |||
| 779f9d00e2 | |||
| 4c7fa938a5 | |||
| 45332f1a8b | |||
| af46b15391 | |||
| e1d605dba7 | |||
| c8c8794daa | |||
| b5862ef529 | |||
|
|
343e53081a | ||
| 602fbc6ab3 | |||
| 1fd935b87e | |||
| b6c6dbd838 | |||
|
|
26bf4ab8d3 | ||
| cb802ee76f | |||
| 0e8758e9e1 | |||
| 7785a16bff | |||
| 68568b2b66 | |||
| 38df5b4ebb | |||
| fea550c851 | |||
| 13b17a11e1 | |||
| 96d13052b4 | |||
| a01fa091d4 | |||
| 62aab7164e | |||
| 7e12dab4ae | |||
| 1e69337ffd | |||
| 82ad626a94 | |||
| 921eaba8b3 | |||
|
|
65e0009118 | ||
|
|
9b1f3ddaf0 | ||
| 837c42a00d | |||
| c0bb4f6276 | |||
| 2996d18ace | |||
| bb5eff1382 | |||
| 8b1d6483cf | |||
| 6c00d6a321 | |||
| 2460ba27c7 | |||
| 2367e08140 | |||
| f188997192 | |||
| 7e5f673f7d | |||
| be4966b01d | |||
|
|
82cc223fb8 | ||
| 5f03e4cbef | |||
|
|
587ca8a98e | ||
| 40b0917c33 | |||
| c76d5b0dd7 | |||
|
|
c62444cc0e | ||
|
|
dd13569413 | ||
| 816d165db4 | |||
| cbcae34b79 | |||
| 061189670a | |||
| 8fbe7c0033 | |||
| 15ff5acca7 | |||
| f2743198e5 | |||
| 6512c805be | |||
| 1da1d50171 | |||
| 6a8b6a679e | |||
| ddf8332cd7 | |||
| e9429e6177 | |||
| 2b06161cb4 | |||
| c1b82608d5 | |||
|
|
08bc23f6df | ||
| 5dac6337e6 | |||
|
|
4b8d1b2ff7 | ||
| 5556c06153 | |||
| 5a1290a8f9 | |||
| 7b75cdad1a | |||
| b09017c949 | |||
| 1726558a7a | |||
| 5a3f4d1df6 | |||
| b2f01b42f3 | |||
| a7eb2ba3e5 | |||
| 4035b4cfc3 | |||
|
|
7708c63698 | ||
| 131d85a0d3 | |||
| 44691742c8 | |||
|
|
814624045a | ||
| 929c9ecd74 | |||
| 8592361095 | |||
| 35440b7463 | |||
| d36b79371d | |||
| 3b0b9d0f16 | |||
| 4116232b27 | |||
| c7dcce18c2 | |||
| 8e03a209be | |||
|
|
a4879b6b3f | ||
| 2180b61440 | |||
| c2d9adad25 | |||
| 76668d8346 | |||
| d8e5490a0e | |||
| 6409360428 | |||
| 6c5ecc9e00 | |||
| df6b79d676 | |||
| 0dbd64a6f4 | |||
| 8e21201dd4 | |||
| 80e3b23aec | |||
| 36643dd652 | |||
| da6a17cdcb | |||
| cc3a65f4a4 | |||
| c68b751590 | |||
|
|
c249b2d74e |
162
.gitea/workflows/ota-release.yml
Normal file
162
.gitea/workflows/ota-release.yml
Normal file
@ -0,0 +1,162 @@
|
|||||||
|
# .gitea/workflows/ota-release.yml
|
||||||
|
# Gitea Actions — ESP32 OTA firmware build & release (bd-9kod)
|
||||||
|
#
|
||||||
|
# Triggers on signed release tags:
|
||||||
|
# esp32-balance/vX.Y.Z → builds esp32s3/balance/ (ESP32-S3 Balance board)
|
||||||
|
# esp32-io/vX.Y.Z → builds esp32s3-io/ (ESP32-S3 IO board)
|
||||||
|
#
|
||||||
|
# Uses the official espressif/idf Docker image for reproducible builds.
|
||||||
|
# Attaches <app>_<version>.bin + <app>_<version>.sha256 to the Gitea release.
|
||||||
|
# The ESP32 Balance OTA system fetches the .bin from the release asset URL.
|
||||||
|
|
||||||
|
name: OTA release — build & attach firmware
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "esp32-balance/v*"
|
||||||
|
- "esp32-io/v*"
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-release:
|
||||||
|
name: Build ${{ github.ref_name }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: espressif/idf:v5.2.2
|
||||||
|
options: --user root
|
||||||
|
|
||||||
|
steps:
|
||||||
|
# ── 1. Checkout ───────────────────────────────────────────────────────────
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# ── 2. Resolve build target from tag ─────────────────────────────────────
|
||||||
|
# Tag format: esp32-balance/v1.2.3 or esp32-io/v1.2.3
|
||||||
|
- name: Resolve project from tag
|
||||||
|
id: proj
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
TAG="${GITHUB_REF_NAME}"
|
||||||
|
case "$TAG" in
|
||||||
|
esp32-balance/*)
|
||||||
|
DIR="esp32s3/balance"
|
||||||
|
APP="esp32s3_balance"
|
||||||
|
;;
|
||||||
|
esp32-io/*)
|
||||||
|
DIR="esp32s3-io"
|
||||||
|
APP="esp32s3_io"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "::error::Unrecognised tag prefix: ${TAG}"
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
VERSION="${TAG#*/}"
|
||||||
|
echo "dir=${DIR}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "app=${APP}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "Build: ${APP} ${VERSION} from ${DIR}"
|
||||||
|
|
||||||
|
# ── 3. Build with ESP-IDF ─────────────────────────────────────────────────
|
||||||
|
- name: Build firmware (idf.py build)
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
. "${IDF_PATH}/export.sh"
|
||||||
|
cd "${{ steps.proj.outputs.dir }}"
|
||||||
|
idf.py build
|
||||||
|
|
||||||
|
# ── 4. Collect binary & generate checksum ────────────────────────────────
|
||||||
|
- name: Collect artifacts
|
||||||
|
id: art
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
APP="${{ steps.proj.outputs.app }}"
|
||||||
|
VER="${{ steps.proj.outputs.version }}"
|
||||||
|
BIN_SRC="${{ steps.proj.outputs.dir }}/build/${APP}.bin"
|
||||||
|
BIN_OUT="${APP}_${VER}.bin"
|
||||||
|
SHA_OUT="${APP}_${VER}.sha256"
|
||||||
|
|
||||||
|
cp "$BIN_SRC" "$BIN_OUT"
|
||||||
|
sha256sum "$BIN_OUT" > "$SHA_OUT"
|
||||||
|
|
||||||
|
echo "bin=${BIN_OUT}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "sha=${SHA_OUT}" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
echo "Binary: ${BIN_OUT} ($(wc -c < "$BIN_OUT") bytes)"
|
||||||
|
echo "Checksum: $(cat "$SHA_OUT")"
|
||||||
|
|
||||||
|
# ── 5. Archive artifacts in CI workspace ─────────────────────────────────
|
||||||
|
- name: Upload build artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: firmware-${{ steps.proj.outputs.app }}-${{ steps.proj.outputs.version }}
|
||||||
|
path: |
|
||||||
|
${{ steps.art.outputs.bin }}
|
||||||
|
${{ steps.art.outputs.sha }}
|
||||||
|
|
||||||
|
# ── 6. Create Gitea release (if needed) & upload assets ──────────────────
|
||||||
|
# Uses GITHUB_TOKEN (auto-provided, contents:write from permissions block).
|
||||||
|
# URL-encodes the tag to handle the slash in esp32-balance/vX.Y.Z.
|
||||||
|
- name: Publish assets to Gitea release
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
GITEA_URL: https://gitea.vayrette.com
|
||||||
|
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
REPO: ${{ github.repository }}
|
||||||
|
TAG: ${{ steps.proj.outputs.tag }}
|
||||||
|
BIN: ${{ steps.art.outputs.bin }}
|
||||||
|
SHA: ${{ steps.art.outputs.sha }}
|
||||||
|
run: |
|
||||||
|
API="${GITEA_URL}/api/v1/repos/${REPO}"
|
||||||
|
|
||||||
|
# URL-encode the tag (slash in esp32-balance/vX.Y.Z must be escaped)
|
||||||
|
TAG_ENC=$(python3 -c "
|
||||||
|
import urllib.parse, sys
|
||||||
|
print(urllib.parse.quote(sys.argv[1], safe=''))
|
||||||
|
" "$TAG")
|
||||||
|
|
||||||
|
# Try to fetch an existing release for this tag
|
||||||
|
RELEASE=$(curl -sf \
|
||||||
|
-H "Authorization: token ${TOKEN}" \
|
||||||
|
"${API}/releases/tags/${TAG_ENC}") || true
|
||||||
|
|
||||||
|
# If no release yet, create it
|
||||||
|
if [ -z "$RELEASE" ]; then
|
||||||
|
echo "Creating release for tag: ${TAG}"
|
||||||
|
RELEASE=$(curl -sf \
|
||||||
|
-X POST \
|
||||||
|
-H "Authorization: token ${TOKEN}" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d "$(python3 -c "
|
||||||
|
import json, sys
|
||||||
|
print(json.dumps({
|
||||||
|
'tag_name': sys.argv[1],
|
||||||
|
'name': sys.argv[1],
|
||||||
|
'draft': False,
|
||||||
|
'prerelease': False,
|
||||||
|
}))
|
||||||
|
" "$TAG")" \
|
||||||
|
"${API}/releases")
|
||||||
|
fi
|
||||||
|
|
||||||
|
RELEASE_ID=$(echo "$RELEASE" | python3 -c "
|
||||||
|
import sys, json; print(json.load(sys.stdin)['id'])
|
||||||
|
")
|
||||||
|
echo "Release ID: ${RELEASE_ID}"
|
||||||
|
|
||||||
|
# Upload binary and checksum
|
||||||
|
for FILE in "$BIN" "$SHA"; do
|
||||||
|
FNAME=$(basename "$FILE")
|
||||||
|
echo "Uploading: ${FNAME}"
|
||||||
|
curl -sf \
|
||||||
|
-X POST \
|
||||||
|
-H "Authorization: token ${TOKEN}" \
|
||||||
|
-F "attachment=@${FILE}" \
|
||||||
|
"${API}/releases/${RELEASE_ID}/assets?name=${FNAME}"
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "Published: ${BIN} + ${SHA} → release ${TAG}"
|
||||||
@ -7,7 +7,11 @@ The robot can now be armed and operated autonomously from the Jetson without req
|
|||||||
|
|
||||||
### Jetson Autonomous Arming
|
### Jetson Autonomous Arming
|
||||||
- Command: `A\n` (single byte 'A' followed by newline)
|
- Command: `A\n` (single byte 'A' followed by newline)
|
||||||
- Sent via USB CDC to the STM32 firmware
|
<<<<<<< HEAD
|
||||||
|
- Sent via USB CDC to the ESP32 BALANCE firmware
|
||||||
|
=======
|
||||||
|
- Sent via USB Serial (CH343) to the ESP32-S3 firmware
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
- Robot arms after ARMING_HOLD_MS (~500ms) safety hold period
|
- Robot arms after ARMING_HOLD_MS (~500ms) safety hold period
|
||||||
- Works even when RC is not connected or not armed
|
- Works even when RC is not connected or not armed
|
||||||
|
|
||||||
@ -42,7 +46,11 @@ The robot can now be armed and operated autonomously from the Jetson without req
|
|||||||
|
|
||||||
## Command Protocol
|
## Command Protocol
|
||||||
|
|
||||||
### From Jetson to STM32 (USB CDC)
|
<<<<<<< HEAD
|
||||||
|
### From Jetson to ESP32 BALANCE (USB CDC)
|
||||||
|
=======
|
||||||
|
### From Jetson to ESP32-S3 (USB Serial (CH343))
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
```
|
```
|
||||||
A — Request arm (triggers safety hold, then motors enable)
|
A — Request arm (triggers safety hold, then motors enable)
|
||||||
D — Request disarm (immediate motor stop)
|
D — Request disarm (immediate motor stop)
|
||||||
@ -52,7 +60,11 @@ H — Heartbeat (refresh timeout timer, every 500ms)
|
|||||||
C<spd>,<str> — Drive command: speed, steer (also refreshes heartbeat)
|
C<spd>,<str> — Drive command: speed, steer (also refreshes heartbeat)
|
||||||
```
|
```
|
||||||
|
|
||||||
### From STM32 to Jetson (USB CDC)
|
<<<<<<< HEAD
|
||||||
|
### From ESP32 BALANCE to Jetson (USB CDC)
|
||||||
|
=======
|
||||||
|
### From ESP32-S3 to Jetson (USB Serial (CH343))
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
Motor commands are gated by `bal.state == BALANCE_ARMED`:
|
Motor commands are gated by `bal.state == BALANCE_ARMED`:
|
||||||
- When ARMED: Motor commands sent every 20ms (50 Hz)
|
- When ARMED: Motor commands sent every 20ms (50 Hz)
|
||||||
- When DISARMED: Zero sent every 20ms (prevents ESC timeout)
|
- When DISARMED: Zero sent every 20ms (prevents ESC timeout)
|
||||||
|
|||||||
31
CLAUDE.md
31
CLAUDE.md
@ -1,17 +1,36 @@
|
|||||||
# SaltyLab Firmware — Agent Playbook
|
# SaltyLab Firmware — Agent Playbook
|
||||||
|
|
||||||
## Project
|
## Project
|
||||||
Self-balancing two-wheeled robot: STM32F722 flight controller, hoverboard hub motors, Jetson Nano for AI/SLAM.
|
<<<<<<< HEAD
|
||||||
|
**SAUL-TEE** — 4-wheel wagon (870×510×550 mm, 23 kg).
|
||||||
|
Two ESP32-S3 boards + Jetson Orin via CAN. Full spec: `docs/SAUL-TEE-SYSTEM-REFERENCE.md`
|
||||||
|
|
||||||
|
| Board | Role |
|
||||||
|
|-------|------|
|
||||||
|
| **ESP32-S3 BALANCE** | QMI8658 IMU, PID balance, CAN→VESC (L:68 / R:56), GC9A01 LCD (Waveshare Touch LCD 1.28) |
|
||||||
|
| **ESP32-S3 IO** | TBS Crossfire RC, ELRS failover, BTS7960 motors, NFC/baro/ToF, WS2812 |
|
||||||
|
| **Jetson Orin** | AI/SLAM, CANable2 USB→CAN, cmds 0x300–0x303, telemetry 0x400–0x401 |
|
||||||
|
|
||||||
|
> **Legacy:** `src/` and `include/` = archived STM32 HAL — do not extend. New firmware in `esp32/`.
|
||||||
|
=======
|
||||||
|
Self-balancing two-wheeled robot: ESP32-S3 ESP32-S3 BALANCE, hoverboard hub motors, Jetson Orin Nano Super for AI/SLAM.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
## Team
|
## Team
|
||||||
| Agent | Role | Focus |
|
| Agent | Role | Focus |
|
||||||
|-------|------|-------|
|
|-------|------|-------|
|
||||||
| **sl-firmware** | Embedded Firmware Lead | STM32 HAL, USB CDC debugging, SPI/UART, PlatformIO, DFU bootloader |
|
<<<<<<< HEAD
|
||||||
|
| **sl-firmware** | Embedded Firmware Lead | ESP32-S3, ESP-IDF, QMI8658, CAN/UART protocol, BTS7960 |
|
||||||
|
| **sl-controls** | Control Systems Engineer | PID tuning, IMU fusion, balance loop, safety |
|
||||||
|
| **sl-perception** | Perception / SLAM Engineer | Jetson Orin, RealSense D435i, RPLIDAR, ROS2, Nav2 |
|
||||||
|
=======
|
||||||
|
| **sl-firmware** | Embedded Firmware Lead | ESP-IDF, USB Serial (CH343) debugging, SPI/UART, PlatformIO, DFU bootloader |
|
||||||
| **sl-controls** | Control Systems Engineer | PID tuning, IMU sensor fusion, real-time control loops, safety systems |
|
| **sl-controls** | Control Systems Engineer | PID tuning, IMU sensor fusion, real-time control loops, safety systems |
|
||||||
| **sl-perception** | Perception / SLAM Engineer | Jetson Nano, RealSense D435i, RPLIDAR, ROS2, Nav2 |
|
| **sl-perception** | Perception / SLAM Engineer | Jetson Orin Nano Super, RealSense D435i, RPLIDAR, ROS2, Nav2 |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
USB CDC TX bug resolved (PR #10 — DCache MPU non-cacheable region + IWDG ordering fix).
|
USB Serial (CH343) TX bug resolved (PR #10 — DCache MPU non-cacheable region + IWDG ordering fix).
|
||||||
|
|
||||||
## Repo Structure
|
## Repo Structure
|
||||||
- `projects/saltybot/SALTYLAB.md` — Design doc
|
- `projects/saltybot/SALTYLAB.md` — Design doc
|
||||||
@ -29,11 +48,11 @@ USB CDC TX bug resolved (PR #10 — DCache MPU non-cacheable region + IWDG order
|
|||||||
| `saltyrover-dev` | Integration — rover variant |
|
| `saltyrover-dev` | Integration — rover variant |
|
||||||
| `saltytank` | Stable — tracked tank variant |
|
| `saltytank` | Stable — tracked tank variant |
|
||||||
| `saltytank-dev` | Integration — tank variant |
|
| `saltytank-dev` | Integration — tank variant |
|
||||||
| `main` | Shared code only (IMU drivers, USB CDC, balance core, safety) |
|
| `main` | Shared code only (IMU drivers, USB Serial (CH343), balance core, safety) |
|
||||||
|
|
||||||
### Rules
|
### Rules
|
||||||
- Agents branch FROM `<variant>-dev` and PR back TO `<variant>-dev`
|
- Agents branch FROM `<variant>-dev` and PR back TO `<variant>-dev`
|
||||||
- Shared/infrastructure code (IMU drivers, USB CDC, balance core, safety) goes in `main`
|
- Shared/infrastructure code (IMU drivers, USB Serial (CH343), balance core, safety) goes in `main`
|
||||||
- Variant-specific code (motor topology, kinematics, config) goes in variant branches
|
- Variant-specific code (motor topology, kinematics, config) goes in variant branches
|
||||||
- Stable branches get promoted from `-dev` after review and hardware testing
|
- Stable branches get promoted from `-dev` after review and hardware testing
|
||||||
- **Current SaltyLab team** works against `saltylab-dev`
|
- **Current SaltyLab team** works against `saltylab-dev`
|
||||||
|
|||||||
52
TEAM.md
52
TEAM.md
@ -1,12 +1,22 @@
|
|||||||
# SaltyLab — Ideal Team
|
# SaltyLab — Ideal Team
|
||||||
|
|
||||||
## Project
|
## Project
|
||||||
Self-balancing two-wheeled robot using a drone flight controller (STM32F722), hoverboard hub motors, and eventually a Jetson Nano for AI/SLAM.
|
<<<<<<< HEAD
|
||||||
|
**SAUL-TEE** — 4-wheel wagon (870×510×550 mm, 23 kg).
|
||||||
|
Two ESP32-S3 boards (BALANCE + IO) + Jetson Orin. See `docs/SAUL-TEE-SYSTEM-REFERENCE.md`.
|
||||||
|
|
||||||
|
## Current Status
|
||||||
|
- **Hardware:** ESP32-S3 BALANCE (Waveshare Touch LCD 1.28, CH343 USB) + ESP32-S3 IO (bare devkit, JTAG USB)
|
||||||
|
- **Firmware:** ESP-IDF/PlatformIO target; legacy `src/` STM32 HAL archived
|
||||||
|
- **Comms:** UART 460800 baud inter-board; CANable2 USB→CAN for Orin; CAN 500 kbps to VESCs (L:68 / R:56)
|
||||||
|
=======
|
||||||
|
Self-balancing two-wheeled robot using a drone ESP32-S3 BALANCE (ESP32-S3), hoverboard hub motors, and eventually a Jetson Orin Nano Super for AI/SLAM.
|
||||||
|
|
||||||
## Current Status
|
## Current Status
|
||||||
- **Hardware:** Assembled — FC, motors, ESC, IMU, battery, RC all on hand
|
- **Hardware:** Assembled — FC, motors, ESC, IMU, battery, RC all on hand
|
||||||
- **Firmware:** Balance PID + hoverboard ESC protocol written, but blocked by USB CDC bug
|
- **Firmware:** Balance PID + hoverboard ESC protocol written, but blocked by USB Serial (CH343) bug
|
||||||
- **Blocker:** USB CDC TX stops working when peripheral inits (SPI/UART/GPIO) are added alongside USB OTG FS — see `USB_CDC_BUG.md`
|
- **Blocker:** USB Serial (CH343) TX stops working when peripheral inits (SPI/UART/GPIO) are added alongside USB on ESP32-S3 — see `legacy/stm32/USB_CDC_BUG.md` for historical context
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -14,18 +24,30 @@ Self-balancing two-wheeled robot using a drone flight controller (STM32F722), ho
|
|||||||
|
|
||||||
### 1. Embedded Firmware Engineer (Lead)
|
### 1. Embedded Firmware Engineer (Lead)
|
||||||
**Must-have:**
|
**Must-have:**
|
||||||
- Deep STM32 HAL experience (F7 series specifically)
|
<<<<<<< HEAD
|
||||||
|
- Deep ESP32 (Arduino/ESP-IDF) or STM32 HAL experience
|
||||||
- USB OTG FS / CDC ACM debugging (TxState, endpoint management, DMA conflicts)
|
- USB OTG FS / CDC ACM debugging (TxState, endpoint management, DMA conflicts)
|
||||||
- SPI + UART + USB coexistence on STM32
|
- SPI + UART + USB coexistence on ESP32
|
||||||
- PlatformIO or bare-metal STM32 toolchain
|
- PlatformIO or bare-metal ESP32 toolchain
|
||||||
- DFU bootloader implementation
|
- DFU bootloader implementation
|
||||||
|
=======
|
||||||
|
- Deep ESP-IDF experience (ESP32-S3 specifically)
|
||||||
|
- USB Serial (CH343) / UART debugging on ESP32-S3
|
||||||
|
- SPI + UART + USB coexistence on ESP32-S3
|
||||||
|
- ESP-IDF / Arduino-ESP32 toolchain
|
||||||
|
- OTA firmware update implementation
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
**Nice-to-have:**
|
**Nice-to-have:**
|
||||||
- Betaflight/iNav/ArduPilot codebase familiarity
|
- ESP32-S3 peripheral coexistence (SPI + UART + USB)
|
||||||
- PID control loop tuning for balance robots
|
- PID control loop tuning for balance robots
|
||||||
- FOC motor control (hoverboard ESC protocol)
|
- FOC motor control (hoverboard ESC protocol)
|
||||||
|
|
||||||
**Why:** The immediate blocker is a USB peripheral conflict. Need someone who's debugged STM32 USB issues before — this is not a software logic bug, it's a hardware peripheral interaction issue.
|
<<<<<<< HEAD
|
||||||
|
**Why:** The immediate blocker is a USB peripheral conflict. Need someone who's debugged STM32 USB issues before — ESP32 firmware for the balance loop and I/O needs to be written from scratch.
|
||||||
|
=======
|
||||||
|
**Why:** The immediate blocker is a USB peripheral conflict on ESP32-S3. Need someone who's debugged ESP32-S3 USB Serial (CH343) issues before — this is not a software logic bug, it's a hardware peripheral interaction issue.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
### 2. Control Systems / Robotics Engineer
|
### 2. Control Systems / Robotics Engineer
|
||||||
**Must-have:**
|
**Must-have:**
|
||||||
@ -43,7 +65,7 @@ Self-balancing two-wheeled robot using a drone flight controller (STM32F722), ho
|
|||||||
|
|
||||||
### 3. Perception / SLAM Engineer (Phase 2)
|
### 3. Perception / SLAM Engineer (Phase 2)
|
||||||
**Must-have:**
|
**Must-have:**
|
||||||
- Jetson Nano / NVIDIA Jetson platform
|
- Jetson Orin Nano Super / NVIDIA Jetson platform
|
||||||
- Intel RealSense D435i depth camera
|
- Intel RealSense D435i depth camera
|
||||||
- RPLIDAR integration
|
- RPLIDAR integration
|
||||||
- SLAM (ORB-SLAM3, RTAB-Map, or similar)
|
- SLAM (ORB-SLAM3, RTAB-Map, or similar)
|
||||||
@ -54,19 +76,23 @@ Self-balancing two-wheeled robot using a drone flight controller (STM32F722), ho
|
|||||||
- Obstacle avoidance
|
- Obstacle avoidance
|
||||||
- Nav2 stack
|
- Nav2 stack
|
||||||
|
|
||||||
**Why:** Phase 2 goal is autonomous navigation. Jetson Nano with RealSense + RPLIDAR for indoor mapping and person following.
|
**Why:** Phase 2 goal is autonomous navigation. Jetson Orin Nano Super with RealSense + RPLIDAR for indoor mapping and person following.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Hardware Reference
|
## Hardware Reference
|
||||||
| Component | Details |
|
| Component | Details |
|
||||||
|-----------|---------|
|
|-----------|---------|
|
||||||
| FC | MAMBA F722S (STM32F722RET6, MPU6000) |
|
<<<<<<< HEAD
|
||||||
|
| FC | ESP32 BALANCE (ESP32RET6, MPU6000) |
|
||||||
|
=======
|
||||||
|
| FC | ESP32-S3 BALANCE (ESP32-S3RET6, QMI8658) |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
| Motors | 2x 8" pneumatic hoverboard hub motors |
|
| Motors | 2x 8" pneumatic hoverboard hub motors |
|
||||||
| ESC | Hoverboard ESC (EFeru FOC firmware) |
|
| ESC | Hoverboard ESC (EFeru FOC firmware) |
|
||||||
| Battery | 36V pack |
|
| Battery | 36V pack |
|
||||||
| RC | BetaFPV ELRS 2.4GHz TX + RX |
|
| RC | BetaFPV ELRS 2.4GHz TX + RX |
|
||||||
| AI Brain | Jetson Nano + Noctua fan |
|
| AI Brain | Jetson Orin Nano Super + Noctua fan |
|
||||||
| Depth | Intel RealSense D435i |
|
| Depth | Intel RealSense D435i |
|
||||||
| LIDAR | RPLIDAR A1M8 |
|
| LIDAR | RPLIDAR A1M8 |
|
||||||
| Spare IMUs | BNO055, MPU6050 |
|
| Spare IMUs | BNO055, MPU6050 |
|
||||||
@ -74,4 +100,4 @@ Self-balancing two-wheeled robot using a drone flight controller (STM32F722), ho
|
|||||||
## Repo
|
## Repo
|
||||||
- Gitea: https://gitea.vayrette.com/seb/saltylab-firmware
|
- Gitea: https://gitea.vayrette.com/seb/saltylab-firmware
|
||||||
- Design doc: `projects/saltybot/SALTYLAB.md`
|
- Design doc: `projects/saltybot/SALTYLAB.md`
|
||||||
- Bug doc: `USB_CDC_BUG.md`
|
- Bug doc: `legacy/stm32/USB_CDC_BUG.md` (archived — STM32 era)
|
||||||
|
|||||||
46
android/build.gradle
Normal file
46
android/build.gradle
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
plugins {
|
||||||
|
id 'com.android.application'
|
||||||
|
id 'kotlin-android'
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
compileSdk 34
|
||||||
|
namespace 'com.saltylab.uwbtag'
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId "com.saltylab.uwbtag"
|
||||||
|
minSdk 26
|
||||||
|
targetSdk 34
|
||||||
|
versionCode 1
|
||||||
|
versionName "1.0"
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
minifyEnabled false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
viewBinding true
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility JavaVersion.VERSION_17
|
||||||
|
targetCompatibility JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlinOptions {
|
||||||
|
jvmTarget = '17'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation 'androidx.core:core-ktx:1.12.0'
|
||||||
|
implementation 'androidx.appcompat:appcompat:1.6.1'
|
||||||
|
implementation 'com.google.android.material:material:1.11.0'
|
||||||
|
implementation 'androidx.recyclerview:recyclerview:1.3.2'
|
||||||
|
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.7.0'
|
||||||
|
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
||||||
|
implementation 'com.google.code.gson:gson:2.10.1'
|
||||||
|
}
|
||||||
37
android/src/main/AndroidManifest.xml
Normal file
37
android/src/main/AndroidManifest.xml
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
|
||||||
|
<!-- BLE permissions (API 31+) -->
|
||||||
|
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"
|
||||||
|
android:usesPermissionFlags="neverForLocation" />
|
||||||
|
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||||
|
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
|
||||||
|
|
||||||
|
<!-- Legacy BLE (API < 31) -->
|
||||||
|
<uses-permission android:name="android.permission.BLUETOOTH"
|
||||||
|
android:maxSdkVersion="30" />
|
||||||
|
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
|
||||||
|
android:maxSdkVersion="30" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
|
||||||
|
android:maxSdkVersion="30" />
|
||||||
|
|
||||||
|
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:allowBackup="true"
|
||||||
|
android:label="UWB Tag Config"
|
||||||
|
android:theme="@style/Theme.MaterialComponents.DayNight.DarkActionBar">
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".UwbTagBleActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:launchMode="singleTop">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
|
||||||
|
</application>
|
||||||
|
|
||||||
|
</manifest>
|
||||||
444
android/src/main/kotlin/com/saltylab/uwbtag/UwbTagBleActivity.kt
Normal file
444
android/src/main/kotlin/com/saltylab/uwbtag/UwbTagBleActivity.kt
Normal file
@ -0,0 +1,444 @@
|
|||||||
|
package com.saltylab.uwbtag
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.bluetooth.*
|
||||||
|
import android.bluetooth.le.*
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.Button
|
||||||
|
import android.widget.TextView
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import androidx.core.app.ActivityCompat
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import com.google.android.material.card.MaterialCardView
|
||||||
|
import com.google.android.material.switchmaterial.SwitchMaterial
|
||||||
|
import com.google.android.material.textfield.TextInputEditText
|
||||||
|
import com.google.gson.Gson
|
||||||
|
import com.saltylab.uwbtag.databinding.ActivityUwbTagBleBinding
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// GATT service / characteristic UUIDs
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
private val SERVICE_UUID = UUID.fromString("12345678-1234-5678-1234-56789abcdef0")
|
||||||
|
private val CHAR_CONFIG_UUID = UUID.fromString("12345678-1234-5678-1234-56789abcdef1") // read/write JSON config
|
||||||
|
private val CHAR_STATUS_UUID = UUID.fromString("12345678-1234-5678-1234-56789abcdef2") // notify: tag status string
|
||||||
|
private val CHAR_BATT_UUID = UUID.fromString("12345678-1234-5678-1234-56789abcdef3") // notify: battery %
|
||||||
|
private val CCCD_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
|
||||||
|
|
||||||
|
// BLE scan timeout
|
||||||
|
private const val SCAN_TIMEOUT_MS = 15_000L
|
||||||
|
|
||||||
|
// Permissions request code
|
||||||
|
private const val REQ_PERMISSIONS = 1001
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Data model
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
data class TagConfig(
|
||||||
|
val tag_name: String = "UWB_TAG_0001",
|
||||||
|
val sleep_timeout_s: Int = 300,
|
||||||
|
val display_brightness: Int = 50,
|
||||||
|
val uwb_channel: Int = 9,
|
||||||
|
val ranging_interval_ms: Int = 100,
|
||||||
|
val battery_report: Boolean = true
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ScannedDevice(
|
||||||
|
val name: String,
|
||||||
|
val address: String,
|
||||||
|
var rssi: Int,
|
||||||
|
val device: BluetoothDevice
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// RecyclerView adapter for scanned devices
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
class DeviceAdapter(
|
||||||
|
private val onConnect: (ScannedDevice) -> Unit
|
||||||
|
) : RecyclerView.Adapter<DeviceAdapter.VH>() {
|
||||||
|
|
||||||
|
private val items = mutableListOf<ScannedDevice>()
|
||||||
|
|
||||||
|
fun update(device: ScannedDevice) {
|
||||||
|
val idx = items.indexOfFirst { it.address == device.address }
|
||||||
|
if (idx >= 0) {
|
||||||
|
items[idx] = device
|
||||||
|
notifyItemChanged(idx)
|
||||||
|
} else {
|
||||||
|
items.add(device)
|
||||||
|
notifyItemInserted(items.size - 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear() {
|
||||||
|
items.clear()
|
||||||
|
notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val view = LayoutInflater.from(parent.context)
|
||||||
|
.inflate(R.layout.item_ble_device, parent, false)
|
||||||
|
return VH(view)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int) = holder.bind(items[position])
|
||||||
|
override fun getItemCount() = items.size
|
||||||
|
|
||||||
|
inner class VH(view: View) : RecyclerView.ViewHolder(view) {
|
||||||
|
private val tvName = view.findViewById<TextView>(R.id.tvDeviceName)
|
||||||
|
private val tvAddress = view.findViewById<TextView>(R.id.tvDeviceAddress)
|
||||||
|
private val tvRssi = view.findViewById<TextView>(R.id.tvRssi)
|
||||||
|
private val btnConn = view.findViewById<Button>(R.id.btnConnect)
|
||||||
|
|
||||||
|
fun bind(item: ScannedDevice) {
|
||||||
|
tvName.text = item.name
|
||||||
|
tvAddress.text = item.address
|
||||||
|
tvRssi.text = "${item.rssi} dBm"
|
||||||
|
btnConn.setOnClickListener { onConnect(item) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Activity
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
@SuppressLint("MissingPermission") // permissions checked at runtime before any BLE call
|
||||||
|
class UwbTagBleActivity : AppCompatActivity() {
|
||||||
|
|
||||||
|
private lateinit var binding: ActivityUwbTagBleBinding
|
||||||
|
private val gson = Gson()
|
||||||
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
|
// BLE
|
||||||
|
private val btManager by lazy { getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager }
|
||||||
|
private val btAdapter by lazy { btManager.adapter }
|
||||||
|
private var bleScanner: BluetoothLeScanner? = null
|
||||||
|
private var gatt: BluetoothGatt? = null
|
||||||
|
private var configChar: BluetoothGattCharacteristic? = null
|
||||||
|
private var statusChar: BluetoothGattCharacteristic? = null
|
||||||
|
private var battChar: BluetoothGattCharacteristic? = null
|
||||||
|
private var isScanning = false
|
||||||
|
|
||||||
|
private val deviceAdapter = DeviceAdapter(onConnect = ::connectToDevice)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Lifecycle
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
binding = ActivityUwbTagBleBinding.inflate(layoutInflater)
|
||||||
|
setContentView(binding.root)
|
||||||
|
setSupportActionBar(binding.toolbar)
|
||||||
|
|
||||||
|
binding.rvDevices.layoutManager = LinearLayoutManager(this)
|
||||||
|
binding.rvDevices.adapter = deviceAdapter
|
||||||
|
|
||||||
|
binding.btnScan.setOnClickListener {
|
||||||
|
if (isScanning) stopScan() else startScanIfPermitted()
|
||||||
|
}
|
||||||
|
binding.btnDisconnect.setOnClickListener { disconnectGatt() }
|
||||||
|
binding.btnReadConfig.setOnClickListener { readConfig() }
|
||||||
|
binding.btnWriteConfig.setOnClickListener { writeConfig() }
|
||||||
|
|
||||||
|
requestBlePermissions()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
stopScan()
|
||||||
|
disconnectGatt()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Permissions
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
private fun requestBlePermissions() {
|
||||||
|
val needed = mutableListOf<String>()
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||||
|
if (!hasPermission(Manifest.permission.BLUETOOTH_SCAN))
|
||||||
|
needed += Manifest.permission.BLUETOOTH_SCAN
|
||||||
|
if (!hasPermission(Manifest.permission.BLUETOOTH_CONNECT))
|
||||||
|
needed += Manifest.permission.BLUETOOTH_CONNECT
|
||||||
|
} else {
|
||||||
|
if (!hasPermission(Manifest.permission.ACCESS_FINE_LOCATION))
|
||||||
|
needed += Manifest.permission.ACCESS_FINE_LOCATION
|
||||||
|
}
|
||||||
|
if (needed.isNotEmpty()) {
|
||||||
|
ActivityCompat.requestPermissions(this, needed.toTypedArray(), REQ_PERMISSIONS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasPermission(perm: String) =
|
||||||
|
ContextCompat.checkSelfPermission(this, perm) == PackageManager.PERMISSION_GRANTED
|
||||||
|
|
||||||
|
override fun onRequestPermissionsResult(
|
||||||
|
requestCode: Int, permissions: Array<out String>, grantResults: IntArray
|
||||||
|
) {
|
||||||
|
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||||
|
if (requestCode == REQ_PERMISSIONS &&
|
||||||
|
grantResults.any { it != PackageManager.PERMISSION_GRANTED }) {
|
||||||
|
toast("BLE permissions required")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// BLE Scan
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
private fun startScanIfPermitted() {
|
||||||
|
if (btAdapter?.isEnabled != true) { toast("Bluetooth is off"); return }
|
||||||
|
bleScanner = btAdapter.bluetoothLeScanner
|
||||||
|
val filter = ScanFilter.Builder()
|
||||||
|
.setDeviceNamePattern("UWB_TAG_.*".toRegex().toPattern())
|
||||||
|
.build()
|
||||||
|
val settings = ScanSettings.Builder()
|
||||||
|
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
|
||||||
|
.build()
|
||||||
|
deviceAdapter.clear()
|
||||||
|
bleScanner?.startScan(listOf(filter), settings, scanCallback)
|
||||||
|
isScanning = true
|
||||||
|
binding.btnScan.text = "Stop"
|
||||||
|
binding.tvScanStatus.text = "Scanning…"
|
||||||
|
mainHandler.postDelayed({ stopScan() }, SCAN_TIMEOUT_MS)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopScan() {
|
||||||
|
bleScanner?.stopScan(scanCallback)
|
||||||
|
isScanning = false
|
||||||
|
binding.btnScan.text = "Scan"
|
||||||
|
binding.tvScanStatus.text = "Scan stopped"
|
||||||
|
}
|
||||||
|
|
||||||
|
private val scanCallback = object : ScanCallback() {
|
||||||
|
override fun onScanResult(callbackType: Int, result: ScanResult) {
|
||||||
|
val name = result.device.name ?: return
|
||||||
|
if (!name.startsWith("UWB_TAG_")) return
|
||||||
|
val dev = ScannedDevice(
|
||||||
|
name = name,
|
||||||
|
address = result.device.address,
|
||||||
|
rssi = result.rssi,
|
||||||
|
device = result.device
|
||||||
|
)
|
||||||
|
mainHandler.post { deviceAdapter.update(dev) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onScanFailed(errorCode: Int) {
|
||||||
|
mainHandler.post {
|
||||||
|
binding.tvScanStatus.text = "Scan failed (code $errorCode)"
|
||||||
|
isScanning = false
|
||||||
|
binding.btnScan.text = "Scan"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// GATT Connection
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
private fun connectToDevice(scanned: ScannedDevice) {
|
||||||
|
stopScan()
|
||||||
|
binding.tvScanStatus.text = "Connecting to ${scanned.name}…"
|
||||||
|
gatt = scanned.device.connectGatt(this, false, gattCallback, BluetoothDevice.TRANSPORT_LE)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun disconnectGatt() {
|
||||||
|
gatt?.disconnect()
|
||||||
|
gatt?.close()
|
||||||
|
gatt = null
|
||||||
|
configChar = null
|
||||||
|
statusChar = null
|
||||||
|
battChar = null
|
||||||
|
mainHandler.post {
|
||||||
|
binding.cardConfig.visibility = View.GONE
|
||||||
|
binding.tvScanStatus.text = "Disconnected"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val gattCallback = object : BluetoothGattCallback() {
|
||||||
|
|
||||||
|
override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
|
||||||
|
when (newState) {
|
||||||
|
BluetoothProfile.STATE_CONNECTED -> {
|
||||||
|
mainHandler.post { binding.tvScanStatus.text = "Connected — discovering services…" }
|
||||||
|
g.discoverServices()
|
||||||
|
}
|
||||||
|
BluetoothProfile.STATE_DISCONNECTED -> {
|
||||||
|
mainHandler.post {
|
||||||
|
binding.cardConfig.visibility = View.GONE
|
||||||
|
binding.tvScanStatus.text = "Disconnected"
|
||||||
|
toast("Tag disconnected")
|
||||||
|
}
|
||||||
|
gatt?.close()
|
||||||
|
gatt = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onServicesDiscovered(g: BluetoothGatt, status: Int) {
|
||||||
|
if (status != BluetoothGatt.GATT_SUCCESS) {
|
||||||
|
mainHandler.post { toast("Service discovery failed") }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val service = g.getService(SERVICE_UUID)
|
||||||
|
if (service == null) {
|
||||||
|
mainHandler.post { toast("UWB config service not found on tag") }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
configChar = service.getCharacteristic(CHAR_CONFIG_UUID)
|
||||||
|
statusChar = service.getCharacteristic(CHAR_STATUS_UUID)
|
||||||
|
battChar = service.getCharacteristic(CHAR_BATT_UUID)
|
||||||
|
|
||||||
|
// Subscribe to status notifications
|
||||||
|
statusChar?.let { enableNotifications(g, it) }
|
||||||
|
battChar?.let { enableNotifications(g, it) }
|
||||||
|
|
||||||
|
// Initial config read
|
||||||
|
configChar?.let { g.readCharacteristic(it) }
|
||||||
|
|
||||||
|
mainHandler.post {
|
||||||
|
val devName = g.device.name ?: g.device.address
|
||||||
|
binding.tvConnectedName.text = "Connected: $devName"
|
||||||
|
binding.cardConfig.visibility = View.VISIBLE
|
||||||
|
binding.tvScanStatus.text = "Connected to $devName"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCharacteristicRead(
|
||||||
|
g: BluetoothGatt,
|
||||||
|
characteristic: BluetoothGattCharacteristic,
|
||||||
|
status: Int
|
||||||
|
) {
|
||||||
|
if (status != BluetoothGatt.GATT_SUCCESS) return
|
||||||
|
if (characteristic.uuid == CHAR_CONFIG_UUID) {
|
||||||
|
val json = characteristic.value?.toString(Charsets.UTF_8) ?: return
|
||||||
|
val cfg = runCatching { gson.fromJson(json, TagConfig::class.java) }.getOrNull() ?: return
|
||||||
|
mainHandler.post { populateFields(cfg) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// API 33+ callback
|
||||||
|
override fun onCharacteristicRead(
|
||||||
|
g: BluetoothGatt,
|
||||||
|
characteristic: BluetoothGattCharacteristic,
|
||||||
|
value: ByteArray,
|
||||||
|
status: Int
|
||||||
|
) {
|
||||||
|
if (status != BluetoothGatt.GATT_SUCCESS) return
|
||||||
|
if (characteristic.uuid == CHAR_CONFIG_UUID) {
|
||||||
|
val json = value.toString(Charsets.UTF_8)
|
||||||
|
val cfg = runCatching { gson.fromJson(json, TagConfig::class.java) }.getOrNull() ?: return
|
||||||
|
mainHandler.post { populateFields(cfg) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCharacteristicWrite(
|
||||||
|
g: BluetoothGatt,
|
||||||
|
characteristic: BluetoothGattCharacteristic,
|
||||||
|
status: Int
|
||||||
|
) {
|
||||||
|
val msg = if (status == BluetoothGatt.GATT_SUCCESS) "Config written" else "Write failed ($status)"
|
||||||
|
mainHandler.post { toast(msg) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCharacteristicChanged(
|
||||||
|
g: BluetoothGatt,
|
||||||
|
characteristic: BluetoothGattCharacteristic
|
||||||
|
) {
|
||||||
|
val value = characteristic.value ?: return
|
||||||
|
handleNotification(characteristic.uuid, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// API 33+ callback
|
||||||
|
override fun onCharacteristicChanged(
|
||||||
|
g: BluetoothGatt,
|
||||||
|
characteristic: BluetoothGattCharacteristic,
|
||||||
|
value: ByteArray
|
||||||
|
) {
|
||||||
|
handleNotification(characteristic.uuid, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Notification helpers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
private fun enableNotifications(g: BluetoothGatt, char: BluetoothGattCharacteristic) {
|
||||||
|
g.setCharacteristicNotification(char, true)
|
||||||
|
val descriptor = char.getDescriptor(CCCD_UUID) ?: return
|
||||||
|
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
|
||||||
|
g.writeDescriptor(descriptor)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleNotification(uuid: UUID, value: ByteArray) {
|
||||||
|
val text = value.toString(Charsets.UTF_8)
|
||||||
|
mainHandler.post {
|
||||||
|
when (uuid) {
|
||||||
|
CHAR_STATUS_UUID -> binding.tvTagStatus.text = "Status: $text"
|
||||||
|
CHAR_BATT_UUID -> {
|
||||||
|
val pct = text.toIntOrNull() ?: return@post
|
||||||
|
binding.tvTagStatus.text = binding.tvTagStatus.text.toString()
|
||||||
|
.replace(Regex("\\| Batt:.*"), "")
|
||||||
|
.trimEnd() + " | Batt: $pct%"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Config read / write
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
private fun readConfig() {
|
||||||
|
val g = gatt ?: run { toast("Not connected"); return }
|
||||||
|
val c = configChar ?: run { toast("Config char not found"); return }
|
||||||
|
g.readCharacteristic(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun writeConfig() {
|
||||||
|
val g = gatt ?: run { toast("Not connected"); return }
|
||||||
|
val c = configChar ?: run { toast("Config char not found"); return }
|
||||||
|
val cfg = buildConfigFromFields()
|
||||||
|
val json = gson.toJson(cfg)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
g.writeCharacteristic(c, json.toByteArray(Charsets.UTF_8),
|
||||||
|
BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT)
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
c.value = json.toByteArray(Charsets.UTF_8)
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
g.writeCharacteristic(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// UI helpers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
private fun populateFields(cfg: TagConfig) {
|
||||||
|
binding.etTagName.setText(cfg.tag_name)
|
||||||
|
binding.etSleepTimeout.setText(cfg.sleep_timeout_s.toString())
|
||||||
|
binding.etBrightness.setText(cfg.display_brightness.toString())
|
||||||
|
binding.etUwbChannel.setText(cfg.uwb_channel.toString())
|
||||||
|
binding.etRangingInterval.setText(cfg.ranging_interval_ms.toString())
|
||||||
|
binding.switchBatteryReport.isChecked = cfg.battery_report
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildConfigFromFields() = TagConfig(
|
||||||
|
tag_name = binding.etTagName.text?.toString() ?: "UWB_TAG_0001",
|
||||||
|
sleep_timeout_s = binding.etSleepTimeout.text?.toString()?.toIntOrNull() ?: 300,
|
||||||
|
display_brightness = binding.etBrightness.text?.toString()?.toIntOrNull() ?: 50,
|
||||||
|
uwb_channel = binding.etUwbChannel.text?.toString()?.toIntOrNull() ?: 9,
|
||||||
|
ranging_interval_ms = binding.etRangingInterval.text?.toString()?.toIntOrNull() ?: 100,
|
||||||
|
battery_report = binding.switchBatteryReport.isChecked
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun toast(msg: String) =
|
||||||
|
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
238
android/src/main/res/layout/activity_uwb_tag_ble.xml
Normal file
238
android/src/main/res/layout/activity_uwb_tag_ble.xml
Normal file
@ -0,0 +1,238 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
android:orientation="vertical">
|
||||||
|
|
||||||
|
<androidx.appcompat.widget.Toolbar
|
||||||
|
android:id="@+id/toolbar"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="?attr/actionBarSize"
|
||||||
|
android:background="?attr/colorPrimary"
|
||||||
|
android:elevation="4dp"
|
||||||
|
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
|
||||||
|
app:title="UWB Tag BLE Config" />
|
||||||
|
|
||||||
|
<!-- Scan controls -->
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:padding="12dp"
|
||||||
|
android:gravity="center_vertical">
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/btnScan"
|
||||||
|
style="@style/Widget.MaterialComponents.Button"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="Scan" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/tvScanStatus"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:layout_marginStart="12dp"
|
||||||
|
android:text="Tap Scan to find UWB tags"
|
||||||
|
android:textAppearance="@style/TextAppearance.MaterialComponents.Body2" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<!-- Scan results list -->
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:paddingHorizontal="12dp"
|
||||||
|
android:text="Nearby Tags"
|
||||||
|
android:textAppearance="@style/TextAppearance.MaterialComponents.Subtitle1"
|
||||||
|
android:textStyle="bold" />
|
||||||
|
|
||||||
|
<androidx.recyclerview.widget.RecyclerView
|
||||||
|
android:id="@+id/rvDevices"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="0dp"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:padding="8dp"
|
||||||
|
android:clipToPadding="false" />
|
||||||
|
|
||||||
|
<!-- Connected device config panel -->
|
||||||
|
<com.google.android.material.card.MaterialCardView
|
||||||
|
android:id="@+id/cardConfig"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_margin="8dp"
|
||||||
|
android:visibility="gone"
|
||||||
|
app:cardElevation="4dp">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:padding="12dp">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:gravity="center_vertical">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/tvConnectedName"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:text="Connected: —"
|
||||||
|
android:textAppearance="@style/TextAppearance.MaterialComponents.Subtitle1"
|
||||||
|
android:textStyle="bold" />
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/btnDisconnect"
|
||||||
|
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="Disconnect" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<!-- tag_name -->
|
||||||
|
<com.google.android.material.textfield.TextInputLayout
|
||||||
|
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="8dp"
|
||||||
|
android:hint="Tag Name">
|
||||||
|
<com.google.android.material.textfield.TextInputEditText
|
||||||
|
android:id="@+id/etTagName"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:inputType="text" />
|
||||||
|
</com.google.android.material.textfield.TextInputLayout>
|
||||||
|
|
||||||
|
<!-- sleep_timeout_s and uwb_channel (row) -->
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:layout_marginTop="4dp">
|
||||||
|
|
||||||
|
<com.google.android.material.textfield.TextInputLayout
|
||||||
|
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:layout_marginEnd="4dp"
|
||||||
|
android:hint="Sleep Timeout (s)">
|
||||||
|
<com.google.android.material.textfield.TextInputEditText
|
||||||
|
android:id="@+id/etSleepTimeout"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:inputType="number" />
|
||||||
|
</com.google.android.material.textfield.TextInputLayout>
|
||||||
|
|
||||||
|
<com.google.android.material.textfield.TextInputLayout
|
||||||
|
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:layout_marginStart="4dp"
|
||||||
|
android:hint="UWB Channel">
|
||||||
|
<com.google.android.material.textfield.TextInputEditText
|
||||||
|
android:id="@+id/etUwbChannel"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:inputType="number" />
|
||||||
|
</com.google.android.material.textfield.TextInputLayout>
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<!-- display_brightness and ranging_interval_ms (row) -->
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:layout_marginTop="4dp">
|
||||||
|
|
||||||
|
<com.google.android.material.textfield.TextInputLayout
|
||||||
|
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:layout_marginEnd="4dp"
|
||||||
|
android:hint="Brightness (0-100)">
|
||||||
|
<com.google.android.material.textfield.TextInputEditText
|
||||||
|
android:id="@+id/etBrightness"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:inputType="number" />
|
||||||
|
</com.google.android.material.textfield.TextInputLayout>
|
||||||
|
|
||||||
|
<com.google.android.material.textfield.TextInputLayout
|
||||||
|
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:layout_marginStart="4dp"
|
||||||
|
android:hint="Ranging Interval (ms)">
|
||||||
|
<com.google.android.material.textfield.TextInputEditText
|
||||||
|
android:id="@+id/etRangingInterval"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:inputType="number" />
|
||||||
|
</com.google.android.material.textfield.TextInputLayout>
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<!-- battery_report toggle -->
|
||||||
|
<com.google.android.material.switchmaterial.SwitchMaterial
|
||||||
|
android:id="@+id/switchBatteryReport"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="8dp"
|
||||||
|
android:text="Battery Reporting" />
|
||||||
|
|
||||||
|
<!-- Action buttons -->
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:layout_marginTop="8dp">
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/btnReadConfig"
|
||||||
|
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:layout_marginEnd="4dp"
|
||||||
|
android:text="Read" />
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/btnWriteConfig"
|
||||||
|
style="@style/Widget.MaterialComponents.Button"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:layout_marginStart="4dp"
|
||||||
|
android:text="Write" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<!-- Status notifications from tag -->
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/tvTagStatus"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="8dp"
|
||||||
|
android:background="#1A000000"
|
||||||
|
android:fontFamily="monospace"
|
||||||
|
android:padding="8dp"
|
||||||
|
android:text="Tag status: —"
|
||||||
|
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
</com.google.android.material.card.MaterialCardView>
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
60
android/src/main/res/layout/item_ble_device.xml
Normal file
60
android/src/main/res/layout/item_ble_device.xml
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<com.google.android.material.card.MaterialCardView
|
||||||
|
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_margin="4dp"
|
||||||
|
app:cardElevation="2dp"
|
||||||
|
android:clickable="true"
|
||||||
|
android:focusable="true">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:padding="12dp"
|
||||||
|
android:gravity="center_vertical">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:orientation="vertical">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/tvDeviceName"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="UWB_TAG_XXXX"
|
||||||
|
android:textAppearance="@style/TextAppearance.MaterialComponents.Subtitle2"
|
||||||
|
android:textStyle="bold" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/tvDeviceAddress"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="XX:XX:XX:XX:XX:XX"
|
||||||
|
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/tvRssi"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="-70 dBm"
|
||||||
|
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||||
|
android:textColor="?attr/colorSecondary" />
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/btnConnect"
|
||||||
|
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginStart="8dp"
|
||||||
|
android:text="Connect" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
</com.google.android.material.card.MaterialCardView>
|
||||||
@ -60,7 +60,7 @@ color("Purple", 0.9)
|
|||||||
translate([0, 0, h_fc])
|
translate([0, 0, h_fc])
|
||||||
cube([36, 36, 5], center=true);
|
cube([36, 36, 5], center=true);
|
||||||
|
|
||||||
// Jetson Nano
|
// Jetson Orin Nano Super
|
||||||
color("LimeGreen", 0.7)
|
color("LimeGreen", 0.7)
|
||||||
translate([0, 0, h_jetson])
|
translate([0, 0, h_jetson])
|
||||||
cube([100, 80, 29], center=true);
|
cube([100, 80, 29], center=true);
|
||||||
|
|||||||
@ -20,7 +20,7 @@ fc_hole_dia = 3.2; // M3 clearance
|
|||||||
fc_board_size = 36; // Typical FC PCB
|
fc_board_size = 36; // Typical FC PCB
|
||||||
fc_standoff_h = 5; // Rubber standoff height
|
fc_standoff_h = 5; // Rubber standoff height
|
||||||
|
|
||||||
// --- Jetson Nano ---
|
// --- Jetson Orin Nano Super ---
|
||||||
jetson_w = 100;
|
jetson_w = 100;
|
||||||
jetson_d = 80;
|
jetson_d = 80;
|
||||||
jetson_h = 29; // With heatsink
|
jetson_h = 29; // With heatsink
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
// ============================================
|
// ============================================
|
||||||
// SaltyLab — Jetson Nano Shelf
|
// SaltyLab — Jetson Orin Nano Super Shelf
|
||||||
// 120×100×15mm PETG
|
// 120×100×15mm PETG
|
||||||
// Mounts Jetson Nano to 2020 extrusion
|
// Mounts Jetson Orin Nano Super to 2020 extrusion
|
||||||
// ============================================
|
// ============================================
|
||||||
include <dimensions.scad>
|
include <dimensions.scad>
|
||||||
|
|
||||||
|
|||||||
@ -56,15 +56,24 @@
|
|||||||
3. Fasten 4× M4×12 SHCS. Torque 2.5 N·m.
|
3. Fasten 4× M4×12 SHCS. Torque 2.5 N·m.
|
||||||
4. Insert battery pack; route Velcro straps through slots and cinch.
|
4. Insert battery pack; route Velcro straps through slots and cinch.
|
||||||
|
|
||||||
### 7 FC mount (MAMBA F722S)
|
<<<<<<< HEAD
|
||||||
1. Place silicone anti-vibration grommets onto nylon M3 standoffs.
|
### 7 MCU mount (ESP32 BALANCE + ESP32 IO)
|
||||||
2. Lower FC onto standoffs; secure with M3×6 BHCS. Snug only — do not over-torque.
|
|
||||||
3. Orient USB-C port toward front of robot for cable access.
|
|
||||||
|
|
||||||
### 8 Jetson Nano mount plate
|
> ⚠️ **ARCHITECTURE CHANGE (2026-04-03):** ESP32 BALANCE retired. Two ESP32 boards replace it.
|
||||||
|
> Board dimensions and hole patterns TBD — await spec from max before machining mount plate.
|
||||||
|
|
||||||
|
=======
|
||||||
|
### 7 FC mount (ESP32-S3 BALANCE)
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
1. Place silicone anti-vibration grommets onto nylon M3 standoffs.
|
||||||
|
2. Lower ESP32 BALANCE board onto standoffs; secure with M3×6 BHCS. Snug only.
|
||||||
|
3. Mount ESP32 IO board adjacent — exact placement TBD pending board dimensions.
|
||||||
|
4. Orient USB connectors toward front of robot for cable access.
|
||||||
|
|
||||||
|
### 8 Jetson Orin Nano Super mount plate
|
||||||
1. Press or thread M3 nylon standoffs (8mm) into plate holes.
|
1. Press or thread M3 nylon standoffs (8mm) into plate holes.
|
||||||
2. Bolt plate to deck: 4× M3×10 SHCS at deck corners.
|
2. Bolt plate to deck: 4× M3×10 SHCS at deck corners.
|
||||||
3. Set Jetson Nano B01 carrier onto plate standoffs; fasten M3×6 BHCS.
|
3. Set Jetson Orin Nano Super B01 carrier onto plate standoffs; fasten M3×6 BHCS.
|
||||||
|
|
||||||
### 9 Bumper brackets
|
### 9 Bumper brackets
|
||||||
1. Slide 22mm EMT conduit through saddle clamp openings.
|
1. Slide 22mm EMT conduit through saddle clamp openings.
|
||||||
@ -86,7 +95,8 @@
|
|||||||
| Wheelbase (axle C/L to C/L) | 600 mm | ±1 mm |
|
| Wheelbase (axle C/L to C/L) | 600 mm | ±1 mm |
|
||||||
| Motor fork slot width | 24 mm | +0.5 / 0 |
|
| Motor fork slot width | 24 mm | +0.5 / 0 |
|
||||||
| Motor fork dropout depth | 60 mm | ±0.5 mm |
|
| Motor fork dropout depth | 60 mm | ±0.5 mm |
|
||||||
| FC hole pattern | 30.5 × 30.5 mm | ±0.2 mm |
|
| ESP32 BALANCE hole pattern | TBD — await spec from max | ±0.2 mm |
|
||||||
|
| ESP32 IO hole pattern | TBD — await spec from max | ±0.2 mm |
|
||||||
| Jetson hole pattern | 58 × 58 mm | ±0.2 mm |
|
| Jetson hole pattern | 58 × 58 mm | ±0.2 mm |
|
||||||
| Battery tray inner | 185 × 72 × 52 mm | +2 / 0 mm |
|
| Battery tray inner | 185 × 72 × 52 mm | +2 / 0 mm |
|
||||||
|
|
||||||
|
|||||||
@ -41,7 +41,11 @@ PR #7 (`chassis_frame.scad`) used placeholder values. The table below records th
|
|||||||
| 3 | Dropout clamp — upper | 2 | 8mm 6061-T6 Al | 90×70mm blank | D-cut bore; `RENDER="clamp_upper_2d"` |
|
| 3 | Dropout clamp — upper | 2 | 8mm 6061-T6 Al | 90×70mm blank | D-cut bore; `RENDER="clamp_upper_2d"` |
|
||||||
| 4 | Stem flange ring | 2 | 6mm Al or acrylic | Ø82mm disc | One above + one below plate; `RENDER="stem_flange_2d"` |
|
| 4 | Stem flange ring | 2 | 6mm Al or acrylic | Ø82mm disc | One above + one below plate; `RENDER="stem_flange_2d"` |
|
||||||
| 5 | Vertical stem tube | 1 | 38.1mm OD × 1.5mm wall 6061-T6 Al | 1050mm length | 1.5" EMT conduit is a drop-in alternative |
|
| 5 | Vertical stem tube | 1 | 38.1mm OD × 1.5mm wall 6061-T6 Al | 1050mm length | 1.5" EMT conduit is a drop-in alternative |
|
||||||
| 6 | FC standoff M3×6mm nylon | 4 | Nylon | — | MAMBA F722S vibration isolation |
|
<<<<<<< HEAD
|
||||||
|
| 6 | MCU standoff M3×6mm nylon | 4 | Nylon | — | ESP32 BALANCE / IO board isolation (dimensions TBD) |
|
||||||
|
=======
|
||||||
|
| 6 | FC standoff M3×6mm nylon | 4 | Nylon | — | ESP32-S3 BALANCE vibration isolation |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
| 7 | Ø4mm × 16mm alignment pin | 8 | Steel dowel | — | Dropout clamp-to-plate alignment |
|
| 7 | Ø4mm × 16mm alignment pin | 8 | Steel dowel | — | Dropout clamp-to-plate alignment |
|
||||||
|
|
||||||
### Battery Stem Clamp (`stem_battery_clamp.scad`) — Part B
|
### Battery Stem Clamp (`stem_battery_clamp.scad`) — Part B
|
||||||
@ -70,7 +74,7 @@ PR #7 (`chassis_frame.scad`) used placeholder values. The table below records th
|
|||||||
| 10 | Motor fork bracket (R) | 1 | 8mm 6061 aluminium | Mirror of item 9 |
|
| 10 | Motor fork bracket (R) | 1 | 8mm 6061 aluminium | Mirror of item 9 |
|
||||||
| 11 | Battery tray | 1 | 3mm PETG FDM or 3mm aluminium fold | `chassis_frame.scad` — `battery_tray()` module |
|
| 11 | Battery tray | 1 | 3mm PETG FDM or 3mm aluminium fold | `chassis_frame.scad` — `battery_tray()` module |
|
||||||
| 12 | FC mount plate / standoffs | 1 set | PETG or nylon FDM | Includes 4× M3 nylon standoffs, 6mm height |
|
| 12 | FC mount plate / standoffs | 1 set | PETG or nylon FDM | Includes 4× M3 nylon standoffs, 6mm height |
|
||||||
| 13 | Jetson Nano mount plate | 1 | 4mm 5052 aluminium or 4mm PETG FDM | B01 58×58mm hole pattern |
|
| 13 | Jetson Orin Nano Super mount plate | 1 | 4mm 5052 aluminium or 4mm PETG FDM | B01 58×58mm hole pattern |
|
||||||
| 14 | Front bumper bracket | 1 | 5mm PETG FDM | Saddle clamps for 22mm EMT conduit |
|
| 14 | Front bumper bracket | 1 | 5mm PETG FDM | Saddle clamps for 22mm EMT conduit |
|
||||||
| 15 | Rear bumper bracket | 1 | 5mm PETG FDM | Mirror of item 14 |
|
| 15 | Rear bumper bracket | 1 | 5mm PETG FDM | Mirror of item 14 |
|
||||||
|
|
||||||
@ -88,12 +92,23 @@ PR #7 (`chassis_frame.scad`) used placeholder values. The table below records th
|
|||||||
|
|
||||||
## Electronics Mounts
|
## Electronics Mounts
|
||||||
|
|
||||||
|
> ⚠️ **ARCHITECTURE CHANGE (2026-04-03):** ESP32 BALANCE (ESP32) is retired.
|
||||||
|
> Replaced by **ESP32 BALANCE** + **ESP32 IO**. Board dimensions and hole patterns TBD — await spec from max.
|
||||||
|
|
||||||
| # | Part | Qty | Spec | Notes |
|
| # | Part | Qty | Spec | Notes |
|
||||||
|---|------|-----|------|-------|
|
|---|------|-----|------|-------|
|
||||||
| 13 | STM32 MAMBA F722S FC | 1 | 36×36mm PCB, 30.5×30.5mm M3 mount | Oriented USB-C port toward front |
|
<<<<<<< HEAD
|
||||||
|
| 13 | ESP32 BALANCE board | 1 | TBD — mount pattern TBD | PID balance loop; replaces ESP32 BALANCE |
|
||||||
|
| 13b | ESP32 IO board | 1 | TBD — mount pattern TBD | Motor/sensor/comms I/O |
|
||||||
|
| 14 | Nylon M3 standoff 6mm | 4 | F/F nylon | ESP32 board isolation |
|
||||||
|
| 15 | Anti-vibration grommet M3 | 4 | Ø6mm silicone | Under ESP32 mount pads |
|
||||||
|
| 16 | Jetson Orin module | 1 | 69.6×45mm module + carrier | 58×58mm M3 carrier hole pattern |
|
||||||
|
=======
|
||||||
|
| 13 | ESP32-S3 ESP32-S3 BALANCE FC | 1 | 36×36mm PCB, 30.5×30.5mm M3 mount | Oriented USB-C port toward front |
|
||||||
| 14 | Nylon M3 standoff 6mm | 4 | F/F nylon | FC vibration isolation |
|
| 14 | Nylon M3 standoff 6mm | 4 | F/F nylon | FC vibration isolation |
|
||||||
| 15 | Anti-vibration grommet M3 | 4 | Ø6mm silicone | Under FC mount pads |
|
| 15 | Anti-vibration grommet M3 | 4 | Ø6mm silicone | Under FC mount pads |
|
||||||
| 16 | Jetson Nano B01 module | 1 | 69.6×45mm module + carrier | 58×58mm M3 carrier hole pattern |
|
| 16 | Jetson Orin Nano Super B01 module | 1 | 69.6×45mm module + carrier | 58×58mm M3 carrier hole pattern |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
| 17 | Nylon M3 standoff 8mm | 4 | F/F nylon | Jetson board standoffs |
|
| 17 | Nylon M3 standoff 8mm | 4 | F/F nylon | Jetson board standoffs |
|
||||||
|
|
||||||
---
|
---
|
||||||
@ -144,8 +159,8 @@ Slide entire carousel up/down the stem with M6 collar bolts loosened. Tighten at
|
|||||||
| 26 | M6×60 SHCS | 4 | ISO 4762, SS | Collar clamping bolts |
|
| 26 | M6×60 SHCS | 4 | ISO 4762, SS | Collar clamping bolts |
|
||||||
| 27 | M6 hex nut | 4 | ISO 4032, SS | Captured in collar pockets |
|
| 27 | M6 hex nut | 4 | ISO 4032, SS | Captured in collar pockets |
|
||||||
| 28 | M6×12 set screw | 2 | ISO 4026, SS cup-point | Stem height lock (1 per collar half) |
|
| 28 | M6×12 set screw | 2 | ISO 4026, SS cup-point | Stem height lock (1 per collar half) |
|
||||||
| 29 | M3×10 SHCS | 12 | ISO 4762, SS | FC mount + miscellaneous |
|
| 29 | M3×10 SHCS | 12 | ISO 4762, SS | ESP32 mount + miscellaneous |
|
||||||
| 30 | M3×6 BHCS | 4 | ISO 4762, SS | FC board bolts |
|
| 30 | M3×6 BHCS | 4 | ISO 4762, SS | ESP32 board bolts (qty TBD pending board spec) |
|
||||||
| 31 | Axle lock nut (match axle tip thread) | 4 | Flanged, confirm thread | 2 per motor |
|
| 31 | Axle lock nut (match axle tip thread) | 4 | Flanged, confirm thread | 2 per motor |
|
||||||
| 32 | Flat washer M5 | 32 | SS | |
|
| 32 | Flat washer M5 | 32 | SS | |
|
||||||
| 33 | Flat washer M4 | 32 | SS | |
|
| 33 | Flat washer M4 | 32 | SS | |
|
||||||
|
|||||||
410
chassis/battery_holder.scad
Normal file
410
chassis/battery_holder.scad
Normal file
@ -0,0 +1,410 @@
|
|||||||
|
// ============================================================
|
||||||
|
// battery_holder.scad — 6S LiPo Battery Holder for 2020 T-Slot Chassis
|
||||||
|
// Issue: #588 Agent: sl-mechanical Date: 2026-03-14
|
||||||
|
// ============================================================
|
||||||
|
//
|
||||||
|
// Parametric bracket holding a 6S 5000 mAh LiPo pack on 2020 aluminium
|
||||||
|
// T-slot rails. Designed for low centre-of-gravity mounting: pack sits
|
||||||
|
// flat between the two chassis rails, as close to ground as clearance
|
||||||
|
// allows. Quick-release via captive Velcro straps — battery swap in
|
||||||
|
// under 60 s without tools.
|
||||||
|
//
|
||||||
|
// Architecture:
|
||||||
|
// Tray → flat floor + perimeter walls, battery sits inside
|
||||||
|
// Rail saddles→ two T-nut feet drop onto 2020 rails, thumbscrew locks
|
||||||
|
// Strap slots → four pairs of slots for 25 mm Velcro strap loops
|
||||||
|
// XT60 window → cut-out in rear wall for XT60 connector exit
|
||||||
|
// Balance port→ open channel in front wall for balance lead routing
|
||||||
|
// QR tab → front-edge pull tab for one-handed battery extraction
|
||||||
|
//
|
||||||
|
// Part catalogue:
|
||||||
|
// Part 1 — battery_tray() Main tray body (single-piece print)
|
||||||
|
// Part 2 — rail_saddle() T-nut saddle foot (print x2 per tray)
|
||||||
|
// Part 3 — strap_guide() 25 mm Velcro strap guide (print x4)
|
||||||
|
// Part 4 — assembly_preview()
|
||||||
|
//
|
||||||
|
// Hardware BOM:
|
||||||
|
// 2× M3 × 16 mm SHCS + M3 hex nut T-nut rail clamp thumbscrews
|
||||||
|
// 2× 25 mm × 250 mm Velcro strap battery retention (hook + loop)
|
||||||
|
// 1× XT60 female connector (mounted on ESC/PDB harness)
|
||||||
|
// — battery slides in from front, Velcro strap over top —
|
||||||
|
//
|
||||||
|
// 6S LiPo target pack (verify with calipers — packs vary by brand):
|
||||||
|
// BATT_L = 155 mm (length, X axis in tray)
|
||||||
|
// BATT_W = 48 mm (width, Y axis in tray)
|
||||||
|
// BATT_H = 52 mm (height, Z axis in tray)
|
||||||
|
// Clearance 1 mm each side added automatically (BATT_CLEAR)
|
||||||
|
//
|
||||||
|
// Mounting:
|
||||||
|
// Rail span : RAIL_SPAN — distance between 2020 rail centrelines
|
||||||
|
// Default 80 mm; adjust to chassis rail spacing
|
||||||
|
// Saddle height: SADDLE_H — total height of saddle (tray floor above rail)
|
||||||
|
// Keep low for CoG; default 8 mm
|
||||||
|
//
|
||||||
|
// RENDER options:
|
||||||
|
// "assembly" full assembly preview (default)
|
||||||
|
// "tray_stl" Part 1 — battery tray
|
||||||
|
// "saddle_stl" Part 2 — rail saddle (print x2)
|
||||||
|
// "strap_guide_stl" Part 3 — strap guide (print x4)
|
||||||
|
//
|
||||||
|
// Export commands:
|
||||||
|
// openscad battery_holder.scad -D 'RENDER="tray_stl"' -o bh_tray.stl
|
||||||
|
// openscad battery_holder.scad -D 'RENDER="saddle_stl"' -o bh_saddle.stl
|
||||||
|
// openscad battery_holder.scad -D 'RENDER="strap_guide_stl"' -o bh_strap_guide.stl
|
||||||
|
//
|
||||||
|
// Print settings (all parts):
|
||||||
|
// Material : PETG
|
||||||
|
// Perimeters : 5 (tray, saddle), 3 (strap_guide)
|
||||||
|
// Infill : 40 % gyroid (tray floor, saddle), 20 % (strap_guide)
|
||||||
|
// Orientation:
|
||||||
|
// tray — floor flat on bed (no supports needed)
|
||||||
|
// saddle — flat face on bed (no supports)
|
||||||
|
// strap_guide — flat face on bed (no supports)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
$fn = 64;
|
||||||
|
e = 0.01;
|
||||||
|
|
||||||
|
// ── Battery pack dimensions (verify with calipers) ────────────────────────────
|
||||||
|
BATT_L = 155.0; // pack length (X)
|
||||||
|
BATT_W = 48.0; // pack width (Y)
|
||||||
|
BATT_H = 52.0; // pack height (Z)
|
||||||
|
BATT_CLEAR = 1.0; // per-side fit clearance
|
||||||
|
|
||||||
|
// ── Tray geometry ─────────────────────────────────────────────────────────────
|
||||||
|
TRAY_FLOOR_T = 4.0; // tray floor thickness
|
||||||
|
TRAY_WALL_T = 4.0; // tray perimeter wall thickness
|
||||||
|
TRAY_WALL_H = 20.0; // tray wall height (Z) — cradles lower half of pack
|
||||||
|
TRAY_FILLET_R = 3.0; // inner corner radius
|
||||||
|
|
||||||
|
// Inner tray cavity (battery + clearance)
|
||||||
|
TRAY_INN_L = BATT_L + 2*BATT_CLEAR;
|
||||||
|
TRAY_INN_W = BATT_W + 2*BATT_CLEAR;
|
||||||
|
|
||||||
|
// Outer tray footprint
|
||||||
|
TRAY_OUT_L = TRAY_INN_L + 2*TRAY_WALL_T;
|
||||||
|
TRAY_OUT_W = TRAY_INN_W + 2*TRAY_WALL_T;
|
||||||
|
TRAY_TOTAL_H = TRAY_FLOOR_T + TRAY_WALL_H;
|
||||||
|
|
||||||
|
// ── Rail interface ─────────────────────────────────────────────────────────────
|
||||||
|
RAIL_SPAN = 80.0; // distance between 2020 rail centrelines (Y)
|
||||||
|
RAIL_W = 20.0; // 2020 extrusion width
|
||||||
|
SLOT_NECK_H = 3.2; // T-slot neck height
|
||||||
|
SLOT_OPEN = 6.0; // T-slot opening width
|
||||||
|
SLOT_INN_W = 10.2; // T-slot inner width
|
||||||
|
SLOT_INN_H = 5.8; // T-slot inner height
|
||||||
|
|
||||||
|
// ── T-nut / saddle geometry ───────────────────────────────────────────────────
|
||||||
|
TNUT_W = 9.8;
|
||||||
|
TNUT_H = 5.5;
|
||||||
|
TNUT_L = 12.0;
|
||||||
|
TNUT_NUT_AF = 5.5; // M3 hex nut across-flats
|
||||||
|
TNUT_NUT_H = 2.4;
|
||||||
|
TNUT_BOLT_D = 3.3; // M3 clearance
|
||||||
|
|
||||||
|
SADDLE_W = 30.0; // saddle foot width (X, along rail)
|
||||||
|
SADDLE_T = 8.0; // saddle body thickness (Z, above rail top face)
|
||||||
|
SADDLE_PAD_T = 2.0; // rubber-pad recess depth (optional anti-slip)
|
||||||
|
|
||||||
|
// ── Velcro strap slots ────────────────────────────────────────────────────────
|
||||||
|
STRAP_W = 26.0; // 25 mm strap + 1 mm clearance
|
||||||
|
STRAP_T = 4.0; // slot through-thickness (tray wall)
|
||||||
|
// Four slot pairs: one near each end of tray (X), one each side (Y)
|
||||||
|
// Slots run through side walls (Y direction) — strap loops over battery top
|
||||||
|
|
||||||
|
// ── XT60 connector window (rear wall) ─────────────────────────────────────────
|
||||||
|
XT60_W = 14.0; // XT60 body width
|
||||||
|
XT60_H = 18.0; // XT60 body height (with cable exit)
|
||||||
|
XT60_OFFSET_Z = 4.0; // height above tray floor
|
||||||
|
|
||||||
|
// ── Balance lead port (front wall) ────────────────────────────────────────────
|
||||||
|
BAL_W = 40.0; // balance lead bundle width (6S = 7 wires)
|
||||||
|
BAL_H = 6.0; // balance lead channel height
|
||||||
|
BAL_OFFSET_Z = 8.0; // height above tray floor
|
||||||
|
|
||||||
|
// ── Quick-release pull tab (front edge) ──────────────────────────────────────
|
||||||
|
QR_TAB_W = 30.0; // tab width
|
||||||
|
QR_TAB_H = 12.0; // tab height above front wall top
|
||||||
|
QR_TAB_T = 4.0; // tab thickness
|
||||||
|
QR_HOLE_D = 10.0; // finger-loop hole diameter
|
||||||
|
|
||||||
|
// ── Strap guide clip ─────────────────────────────────────────────────────────
|
||||||
|
GUIDE_OD = STRAP_W + 6.0;
|
||||||
|
GUIDE_T = 3.0;
|
||||||
|
GUIDE_BODY_H = 14.0;
|
||||||
|
|
||||||
|
// ── Fasteners ─────────────────────────────────────────────────────────────────
|
||||||
|
M3_D = 3.3;
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// RENDER DISPATCH
|
||||||
|
// ============================================================
|
||||||
|
RENDER = "assembly";
|
||||||
|
|
||||||
|
if (RENDER == "assembly") assembly_preview();
|
||||||
|
else if (RENDER == "tray_stl") battery_tray();
|
||||||
|
else if (RENDER == "saddle_stl") rail_saddle();
|
||||||
|
else if (RENDER == "strap_guide_stl") strap_guide();
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// ASSEMBLY PREVIEW
|
||||||
|
// ============================================================
|
||||||
|
module assembly_preview() {
|
||||||
|
// Ghost 2020 rails (Y direction, RAIL_SPAN apart)
|
||||||
|
for (ry = [-RAIL_SPAN/2, RAIL_SPAN/2])
|
||||||
|
%color("Silver", 0.28)
|
||||||
|
translate([-TRAY_OUT_L/2 - 30, ry - RAIL_W/2, -SADDLE_T - TNUT_H])
|
||||||
|
cube([TRAY_OUT_L + 60, RAIL_W, RAIL_W]);
|
||||||
|
|
||||||
|
// Rail saddles (left and right)
|
||||||
|
for (sy = [-RAIL_SPAN/2, RAIL_SPAN/2])
|
||||||
|
color("DimGray", 0.85)
|
||||||
|
translate([0, sy, -SADDLE_T])
|
||||||
|
rail_saddle();
|
||||||
|
|
||||||
|
// Battery tray (sitting on saddles)
|
||||||
|
color("OliveDrab", 0.85)
|
||||||
|
battery_tray();
|
||||||
|
|
||||||
|
// Battery ghost
|
||||||
|
%color("SaddleBrown", 0.35)
|
||||||
|
translate([-BATT_L/2, -BATT_W/2, TRAY_FLOOR_T])
|
||||||
|
cube([BATT_L, BATT_W, BATT_H]);
|
||||||
|
|
||||||
|
// Strap guides (4×, two each end)
|
||||||
|
for (sx = [-TRAY_OUT_L/2 + STRAP_W/2 + TRAY_WALL_T + 8,
|
||||||
|
TRAY_OUT_L/2 - STRAP_W/2 - TRAY_WALL_T - 8])
|
||||||
|
for (sy = [-1, 1])
|
||||||
|
color("SteelBlue", 0.75)
|
||||||
|
translate([sx, sy*(TRAY_OUT_W/2), TRAY_TOTAL_H + 2])
|
||||||
|
rotate([sy > 0 ? 0 : 180, 0, 0])
|
||||||
|
strap_guide();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// PART 1 — BATTERY TRAY
|
||||||
|
// ============================================================
|
||||||
|
// Single-piece tray: flat floor, four perimeter walls, T-nut saddle
|
||||||
|
// attachment bosses on underside, Velcro strap slots through side walls,
|
||||||
|
// XT60 window in rear wall, balance lead channel in front wall, and
|
||||||
|
// quick-release pull tab on front edge.
|
||||||
|
//
|
||||||
|
// Battery inserts from the front (−X end) — front wall is lower than
|
||||||
|
// rear wall so the pack slides in and the rear wall stops it.
|
||||||
|
// Velcro straps loop over the top of the pack through the side slots.
|
||||||
|
//
|
||||||
|
// Coordinate convention:
|
||||||
|
// X: along battery length (−X = front/plug-end, +X = rear/balance-end)
|
||||||
|
// Y: across battery width (centred, ±TRAY_OUT_W/2)
|
||||||
|
// Z: vertical (Z=0 = tray floor top face; −Z = underside → saddles)
|
||||||
|
//
|
||||||
|
// Print: floor flat on bed, PETG, 5 perims, 40% gyroid. No supports.
|
||||||
|
module battery_tray() {
|
||||||
|
// Short rear wall height (XT60 connector exits here — full wall height)
|
||||||
|
// Front wall is lower to allow battery slide-in
|
||||||
|
front_wall_h = TRAY_WALL_H * 0.55; // 55% height — battery slides over
|
||||||
|
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// ── Floor ────────────────────────────────────────────────────
|
||||||
|
translate([-TRAY_OUT_L/2, -TRAY_OUT_W/2, -TRAY_FLOOR_T])
|
||||||
|
cube([TRAY_OUT_L, TRAY_OUT_W, TRAY_FLOOR_T]);
|
||||||
|
|
||||||
|
// ── Rear wall (+X, full height) ───────────────────────────────
|
||||||
|
translate([TRAY_INN_L/2, -TRAY_OUT_W/2, 0])
|
||||||
|
cube([TRAY_WALL_T, TRAY_OUT_W, TRAY_WALL_H]);
|
||||||
|
|
||||||
|
// ── Front wall (−X, lowered for slide-in) ────────────────────
|
||||||
|
translate([-TRAY_INN_L/2 - TRAY_WALL_T, -TRAY_OUT_W/2, 0])
|
||||||
|
cube([TRAY_WALL_T, TRAY_OUT_W, front_wall_h]);
|
||||||
|
|
||||||
|
// ── Side walls (±Y) ───────────────────────────────────────────
|
||||||
|
for (sy = [-1, 1])
|
||||||
|
translate([-TRAY_OUT_L/2,
|
||||||
|
sy*(TRAY_INN_W/2 + (sy>0 ? 0 : -TRAY_WALL_T)),
|
||||||
|
0])
|
||||||
|
cube([TRAY_OUT_L,
|
||||||
|
TRAY_WALL_T,
|
||||||
|
TRAY_WALL_H]);
|
||||||
|
|
||||||
|
// ── Quick-release pull tab (front wall top edge) ──────────────
|
||||||
|
translate([-TRAY_INN_L/2 - TRAY_WALL_T - e,
|
||||||
|
-QR_TAB_W/2, front_wall_h])
|
||||||
|
cube([QR_TAB_T, QR_TAB_W, QR_TAB_H]);
|
||||||
|
|
||||||
|
// ── Saddle attachment bosses (underside, one per rail) ─────────
|
||||||
|
// Bosses drop into saddle sockets; M3 bolt through floor
|
||||||
|
for (sy = [-RAIL_SPAN/2, RAIL_SPAN/2])
|
||||||
|
translate([-SADDLE_W/2, sy - SADDLE_W/2, -TRAY_FLOOR_T - SADDLE_T/2])
|
||||||
|
cube([SADDLE_W, SADDLE_W, SADDLE_T/2 + e]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Battery cavity (hollow interior) ──────────────────────────────
|
||||||
|
translate([-TRAY_INN_L/2, -TRAY_INN_W/2, -e])
|
||||||
|
cube([TRAY_INN_L, TRAY_INN_W, TRAY_WALL_H + 2*e]);
|
||||||
|
|
||||||
|
// ── XT60 connector window (rear wall) ─────────────────────────────
|
||||||
|
// Centred on rear wall, low position so cable exits cleanly
|
||||||
|
translate([TRAY_INN_L/2 - e, -XT60_W/2, XT60_OFFSET_Z])
|
||||||
|
cube([TRAY_WALL_T + 2*e, XT60_W, XT60_H]);
|
||||||
|
|
||||||
|
// ── Balance lead channel (front wall) ─────────────────────────────
|
||||||
|
// Wide slot for 6S balance lead (7-pin JST-XH ribbon)
|
||||||
|
translate([-TRAY_INN_L/2 - TRAY_WALL_T - e,
|
||||||
|
-BAL_W/2, BAL_OFFSET_Z])
|
||||||
|
cube([TRAY_WALL_T + 2*e, BAL_W, BAL_H]);
|
||||||
|
|
||||||
|
// ── Velcro strap slots (side walls, 2 pairs) ──────────────────────
|
||||||
|
// Pair A: near front end (−X), Pair B: near rear end (+X)
|
||||||
|
// Each slot runs through the wall in Y direction
|
||||||
|
for (sx = [-TRAY_INN_L/2 + STRAP_W*0.5 + 10,
|
||||||
|
TRAY_INN_L/2 - STRAP_W*0.5 - 10])
|
||||||
|
for (sy = [-1, 1]) {
|
||||||
|
translate([sx - STRAP_W/2,
|
||||||
|
sy*(TRAY_INN_W/2) - (sy > 0 ? TRAY_WALL_T + e : -e),
|
||||||
|
TRAY_WALL_H * 0.35])
|
||||||
|
cube([STRAP_W, TRAY_WALL_T + 2*e, STRAP_T]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── QR tab finger-loop hole ────────────────────────────────────────
|
||||||
|
translate([-TRAY_INN_L/2 - TRAY_WALL_T/2,
|
||||||
|
0, front_wall_h + QR_TAB_H * 0.55])
|
||||||
|
rotate([0, 90, 0])
|
||||||
|
cylinder(d = QR_HOLE_D, h = QR_TAB_T + 2*e, center = true);
|
||||||
|
|
||||||
|
// ── Saddle bolt holes (M3 through floor into saddle boss) ─────────
|
||||||
|
for (sy = [-RAIL_SPAN/2, RAIL_SPAN/2])
|
||||||
|
translate([0, sy, -TRAY_FLOOR_T - e])
|
||||||
|
cylinder(d = M3_D, h = TRAY_FLOOR_T + 2*e);
|
||||||
|
|
||||||
|
// ── Floor lightening grid (non-structural area) ───────────────────
|
||||||
|
// 2D grid of pockets reduces weight without weakening battery support
|
||||||
|
for (gx = [-40, 0, 40])
|
||||||
|
for (gy = [-12, 12])
|
||||||
|
translate([gx, gy, -TRAY_FLOOR_T - e])
|
||||||
|
cylinder(d = 14, h = TRAY_FLOOR_T - 1.5 + e);
|
||||||
|
|
||||||
|
// ── Inner corner chamfers (battery slide-in guidance) ─────────────
|
||||||
|
// 45° chamfers at bottom-front inner corners
|
||||||
|
translate([-TRAY_INN_L/2, -TRAY_INN_W/2 - e, -e])
|
||||||
|
rotate([0, 0, 45])
|
||||||
|
cube([4, 4, TRAY_WALL_H * 0.3 + e]);
|
||||||
|
translate([-TRAY_INN_L/2, TRAY_INN_W/2 + e, -e])
|
||||||
|
rotate([0, 0, -45])
|
||||||
|
cube([4, 4, TRAY_WALL_H * 0.3 + e]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// PART 2 — RAIL SADDLE
|
||||||
|
// ============================================================
|
||||||
|
// T-nut foot that clamps to the top face of a 2020 T-slot rail.
|
||||||
|
// Battery tray boss drops into saddle socket; M3 bolt through tray
|
||||||
|
// floor and saddle body locks everything together.
|
||||||
|
// M3 thumbscrew through side of saddle body grips the rail T-groove
|
||||||
|
// (same thumbscrew interface as all other SaltyLab rail brackets).
|
||||||
|
//
|
||||||
|
// Saddle sits on top of rail (no T-nut tongue needed — saddle clamps
|
||||||
|
// from the top using a T-nut inserted into the rail T-groove from the
|
||||||
|
// end). Low profile keeps battery CoG as low as possible.
|
||||||
|
//
|
||||||
|
// Print: flat base on bed, PETG, 5 perims, 50% gyroid.
|
||||||
|
module rail_saddle() {
|
||||||
|
sock_d = SADDLE_W - 4; // tray boss socket diameter
|
||||||
|
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// ── Main saddle body ──────────────────────────────────────────
|
||||||
|
translate([-SADDLE_W/2, -SADDLE_W/2, 0])
|
||||||
|
cube([SADDLE_W, SADDLE_W, SADDLE_T]);
|
||||||
|
|
||||||
|
// ── T-nut tongue (enters rail T-groove from above) ────────────
|
||||||
|
translate([-TNUT_W/2, -TNUT_L/2, -SLOT_NECK_H])
|
||||||
|
cube([TNUT_W, TNUT_L, SLOT_NECK_H + e]);
|
||||||
|
|
||||||
|
// ── T-nut inner body (locks in groove) ────────────────────────
|
||||||
|
translate([-TNUT_W/2, -TNUT_L/2, -SLOT_NECK_H - (TNUT_H - SLOT_NECK_H)])
|
||||||
|
cube([TNUT_W, TNUT_L, TNUT_H - SLOT_NECK_H + e]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Rail channel clearance (bottom of saddle straddles rail) ──────
|
||||||
|
// Saddle body has a channel that sits over the rail top face
|
||||||
|
translate([-RAIL_W/2 - e, -SADDLE_W/2 - e, -e])
|
||||||
|
cube([RAIL_W + 2*e, SADDLE_W + 2*e, 2.0]);
|
||||||
|
|
||||||
|
// ── M3 clamp bolt bore (through saddle body into T-nut) ───────────
|
||||||
|
translate([0, 0, -SLOT_NECK_H - TNUT_H - e])
|
||||||
|
cylinder(d = TNUT_BOLT_D, h = SADDLE_T + TNUT_H + 2*e);
|
||||||
|
|
||||||
|
// ── M3 hex nut pocket (top face of saddle for thumbscrew) ─────────
|
||||||
|
translate([0, 0, SADDLE_T - TNUT_NUT_H - 0.5])
|
||||||
|
cylinder(d = TNUT_NUT_AF / cos(30),
|
||||||
|
h = TNUT_NUT_H + 0.6, $fn = 6);
|
||||||
|
|
||||||
|
// ── Tray boss socket (top face of saddle, tray boss nests here) ───
|
||||||
|
// Cylindrical socket receives tray underside boss; M3 bolt centres
|
||||||
|
translate([0, 0, SADDLE_T - 3])
|
||||||
|
cylinder(d = sock_d + 0.4, h = 3 + e);
|
||||||
|
|
||||||
|
// ── M3 tray bolt bore (vertical, through saddle top) ──────────────
|
||||||
|
translate([0, 0, SADDLE_T - 3 - e])
|
||||||
|
cylinder(d = M3_D, h = SADDLE_T + e);
|
||||||
|
|
||||||
|
// ── Anti-slip pad recess (bottom face, optional rubber adhesive) ──
|
||||||
|
translate([0, 0, -e])
|
||||||
|
cylinder(d = SADDLE_W - 8, h = SADDLE_PAD_T + e);
|
||||||
|
|
||||||
|
// ── Lightening pockets ─────────────────────────────────────────────
|
||||||
|
for (lx = [-1, 1], ly = [-1, 1])
|
||||||
|
translate([lx*8, ly*8, -e])
|
||||||
|
cylinder(d = 5, h = SADDLE_T - 3 - 1 + e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// PART 3 — STRAP GUIDE
|
||||||
|
// ============================================================
|
||||||
|
// Snap-on guide that sits on top of tray wall at each strap slot,
|
||||||
|
// directing the 25 mm Velcro strap from the side slot up and over
|
||||||
|
// the battery top. Four per tray, one at each slot exit.
|
||||||
|
// Curved lip prevents strap from cutting into PETG wall edge.
|
||||||
|
// Push-fit onto tray wall top; no fasteners required.
|
||||||
|
//
|
||||||
|
// Print: flat base on bed, PETG, 3 perims, 20% infill.
|
||||||
|
module strap_guide() {
|
||||||
|
strap_w_clr = STRAP_W + 0.5; // strap slot with clearance
|
||||||
|
lip_r = 3.0; // guide lip radius
|
||||||
|
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// ── Body (sits on tray wall top edge) ─────────────────────────
|
||||||
|
translate([-GUIDE_OD/2, 0, 0])
|
||||||
|
cube([GUIDE_OD, GUIDE_T, GUIDE_BODY_H]);
|
||||||
|
|
||||||
|
// ── Curved guide lip (top of body, strap bends around this) ───
|
||||||
|
translate([0, GUIDE_T/2, GUIDE_BODY_H])
|
||||||
|
rotate([0, 90, 0])
|
||||||
|
cylinder(r = lip_r, h = GUIDE_OD, center = true);
|
||||||
|
|
||||||
|
// ── Wall engagement tabs (snap over tray wall top) ────────────
|
||||||
|
for (sy = [0, -(TRAY_WALL_T + GUIDE_T)])
|
||||||
|
translate([-strap_w_clr/2 - 3, sy - GUIDE_T, 0])
|
||||||
|
cube([strap_w_clr + 6, GUIDE_T, GUIDE_BODY_H * 0.4]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Strap slot (through body) ──────────────────────────────────────
|
||||||
|
translate([-strap_w_clr/2, -e, -e])
|
||||||
|
cube([strap_w_clr, GUIDE_T + 2*e, GUIDE_BODY_H + 2*e]);
|
||||||
|
|
||||||
|
// ── Wall clearance slot (body slides over tray wall) ──────────────
|
||||||
|
translate([-strap_w_clr/2 - 3 - e,
|
||||||
|
-TRAY_WALL_T - GUIDE_T, -e])
|
||||||
|
cube([strap_w_clr + 6 + 2*e,
|
||||||
|
TRAY_WALL_T, GUIDE_BODY_H * 0.4 + 2*e]);
|
||||||
|
|
||||||
|
// ── Lightening pockets on side faces ──────────────────────────────
|
||||||
|
for (lx = [-GUIDE_OD/4, GUIDE_OD/4])
|
||||||
|
translate([lx, GUIDE_T/2, GUIDE_BODY_H/2])
|
||||||
|
cube([6, GUIDE_T + 2*e, GUIDE_BODY_H * 0.5], center = true);
|
||||||
|
}
|
||||||
|
}
|
||||||
410
chassis/cable_tray.scad
Normal file
410
chassis/cable_tray.scad
Normal file
@ -0,0 +1,410 @@
|
|||||||
|
// ============================================================
|
||||||
|
// Cable Management Tray — Issue #628
|
||||||
|
// Agent : sl-mechanical
|
||||||
|
// Date : 2026-03-15
|
||||||
|
// Part catalogue:
|
||||||
|
// 1. tray_body — under-plate tray with snap-in cable channels, Velcro
|
||||||
|
// tie-down slots every 40 mm, pass-through holes, label slots
|
||||||
|
// 2. tnut_bracket — 2020 T-nut rail mount bracket (×2, slide under tray)
|
||||||
|
// 3. channel_clip — snap-in divider clip separating power / signal / servo zones
|
||||||
|
// 4. cover_panel — hinged snap-on lid (living-hinge PETG flexure strip)
|
||||||
|
// 5. cable_saddle — individual cable saddle / strain-relief clip (×n)
|
||||||
|
//
|
||||||
|
// BOM:
|
||||||
|
// 4 × M5×10 BHCS + M5 T-nuts (tnut_bracket × 2 to rail)
|
||||||
|
// 4 × M3×8 SHCS (tnut_bracket to tray body)
|
||||||
|
// n × 100 mm Velcro tie-down strips (through 6×2 mm slots, every 40 mm)
|
||||||
|
//
|
||||||
|
// Cable channel layout (X axis, inside tray):
|
||||||
|
// Zone A — Power (2S–6S LiPo, XT60/XT30): 20 mm wide, 14 mm deep
|
||||||
|
// Zone B — Signal (JST-SH, PWM, I2C, UART): 14 mm wide, 10 mm deep
|
||||||
|
// Zone C — Servo (JST-PH, thick servo leads): 14 mm wide, 12 mm deep
|
||||||
|
// Divider walls: 2.5 mm thick between zones
|
||||||
|
//
|
||||||
|
// Print settings (PETG):
|
||||||
|
// tray_body / tnut_bracket / channel_clip : 5 perimeters, 40 % gyroid, no supports
|
||||||
|
// cover_panel : 3 perimeters, 20 % gyroid, no supports
|
||||||
|
// (living-hinge — print flat, thin strip flexes)
|
||||||
|
// cable_saddle : 3 perimeters, 30 % gyroid, no supports
|
||||||
|
//
|
||||||
|
// Export commands:
|
||||||
|
// openscad -D 'RENDER="tray_body"' -o tray_body.stl cable_tray.scad
|
||||||
|
// openscad -D 'RENDER="tnut_bracket"' -o tnut_bracket.stl cable_tray.scad
|
||||||
|
// openscad -D 'RENDER="channel_clip"' -o channel_clip.stl cable_tray.scad
|
||||||
|
// openscad -D 'RENDER="cover_panel"' -o cover_panel.stl cable_tray.scad
|
||||||
|
// openscad -D 'RENDER="cable_saddle"' -o cable_saddle.stl cable_tray.scad
|
||||||
|
// openscad -D 'RENDER="assembly"' -o assembly.png cable_tray.scad
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
RENDER = "assembly"; // tray_body | tnut_bracket | channel_clip | cover_panel | cable_saddle | assembly
|
||||||
|
|
||||||
|
$fn = 48;
|
||||||
|
EPS = 0.01;
|
||||||
|
|
||||||
|
// ── 2020 rail constants ──────────────────────────────────────
|
||||||
|
RAIL_W = 20.0;
|
||||||
|
TNUT_W = 9.8;
|
||||||
|
TNUT_H = 5.5;
|
||||||
|
TNUT_L = 12.0;
|
||||||
|
SLOT_NECK_H = 3.2;
|
||||||
|
M5_D = 5.2;
|
||||||
|
M5_HEAD_D = 9.5;
|
||||||
|
M5_HEAD_H = 4.0;
|
||||||
|
|
||||||
|
// ── Tray geometry ────────────────────────────────────────────
|
||||||
|
TRAY_L = 280.0; // length along rail (7 × 40 mm tie-down pitch)
|
||||||
|
TRAY_W = 60.0; // width across rail (covers standard 40 mm rail pair)
|
||||||
|
TRAY_WALL = 2.5; // side / floor wall thickness
|
||||||
|
TRAY_DEPTH = 18.0; // interior depth (tallest zone + wall)
|
||||||
|
|
||||||
|
// Cable channel zones (widths must sum to TRAY_W - 2*TRAY_WALL - 2*DIV_T)
|
||||||
|
DIV_T = 2.5; // divider wall thickness
|
||||||
|
ZONE_A_W = 20.0; // Power
|
||||||
|
ZONE_A_D = 14.0;
|
||||||
|
ZONE_B_W = 14.0; // Signal
|
||||||
|
ZONE_B_D = 10.0;
|
||||||
|
ZONE_C_W = 14.0; // Servo
|
||||||
|
ZONE_C_D = 12.0;
|
||||||
|
// Total inner width used: ZONE_A_W + ZONE_B_W + ZONE_C_W + 2*DIV_T = 55 mm < TRAY_W - 2*TRAY_WALL = 55 mm ✓
|
||||||
|
|
||||||
|
// Tie-down slots (Velcro strips)
|
||||||
|
TIEDOWN_PITCH = 40.0;
|
||||||
|
TIEDOWN_W = 6.0; // slot width (fits 6 mm wide Velcro)
|
||||||
|
TIEDOWN_T = 2.2; // slot through-thickness (floor)
|
||||||
|
TIEDOWN_CNT = 7; // 7 positions along tray
|
||||||
|
|
||||||
|
// Pass-through holes in floor
|
||||||
|
PASSTHRU_D = 12.0; // circular grommet-compatible pass-through
|
||||||
|
PASSTHRU_CNT = 3; // one per zone, at tray mid-length
|
||||||
|
|
||||||
|
// Label slots (rear outer wall)
|
||||||
|
LABEL_W = 24.0;
|
||||||
|
LABEL_H = 8.0;
|
||||||
|
LABEL_T = 1.0; // depth from outer face
|
||||||
|
|
||||||
|
// Snap ledge for cover
|
||||||
|
SNAP_LEDGE_H = 2.5;
|
||||||
|
SNAP_LEDGE_D = 1.5;
|
||||||
|
|
||||||
|
// ── T-nut bracket ────────────────────────────────────────────
|
||||||
|
BKT_L = 60.0;
|
||||||
|
BKT_W = TRAY_W;
|
||||||
|
BKT_T = 6.0;
|
||||||
|
BOLT_PITCH = 40.0;
|
||||||
|
M3_D = 3.2;
|
||||||
|
M3_HEAD_D = 6.0;
|
||||||
|
M3_HEAD_H = 3.0;
|
||||||
|
M3_NUT_W = 5.5;
|
||||||
|
M3_NUT_H = 2.4;
|
||||||
|
|
||||||
|
// ── Cover panel ──────────────────────────────────────────────
|
||||||
|
CVR_T = 1.8; // panel thickness
|
||||||
|
HINGE_T = 0.6; // living-hinge strip thickness (printed in PETG)
|
||||||
|
HINGE_W = 3.0; // hinge strip width (flexes easily)
|
||||||
|
SNAP_HOOK_H = 3.5; // snap hook height
|
||||||
|
SNAP_HOOK_T = 2.2;
|
||||||
|
|
||||||
|
// ── Cable saddle ─────────────────────────────────────────────
|
||||||
|
SAD_W = 12.0;
|
||||||
|
SAD_H = 8.0;
|
||||||
|
SAD_T = 2.5;
|
||||||
|
SAD_BORE_D = 7.0; // cable bundle bore
|
||||||
|
SAD_CLIP_T = 1.6; // snap arm thickness
|
||||||
|
|
||||||
|
// ── Utilities ────────────────────────────────────────────────
|
||||||
|
module chamfer_cube(size, ch=1.0) {
|
||||||
|
hull() {
|
||||||
|
translate([ch, ch, 0]) cube([size[0]-2*ch, size[1]-2*ch, EPS]);
|
||||||
|
translate([0, 0, ch]) cube(size - [0, 0, ch]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module hex_pocket(af, depth) {
|
||||||
|
cylinder(d=af/cos(30), h=depth, $fn=6);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 1: tray_body ───────────────────────────────────────
|
||||||
|
module tray_body() {
|
||||||
|
difference() {
|
||||||
|
// Outer shell
|
||||||
|
union() {
|
||||||
|
chamfer_cube([TRAY_L, TRAY_W, TRAY_DEPTH + TRAY_WALL], ch=1.5);
|
||||||
|
|
||||||
|
// Snap ledge along top of both long walls (for cover_panel)
|
||||||
|
for (y = [-SNAP_LEDGE_D, TRAY_W])
|
||||||
|
translate([0, y, TRAY_DEPTH])
|
||||||
|
cube([TRAY_L, TRAY_WALL + SNAP_LEDGE_D, SNAP_LEDGE_H]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Interior cavity
|
||||||
|
translate([TRAY_WALL, TRAY_WALL, TRAY_WALL])
|
||||||
|
cube([TRAY_L - 2*TRAY_WALL, TRAY_W - 2*TRAY_WALL,
|
||||||
|
TRAY_DEPTH + EPS]);
|
||||||
|
|
||||||
|
// ── Zone dividers (subtract from solid to leave walls) ──
|
||||||
|
// Zone A (Power) inner floor cut — full depth A
|
||||||
|
translate([TRAY_WALL, TRAY_WALL, TRAY_WALL + (TRAY_DEPTH - ZONE_A_D)])
|
||||||
|
cube([TRAY_L - 2*TRAY_WALL, ZONE_A_W, ZONE_A_D + EPS]);
|
||||||
|
|
||||||
|
// Zone B (Signal) inner floor cut
|
||||||
|
translate([TRAY_WALL, TRAY_WALL + ZONE_A_W + DIV_T,
|
||||||
|
TRAY_WALL + (TRAY_DEPTH - ZONE_B_D)])
|
||||||
|
cube([TRAY_L - 2*TRAY_WALL, ZONE_B_W, ZONE_B_D + EPS]);
|
||||||
|
|
||||||
|
// Zone C (Servo) inner floor cut
|
||||||
|
translate([TRAY_WALL, TRAY_WALL + ZONE_A_W + DIV_T + ZONE_B_W + DIV_T,
|
||||||
|
TRAY_WALL + (TRAY_DEPTH - ZONE_C_D)])
|
||||||
|
cube([TRAY_L - 2*TRAY_WALL, ZONE_C_W, ZONE_C_D + EPS]);
|
||||||
|
|
||||||
|
// ── Velcro tie-down slots (floor, every 40 mm) ──────────
|
||||||
|
for (i = [0:TIEDOWN_CNT-1]) {
|
||||||
|
x = TRAY_WALL + 20 + i * TIEDOWN_PITCH - TIEDOWN_W/2;
|
||||||
|
// Zone A slot
|
||||||
|
translate([x, TRAY_WALL + 2, -EPS])
|
||||||
|
cube([TIEDOWN_W, ZONE_A_W - 4, TRAY_WALL + 2*EPS]);
|
||||||
|
// Zone B slot
|
||||||
|
translate([x, TRAY_WALL + ZONE_A_W + DIV_T + 2, -EPS])
|
||||||
|
cube([TIEDOWN_W, ZONE_B_W - 4, TRAY_WALL + 2*EPS]);
|
||||||
|
// Zone C slot
|
||||||
|
translate([x, TRAY_WALL + ZONE_A_W + DIV_T + ZONE_B_W + DIV_T + 2, -EPS])
|
||||||
|
cube([TIEDOWN_W, ZONE_C_W - 4, TRAY_WALL + 2*EPS]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Pass-through holes in floor (centre of each zone at mid-length) ──
|
||||||
|
mid_x = TRAY_L / 2;
|
||||||
|
// Zone A
|
||||||
|
translate([mid_x, TRAY_WALL + ZONE_A_W/2, -EPS])
|
||||||
|
cylinder(d=PASSTHRU_D, h=TRAY_WALL + 2*EPS);
|
||||||
|
// Zone B
|
||||||
|
translate([mid_x, TRAY_WALL + ZONE_A_W + DIV_T + ZONE_B_W/2, -EPS])
|
||||||
|
cylinder(d=PASSTHRU_D, h=TRAY_WALL + 2*EPS);
|
||||||
|
// Zone C
|
||||||
|
translate([mid_x, TRAY_WALL + ZONE_A_W + DIV_T + ZONE_B_W + DIV_T + ZONE_C_W/2, -EPS])
|
||||||
|
cylinder(d=PASSTHRU_D, h=TRAY_WALL + 2*EPS);
|
||||||
|
|
||||||
|
// ── Label slots on front wall (y = 0) — one per zone ────
|
||||||
|
zone_ctrs = [TRAY_WALL + ZONE_A_W/2,
|
||||||
|
TRAY_WALL + ZONE_A_W + DIV_T + ZONE_B_W/2,
|
||||||
|
TRAY_WALL + ZONE_A_W + DIV_T + ZONE_B_W + DIV_T + ZONE_C_W/2];
|
||||||
|
label_z = TRAY_WALL + 2;
|
||||||
|
for (yc = zone_ctrs)
|
||||||
|
translate([TRAY_L/2 - LABEL_W/2, -EPS, label_z])
|
||||||
|
cube([LABEL_W, LABEL_T + EPS, LABEL_H]);
|
||||||
|
|
||||||
|
// ── M3 bracket bolt holes in floor (4 corners) ──────────
|
||||||
|
for (x = [20, TRAY_L - 20])
|
||||||
|
for (y = [TRAY_W/4, 3*TRAY_W/4])
|
||||||
|
translate([x, y, -EPS])
|
||||||
|
cylinder(d=M3_D, h=TRAY_WALL + 2*EPS);
|
||||||
|
|
||||||
|
// ── Channel clip snap sockets (top of each divider, every 80 mm) ──
|
||||||
|
for (i = [0:2]) {
|
||||||
|
cx = 40 + i * 80;
|
||||||
|
for (dy = [ZONE_A_W, ZONE_A_W + DIV_T + ZONE_B_W])
|
||||||
|
translate([cx - 3, TRAY_WALL + dy - 1, TRAY_DEPTH - 4])
|
||||||
|
cube([6, DIV_T + 2, 4 + EPS]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Divider walls (positive geometry) ───────────────────
|
||||||
|
// Wall between Zone A and Zone B
|
||||||
|
translate([TRAY_WALL, TRAY_WALL + ZONE_A_W, TRAY_WALL])
|
||||||
|
cube([TRAY_L - 2*TRAY_WALL, DIV_T,
|
||||||
|
TRAY_DEPTH - ZONE_A_D]); // partial height — lower in A zone
|
||||||
|
|
||||||
|
// Wall between Zone B and Zone C
|
||||||
|
translate([TRAY_WALL, TRAY_WALL + ZONE_A_W + DIV_T + ZONE_B_W, TRAY_WALL])
|
||||||
|
cube([TRAY_L - 2*TRAY_WALL, DIV_T,
|
||||||
|
TRAY_DEPTH - ZONE_B_D]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 2: tnut_bracket ────────────────────────────────────
|
||||||
|
module tnut_bracket() {
|
||||||
|
difference() {
|
||||||
|
chamfer_cube([BKT_L, BKT_W, BKT_T], ch=1.5);
|
||||||
|
|
||||||
|
// M5 T-nut holes (2 per bracket, on rail centreline)
|
||||||
|
for (x = [BKT_L/2 - BOLT_PITCH/2, BKT_L/2 + BOLT_PITCH/2]) {
|
||||||
|
translate([x, BKT_W/2, -EPS]) {
|
||||||
|
cylinder(d=M5_D, h=BKT_T + 2*EPS);
|
||||||
|
cylinder(d=M5_HEAD_D, h=M5_HEAD_H + EPS);
|
||||||
|
}
|
||||||
|
translate([x - TNUT_L/2, BKT_W/2 - TNUT_W/2, BKT_T - TNUT_H])
|
||||||
|
cube([TNUT_L, TNUT_W, TNUT_H + EPS]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// M3 tray-attachment holes (4 corners)
|
||||||
|
for (x = [10, BKT_L - 10])
|
||||||
|
for (y = [10, BKT_W - 10]) {
|
||||||
|
translate([x, y, -EPS])
|
||||||
|
cylinder(d=M3_D, h=BKT_T + 2*EPS);
|
||||||
|
// M3 hex nut captured pocket (from top)
|
||||||
|
translate([x, y, BKT_T - M3_NUT_H - 0.2])
|
||||||
|
hex_pocket(M3_NUT_W + 0.3, M3_NUT_H + 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Weight relief
|
||||||
|
translate([15, 8, -EPS])
|
||||||
|
cube([BKT_L - 30, BKT_W - 16, BKT_T/2]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 3: channel_clip ────────────────────────────────────
|
||||||
|
// Snap-in clip that locks into divider-wall snap sockets;
|
||||||
|
// holds individual bundles in their zone and acts as colour-coded zone marker.
|
||||||
|
module channel_clip() {
|
||||||
|
clip_body_w = 6.0;
|
||||||
|
clip_body_h = DIV_T + 4.0;
|
||||||
|
clip_body_t = 8.0;
|
||||||
|
tab_h = 3.5;
|
||||||
|
tab_w = 2.5;
|
||||||
|
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// Body spanning divider
|
||||||
|
cube([clip_body_t, clip_body_w, clip_body_h]);
|
||||||
|
|
||||||
|
// Snap tabs (bottom, straddle divider)
|
||||||
|
for (s = [0, clip_body_w - tab_w])
|
||||||
|
translate([clip_body_t/2 - 1, s, -tab_h])
|
||||||
|
cube([2, tab_w, tab_h + 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cable radius slot on each face
|
||||||
|
translate([-EPS, clip_body_w/2, clip_body_h * 0.6])
|
||||||
|
rotate([0, 90, 0])
|
||||||
|
cylinder(d=5.0, h=clip_body_t + 2*EPS);
|
||||||
|
|
||||||
|
// Snap tab undercut for flex
|
||||||
|
for (s = [0, clip_body_w - tab_w])
|
||||||
|
translate([clip_body_t/2 - 2, s - EPS, -tab_h + 1.5])
|
||||||
|
cube([4, tab_w + 2*EPS, 1.5]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 4: cover_panel ─────────────────────────────────────
|
||||||
|
// Flat snap-on lid with living-hinge along one long edge.
|
||||||
|
// Print flat; PETG living hinge flexes ~90° to snap onto tray.
|
||||||
|
module cover_panel() {
|
||||||
|
total_w = TRAY_W + 2 * SNAP_HOOK_T;
|
||||||
|
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// Main panel
|
||||||
|
cube([TRAY_L, TRAY_W, CVR_T]);
|
||||||
|
|
||||||
|
// Living hinge strip along back edge (thin, flexes)
|
||||||
|
translate([0, TRAY_W - EPS, 0])
|
||||||
|
cube([TRAY_L, HINGE_W, HINGE_T]);
|
||||||
|
|
||||||
|
// Snap hooks along front edge (clips under tray snap ledge)
|
||||||
|
for (x = [20, TRAY_L/2 - 20, TRAY_L/2 + 20, TRAY_L - 20])
|
||||||
|
translate([x - SNAP_HOOK_T/2, -SNAP_HOOK_H + EPS, 0])
|
||||||
|
difference() {
|
||||||
|
cube([SNAP_HOOK_T, SNAP_HOOK_H, CVR_T + 1.5]);
|
||||||
|
// Hook nose chamfer
|
||||||
|
translate([-EPS, -EPS, CVR_T])
|
||||||
|
rotate([0, 0, 0])
|
||||||
|
cube([SNAP_HOOK_T + 2*EPS, 1.5, 1.5]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ventilation slots (3 rows × 6 slots)
|
||||||
|
for (row = [0:2])
|
||||||
|
for (col = [0:5]) {
|
||||||
|
sx = 20 + col * 40 + row * 10;
|
||||||
|
sy = 10 + row * 12;
|
||||||
|
if (sx + 25 < TRAY_L && sy + 6 < TRAY_W)
|
||||||
|
translate([sx, sy, -EPS])
|
||||||
|
cube([25, 6, CVR_T + 2*EPS]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Zone label windows (align with tray label slots)
|
||||||
|
zone_ctrs = [TRAY_WALL + ZONE_A_W/2,
|
||||||
|
TRAY_WALL + ZONE_A_W + DIV_T + ZONE_B_W/2,
|
||||||
|
TRAY_WALL + ZONE_A_W + DIV_T + ZONE_B_W + DIV_T + ZONE_C_W/2];
|
||||||
|
for (yc = zone_ctrs)
|
||||||
|
translate([TRAY_L/2 - LABEL_W/2, yc - LABEL_H/2, -EPS])
|
||||||
|
cube([LABEL_W, LABEL_H, CVR_T + 2*EPS]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 5: cable_saddle ────────────────────────────────────
|
||||||
|
// Snap-in cable saddle / strain-relief clip; press-fits onto tray top edge.
|
||||||
|
module cable_saddle() {
|
||||||
|
arm_gap = TRAY_WALL + 0.4; // fits over tray wall
|
||||||
|
arm_len = 8.0;
|
||||||
|
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// Body
|
||||||
|
chamfer_cube([SAD_W, SAD_T * 2 + arm_gap, SAD_H], ch=1.0);
|
||||||
|
|
||||||
|
// Cable retaining arch
|
||||||
|
translate([SAD_W/2, SAD_T + arm_gap/2, SAD_H])
|
||||||
|
scale([1, 0.6, 1])
|
||||||
|
difference() {
|
||||||
|
cylinder(d=SAD_BORE_D + SAD_CLIP_T * 2, h=SAD_T);
|
||||||
|
translate([0, 0, -EPS])
|
||||||
|
cylinder(d=SAD_BORE_D, h=SAD_T + 2*EPS);
|
||||||
|
translate([-SAD_BORE_D, 0, -EPS])
|
||||||
|
cube([SAD_BORE_D * 2, SAD_BORE_D, SAD_T + 2*EPS]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Slot for tray wall (negative)
|
||||||
|
translate([0, SAD_T, -EPS])
|
||||||
|
cube([SAD_W, arm_gap, arm_len + EPS]);
|
||||||
|
|
||||||
|
// M3 tie-down hole
|
||||||
|
translate([SAD_W/2, SAD_T + arm_gap/2, -EPS])
|
||||||
|
cylinder(d=M3_D, h=SAD_H + 2*EPS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Assembly ────────────────────────────────────────────────
|
||||||
|
module assembly() {
|
||||||
|
// Tray body (open face up for visibility)
|
||||||
|
color("SteelBlue")
|
||||||
|
tray_body();
|
||||||
|
|
||||||
|
// Two T-nut brackets underneath at 1/4 and 3/4 length
|
||||||
|
for (bx = [TRAY_L/4 - BKT_L/2, 3*TRAY_L/4 - BKT_L/2])
|
||||||
|
color("DodgerBlue")
|
||||||
|
translate([bx, 0, -BKT_T])
|
||||||
|
tnut_bracket();
|
||||||
|
|
||||||
|
// Channel clips (3 per divider position, every 80 mm)
|
||||||
|
for (i = [0:2]) {
|
||||||
|
cx = 40 + i * 80;
|
||||||
|
// Divider A/B
|
||||||
|
color("Tomato", 0.8)
|
||||||
|
translate([cx - 4, TRAY_WALL + ZONE_A_W - 2, TRAY_DEPTH - 3])
|
||||||
|
channel_clip();
|
||||||
|
// Divider B/C
|
||||||
|
color("Orange", 0.8)
|
||||||
|
translate([cx - 4,
|
||||||
|
TRAY_WALL + ZONE_A_W + DIV_T + ZONE_B_W - 2,
|
||||||
|
TRAY_DEPTH - 3])
|
||||||
|
channel_clip();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cover panel (raised above tray to show interior)
|
||||||
|
color("LightSteelBlue", 0.5)
|
||||||
|
translate([0, 0, TRAY_DEPTH + SNAP_LEDGE_H + 4])
|
||||||
|
cover_panel();
|
||||||
|
|
||||||
|
// Cable saddles along front tray edge
|
||||||
|
for (x = [40, 120, 200])
|
||||||
|
color("SlateGray")
|
||||||
|
translate([x - SAD_W/2, -SAD_T * 2 - TRAY_WALL, 0])
|
||||||
|
cable_saddle();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Dispatch ────────────────────────────────────────────────
|
||||||
|
if (RENDER == "tray_body") tray_body();
|
||||||
|
else if (RENDER == "tnut_bracket") tnut_bracket();
|
||||||
|
else if (RENDER == "channel_clip") channel_clip();
|
||||||
|
else if (RENDER == "cover_panel") cover_panel();
|
||||||
|
else if (RENDER == "cable_saddle") cable_saddle();
|
||||||
|
else assembly();
|
||||||
265
chassis/canable_mount.scad
Normal file
265
chassis/canable_mount.scad
Normal file
@ -0,0 +1,265 @@
|
|||||||
|
// ============================================================
|
||||||
|
// canable_mount.scad — CANable 2.0 USB-CAN Adapter Cradle
|
||||||
|
// Issue #654 / sl-mechanical 2026-03-16
|
||||||
|
// ============================================================
|
||||||
|
// Snap-fit cradle for CANable 2.0 PCB (~60 × 18 × 10 mm).
|
||||||
|
// Attaches to 2020 aluminium T-slot rail via 2× M5 T-nuts.
|
||||||
|
//
|
||||||
|
// Port access:
|
||||||
|
// USB-C port — X− end wall cutout (connector protrudes through)
|
||||||
|
// CAN terminal — X+ end wall cutout (CANH / CANL / GND wire exit)
|
||||||
|
// LED status window— slot in Y+ side wall, PCB top-face LEDs visible
|
||||||
|
//
|
||||||
|
// Retention: snap-fit cantilever lips on both side walls (PETG flex).
|
||||||
|
// Cable strain relief: zip-tie boss pair on X+ shelf (CAN wires).
|
||||||
|
//
|
||||||
|
// ⚠ VERIFY WITH CALIPERS BEFORE PRINTING:
|
||||||
|
// PCB_L, PCB_W board outline
|
||||||
|
// USBC_W, USBC_H USB-C shell at X− edge
|
||||||
|
// TERM_W, TERM_H 3-pos terminal block at X+ edge
|
||||||
|
// LED_X_CTR, LED_WIN_W LED window position on Y+ wall
|
||||||
|
//
|
||||||
|
// Print settings (PETG):
|
||||||
|
// 3 perimeters, 40 % gyroid infill, no supports, 0.2 mm layer
|
||||||
|
// Print orientation: open face UP (as modelled)
|
||||||
|
//
|
||||||
|
// BOM:
|
||||||
|
// 2 × M5×10 BHCS + 2 × M5 slide-in T-nut (2020 rail)
|
||||||
|
//
|
||||||
|
// Export commands:
|
||||||
|
// openscad -D 'RENDER="mount"' -o canable_mount.stl canable_mount.scad
|
||||||
|
// openscad -D 'RENDER="assembly"' -o canable_assembly.png canable_mount.scad
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
RENDER = "assembly"; // mount | assembly
|
||||||
|
|
||||||
|
$fn = 48;
|
||||||
|
EPS = 0.01;
|
||||||
|
|
||||||
|
// ── ⚠ Verify before printing ─────────────────────────────────
|
||||||
|
// CANable 2.0 PCB
|
||||||
|
PCB_L = 60.0; // board length (X: USB-C end → terminal end)
|
||||||
|
PCB_W = 18.0; // board width (Y)
|
||||||
|
PCB_T = 1.6; // board thickness
|
||||||
|
COMP_H = 8.5; // tallest component above board (USB-C shell ≈ 3.5 mm;
|
||||||
|
// terminal block ≈ 8.5 mm)
|
||||||
|
|
||||||
|
// USB-C connector (at X− end face of PCB)
|
||||||
|
USBC_W = 9.5; // connector outer width
|
||||||
|
USBC_H = 3.8; // connector outer height above board surface
|
||||||
|
USBC_Z0 = 0.0; // connector bottom offset above board surface
|
||||||
|
|
||||||
|
// CAN screw-terminal block (at X+ end face, 3-pos 5.0 mm pitch)
|
||||||
|
TERM_W = 16.0; // terminal block span (3 × 5 mm + housing)
|
||||||
|
TERM_H = 9.0; // terminal block height above board surface
|
||||||
|
TERM_Z0 = 0.5; // terminal bottom offset above board surface
|
||||||
|
|
||||||
|
// Status LED window (LEDs near USB-C end on PCB top face)
|
||||||
|
// Rectangular slot cut in Y+ side wall — LEDs visible from the side
|
||||||
|
LED_X_CTR = 11.0; // LED zone centre measured from PCB X− edge
|
||||||
|
LED_WIN_W = 14.0; // window width (X)
|
||||||
|
LED_WIN_H = 5.5; // window height (Z) — opens top portion of side wall
|
||||||
|
|
||||||
|
// ── Cradle geometry ──────────────────────────────────────────
|
||||||
|
WALL_T = 2.5; // side/end wall thickness
|
||||||
|
FLOOR_T = 4.0; // floor plate thickness (accommodates M5 BHCS head pocket)
|
||||||
|
CL_SIDE = 0.30; // Y clearance per side (total 0.6 mm play)
|
||||||
|
CL_END = 0.40; // X clearance per end
|
||||||
|
|
||||||
|
// Interior cavity
|
||||||
|
INN_W = PCB_W + 2*CL_SIDE; // Y span
|
||||||
|
INN_L = PCB_L + 2*CL_END; // X span
|
||||||
|
INN_H = PCB_T + COMP_H + 1.2; // Z height (board + tallest comp + margin)
|
||||||
|
|
||||||
|
// Outer body
|
||||||
|
OTR_W = INN_W + 2*WALL_T; // Y
|
||||||
|
OTR_L = INN_L + 2*WALL_T; // X
|
||||||
|
OTR_H = FLOOR_T + INN_H; // Z
|
||||||
|
|
||||||
|
// PCB reference origin within body (lower-left corner of board)
|
||||||
|
PCB_X0 = WALL_T + CL_END; // board X start inside body
|
||||||
|
PCB_Y0 = WALL_T + CL_SIDE; // board Y start inside body
|
||||||
|
PCB_Z0 = FLOOR_T; // board bottom sits on floor
|
||||||
|
|
||||||
|
// ── Snap-fit lips ─────────────────────────────────────────────
|
||||||
|
// Cantilever ledge on inner face of each side wall, at PCB-top Z.
|
||||||
|
// Tapered (chamfered) entry guides PCB in from above.
|
||||||
|
SNAP_IN = 0.8; // how far inward ledge protrudes over PCB edge
|
||||||
|
SNAP_T = 1.2; // snap-arm thickness (thin for PETG flex)
|
||||||
|
SNAP_H = 4.0; // cantilever arm height (root at OTR_H, tip near PCB_Z0+PCB_T)
|
||||||
|
SNAP_L = 18.0; // arm length along X (centred on PCB, shorter = more flex)
|
||||||
|
// Snap on Y− wall protrudes in +Y direction; Y+ wall protrudes in −Y direction
|
||||||
|
|
||||||
|
// ── M5 T-nut mount (2020 rail) ────────────────────────────────
|
||||||
|
M5_D = 5.3; // M5 bolt clearance bore
|
||||||
|
M5_HEAD_D = 9.5; // M5 BHCS head pocket diameter (from bottom face)
|
||||||
|
M5_HEAD_H = 3.0; // BHCS head pocket depth
|
||||||
|
M5_SPAC = 20.0; // bolt spacing along X (centred on cradle)
|
||||||
|
// Standard M5 slide-in T-nuts used — no T-nut pocket moulded in.
|
||||||
|
|
||||||
|
// ── Cable strain relief ───────────────────────────────────────
|
||||||
|
// Two zip-tie anchor bosses on a shelf inside the X+ end, straddling
|
||||||
|
// the CAN terminal wires.
|
||||||
|
SR_BOSS_OD = 7.0; // boss outer diameter
|
||||||
|
SR_BOSS_H = 5.5; // boss height above floor
|
||||||
|
SR_SLOT_W = 3.5; // zip-tie slot width
|
||||||
|
SR_SLOT_T = 2.2; // zip-tie slot through-height
|
||||||
|
// Boss Y positions (straddle terminal block)
|
||||||
|
SR_Y1 = WALL_T + INN_W * 0.25;
|
||||||
|
SR_Y2 = WALL_T + INN_W * 0.75;
|
||||||
|
SR_X = OTR_L - WALL_T - SR_BOSS_OD/2 - 2.5; // just inside X+ end wall
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────
|
||||||
|
module canable_mount() {
|
||||||
|
difference() {
|
||||||
|
// ── Outer solid body ──────────────────────────────────
|
||||||
|
union() {
|
||||||
|
cube([OTR_L, OTR_W, OTR_H]);
|
||||||
|
|
||||||
|
// ── Snap cantilever arms on Y− wall (protrude inward +Y) ──
|
||||||
|
// Arms hang down from top of Y− wall inner face.
|
||||||
|
// Root is flush with inner face (Y = WALL_T); tip at PCB level.
|
||||||
|
translate([OTR_L/2 - SNAP_L/2, WALL_T - SNAP_T, OTR_H - SNAP_H])
|
||||||
|
cube([SNAP_L, SNAP_T, SNAP_H]);
|
||||||
|
|
||||||
|
// ── Snap cantilever arms on Y+ wall (protrude inward −Y) ──
|
||||||
|
translate([OTR_L/2 - SNAP_L/2, OTR_W - WALL_T, OTR_H - SNAP_H])
|
||||||
|
cube([SNAP_L, SNAP_T, SNAP_H]);
|
||||||
|
|
||||||
|
// ── Cable strain relief bosses (X+ end, inside) ────
|
||||||
|
for (sy = [SR_Y1, SR_Y2])
|
||||||
|
translate([SR_X, sy, 0])
|
||||||
|
cylinder(d=SR_BOSS_OD, h=SR_BOSS_H);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Interior cavity ───────────────────────────────────
|
||||||
|
translate([WALL_T, WALL_T, FLOOR_T])
|
||||||
|
cube([INN_L, INN_W, INN_H + EPS]);
|
||||||
|
|
||||||
|
// ── USB-C cutout — X− end wall ────────────────────────
|
||||||
|
// Centred on PCB width; opened from board surface upward
|
||||||
|
translate([-EPS,
|
||||||
|
PCB_Y0 + PCB_W/2 - (USBC_W + 1.5)/2,
|
||||||
|
PCB_Z0 + USBC_Z0 - 0.5])
|
||||||
|
cube([WALL_T + 2*EPS, USBC_W + 1.5, USBC_H + 2.5]);
|
||||||
|
|
||||||
|
// ── CAN terminal cutout — X+ end wall ─────────────────
|
||||||
|
// Full terminal width + 2 mm margin for screwdriver access;
|
||||||
|
// height clears terminal block + wire bend radius
|
||||||
|
translate([OTR_L - WALL_T - EPS,
|
||||||
|
PCB_Y0 + PCB_W/2 - (TERM_W + 2.0)/2,
|
||||||
|
PCB_Z0 + TERM_Z0 - 0.5])
|
||||||
|
cube([WALL_T + 2*EPS, TERM_W + 2.0, TERM_H + 5.0]);
|
||||||
|
|
||||||
|
// ── LED status window — Y+ side wall ─────────────────
|
||||||
|
// Rectangular slot; LEDs at top-face of PCB are visible through it
|
||||||
|
translate([PCB_X0 + LED_X_CTR - LED_WIN_W/2,
|
||||||
|
OTR_W - WALL_T - EPS,
|
||||||
|
OTR_H - LED_WIN_H])
|
||||||
|
cube([LED_WIN_W, WALL_T + 2*EPS, LED_WIN_H + EPS]);
|
||||||
|
|
||||||
|
// ── M5 BHCS head pockets (from bottom face of floor) ──
|
||||||
|
for (mx = [OTR_L/2 - M5_SPAC/2, OTR_L/2 + M5_SPAC/2])
|
||||||
|
translate([mx, OTR_W/2, -EPS]) {
|
||||||
|
// Clearance bore through full floor
|
||||||
|
cylinder(d=M5_D, h=FLOOR_T + 2*EPS);
|
||||||
|
// BHCS head pocket from bottom face
|
||||||
|
cylinder(d=M5_HEAD_D, h=M5_HEAD_H + EPS);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Snap-arm ledge slot — Y− arm (hollow out to thin arm) ──
|
||||||
|
// Arm is SNAP_T thick; cut away material behind arm
|
||||||
|
translate([OTR_L/2 - SNAP_L/2 - EPS, EPS, OTR_H - SNAP_H])
|
||||||
|
cube([SNAP_L + 2*EPS, WALL_T - SNAP_T - EPS, SNAP_H + EPS]);
|
||||||
|
|
||||||
|
// ── Snap-arm ledge slot — Y+ arm ──────────────────────
|
||||||
|
translate([OTR_L/2 - SNAP_L/2 - EPS, OTR_W - WALL_T + SNAP_T, OTR_H - SNAP_H])
|
||||||
|
cube([SNAP_L + 2*EPS, WALL_T - SNAP_T - EPS, SNAP_H + EPS]);
|
||||||
|
|
||||||
|
// ── Snap-arm inward ledge notch (entry chamfer removed) ─
|
||||||
|
// Chamfer top of snap arm so PCB slides in easily
|
||||||
|
// Y− arm: chamfer on upper-inner edge → 45° wedge on +Y/+Z corner
|
||||||
|
translate([OTR_L/2 - SNAP_L/2 - EPS,
|
||||||
|
WALL_T - SNAP_T - EPS,
|
||||||
|
OTR_H - SNAP_IN])
|
||||||
|
rotate([0, 0, 0])
|
||||||
|
rotate([45, 0, 0])
|
||||||
|
cube([SNAP_L + 2*EPS, SNAP_IN * 1.5, SNAP_IN * 1.5]);
|
||||||
|
|
||||||
|
// Y+ arm: chamfer on upper-inner edge
|
||||||
|
translate([OTR_L/2 - SNAP_L/2 - EPS,
|
||||||
|
OTR_W - WALL_T + SNAP_T - SNAP_IN * 1.5 + EPS,
|
||||||
|
OTR_H - SNAP_IN])
|
||||||
|
rotate([45, 0, 0])
|
||||||
|
cube([SNAP_L + 2*EPS, SNAP_IN * 1.5, SNAP_IN * 1.5]);
|
||||||
|
|
||||||
|
// ── Snap ledge cutout on Y− arm inner tip ─────────────
|
||||||
|
// Creates inward nub: remove top portion of arm inner tip
|
||||||
|
// leaving bottom SNAP_IN height as the retaining ledge
|
||||||
|
translate([OTR_L/2 - SNAP_L/2 - EPS,
|
||||||
|
WALL_T - SNAP_T - EPS,
|
||||||
|
PCB_Z0 + PCB_T + SNAP_IN])
|
||||||
|
cube([SNAP_L + 2*EPS, SNAP_T + 2*EPS,
|
||||||
|
OTR_H - (PCB_Z0 + PCB_T + SNAP_IN) + EPS]);
|
||||||
|
|
||||||
|
// ── Snap ledge cutout on Y+ arm inner tip ─────────────
|
||||||
|
translate([OTR_L/2 - SNAP_L/2 - EPS,
|
||||||
|
OTR_W - WALL_T - EPS,
|
||||||
|
PCB_Z0 + PCB_T + SNAP_IN])
|
||||||
|
cube([SNAP_L + 2*EPS, SNAP_T + 2*EPS,
|
||||||
|
OTR_H - (PCB_Z0 + PCB_T + SNAP_IN) + EPS]);
|
||||||
|
|
||||||
|
// ── Zip-tie slots through strain relief bosses ─────────
|
||||||
|
for (sy = [SR_Y1, SR_Y2])
|
||||||
|
translate([SR_X, sy,
|
||||||
|
SR_BOSS_H/2 - SR_SLOT_T/2])
|
||||||
|
rotate([0, 90, 0])
|
||||||
|
cube([SR_SLOT_T, SR_SLOT_W,
|
||||||
|
SR_BOSS_OD + 2*EPS],
|
||||||
|
center=true);
|
||||||
|
|
||||||
|
// ── Weight relief pocket in floor (underside) ─────────
|
||||||
|
translate([WALL_T + 8, WALL_T + 3, -EPS])
|
||||||
|
cube([OTR_L - 2*WALL_T - 16, OTR_W - 2*WALL_T - 6,
|
||||||
|
FLOOR_T - 1.5 + EPS]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Assembly preview ─────────────────────────────────────────
|
||||||
|
if (RENDER == "assembly") {
|
||||||
|
color("DimGray", 0.93) canable_mount();
|
||||||
|
|
||||||
|
// Phantom PCB
|
||||||
|
color("MidnightBlue", 0.35)
|
||||||
|
translate([PCB_X0, PCB_Y0, PCB_Z0])
|
||||||
|
cube([PCB_L, PCB_W, PCB_T]);
|
||||||
|
|
||||||
|
// Phantom component block (top of PCB)
|
||||||
|
color("DarkSlateGray", 0.25)
|
||||||
|
translate([PCB_X0, PCB_Y0, PCB_Z0 + PCB_T])
|
||||||
|
cube([PCB_L, PCB_W, COMP_H]);
|
||||||
|
|
||||||
|
// USB-C port highlight
|
||||||
|
color("Gold", 0.8)
|
||||||
|
translate([-1,
|
||||||
|
PCB_Y0 + PCB_W/2 - USBC_W/2,
|
||||||
|
PCB_Z0 + USBC_Z0])
|
||||||
|
cube([WALL_T + 2, USBC_W, USBC_H]);
|
||||||
|
|
||||||
|
// Terminal block highlight
|
||||||
|
color("Tomato", 0.7)
|
||||||
|
translate([OTR_L - WALL_T - 1,
|
||||||
|
PCB_Y0 + PCB_W/2 - TERM_W/2,
|
||||||
|
PCB_Z0 + TERM_Z0])
|
||||||
|
cube([WALL_T + 2, TERM_W, TERM_H]);
|
||||||
|
|
||||||
|
// LED zone highlight
|
||||||
|
color("LimeGreen", 0.9)
|
||||||
|
translate([PCB_X0 + LED_X_CTR - LED_WIN_W/2,
|
||||||
|
OTR_W - WALL_T - 0.5,
|
||||||
|
OTR_H - LED_WIN_H + 1])
|
||||||
|
cube([LED_WIN_W, 1, LED_WIN_H - 2]);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
canable_mount();
|
||||||
|
}
|
||||||
@ -8,9 +8,9 @@
|
|||||||
// Requirements:
|
// Requirements:
|
||||||
// - 600mm wheelbase
|
// - 600mm wheelbase
|
||||||
// - 2x hoverboard hub motors (170mm OD)
|
// - 2x hoverboard hub motors (170mm OD)
|
||||||
// - STM32 MAMBA F722S FC mount (30.5x30.5mm pattern)
|
// - ESP32-S3 ESP32-S3 BALANCE FC mount (30.5x30.5mm pattern)
|
||||||
// - Battery tray (24V 4Ah — ~180x70x50mm pack)
|
// - Battery tray (24V 4Ah — ~180x70x50mm pack)
|
||||||
// - Jetson Nano B01 mount plate (100x80mm, M3 holes)
|
// - Jetson Orin Nano Super B01 mount plate (100x80mm, M3 holes)
|
||||||
// - Front/rear bumper brackets
|
// - Front/rear bumper brackets
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
|
|
||||||
@ -37,7 +37,7 @@ MOTOR_FORK_H = 80; // mm, total height of motor fork bracket
|
|||||||
MOTOR_FORK_T = 8; // mm, fork plate thickness
|
MOTOR_FORK_T = 8; // mm, fork plate thickness
|
||||||
AXLE_HEIGHT = 310; // mm, axle CL above ground (motor radius + clearance)
|
AXLE_HEIGHT = 310; // mm, axle CL above ground (motor radius + clearance)
|
||||||
|
|
||||||
// ── FC mount (MAMBA F722S — 30.5 × 30.5 mm M3 pattern) ──────────────────────
|
// ── FC mount (ESP32-S3 BALANCE — 30.5 × 30.5 mm M3 pattern) ──────────────────────
|
||||||
FC_MOUNT_SPACING = 30.5; // mm, hole pattern pitch
|
FC_MOUNT_SPACING = 30.5; // mm, hole pattern pitch
|
||||||
FC_MOUNT_HOLE_D = 3.2; // mm, M3 clearance
|
FC_MOUNT_HOLE_D = 3.2; // mm, M3 clearance
|
||||||
FC_STANDOFF_H = 6; // mm, standoff height
|
FC_STANDOFF_H = 6; // mm, standoff height
|
||||||
@ -52,7 +52,7 @@ BATT_FLOOR = 4; // mm, tray floor thickness
|
|||||||
BATT_STRAP_W = 20; // mm, Velcro strap slot width
|
BATT_STRAP_W = 20; // mm, Velcro strap slot width
|
||||||
BATT_STRAP_T = 2; // mm, strap slot depth
|
BATT_STRAP_T = 2; // mm, strap slot depth
|
||||||
|
|
||||||
// ── Jetson Nano B01 mount plate ──────────────────────────────────────────────
|
// ── Jetson Orin Nano Super B01 mount plate ──────────────────────────────────────────────
|
||||||
// B01 carrier board hole pattern: 58 x 58 mm M3 (inner) + corner pass-throughs
|
// B01 carrier board hole pattern: 58 x 58 mm M3 (inner) + corner pass-throughs
|
||||||
JETSON_HOLE_PITCH = 58; // mm, M3 mounting hole pattern
|
JETSON_HOLE_PITCH = 58; // mm, M3 mounting hole pattern
|
||||||
JETSON_HOLE_D = 3.2; // mm
|
JETSON_HOLE_D = 3.2; // mm
|
||||||
@ -210,7 +210,7 @@ module battery_tray() {
|
|||||||
|
|
||||||
// ─── FC mount holes helper ────────────────────────────────────────────────────
|
// ─── FC mount holes helper ────────────────────────────────────────────────────
|
||||||
module fc_mount_holes(z_offset=0, depth=10) {
|
module fc_mount_holes(z_offset=0, depth=10) {
|
||||||
// MAMBA F722S: 30.5×30.5 mm M3 pattern, centred at origin
|
// ESP32-S3 BALANCE: 30.5×30.5 mm M3 pattern, centred at origin
|
||||||
for (x = [-FC_MOUNT_SPACING/2, FC_MOUNT_SPACING/2])
|
for (x = [-FC_MOUNT_SPACING/2, FC_MOUNT_SPACING/2])
|
||||||
for (y = [-FC_MOUNT_SPACING/2, FC_MOUNT_SPACING/2])
|
for (y = [-FC_MOUNT_SPACING/2, FC_MOUNT_SPACING/2])
|
||||||
translate([x, y, z_offset])
|
translate([x, y, z_offset])
|
||||||
@ -247,7 +247,7 @@ module fc_mount_plate() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Jetson Nano B01 mount plate ─────────────────────────────────────────────
|
// ─── Jetson Orin Nano Super B01 mount plate ─────────────────────────────────────────────
|
||||||
// Positioned rear of deck, elevated on standoffs
|
// Positioned rear of deck, elevated on standoffs
|
||||||
module jetson_mount_plate() {
|
module jetson_mount_plate() {
|
||||||
jet_x = 60; // offset toward rear
|
jet_x = 60; // offset toward rear
|
||||||
|
|||||||
@ -104,7 +104,11 @@ IP54-rated enclosures and sensor housings for all-weather outdoor robot operatio
|
|||||||
| Component | Thermal strategy | Max junction | Enclosure budget |
|
| Component | Thermal strategy | Max junction | Enclosure budget |
|
||||||
|-----------|-----------------|-------------|-----------------|
|
|-----------|-----------------|-------------|-----------------|
|
||||||
| Jetson Orin NX | Al pad → lid → fan forced convection | 95 °C Tj | Target ≤ 60 °C case |
|
| Jetson Orin NX | Al pad → lid → fan forced convection | 95 °C Tj | Target ≤ 60 °C case |
|
||||||
| FC (MAMBA F722S) | Passive; FC has own EMI shield | 85 °C | <60 °C ambient OK |
|
<<<<<<< HEAD
|
||||||
|
| FC (ESP32 BALANCE) | Passive; FC has own EMI shield | 85 °C | <60 °C ambient OK |
|
||||||
|
=======
|
||||||
|
| FC (ESP32-S3 BALANCE) | Passive; FC has own EMI shield | 85 °C | <60 °C ambient OK |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
| ESC × 2 | Al pad → lid | 100 °C Tj | Target ≤ 60 °C |
|
| ESC × 2 | Al pad → lid | 100 °C Tj | Target ≤ 60 °C |
|
||||||
| D435i | Passive; housing vent gap on rear cap | 45 °C surface | — |
|
| D435i | Passive; housing vent gap on rear cap | 45 °C surface | — |
|
||||||
|
|
||||||
|
|||||||
386
chassis/jetson_orin_mount.scad
Normal file
386
chassis/jetson_orin_mount.scad
Normal file
@ -0,0 +1,386 @@
|
|||||||
|
// ============================================================
|
||||||
|
// Jetson Orin Nano Carrier Board Mount — Issue #612
|
||||||
|
// Agent : sl-mechanical
|
||||||
|
// Date : 2026-03-15
|
||||||
|
// Part catalogue:
|
||||||
|
// 1. tnut_base — 2020 T-slot rail interface plate, M5 T-nut captive pockets
|
||||||
|
// 2. standoff_post — M2.5 captive-nut standoff post (×4), 10 mm airflow gap
|
||||||
|
// 3. side_brace — lateral stiffening brace with port-access cutouts (×2)
|
||||||
|
// 4. duct_shroud — optional top heatsink duct / fan-exhaust channel
|
||||||
|
// 5. cable_clip — snap-on cable management clip for brace edge
|
||||||
|
//
|
||||||
|
// BOM:
|
||||||
|
// 4 × M5×10 BHCS + M5 T-nuts (tnut_base to rail, 2 per rail)
|
||||||
|
// 4 × M2.5×20 SHCS (board to standoff posts)
|
||||||
|
// 4 × M2.5 hex nuts (captured in standoff posts)
|
||||||
|
// 4 × M3×8 SHCS + washers (side_brace to tnut_base)
|
||||||
|
// 2 × M3×16 SHCS (duct_shroud to side_brace tops)
|
||||||
|
//
|
||||||
|
// Jetson Orin Nano carrier board (Seeed reComputer / official dev kit):
|
||||||
|
// Board dims : 100 × 80 mm
|
||||||
|
// Mounting hole pattern : 86 × 58 mm (centre-to-centre), M2.5, Ø3.5 pad
|
||||||
|
// PCB thickness: 1.6 mm
|
||||||
|
// Connector side: -Y (USB-A, USB-C, HDMI, DP, GbE, SD on one long edge)
|
||||||
|
// Fan header & PWM header: +X short edge
|
||||||
|
// M.2 / NVMe: bottom face
|
||||||
|
//
|
||||||
|
// Print settings (PETG):
|
||||||
|
// tnut_base / standoff_post / side_brace / duct_shroud : 5 perimeters, 40 % gyroid, no supports
|
||||||
|
// cable_clip : 3 perimeters, 30 % gyroid, no supports
|
||||||
|
//
|
||||||
|
// Export commands:
|
||||||
|
// openscad -D 'RENDER="tnut_base"' -o tnut_base.stl jetson_orin_mount.scad
|
||||||
|
// openscad -D 'RENDER="standoff_post"' -o standoff_post.stl jetson_orin_mount.scad
|
||||||
|
// openscad -D 'RENDER="side_brace"' -o side_brace.stl jetson_orin_mount.scad
|
||||||
|
// openscad -D 'RENDER="duct_shroud"' -o duct_shroud.stl jetson_orin_mount.scad
|
||||||
|
// openscad -D 'RENDER="cable_clip"' -o cable_clip.stl jetson_orin_mount.scad
|
||||||
|
// openscad -D 'RENDER="assembly"' -o assembly.png jetson_orin_mount.scad
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
// ── Render selector ─────────────────────────────────────────
|
||||||
|
RENDER = "assembly"; // tnut_base | standoff_post | side_brace | duct_shroud | cable_clip | assembly
|
||||||
|
|
||||||
|
// ── Global constants ────────────────────────────────────────
|
||||||
|
$fn = 64;
|
||||||
|
EPS = 0.01;
|
||||||
|
|
||||||
|
// 2020 rail
|
||||||
|
RAIL_W = 20.0;
|
||||||
|
SLOT_NECK_H = 3.2;
|
||||||
|
TNUT_W = 9.8;
|
||||||
|
TNUT_H = 5.5;
|
||||||
|
TNUT_L = 12.0;
|
||||||
|
M5_D = 5.2;
|
||||||
|
M5_HEAD_D = 9.5;
|
||||||
|
M5_HEAD_H = 4.0;
|
||||||
|
|
||||||
|
// Jetson Orin Nano carrier board
|
||||||
|
BOARD_L = 100.0; // board X
|
||||||
|
BOARD_W = 80.0; // board Y
|
||||||
|
BOARD_T = 1.6; // PCB thickness
|
||||||
|
MH_SX = 86.0; // mounting hole span X (centre-to-centre)
|
||||||
|
MH_SY = 58.0; // mounting hole span Y
|
||||||
|
M25_D = 2.7; // M2.5 clearance bore
|
||||||
|
M25_NUT_W = 5.0; // M2.5 hex nut across-flats
|
||||||
|
M25_NUT_H = 2.0; // M2.5 hex nut height
|
||||||
|
M25_HEAD_D = 5.0; // M2.5 SHCS head diameter
|
||||||
|
M25_HEAD_H = 2.5;
|
||||||
|
|
||||||
|
// Base plate
|
||||||
|
BASE_L = 120.0; // length along X (covers board + overhang for braces)
|
||||||
|
BASE_W = 50.0; // width along Y (rail mount footprint)
|
||||||
|
BASE_T = 6.0; // plate thickness
|
||||||
|
BOLT_PITCH = 40.0; // M5 rail bolt pitch (per rail, 2 rails at Y=0 & Y=BASE_W)
|
||||||
|
M3_D = 3.2;
|
||||||
|
M3_HEAD_D = 6.0;
|
||||||
|
M3_HEAD_H = 3.0;
|
||||||
|
|
||||||
|
// Standoff posts
|
||||||
|
POST_H = 12.0; // airflow gap + PCB seating (>= 10 mm clearance spec)
|
||||||
|
POST_OD = 8.0; // outer diameter
|
||||||
|
POST_BASE_D = 11.0; // flange diameter
|
||||||
|
POST_BASE_H = 3.0; // flange height
|
||||||
|
NUT_TRAP_H = M25_NUT_H + 0.3;
|
||||||
|
NUT_TRAP_W = M25_NUT_W + 0.4;
|
||||||
|
|
||||||
|
// Side braces
|
||||||
|
BRACE_T = 5.0; // brace thickness (X)
|
||||||
|
BRACE_H = POST_H + POST_BASE_H + BOARD_T + 4.0; // full height
|
||||||
|
BRACE_W = BASE_W; // same width as base
|
||||||
|
|
||||||
|
// Port-access cutouts (connector side -Y)
|
||||||
|
USB_CUT_W = 60.0; // wide cutout for USB-A stack + HDMI + DP
|
||||||
|
USB_CUT_H = 22.0;
|
||||||
|
GBE_CUT_W = 20.0; // GbE jack
|
||||||
|
GBE_CUT_H = 18.0;
|
||||||
|
|
||||||
|
// Duct shroud
|
||||||
|
DUCT_T = 3.0; // wall thickness
|
||||||
|
DUCT_FLANGE = 6.0; // side tab width for M3 attachment
|
||||||
|
FAN_W = 40.0; // standard 40 mm blower clearance cutout
|
||||||
|
FAN_H = 10.0; // duct outlet height
|
||||||
|
|
||||||
|
// Cable clip
|
||||||
|
CLIP_OD = 12.0;
|
||||||
|
CLIP_ID = 7.0;
|
||||||
|
CLIP_GAP = 7.5;
|
||||||
|
CLIP_W = 10.0;
|
||||||
|
SNAP_T = 1.8;
|
||||||
|
|
||||||
|
// ── Utilities ───────────────────────────────────────────────
|
||||||
|
module chamfer_cube(size, ch=1.0) {
|
||||||
|
hull() {
|
||||||
|
translate([ch, ch, 0]) cube([size[0]-2*ch, size[1]-2*ch, EPS]);
|
||||||
|
translate([0, 0, ch]) cube(size - [0, 0, ch]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module hex_pocket(af, depth) {
|
||||||
|
cylinder(d=af/cos(30), h=depth, $fn=6);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 1: tnut_base ───────────────────────────────────────
|
||||||
|
module tnut_base() {
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
chamfer_cube([BASE_L, BASE_W, BASE_T], ch=1.5);
|
||||||
|
|
||||||
|
// Raised mounting bosses for M3 brace attachment (4 corners)
|
||||||
|
for (x = [8, BASE_L-8])
|
||||||
|
for (y = [8, BASE_W-8])
|
||||||
|
translate([x, y, BASE_T])
|
||||||
|
cylinder(d=10, h=2.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
// T-nut pockets and M5 bolts — front rail (y = BASE_W/4)
|
||||||
|
for (x = [BASE_L/2 - BOLT_PITCH/2, BASE_L/2 + BOLT_PITCH/2]) {
|
||||||
|
translate([x, BASE_W/4, -EPS]) {
|
||||||
|
cylinder(d=M5_D, h=BASE_T + 2*EPS);
|
||||||
|
cylinder(d=M5_HEAD_D, h=M5_HEAD_H + EPS);
|
||||||
|
}
|
||||||
|
translate([x - TNUT_L/2, BASE_W/4 - TNUT_W/2, BASE_T - TNUT_H])
|
||||||
|
cube([TNUT_L, TNUT_W, TNUT_H + EPS]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// T-nut pockets and M5 bolts — rear rail (y = 3*BASE_W/4)
|
||||||
|
for (x = [BASE_L/2 - BOLT_PITCH/2, BASE_L/2 + BOLT_PITCH/2]) {
|
||||||
|
translate([x, 3*BASE_W/4, -EPS]) {
|
||||||
|
cylinder(d=M5_D, h=BASE_T + 2*EPS);
|
||||||
|
cylinder(d=M5_HEAD_D, h=M5_HEAD_H + EPS);
|
||||||
|
}
|
||||||
|
translate([x - TNUT_L/2, 3*BASE_W/4 - TNUT_W/2, BASE_T - TNUT_H])
|
||||||
|
cube([TNUT_L, TNUT_W, TNUT_H + EPS]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// M3 boss bolt holes (corner braces)
|
||||||
|
for (x = [8, BASE_L-8])
|
||||||
|
for (y = [8, BASE_W-8])
|
||||||
|
translate([x, y, -EPS])
|
||||||
|
cylinder(d=M3_D, h=BASE_T + 2.5 + 2*EPS);
|
||||||
|
|
||||||
|
// M3 boss counterbores (head from bottom)
|
||||||
|
for (x = [8, BASE_L-8])
|
||||||
|
for (y = [8, BASE_W-8])
|
||||||
|
translate([x, y, -EPS])
|
||||||
|
cylinder(d=M3_HEAD_D, h=M3_HEAD_H + EPS);
|
||||||
|
|
||||||
|
// Standoff post seating holes (board hole pattern, centred on plate)
|
||||||
|
bx0 = BASE_L/2 - MH_SX/2;
|
||||||
|
by0 = BASE_W/2 - MH_SY/2;
|
||||||
|
for (dx = [0, MH_SX])
|
||||||
|
for (dy = [0, MH_SY])
|
||||||
|
translate([bx0+dx, by0+dy, -EPS])
|
||||||
|
cylinder(d=POST_BASE_D + 0.4, h=BASE_T + 2*EPS);
|
||||||
|
|
||||||
|
// Weight relief grid (2 pockets)
|
||||||
|
translate([20, 12, -EPS]) cube([30, BASE_W-24, BASE_T/2]);
|
||||||
|
translate([BASE_L-50, 12, -EPS]) cube([30, BASE_W-24, BASE_T/2]);
|
||||||
|
|
||||||
|
// Cable pass-through slot
|
||||||
|
translate([BASE_L/2 - 8, BASE_W/2 - 3, -EPS])
|
||||||
|
cube([16, 6, BASE_T + 2*EPS]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 2: standoff_post ───────────────────────────────────
|
||||||
|
module standoff_post() {
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// Flange
|
||||||
|
cylinder(d=POST_BASE_D, h=POST_BASE_H);
|
||||||
|
// Post body
|
||||||
|
translate([0, 0, POST_BASE_H])
|
||||||
|
cylinder(d=POST_OD, h=POST_H);
|
||||||
|
}
|
||||||
|
|
||||||
|
// M2.5 through bore
|
||||||
|
translate([0, 0, -EPS])
|
||||||
|
cylinder(d=M25_D, h=POST_BASE_H + POST_H + 2*EPS);
|
||||||
|
|
||||||
|
// Captured hex nut trap (from top)
|
||||||
|
translate([0, 0, POST_BASE_H + POST_H - NUT_TRAP_H])
|
||||||
|
hex_pocket(NUT_TRAP_W, NUT_TRAP_H + EPS);
|
||||||
|
|
||||||
|
// Anti-rotation flat on nut pocket
|
||||||
|
translate([-M25_NUT_W/2 - 0.2, -POST_OD/2 - EPS,
|
||||||
|
POST_BASE_H + POST_H - NUT_TRAP_H])
|
||||||
|
cube([M25_NUT_W + 0.4, 2.0, NUT_TRAP_H + EPS]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 3: side_brace ──────────────────────────────────────
|
||||||
|
// Printed as +X face. Mirror for -X side.
|
||||||
|
module side_brace() {
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
chamfer_cube([BRACE_T, BRACE_W, BRACE_H], ch=1.0);
|
||||||
|
|
||||||
|
// Top lip to retain board edge
|
||||||
|
translate([0, 0, BRACE_H])
|
||||||
|
cube([BRACE_T + 8.0, BRACE_W, 2.5]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// M3 bolt holes at base (attach to tnut_base bosses)
|
||||||
|
for (y = [8, BRACE_W-8])
|
||||||
|
translate([-EPS, y, 4])
|
||||||
|
rotate([0, 90, 0])
|
||||||
|
cylinder(d=M3_D, h=BRACE_T + 2*EPS);
|
||||||
|
|
||||||
|
// M3 counterbore from outer face
|
||||||
|
for (y = [8, BRACE_W-8])
|
||||||
|
translate([-EPS, y, 4])
|
||||||
|
rotate([0, 90, 0])
|
||||||
|
cylinder(d=M3_HEAD_D, h=M3_HEAD_H + EPS);
|
||||||
|
|
||||||
|
// Port-access cutout — USB/HDMI/DP cluster (centred on brace face)
|
||||||
|
translate([-EPS, BRACE_W/2 - USB_CUT_W/2, POST_BASE_H + 2.0])
|
||||||
|
cube([BRACE_T + 2*EPS, USB_CUT_W, USB_CUT_H]);
|
||||||
|
|
||||||
|
// GbE cutout (offset toward +Y)
|
||||||
|
translate([-EPS, BRACE_W/2 + USB_CUT_W/2 - GBE_CUT_W - 2, POST_BASE_H + 2.0])
|
||||||
|
cube([BRACE_T + 2*EPS, GBE_CUT_W, GBE_CUT_H]);
|
||||||
|
|
||||||
|
// M3 duct attachment holes (top edge)
|
||||||
|
for (y = [BRACE_W/4, 3*BRACE_W/4])
|
||||||
|
translate([BRACE_T/2, y, BRACE_H - 2])
|
||||||
|
cylinder(d=M3_D, h=10);
|
||||||
|
|
||||||
|
// Ventilation slots (3 tall slots for airflow)
|
||||||
|
for (i = [0:2])
|
||||||
|
translate([-EPS,
|
||||||
|
(BRACE_W - 3*8 - 2*4) / 2 + i*(8+4),
|
||||||
|
POST_BASE_H + USB_CUT_H + 6])
|
||||||
|
cube([BRACE_T + 2*EPS, 8, BRACE_H - POST_BASE_H - USB_CUT_H - 10]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 4: duct_shroud ─────────────────────────────────────
|
||||||
|
// Top cap that channels fan exhaust away from board; optional print.
|
||||||
|
module duct_shroud() {
|
||||||
|
duct_l = BASE_L - 2*BRACE_T - 1.0; // span between inner brace faces
|
||||||
|
duct_w = BRACE_W;
|
||||||
|
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// Top plate
|
||||||
|
cube([duct_l, duct_w, DUCT_T]);
|
||||||
|
|
||||||
|
// Front wall (fan inlet side)
|
||||||
|
translate([0, 0, -FAN_H])
|
||||||
|
cube([DUCT_T, duct_w, FAN_H + DUCT_T]);
|
||||||
|
|
||||||
|
// Rear wall (exhaust side — open centre)
|
||||||
|
translate([duct_l - DUCT_T, 0, -FAN_H])
|
||||||
|
cube([DUCT_T, duct_w, FAN_H + DUCT_T]);
|
||||||
|
|
||||||
|
// Side flanges for M3 attachment
|
||||||
|
translate([-DUCT_FLANGE, 0, -FAN_H])
|
||||||
|
cube([DUCT_FLANGE, duct_w, FAN_H + DUCT_T]);
|
||||||
|
translate([duct_l, 0, -FAN_H])
|
||||||
|
cube([DUCT_FLANGE, duct_w, FAN_H + DUCT_T]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fan cutout on top plate (centred)
|
||||||
|
translate([duct_l/2 - FAN_W/2, duct_w/2 - FAN_W/2, -EPS])
|
||||||
|
cube([FAN_W, FAN_W, DUCT_T + 2*EPS]);
|
||||||
|
|
||||||
|
// Fan screw holes (40 mm fan, Ø3.2 at 32 mm BC)
|
||||||
|
for (dx = [-16, 16])
|
||||||
|
for (dy = [-16, 16])
|
||||||
|
translate([duct_l/2 + dx, duct_w/2 + dy, -EPS])
|
||||||
|
cylinder(d=M3_D, h=DUCT_T + 2*EPS);
|
||||||
|
|
||||||
|
// Exhaust slot on rear wall (full width minus corners)
|
||||||
|
translate([duct_l - DUCT_T - EPS, 4, -FAN_H + 2])
|
||||||
|
cube([DUCT_T + 2*EPS, duct_w - 8, FAN_H - 2]);
|
||||||
|
|
||||||
|
// M3 flange attachment holes
|
||||||
|
for (y = [duct_w/4, 3*duct_w/4]) {
|
||||||
|
translate([-DUCT_FLANGE - EPS, y, -FAN_H/2])
|
||||||
|
rotate([0, 90, 0])
|
||||||
|
cylinder(d=M3_D, h=DUCT_FLANGE + 2*EPS);
|
||||||
|
translate([duct_l + DUCT_T - EPS, y, -FAN_H/2])
|
||||||
|
rotate([0, 90, 0])
|
||||||
|
cylinder(d=M3_D, h=DUCT_FLANGE + 2*EPS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 5: cable_clip ──────────────────────────────────────
|
||||||
|
module cable_clip() {
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// Snap-wrap body
|
||||||
|
difference() {
|
||||||
|
cylinder(d=CLIP_OD + 2*SNAP_T, h=CLIP_W);
|
||||||
|
translate([0, 0, -EPS])
|
||||||
|
cylinder(d=CLIP_ID, h=CLIP_W + 2*EPS);
|
||||||
|
// Front gap
|
||||||
|
translate([-CLIP_GAP/2, 0, -EPS])
|
||||||
|
cube([CLIP_GAP, CLIP_OD, CLIP_W + 2*EPS]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mounting tab for brace edge
|
||||||
|
translate([CLIP_OD/2 + SNAP_T - EPS, -SNAP_T, 0])
|
||||||
|
cube([8, SNAP_T*2, CLIP_W]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tab screw hole
|
||||||
|
translate([CLIP_OD/2 + SNAP_T + 4, 0, CLIP_W/2])
|
||||||
|
rotate([90, 0, 0])
|
||||||
|
cylinder(d=M3_D, h=SNAP_T*2 + 2*EPS, center=true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Assembly ────────────────────────────────────────────────
|
||||||
|
module assembly() {
|
||||||
|
// Base plate
|
||||||
|
color("SteelBlue")
|
||||||
|
tnut_base();
|
||||||
|
|
||||||
|
// Standoff posts (board hole pattern)
|
||||||
|
bx0 = BASE_L/2 - MH_SX/2;
|
||||||
|
by0 = BASE_W/2 - MH_SY/2;
|
||||||
|
for (dx = [0, MH_SX])
|
||||||
|
for (dy = [0, MH_SY])
|
||||||
|
color("DodgerBlue")
|
||||||
|
translate([bx0+dx, by0+dy, BASE_T])
|
||||||
|
standoff_post();
|
||||||
|
|
||||||
|
// Side braces (left and right)
|
||||||
|
color("CornflowerBlue")
|
||||||
|
translate([0, 0, BASE_T])
|
||||||
|
side_brace();
|
||||||
|
color("CornflowerBlue")
|
||||||
|
translate([BASE_L, BRACE_W, BASE_T])
|
||||||
|
mirror([1, 0, 0])
|
||||||
|
mirror([0, 1, 0])
|
||||||
|
side_brace();
|
||||||
|
|
||||||
|
// Board silhouette (translucent, for clearance visualisation)
|
||||||
|
color("ForestGreen", 0.25)
|
||||||
|
translate([BASE_L/2 - BOARD_L/2, BASE_W/2 - BOARD_W/2,
|
||||||
|
BASE_T + POST_BASE_H + POST_H])
|
||||||
|
cube([BOARD_L, BOARD_W, BOARD_T]);
|
||||||
|
|
||||||
|
// Duct shroud (above board)
|
||||||
|
color("LightSteelBlue", 0.7)
|
||||||
|
translate([BRACE_T + 0.5, 0,
|
||||||
|
BASE_T + POST_BASE_H + POST_H + BOARD_T + 2.0])
|
||||||
|
duct_shroud();
|
||||||
|
|
||||||
|
// Cable clips (on brace edge, 2×)
|
||||||
|
for (y = [BRACE_W/3, 2*BRACE_W/3])
|
||||||
|
color("SlateGray")
|
||||||
|
translate([BASE_L + 2, y, BASE_T + BRACE_H/2 - CLIP_W/2])
|
||||||
|
rotate([0, 90, 0])
|
||||||
|
cable_clip();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Dispatch ────────────────────────────────────────────────
|
||||||
|
if (RENDER == "tnut_base") tnut_base();
|
||||||
|
else if (RENDER == "standoff_post") standoff_post();
|
||||||
|
else if (RENDER == "side_brace") side_brace();
|
||||||
|
else if (RENDER == "duct_shroud") duct_shroud();
|
||||||
|
else if (RENDER == "cable_clip") cable_clip();
|
||||||
|
else assembly();
|
||||||
@ -65,7 +65,7 @@ CLAMP_ALIGN_D = 4.1; // Ø4 pin
|
|||||||
// D-cut bore clearance
|
// D-cut bore clearance
|
||||||
DCUT_CL = 0.3;
|
DCUT_CL = 0.3;
|
||||||
|
|
||||||
// FC mount — MAMBA F722S 30.5 × 30.5 mm M3
|
// FC mount — ESP32-S3 BALANCE 30.5 × 30.5 mm M3
|
||||||
FC_PITCH = 30.5;
|
FC_PITCH = 30.5;
|
||||||
FC_HOLE_D = 3.2;
|
FC_HOLE_D = 3.2;
|
||||||
// FC is offset toward front of plate (away from stem)
|
// FC is offset toward front of plate (away from stem)
|
||||||
@ -202,7 +202,7 @@ module base_plate() {
|
|||||||
translate([STEM_FLANGE_BC/2, 0, -1])
|
translate([STEM_FLANGE_BC/2, 0, -1])
|
||||||
cylinder(d=M5, h=PLATE_THICK + 2);
|
cylinder(d=M5, h=PLATE_THICK + 2);
|
||||||
|
|
||||||
// ── FC mount (MAMBA F722S 30.5 × 30.5 M3) ────────────────────────
|
// ── FC mount (ESP32-S3 BALANCE 30.5 × 30.5 M3) ────────────────────────
|
||||||
for (x = [FC_X_OFFSET - FC_PITCH/2, FC_X_OFFSET + FC_PITCH/2])
|
for (x = [FC_X_OFFSET - FC_PITCH/2, FC_X_OFFSET + FC_PITCH/2])
|
||||||
for (y = [-FC_PITCH/2, FC_PITCH/2])
|
for (y = [-FC_PITCH/2, FC_PITCH/2])
|
||||||
translate([x, y, -1])
|
translate([x, y, -1])
|
||||||
|
|||||||
@ -11,7 +11,7 @@
|
|||||||
// • Ventilation slots — all 4 walls + lid
|
// • Ventilation slots — all 4 walls + lid
|
||||||
//
|
//
|
||||||
// Shared mounting patterns (swappable with SaltyLab):
|
// Shared mounting patterns (swappable with SaltyLab):
|
||||||
// FC : 30.5 × 30.5 mm M3 (MAMBA F722S / Pixhawk)
|
// FC : 30.5 × 30.5 mm M3 (ESP32-S3 BALANCE / Pixhawk)
|
||||||
// Jetson: 58 × 49 mm M3 (Orin NX / Nano Devkit carrier)
|
// Jetson: 58 × 49 mm M3 (Orin NX / Nano Devkit carrier)
|
||||||
//
|
//
|
||||||
// Coordinate: bay centred at origin; Z=0 = deck top face.
|
// Coordinate: bay centred at origin; Z=0 = deck top face.
|
||||||
|
|||||||
@ -1,76 +1,343 @@
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
// rplidar_mount.scad — RPLIDAR A1M8 Anti-Vibration Ring Rev A
|
// RPLIDAR A1 Mount Bracket — Issue #596
|
||||||
// Agent: sl-mechanical 2026-02-28
|
// Agent : sl-mechanical
|
||||||
// ============================================================
|
// Date : 2026-03-14
|
||||||
// Flat ring sits between platform and RPLIDAR A1M8.
|
// Part catalogue:
|
||||||
// Anti-vibration isolation via 4× M3 silicone grommets
|
// 1. tnut_base — 2020 T-slot rail interface plate with M5 T-nut captive pockets
|
||||||
// (same type as FC vibration mounts — Ø6 mm silicone, M3).
|
// 2. column — hollow elevation column, 120 mm tall, 3 stiffening ribs, cable bore
|
||||||
|
// 3. scan_platform — top plate with Ø40 mm BC M3 mounting pattern, vibration seats
|
||||||
|
// 4. vibe_ring — silicone FC-grommet isolation ring for scan_platform bolts
|
||||||
|
// 5. cable_guide — snap-on cable management clip for column body
|
||||||
//
|
//
|
||||||
// Bolt stack (bottom → top):
|
// BOM:
|
||||||
// M3×30 SHCS → platform (8 mm) → grommet (8 mm) →
|
// 2 × M5×10 BHCS + M5 T-nuts (tnut_base to rail)
|
||||||
// ring (4 mm) → RPLIDAR bottom (threaded M3, ~6 mm engagement)
|
// 4 × M3×8 SHCS (scan_platform to RPLIDAR A1)
|
||||||
|
// 4 × M3 silicone FC grommets Ø8.5 OD / Ø3.2 bore (anti-vibe)
|
||||||
|
// 4 × M3 hex nuts (captured in scan_platform)
|
||||||
//
|
//
|
||||||
// RENDER options:
|
// Print settings (PETG):
|
||||||
// "ring" print-ready flat ring (default)
|
// tnut_base / column / scan_platform : 5 perimeters, 40 % gyroid, no supports
|
||||||
// "assembly" ring in position on platform stub
|
// vibe_ring : 3 perimeters, 20 % gyroid, no supports
|
||||||
|
// cable_guide : 3 perimeters, 30 % gyroid, no supports
|
||||||
|
//
|
||||||
|
// Export commands:
|
||||||
|
// openscad -D 'RENDER="tnut_base"' -o tnut_base.stl rplidar_mount.scad
|
||||||
|
// openscad -D 'RENDER="column"' -o column.stl rplidar_mount.scad
|
||||||
|
// openscad -D 'RENDER="scan_platform"' -o scan_platform.stl rplidar_mount.scad
|
||||||
|
// openscad -D 'RENDER="vibe_ring"' -o vibe_ring.stl rplidar_mount.scad
|
||||||
|
// openscad -D 'RENDER="cable_guide"' -o cable_guide.stl rplidar_mount.scad
|
||||||
|
// openscad -D 'RENDER="assembly"' -o assembly.png rplidar_mount.scad
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
RENDER = "ring";
|
// ── Render selector ─────────────────────────────────────────
|
||||||
|
RENDER = "assembly"; // tnut_base | column | scan_platform | vibe_ring | cable_guide | assembly
|
||||||
// ── RPLIDAR A1M8 ─────────────────────────────────────────────
|
|
||||||
RPL_BODY_D = 70.0; // body diameter
|
|
||||||
RPL_BC = 58.0; // M3 mounting bolt circle
|
|
||||||
|
|
||||||
// ── Mount ring ───────────────────────────────────────────────
|
|
||||||
RING_OD = 82.0; // outer diameter (RPL_BODY_D + 12 mm)
|
|
||||||
RING_ID = 30.0; // inner cutout (cable / airflow)
|
|
||||||
RING_H = 4.0; // ring thickness
|
|
||||||
|
|
||||||
BOLT_D = 3.3; // M3 clearance through-hole
|
|
||||||
GROMMET_D = 7.0; // silicone grommet OD (seat recess on bottom)
|
|
||||||
GROMMET_H = 1.0; // seating recess depth
|
|
||||||
|
|
||||||
|
// ── Global constants ────────────────────────────────────────
|
||||||
$fn = 64;
|
$fn = 64;
|
||||||
e = 0.01;
|
EPS = 0.01;
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
// 2020 rail
|
||||||
module rplidar_ring() {
|
RAIL_W = 20.0; // extrusion cross-section
|
||||||
|
RAIL_H = 20.0;
|
||||||
|
SLOT_NECK_H = 3.2; // T-slot opening width
|
||||||
|
TNUT_W = 9.8; // M5 T-nut width
|
||||||
|
TNUT_H = 5.5; // T-nut height (depth into slot)
|
||||||
|
TNUT_L = 12.0; // T-nut body length
|
||||||
|
M5_D = 5.2; // M5 clearance bore
|
||||||
|
M5_HEAD_D = 9.5; // M5 BHCS head diameter
|
||||||
|
M5_HEAD_H = 4.0; // M5 BHCS head height
|
||||||
|
|
||||||
|
// Base plate
|
||||||
|
BASE_L = 60.0; // length along rail axis
|
||||||
|
BASE_W = 30.0; // width across rail
|
||||||
|
BASE_T = 8.0; // plate thickness
|
||||||
|
BOLT_PITCH = 40.0; // M5 bolt pitch along rail (centre-to-centre)
|
||||||
|
|
||||||
|
// Elevation column
|
||||||
|
COL_OD = 25.0; // column outer diameter
|
||||||
|
COL_ID = 17.0; // inner bore (cable routing)
|
||||||
|
ELEV_H = 120.0; // scan plane above rail top face
|
||||||
|
COL_WALL = (COL_OD - COL_ID) / 2;
|
||||||
|
RIB_W = 3.0; // stiffening rib width
|
||||||
|
RIB_H = 3.5; // rib radial height
|
||||||
|
CABLE_SLOT_W = 8.0; // cable entry slot width
|
||||||
|
CABLE_SLOT_H = 5.0; // cable entry slot height
|
||||||
|
|
||||||
|
// Scan platform
|
||||||
|
PLAT_D = 60.0; // platform disc diameter (clears RPLIDAR body Ø100 mm well)
|
||||||
|
PLAT_T = 6.0; // platform thickness
|
||||||
|
RPL_BC_D = 40.0; // RPLIDAR M3 bolt circle diameter (4 bolts at 45 °)
|
||||||
|
RPL_BORE_D = 36.0; // central pass-through for scan motor cable
|
||||||
|
M3_D = 3.2; // M3 clearance bore
|
||||||
|
M3_NUT_W = 5.5; // M3 hex nut across-flats
|
||||||
|
M3_NUT_H = 2.4; // M3 hex nut height
|
||||||
|
GROM_OD = 8.5; // FC silicone grommet OD
|
||||||
|
GROM_ID = 3.2; // grommet bore
|
||||||
|
GROM_H = 3.0; // grommet seat depth
|
||||||
|
CONN_SLOT_W = 12.0; // connector side-exit slot width
|
||||||
|
CONN_SLOT_H = 5.0; // connector slot height
|
||||||
|
|
||||||
|
// Vibe ring
|
||||||
|
VRING_OD = GROM_OD + 1.6; // printed retainer OD
|
||||||
|
VRING_ID = GROM_ID + 0.3; // pass-through with grommet seated
|
||||||
|
VRING_T = 2.0; // ring flange thickness
|
||||||
|
|
||||||
|
// Cable guide clip
|
||||||
|
CLIP_W = 14.0;
|
||||||
|
CLIP_T = 3.5;
|
||||||
|
CLIP_GAP = COL_OD + 0.4; // snap-fit gap (slight interference)
|
||||||
|
SNAP_T = 1.8;
|
||||||
|
CABLE_CH_W = 8.0;
|
||||||
|
CABLE_CH_H = 5.0;
|
||||||
|
|
||||||
|
// ── Utility modules ─────────────────────────────────────────
|
||||||
|
module chamfer_cube(size, ch=1.0) {
|
||||||
|
// simple chamfered box (bottom edge only for printability)
|
||||||
|
hull() {
|
||||||
|
translate([ch, ch, 0])
|
||||||
|
cube([size[0]-2*ch, size[1]-2*ch, EPS]);
|
||||||
|
translate([0, 0, ch])
|
||||||
|
cube(size - [0, 0, ch]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module hex_pocket(af, depth) {
|
||||||
|
// hex nut pocket (flat-to-flat af)
|
||||||
|
cylinder(d = af / cos(30), h = depth, $fn = 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 1: tnut_base ───────────────────────────────────────
|
||||||
|
module tnut_base() {
|
||||||
difference() {
|
difference() {
|
||||||
cylinder(d = RING_OD, h = RING_H);
|
// Body
|
||||||
|
union() {
|
||||||
// Central cutout
|
chamfer_cube([BASE_L, BASE_W, BASE_T], ch=1.5);
|
||||||
translate([0, 0, -e])
|
// Column socket boss centred on plate top face
|
||||||
cylinder(d = RING_ID, h = RING_H + 2*e);
|
translate([BASE_L/2, BASE_W/2, BASE_T])
|
||||||
|
cylinder(d=COL_OD + 4.0, h=8.0);
|
||||||
// 4× M3 clearance holes on bolt circle
|
|
||||||
for (a = [45, 135, 225, 315]) {
|
|
||||||
translate([RPL_BC/2 * cos(a), RPL_BC/2 * sin(a), -e])
|
|
||||||
cylinder(d = BOLT_D, h = RING_H + 2*e);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Grommet seating recesses — bottom face
|
// M5 bolt holes (counterbored for BHCS heads from underneath)
|
||||||
for (a = [45, 135, 225, 315]) {
|
for (x = [BASE_L/2 - BOLT_PITCH/2, BASE_L/2 + BOLT_PITCH/2])
|
||||||
translate([RPL_BC/2 * cos(a), RPL_BC/2 * sin(a), -e])
|
translate([x, BASE_W/2, -EPS]) {
|
||||||
cylinder(d = GROMMET_D, h = GROMMET_H + e);
|
cylinder(d=M5_D, h=BASE_T + 8.0 + 2*EPS);
|
||||||
|
// counterbore from bottom
|
||||||
|
cylinder(d=M5_HEAD_D, h=M5_HEAD_H + EPS);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// T-nut captive pockets (accessible from bottom)
|
||||||
|
for (x = [BASE_L/2 - BOLT_PITCH/2, BASE_L/2 + BOLT_PITCH/2])
|
||||||
|
translate([x - TNUT_L/2, BASE_W/2 - TNUT_W/2, BASE_T - TNUT_H])
|
||||||
|
cube([TNUT_L, TNUT_W, TNUT_H + EPS]);
|
||||||
|
|
||||||
|
// Column bore into boss
|
||||||
|
translate([BASE_L/2, BASE_W/2, BASE_T - EPS])
|
||||||
|
cylinder(d=COL_OD + 0.3, h=8.0 + 2*EPS);
|
||||||
|
|
||||||
|
// Cable exit slot through base (offset 5 mm from column centre)
|
||||||
|
translate([BASE_L/2 - CABLE_SLOT_W/2, BASE_W/2 + COL_OD/4, -EPS])
|
||||||
|
cube([CABLE_SLOT_W, CABLE_SLOT_H, BASE_T + 8.0 + 2*EPS]);
|
||||||
|
|
||||||
|
// Weight relief pockets on underside
|
||||||
|
for (x = [BASE_L/2 - BOLT_PITCH/2 + 10, BASE_L/2 + BOLT_PITCH/2 - 10])
|
||||||
|
for (y = [7, BASE_W - 7])
|
||||||
|
translate([x - 5, y - 5, -EPS])
|
||||||
|
cube([10, 10, BASE_T/2]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
// ── Part 2: column ──────────────────────────────────────────
|
||||||
// Render selector
|
module column() {
|
||||||
// ─────────────────────────────────────────────────────────────
|
// Actual column height: ELEV_H minus base boss engagement (8 mm) and platform seating (6 mm)
|
||||||
if (RENDER == "ring") {
|
col_h = ELEV_H - 8.0 - PLAT_T;
|
||||||
rplidar_ring();
|
|
||||||
|
|
||||||
} else if (RENDER == "assembly") {
|
|
||||||
// Platform stub
|
|
||||||
color("Silver", 0.5)
|
|
||||||
difference() {
|
difference() {
|
||||||
cylinder(d = 90, h = 8);
|
union() {
|
||||||
translate([0, 0, -e]) cylinder(d = 25.4, h = 8 + 2*e);
|
// Hollow tube
|
||||||
|
cylinder(d=COL_OD, h=col_h);
|
||||||
|
|
||||||
|
// Three 120°-spaced stiffening ribs along full height
|
||||||
|
for (a = [0, 120, 240])
|
||||||
|
rotate([0, 0, a])
|
||||||
|
translate([COL_OD/2 - EPS, -RIB_W/2, 0])
|
||||||
|
cube([RIB_H, RIB_W, col_h]);
|
||||||
|
|
||||||
|
// Bottom spigot (fits into base boss bore)
|
||||||
|
translate([0, 0, -6.0])
|
||||||
|
cylinder(d=COL_OD - 0.4, h=6.0 + EPS);
|
||||||
|
|
||||||
|
// Top spigot (seats into scan_platform recess)
|
||||||
|
translate([0, 0, col_h - EPS])
|
||||||
|
cylinder(d=COL_OD - 0.4, h=6.0);
|
||||||
}
|
}
|
||||||
// Ring floating 8 mm above (grommet gap)
|
|
||||||
color("SkyBlue", 0.9)
|
// Inner cable bore
|
||||||
translate([0, 0, 8 + 8])
|
translate([0, 0, -6.0 - EPS])
|
||||||
rplidar_ring();
|
cylinder(d=COL_ID, h=col_h + 12.0 + 2*EPS);
|
||||||
|
|
||||||
|
// Cable entry slot at bottom (aligns with base slot)
|
||||||
|
translate([-CABLE_SLOT_W/2, -COL_OD/2 - EPS, 2.0])
|
||||||
|
cube([CABLE_SLOT_W, CABLE_SLOT_H + EPS, CABLE_SLOT_H]);
|
||||||
|
|
||||||
|
// Cable exit slot at top (90° rotated for tidy routing)
|
||||||
|
rotate([0, 0, 90])
|
||||||
|
translate([-CABLE_SLOT_W/2, -COL_OD/2 - EPS, col_h - CABLE_SLOT_H - 4.0])
|
||||||
|
cube([CABLE_SLOT_W, CABLE_SLOT_H + EPS, CABLE_SLOT_H]);
|
||||||
|
|
||||||
|
// Cable clip snap groove (at mid-height)
|
||||||
|
translate([0, 0, col_h / 2])
|
||||||
|
difference() {
|
||||||
|
cylinder(d=COL_OD + 2*RIB_H + 0.8, h=4.0, center=true);
|
||||||
|
cylinder(d=COL_OD - 0.2, h=4.0 + 2*EPS, center=true);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 3: scan_platform ───────────────────────────────────
|
||||||
|
module scan_platform() {
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// Main disc
|
||||||
|
cylinder(d=PLAT_D, h=PLAT_T);
|
||||||
|
|
||||||
|
// Rim lip for stiffness
|
||||||
|
translate([0, 0, PLAT_T])
|
||||||
|
difference() {
|
||||||
|
cylinder(d=PLAT_D, h=2.0);
|
||||||
|
cylinder(d=PLAT_D - 4.0, h=2.0 + EPS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Central cable pass-through
|
||||||
|
translate([0, 0, -EPS])
|
||||||
|
cylinder(d=RPL_BORE_D, h=PLAT_T + 4.0);
|
||||||
|
|
||||||
|
// Column spigot socket (bottom recess)
|
||||||
|
translate([0, 0, -EPS])
|
||||||
|
cylinder(d=COL_OD - 0.4 + 0.4, h=6.0);
|
||||||
|
|
||||||
|
// RPLIDAR M3 mounting holes — 4× on Ø40 BC at 45°/135°/225°/315°
|
||||||
|
for (a = [45, 135, 225, 315])
|
||||||
|
rotate([0, 0, a])
|
||||||
|
translate([RPL_BC_D/2, 0, -EPS]) {
|
||||||
|
// Through bore
|
||||||
|
cylinder(d=M3_D, h=PLAT_T + 2*EPS);
|
||||||
|
// Grommet seat (countersunk from top)
|
||||||
|
translate([0, 0, PLAT_T - GROM_H])
|
||||||
|
cylinder(d=GROM_OD + 0.3, h=GROM_H + EPS);
|
||||||
|
// Captured M3 hex nut pocket (from bottom)
|
||||||
|
translate([0, 0, 1.5])
|
||||||
|
hex_pocket(M3_NUT_W + 0.3, M3_NUT_H + 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connector side-exit slots (2× opposing, at 0° and 180°)
|
||||||
|
for (a = [0, 180])
|
||||||
|
rotate([0, 0, a])
|
||||||
|
translate([-CONN_SLOT_W/2, PLAT_D/2 - CONN_SLOT_H, -EPS])
|
||||||
|
cube([CONN_SLOT_W, CONN_SLOT_H + EPS, PLAT_T + 2*EPS]);
|
||||||
|
|
||||||
|
// Weight relief pockets (2× lateral)
|
||||||
|
for (a = [90, 270])
|
||||||
|
rotate([0, 0, a])
|
||||||
|
translate([-10, 15, 1.5])
|
||||||
|
cube([20, 8, PLAT_T - 3.0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 4: vibe_ring ───────────────────────────────────────
|
||||||
|
// Printed silicone-grommet retainer ring — press-fits over M3 bolt with grommet seated
|
||||||
|
module vibe_ring() {
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
cylinder(d=VRING_OD, h=VRING_T + GROM_H);
|
||||||
|
// Flange
|
||||||
|
cylinder(d=VRING_OD + 2.0, h=VRING_T);
|
||||||
|
}
|
||||||
|
// Bore
|
||||||
|
translate([0, 0, -EPS])
|
||||||
|
cylinder(d=VRING_ID, h=VRING_T + GROM_H + 2*EPS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Part 5: cable_guide ─────────────────────────────────────
|
||||||
|
// Snap-on cable clip for column mid-section
|
||||||
|
module cable_guide() {
|
||||||
|
arm_t = SNAP_T;
|
||||||
|
gap = CLIP_GAP;
|
||||||
|
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// Saddle body (U-shape wrapping column)
|
||||||
|
difference() {
|
||||||
|
cylinder(d=gap + 2*CLIP_T, h=CLIP_W);
|
||||||
|
translate([0, 0, -EPS])
|
||||||
|
cylinder(d=gap, h=CLIP_W + 2*EPS);
|
||||||
|
// Open front slot for snap insertion
|
||||||
|
translate([-gap/2, 0, -EPS])
|
||||||
|
cube([gap, gap/2 + CLIP_T + EPS, CLIP_W + 2*EPS]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snap arms
|
||||||
|
for (s = [-1, 1])
|
||||||
|
translate([s*(gap/2 - arm_t), 0, 0])
|
||||||
|
mirror([s < 0 ? 1 : 0, 0, 0])
|
||||||
|
translate([0, -arm_t/2, 0])
|
||||||
|
cube([arm_t + 1.5, arm_t, CLIP_W]);
|
||||||
|
|
||||||
|
// Cable channel bracket (side-mounted)
|
||||||
|
translate([gap/2 + CLIP_T, -(CABLE_CH_W/2 + CLIP_T), 0])
|
||||||
|
cube([CLIP_T + CABLE_CH_H, CABLE_CH_W + 2*CLIP_T, CLIP_W]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cable channel cutout
|
||||||
|
translate([gap/2 + CLIP_T + CLIP_T - EPS, -CABLE_CH_W/2, -EPS])
|
||||||
|
cube([CABLE_CH_H + EPS, CABLE_CH_W, CLIP_W + 2*EPS]);
|
||||||
|
|
||||||
|
// Snap tip undercut (both arms)
|
||||||
|
for (s = [-1, 1])
|
||||||
|
translate([s*(gap/2 + CLIP_T + 1.0), -arm_t, -EPS])
|
||||||
|
rotate([0, 0, s*30])
|
||||||
|
cube([2, arm_t*2, CLIP_W + 2*EPS]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Assembly / render dispatch ───────────────────────────────
|
||||||
|
module assembly() {
|
||||||
|
// tnut_base at origin
|
||||||
|
color("SteelBlue")
|
||||||
|
tnut_base();
|
||||||
|
|
||||||
|
// column rising from base boss
|
||||||
|
color("DodgerBlue")
|
||||||
|
translate([BASE_L/2, BASE_W/2, BASE_T + 8.0 - 6.0])
|
||||||
|
column();
|
||||||
|
|
||||||
|
// scan_platform at top of column
|
||||||
|
col_h_actual = ELEV_H - 8.0 - PLAT_T;
|
||||||
|
color("CornflowerBlue")
|
||||||
|
translate([BASE_L/2, BASE_W/2, BASE_T + 8.0 - 6.0 + col_h_actual + 6.0 - EPS])
|
||||||
|
scan_platform();
|
||||||
|
|
||||||
|
// vibe rings (4×) seated in platform holes
|
||||||
|
for (a = [45, 135, 225, 315])
|
||||||
|
color("Gray", 0.7)
|
||||||
|
translate([BASE_L/2, BASE_W/2,
|
||||||
|
BASE_T + 8.0 - 6.0 + col_h_actual + 6.0 + PLAT_T - GROM_H])
|
||||||
|
rotate([0, 0, a])
|
||||||
|
translate([RPL_BC_D/2, 0, 0])
|
||||||
|
vibe_ring();
|
||||||
|
|
||||||
|
// cable_guide clipped at column mid-height
|
||||||
|
color("LightSteelBlue")
|
||||||
|
translate([BASE_L/2, BASE_W/2,
|
||||||
|
BASE_T + 8.0 - 6.0 + (ELEV_H - 8.0 - PLAT_T)/2 - CLIP_W/2])
|
||||||
|
cable_guide();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Dispatch ────────────────────────────────────────────────
|
||||||
|
if (RENDER == "tnut_base") tnut_base();
|
||||||
|
else if (RENDER == "column") column();
|
||||||
|
else if (RENDER == "scan_platform") scan_platform();
|
||||||
|
else if (RENDER == "vibe_ring") vibe_ring();
|
||||||
|
else if (RENDER == "cable_guide") cable_guide();
|
||||||
|
else assembly();
|
||||||
|
|||||||
@ -17,7 +17,7 @@
|
|||||||
// • Weight target: <2 kg frame (excl. motors/electronics)
|
// • Weight target: <2 kg frame (excl. motors/electronics)
|
||||||
//
|
//
|
||||||
// Shared SaltyLab patterns (swappable electronics):
|
// Shared SaltyLab patterns (swappable electronics):
|
||||||
// FC : 30.5 × 30.5 mm M3 (MAMBA F722S / Pixhawk)
|
// FC : 30.5 × 30.5 mm M3 (ESP32-S3 BALANCE / Pixhawk)
|
||||||
// Jetson: 58 × 49 mm M3 (Orin NX / Nano carrier board)
|
// Jetson: 58 × 49 mm M3 (Orin NX / Nano carrier board)
|
||||||
// Stem : Ø25 mm bore (sensor head unchanged)
|
// Stem : Ø25 mm bore (sensor head unchanged)
|
||||||
//
|
//
|
||||||
@ -87,7 +87,7 @@ STEM_COLLAR_OD = 50.0;
|
|||||||
STEM_COLLAR_H = 20.0; // raised boss height above deck top
|
STEM_COLLAR_H = 20.0; // raised boss height above deck top
|
||||||
STEM_FLANGE_BC = 40.0; // 4× M4 bolt circle for stem adapter
|
STEM_FLANGE_BC = 40.0; // 4× M4 bolt circle for stem adapter
|
||||||
|
|
||||||
// ── FC mount — MAMBA F722S / Pixhawk (30.5 × 30.5 mm M3) ────────────────────
|
// ── FC mount — ESP32-S3 BALANCE / Pixhawk (30.5 × 30.5 mm M3) ────────────────────
|
||||||
// Shared with SaltyLab — swappable electronics
|
// Shared with SaltyLab — swappable electronics
|
||||||
FC_PITCH = 30.5;
|
FC_PITCH = 30.5;
|
||||||
FC_HOLE_D = 3.2;
|
FC_HOLE_D = 3.2;
|
||||||
|
|||||||
@ -1,275 +1,341 @@
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
// uwb_anchor_mount.scad — Stem-Mounted UWB Anchor Rev A
|
// uwb_anchor_mount.scad — Wall/Ceiling UWB Anchor Mount Bracket
|
||||||
// Agent: sl-mechanical 2026-03-01
|
// Issue: #564 Agent: sl-mechanical Date: 2026-03-14
|
||||||
// Closes issues #57, #62
|
// (supersedes Rev A stem-collar mount — see git history)
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// Clamp-on bracket for 2× MaUWB ESP32-S3 anchor modules on
|
|
||||||
// SaltyBot 25 mm OD vertical stem.
|
|
||||||
// Anchors spaced ANCHOR_SPACING = 250 mm apart.
|
|
||||||
//
|
//
|
||||||
// Features:
|
// Parametric wall or ceiling mount bracket for ESP32 UWB Pro anchor.
|
||||||
// • Split D-collar with M4 clamping bolts + M4 set screw
|
// Designed for fixed-infrastructure deployment: anchors screw into
|
||||||
// • Anti-rotation flat tab that keys against a small pin
|
// wall or ceiling drywall/timber with standard M4 or #6 wood screws,
|
||||||
// OR printed key tab that registers on the stem flat (if stem
|
// at a user-defined tilt angle so the UWB antenna faces the desired
|
||||||
// has a ground flat) — see ANTI_ROT_MODE parameter
|
// coverage zone.
|
||||||
// • Module bracket: faces outward, tilted 10° from vertical
|
|
||||||
// so antenna clears stem and faces horizon
|
|
||||||
// • USB cable channel (power from Orin via USB-A) on collar
|
|
||||||
// • Tool-free capture: M4 thumbscrews (slot-head, hand-tighten)
|
|
||||||
// • UWB antenna area: NO material within 10 mm of PCB top face
|
|
||||||
//
|
//
|
||||||
// Components per mount:
|
// Architecture:
|
||||||
// 2× collar_half print in PLA/PETG, flat-face-down
|
// Wall base -> flat backplate with 2x screw holes (wall or ceiling)
|
||||||
// 1× module_bracket print in PLA/PETG, flat-face-down
|
// Tilt knuckle -> single-axis articulating joint; 15deg detent steps
|
||||||
|
// locked with M3 nyloc bolt; range 0-90deg
|
||||||
|
// Anchor cradle-> U-cradle holding ESP32 UWB Pro PCB on M2.5 standoffs
|
||||||
|
// USB-C channel-> routed groove on tilt arm + exit slot in cradle back wall
|
||||||
|
// Label slot -> rear window slot for printed anchor-ID card strip
|
||||||
|
//
|
||||||
|
// Part catalogue:
|
||||||
|
// Part 1 -- wall_base() Backplate + 2-ear pivot block + detent arc
|
||||||
|
// Part 2 -- tilt_arm() Pivoting arm with knuckle + cradle stub
|
||||||
|
// Part 3 -- anchor_cradle() PCB cradle, standoffs, USB-C slot, label window
|
||||||
|
// Part 4 -- cable_clip() Snap-on USB-C cable guide for tilt arm
|
||||||
|
// Part 5 -- assembly_preview()
|
||||||
|
//
|
||||||
|
// Hardware BOM:
|
||||||
|
// 2x M4 x 30mm wood screws (or #6 drywall screws) wall fasteners
|
||||||
|
// 1x M3 x 20mm SHCS + M3 nyloc nut tilt pivot bolt
|
||||||
|
// 4x M2.5 x 8mm SHCS PCB-to-cradle
|
||||||
|
// 4x M2.5 hex nuts captured in standoffs
|
||||||
|
// 1x USB-C cable anchor power
|
||||||
|
//
|
||||||
|
// ESP32 UWB Pro interface (verify with calipers):
|
||||||
|
// PCB size : UWB_L x UWB_W x UWB_H (55 x 28 x 10 mm default)
|
||||||
|
// Mounting holes : M2.5, 4x corners on UWB_HOLE_X x UWB_HOLE_Y pattern
|
||||||
|
// USB-C port : centred on short edge, UWB_USBC_W x UWB_USBC_H
|
||||||
|
// Antenna area : top face rear half -- 10mm keep-out of bracket material
|
||||||
|
//
|
||||||
|
// Tilt angles (15deg detent steps, set TILT_DEG before export):
|
||||||
|
// 0deg -> horizontal face-up (ceiling, antenna faces down)
|
||||||
|
// 30deg -> 30deg downward tilt (wall near ceiling) [default]
|
||||||
|
// 45deg -> diagonal (wall mid-height)
|
||||||
|
// 90deg -> vertical face-out (wall, antenna faces forward)
|
||||||
//
|
//
|
||||||
// RENDER options:
|
// RENDER options:
|
||||||
// "assembly" single mount assembled (default)
|
// "assembly" full assembly at TILT_DEG (default)
|
||||||
// "collar_front" front collar half for slicing (×2 per mount × 2 mounts = 4)
|
// "wall_base_stl" Part 1
|
||||||
// "collar_rear" rear collar half
|
// "tilt_arm_stl" Part 2
|
||||||
// "bracket" module bracket (×2 mounts)
|
// "anchor_cradle_stl" Part 3
|
||||||
// "pair" both mounts on 350 mm stem section
|
// "cable_clip_stl" Part 4
|
||||||
|
//
|
||||||
|
// Export commands:
|
||||||
|
// openscad uwb_anchor_mount.scad -D 'RENDER="wall_base_stl"' -o uwb_wall_base.stl
|
||||||
|
// openscad uwb_anchor_mount.scad -D 'RENDER="tilt_arm_stl"' -o uwb_tilt_arm.stl
|
||||||
|
// openscad uwb_anchor_mount.scad -D 'RENDER="anchor_cradle_stl"' -o uwb_anchor_cradle.stl
|
||||||
|
// openscad uwb_anchor_mount.scad -D 'RENDER="cable_clip_stl"' -o uwb_cable_clip.stl
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
RENDER = "assembly";
|
|
||||||
|
|
||||||
// ── ⚠ Verify with calipers ───────────────────────────────────
|
|
||||||
MAWB_L = 50.0; // PCB length
|
|
||||||
MAWB_W = 25.0; // PCB width
|
|
||||||
MAWB_H = 10.0; // PCB + components
|
|
||||||
MAWB_HOLE_X = 43.0; // M2 mounting hole X span
|
|
||||||
MAWB_HOLE_Y = 20.0; // M2 mounting hole Y span
|
|
||||||
M2_D = 2.2; // M2 clearance
|
|
||||||
|
|
||||||
// ── Stem ─────────────────────────────────────────────────────
|
|
||||||
STEM_OD = 25.0;
|
|
||||||
STEM_BORE = 25.4; // +0.4 clearance
|
|
||||||
WALL = 2.0; // wall thickness (used in thumbscrew recess)
|
|
||||||
|
|
||||||
// ── Collar ───────────────────────────────────────────────────
|
|
||||||
COL_OD = 52.0;
|
|
||||||
COL_H = 30.0; // taller than sensor-head collar for rigidity
|
|
||||||
COL_BOLT_X = 19.0; // M4 bolt CL from stem axis
|
|
||||||
COL_BOLT_D = 4.5; // M4 clearance
|
|
||||||
THUMB_HEAD_D= 8.0; // M4 thumbscrew head OD (slot for access)
|
|
||||||
COL_NUT_W = 7.0; // M4 hex nut A/F
|
|
||||||
COL_NUT_H = 3.4;
|
|
||||||
|
|
||||||
// Anti-rotation flat tab: a 3 mm wall tab that protrudes radially
|
|
||||||
// and bears against the bracket arm, preventing axial rotation
|
|
||||||
// without needing a stem flat.
|
|
||||||
ANTI_ROT_T = 3.0; // tab thickness (radial)
|
|
||||||
ANTI_ROT_W = 8.0; // tab width (tangential)
|
|
||||||
ANTI_ROT_Z = 4.0; // distance from collar base
|
|
||||||
|
|
||||||
// USB cable channel: groove on collar outer surface, runs Z direction
|
|
||||||
// Cable routes from anchor module down to base
|
|
||||||
USB_CHAN_W = 9.0; // channel width (fits USB-A cable Ø6 mm)
|
|
||||||
USB_CHAN_D = 5.0; // channel depth
|
|
||||||
|
|
||||||
// ── Module bracket ───────────────────────────────────────────
|
|
||||||
ARM_L = 20.0; // arm length from collar OD to bracket face
|
|
||||||
ARM_W = MAWB_W + 6.0; // bracket width (Y, includes side walls)
|
|
||||||
ARM_H = 6.0; // arm thickness (Z)
|
|
||||||
BRKT_TILT = 10.0; // tilt outward from vertical (antenna faces horizon)
|
|
||||||
|
|
||||||
BRKT_BACK_T = 3.0; // bracket back wall (module sits against this)
|
|
||||||
BRKT_SIDE_T = 2.0; // bracket side walls
|
|
||||||
|
|
||||||
M2_STNDFF = 3.0; // M2 standoff height
|
|
||||||
M2_STNDFF_OD= 4.5;
|
|
||||||
|
|
||||||
// USB port access notch in bracket side wall (8×5 mm)
|
|
||||||
USB_NOTCH_W = 10.0;
|
|
||||||
USB_NOTCH_H = 7.0;
|
|
||||||
|
|
||||||
// ── Spacing ───────────────────────────────────────────────────
|
|
||||||
ANCHOR_SPACING = 250.0; // centre-to-centre Z separation
|
|
||||||
|
|
||||||
$fn = 64;
|
$fn = 64;
|
||||||
e = 0.01;
|
e = 0.01;
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
// -- Tilt angle (override per anchor, 0-90deg, 15deg steps) ------------------
|
||||||
// collar_half(side)
|
TILT_DEG = 30;
|
||||||
// split at Y=0 plane. Bracket arm on front (+Y) half.
|
|
||||||
// Print flat-face-down.
|
// -- ESP32 UWB Pro PCB dimensions (verify with calipers) ---------------------
|
||||||
// ─────────────────────────────────────────────────────────────
|
UWB_L = 55.0;
|
||||||
module collar_half(side = "front") {
|
UWB_W = 28.0;
|
||||||
y_front = (side == "front");
|
UWB_H = 10.0;
|
||||||
|
UWB_HOLE_X = 47.5;
|
||||||
|
UWB_HOLE_Y = 21.0;
|
||||||
|
UWB_USBC_W = 9.5;
|
||||||
|
UWB_USBC_H = 4.0;
|
||||||
|
UWB_ANTENNA_L = 20.0;
|
||||||
|
|
||||||
|
// -- Wall base geometry -------------------------------------------------------
|
||||||
|
BASE_W = 60.0;
|
||||||
|
BASE_H = 50.0;
|
||||||
|
BASE_T = 5.0;
|
||||||
|
BASE_SCREW_D = 4.5;
|
||||||
|
BASE_SCREW_HD = 8.5;
|
||||||
|
BASE_SCREW_HH = 3.5;
|
||||||
|
BASE_SCREW_SPC = 35.0;
|
||||||
|
KNUCKLE_T = BASE_T + 4.0;
|
||||||
|
|
||||||
|
// -- Tilt arm geometry --------------------------------------------------------
|
||||||
|
ARM_W = 12.0;
|
||||||
|
ARM_T = 5.0;
|
||||||
|
ARM_L = 35.0;
|
||||||
|
PIVOT_D = 3.3;
|
||||||
|
PIVOT_NUT_AF = 5.5;
|
||||||
|
PIVOT_NUT_H = 2.4;
|
||||||
|
DETENT_D = 3.2;
|
||||||
|
DETENT_R = 8.0;
|
||||||
|
|
||||||
|
// -- Anchor cradle geometry ---------------------------------------------------
|
||||||
|
CRADLE_WALL_T = 3.5;
|
||||||
|
CRADLE_BACK_T = 4.0;
|
||||||
|
CRADLE_FLOOR_T = 3.0;
|
||||||
|
CRADLE_LIP_H = 4.0;
|
||||||
|
CRADLE_LIP_T = 2.5;
|
||||||
|
STANDOFF_H = 3.0;
|
||||||
|
STANDOFF_OD = 5.5;
|
||||||
|
LABEL_W = UWB_L - 4.0;
|
||||||
|
LABEL_H = UWB_W * 0.55;
|
||||||
|
LABEL_T = 1.2;
|
||||||
|
|
||||||
|
// -- USB-C routing ------------------------------------------------------------
|
||||||
|
USBC_CHAN_W = 11.0;
|
||||||
|
USBC_CHAN_H = 7.0;
|
||||||
|
|
||||||
|
// -- Cable clip ---------------------------------------------------------------
|
||||||
|
CLIP_CABLE_D = 4.5;
|
||||||
|
CLIP_T = 2.0;
|
||||||
|
CLIP_BODY_W = 16.0;
|
||||||
|
CLIP_BODY_H = 10.0;
|
||||||
|
|
||||||
|
// -- Fasteners ----------------------------------------------------------------
|
||||||
|
M2P5_D = 2.7;
|
||||||
|
M3_D = 3.3;
|
||||||
|
M3_NUT_AF = 5.5;
|
||||||
|
M3_NUT_H = 2.4;
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// RENDER DISPATCH
|
||||||
|
// ============================================================
|
||||||
|
RENDER = "assembly";
|
||||||
|
|
||||||
|
if (RENDER == "assembly") assembly_preview();
|
||||||
|
else if (RENDER == "wall_base_stl") wall_base();
|
||||||
|
else if (RENDER == "tilt_arm_stl") tilt_arm();
|
||||||
|
else if (RENDER == "anchor_cradle_stl") anchor_cradle();
|
||||||
|
else if (RENDER == "cable_clip_stl") cable_clip();
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// ASSEMBLY PREVIEW
|
||||||
|
// ============================================================
|
||||||
|
module assembly_preview() {
|
||||||
|
%color("Wheat", 0.22)
|
||||||
|
translate([-BASE_W/2, -10, -BASE_H/2])
|
||||||
|
cube([BASE_W, 10, BASE_H + 40]);
|
||||||
|
color("OliveDrab", 0.85) wall_base();
|
||||||
|
color("SteelBlue", 0.85)
|
||||||
|
translate([0, KNUCKLE_T, 0]) rotate([TILT_DEG,0,0]) tilt_arm();
|
||||||
|
color("DarkSlateGray", 0.85)
|
||||||
|
translate([0, KNUCKLE_T, 0]) rotate([TILT_DEG,0,0])
|
||||||
|
translate([0, ARM_T, ARM_L]) anchor_cradle();
|
||||||
|
%color("ForestGreen", 0.38)
|
||||||
|
translate([0, KNUCKLE_T, 0]) rotate([TILT_DEG,0,0])
|
||||||
|
translate([-UWB_L/2, ARM_T+CRADLE_BACK_T,
|
||||||
|
ARM_L+CRADLE_FLOOR_T+STANDOFF_H])
|
||||||
|
cube([UWB_L, UWB_W, UWB_H]);
|
||||||
|
color("DimGray", 0.70)
|
||||||
|
translate([ARM_W/2, KNUCKLE_T, 0]) rotate([TILT_DEG,0,0])
|
||||||
|
translate([0, ARM_T+e, ARM_L/2]) rotate([0,-90,90]) cable_clip();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// PART 1 -- WALL BASE
|
||||||
|
// ============================================================
|
||||||
|
// Flat backplate, 2x countersunk M4/#6 wood screws on 35mm centres.
|
||||||
|
// Two pivot ears straddle the tilt arm; M3 pivot bolt through both.
|
||||||
|
// Detent arc on +X ear inner face: 7 notches at 15deg steps (0-90deg).
|
||||||
|
// Shallow rear recess for installation-zone label strip.
|
||||||
|
// Same part for wall mount and ceiling mount.
|
||||||
|
//
|
||||||
|
// Print: backplate flat on bed, PETG, 5 perims, 40% gyroid.
|
||||||
|
module wall_base() {
|
||||||
|
ear_h = ARM_W + 3.0;
|
||||||
|
ear_t = 6.0;
|
||||||
|
ear_sep = ARM_W + 1.0;
|
||||||
|
|
||||||
difference() {
|
difference() {
|
||||||
union() {
|
union() {
|
||||||
// D-shaped body
|
translate([-BASE_W/2, -BASE_T, -BASE_H/2])
|
||||||
intersection() {
|
cube([BASE_W, BASE_T, BASE_H]);
|
||||||
cylinder(d=COL_OD, h=COL_H);
|
for (ex = [-(ear_sep/2 + ear_t), ear_sep/2])
|
||||||
translate([-COL_OD/2, y_front ? 0 : -COL_OD/2, 0])
|
translate([ex, -BASE_T+e, -ear_h/2])
|
||||||
cube([COL_OD, COL_OD/2, COL_H]);
|
cube([ear_t, KNUCKLE_T+e, ear_h]);
|
||||||
|
for (ex = [-(ear_sep/2 + ear_t), ear_sep/2])
|
||||||
|
hull() {
|
||||||
|
translate([ex, -BASE_T, -ear_h/4])
|
||||||
|
cube([ear_t, BASE_T-1, ear_h/2]);
|
||||||
|
translate([ex + (ex<0 ? ear_t*0.5 : 0), -BASE_T, -ear_h/6])
|
||||||
|
cube([ear_t*0.5, 1, ear_h/3]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Anti-rotation tab (front half only, at +X side)
|
|
||||||
if (y_front) {
|
|
||||||
translate([COL_OD/2, -ANTI_ROT_W/2, ANTI_ROT_Z])
|
|
||||||
cube([ANTI_ROT_T, ANTI_ROT_W,
|
|
||||||
COL_H - ANTI_ROT_Z - 4]);
|
|
||||||
}
|
}
|
||||||
|
for (sz = [-BASE_SCREW_SPC/2, BASE_SCREW_SPC/2]) {
|
||||||
// Bracket arm attachment boss (front half only, top centre)
|
translate([0, -BASE_T-e, sz]) rotate([-90,0,0])
|
||||||
if (y_front) {
|
cylinder(d=BASE_SCREW_D, h=BASE_T+2*e);
|
||||||
translate([-ARM_W/2, COL_OD/2, COL_H * 0.3])
|
translate([0, -BASE_T-e, sz]) rotate([-90,0,0])
|
||||||
cube([ARM_W, ARM_L, COL_H * 0.4]);
|
cylinder(d1=BASE_SCREW_HD, d2=BASE_SCREW_D, h=BASE_SCREW_HH+e);
|
||||||
|
}
|
||||||
|
translate([-(ear_sep/2+ear_t+e), KNUCKLE_T*0.55, 0])
|
||||||
|
rotate([0,90,0]) cylinder(d=PIVOT_D, h=ear_sep+2*ear_t+2*e);
|
||||||
|
translate([ear_sep/2+ear_t-PIVOT_NUT_H-0.4, KNUCKLE_T*0.55, 0])
|
||||||
|
rotate([0,90,0])
|
||||||
|
cylinder(d=PIVOT_NUT_AF/cos(30), h=PIVOT_NUT_H+0.5, $fn=6);
|
||||||
|
for (da = [0 : 15 : 90])
|
||||||
|
translate([ear_sep/2-e,
|
||||||
|
KNUCKLE_T*0.55 + DETENT_R*sin(da),
|
||||||
|
DETENT_R*cos(da)])
|
||||||
|
rotate([0,90,0]) cylinder(d=DETENT_D, h=ear_t*0.45+e);
|
||||||
|
translate([0, -BASE_T-e, 0]) rotate([-90,0,0])
|
||||||
|
cube([BASE_W-12, BASE_H-16, 1.6], center=true);
|
||||||
|
translate([0, -BASE_T+1.5, 0])
|
||||||
|
cube([BASE_W-14, BASE_T-3, BASE_H-20], center=true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Stem bore ─────────────────────────────────────────
|
// ============================================================
|
||||||
translate([0,0,-e])
|
// PART 2 -- TILT ARM
|
||||||
cylinder(d=STEM_BORE, h=COL_H + 2*e);
|
// ============================================================
|
||||||
|
// Pivoting arm linking wall_base ears to anchor_cradle.
|
||||||
// ── M4 clamping bolt holes (Y direction) ──────────────
|
// Knuckle (Z=0): M3 pivot bore + spring-plunger detent pocket (3mm).
|
||||||
for (bx=[-COL_BOLT_X, COL_BOLT_X]) {
|
// Cradle end (Z=ARM_L): 2x M3 bolt attachment stub.
|
||||||
translate([bx, y_front ? COL_OD/2 : 0, COL_H/2])
|
// USB-C cable channel groove on outer +Y face, full arm length.
|
||||||
rotate([90,0,0])
|
//
|
||||||
cylinder(d=COL_BOLT_D, h=COL_OD/2 + e);
|
// Print: knuckle face flat on bed, PETG, 5 perims, 40% gyroid.
|
||||||
// Thumbscrew head recess on outer face (front only — access side)
|
module tilt_arm() {
|
||||||
if (y_front) {
|
total_h = ARM_L + 10;
|
||||||
translate([bx, COL_OD/2 - WALL, COL_H/2])
|
difference() {
|
||||||
rotate([90,0,0])
|
union() {
|
||||||
cylinder(d=THUMB_HEAD_D, h=8 + e);
|
translate([-ARM_W/2, 0, 0]) cube([ARM_W, ARM_T, total_h]);
|
||||||
|
translate([0, ARM_T/2, 0]) rotate([90,0,0])
|
||||||
|
cylinder(d=ARM_W, h=ARM_T, center=true);
|
||||||
|
translate([-ARM_W/2, 0, ARM_L])
|
||||||
|
cube([ARM_W, ARM_T+CRADLE_BACK_T, ARM_T]);
|
||||||
|
}
|
||||||
|
translate([-ARM_W/2-e, ARM_T/2, 0]) rotate([0,90,0])
|
||||||
|
cylinder(d=PIVOT_D, h=ARM_W+2*e);
|
||||||
|
translate([0, ARM_T+e, 0]) rotate([90,0,0])
|
||||||
|
cylinder(d=3.2, h=4+e);
|
||||||
|
translate([-USBC_CHAN_W/2, ARM_T-e, ARM_T+4])
|
||||||
|
cube([USBC_CHAN_W, USBC_CHAN_H, ARM_L-ARM_T-8]);
|
||||||
|
for (bx = [-ARM_W/4, ARM_W/4])
|
||||||
|
translate([bx, ARM_T/2, ARM_L+ARM_T/2]) rotate([90,0,0])
|
||||||
|
cylinder(d=M3_D, h=ARM_T+CRADLE_BACK_T+2*e);
|
||||||
|
for (bx = [-ARM_W/4, ARM_W/4])
|
||||||
|
translate([bx, ARM_T/2, ARM_L+ARM_T/2]) rotate([-90,0,0])
|
||||||
|
cylinder(d=M3_NUT_AF/cos(30), h=M3_NUT_H+0.5, $fn=6);
|
||||||
|
translate([0, ARM_T/2, ARM_L/2])
|
||||||
|
cube([ARM_W-4, ARM_T-2, ARM_L-18], center=true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── M4 hex nut pockets (rear half) ────────────────────
|
// ============================================================
|
||||||
if (!y_front) {
|
// PART 3 -- ANCHOR CRADLE
|
||||||
for (bx=[-COL_BOLT_X, COL_BOLT_X]) {
|
// ============================================================
|
||||||
translate([bx, -(COL_OD/4 + e), COL_H/2])
|
// Open-front U-cradle for ESP32 UWB Pro PCB.
|
||||||
rotate([90,0,0])
|
// 4x M2.5 standoffs on UWB_HOLE_X x UWB_HOLE_Y pattern.
|
||||||
cylinder(d=COL_NUT_W/cos(30), h=COL_NUT_H + e,
|
// Back wall: USB-C exit slot + routing groove, label card slot,
|
||||||
$fn=6);
|
// antenna keep-out cutout (material removed above antenna area).
|
||||||
}
|
// Front retaining lip prevents PCB sliding out.
|
||||||
}
|
// Two attachment tabs bolt to tilt_arm cradle stub via M3.
|
||||||
|
//
|
||||||
// ── Set screw (height lock, front half) ───────────────
|
// Label card slot: insert paper/laminate strip to ID this anchor
|
||||||
if (y_front) {
|
// (e.g. "UWB-A3 NE-CORNER"), accessible from open cradle end.
|
||||||
translate([0, COL_OD/2, COL_H * 0.8])
|
//
|
||||||
rotate([90,0,0])
|
// Print: back wall flat on bed, PETG, 5 perims, 40% gyroid.
|
||||||
cylinder(d=COL_BOLT_D,
|
module anchor_cradle() {
|
||||||
h=COL_OD/2 - STEM_BORE/2 + e);
|
outer_l = UWB_L + 2*CRADLE_WALL_T;
|
||||||
}
|
outer_w = UWB_W + CRADLE_FLOOR_T;
|
||||||
|
pcb_z = CRADLE_FLOOR_T + STANDOFF_H;
|
||||||
// ── USB cable routing channel (rear half, −X side) ────
|
total_z = pcb_z + UWB_H + 2;
|
||||||
if (!y_front) {
|
|
||||||
translate([-COL_OD/2, -USB_CHAN_W/2, -e])
|
|
||||||
cube([USB_CHAN_D, USB_CHAN_W, COL_H + 2*e]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── M4 hole through arm boss (Z direction, for bracket bolt) ─
|
|
||||||
if (y_front) {
|
|
||||||
for (dx=[-ARM_W/4, ARM_W/4])
|
|
||||||
translate([dx, COL_OD/2 + ARM_L/2, COL_H * 0.35])
|
|
||||||
cylinder(d=COL_BOLT_D, h=COL_H * 0.35 + e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
|
||||||
// module_bracket()
|
|
||||||
// Bolts to collar arm boss. Holds MaUWB PCB facing outward.
|
|
||||||
// Tilted BRKT_TILT° from vertical — antenna clears stem.
|
|
||||||
// Print flat-face-down (back wall on bed).
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
|
||||||
module module_bracket() {
|
|
||||||
bk = BRKT_BACK_T;
|
|
||||||
sd = BRKT_SIDE_T;
|
|
||||||
|
|
||||||
difference() {
|
difference() {
|
||||||
union() {
|
union() {
|
||||||
// ── Back wall (mounts to collar arm boss) ─────────
|
translate([-outer_l/2, 0, 0]) cube([outer_l, outer_w, total_z]);
|
||||||
cube([ARM_W, bk, MAWB_H + M2_STNDFF + 6]);
|
translate([-outer_l/2, outer_w-CRADLE_LIP_T, 0])
|
||||||
|
cube([outer_l, CRADLE_LIP_T, CRADLE_LIP_H]);
|
||||||
// ── Side walls ────────────────────────────────────
|
for (tx = [-ARM_W/4, ARM_W/4])
|
||||||
for (sx=[0, ARM_W - sd])
|
translate([tx-4, -CRADLE_BACK_T, 0])
|
||||||
translate([sx, bk, 0])
|
cube([8, CRADLE_BACK_T+1, total_z]);
|
||||||
cube([sd, MAWB_L + 2, MAWB_H + M2_STNDFF + 6]);
|
|
||||||
|
|
||||||
// ── M2 standoff posts (PCB mounts to these) ───────
|
|
||||||
for (hx=[0, MAWB_HOLE_X], hy=[0, MAWB_HOLE_Y])
|
|
||||||
translate([(ARM_W - MAWB_HOLE_X)/2 + hx,
|
|
||||||
bk + (MAWB_L - MAWB_HOLE_Y)/2 + hy,
|
|
||||||
0])
|
|
||||||
cylinder(d=M2_STNDFF_OD, h=M2_STNDFF);
|
|
||||||
}
|
}
|
||||||
|
translate([-UWB_L/2, 0, pcb_z]) cube([UWB_L, UWB_W+1, UWB_H+4]);
|
||||||
// ── M2 bores through standoffs ────────────────────────
|
translate([0, -CRADLE_BACK_T-e, pcb_z+UWB_H/2-UWB_USBC_H/2])
|
||||||
for (hx=[0, MAWB_HOLE_X], hy=[0, MAWB_HOLE_Y])
|
cube([UWB_USBC_W+2, CRADLE_BACK_T+2*e, UWB_USBC_H+2],
|
||||||
translate([(ARM_W - MAWB_HOLE_X)/2 + hx,
|
center=[true,false,false]);
|
||||||
bk + (MAWB_L - MAWB_HOLE_Y)/2 + hy,
|
translate([0, -CRADLE_BACK_T-e, -e])
|
||||||
-e])
|
cube([USBC_CHAN_W, USBC_CHAN_H, pcb_z+UWB_H/2+USBC_CHAN_H],
|
||||||
cylinder(d=M2_D, h=M2_STNDFF + e);
|
center=[true,false,false]);
|
||||||
|
translate([0, -CRADLE_BACK_T-e, pcb_z+UWB_H/2])
|
||||||
// ── Antenna clearance cutout in back wall ─────────────
|
cube([LABEL_W, LABEL_T+0.3, LABEL_H], center=[true,false,false]);
|
||||||
// Open slot near top of back wall so antenna is unobstructed
|
translate([0, -e, pcb_z+UWB_H-UWB_ANTENNA_L])
|
||||||
translate([sd, -e, M2_STNDFF + 2])
|
cube([UWB_L-4, CRADLE_BACK_T+2*e, UWB_ANTENNA_L+4],
|
||||||
cube([ARM_W - 2*sd, bk + 2*e, MAWB_H]);
|
center=[true,false,false]);
|
||||||
|
for (tx = [-ARM_W/4, ARM_W/4])
|
||||||
// ── USB port access notch on one side wall ────────────
|
translate([tx, ARM_T/2-CRADLE_BACK_T, total_z/2])
|
||||||
translate([-e, bk + 2, M2_STNDFF - 1])
|
rotate([-90,0,0])
|
||||||
cube([sd + 2*e, USB_NOTCH_W, USB_NOTCH_H]);
|
cylinder(d=M3_D, h=ARM_T+CRADLE_BACK_T+2*e);
|
||||||
|
for (side_x = [-outer_l/2-e, outer_l/2-CRADLE_WALL_T-e])
|
||||||
// ── Mounting holes to collar arm boss (×2) ────────────
|
translate([side_x, 2, pcb_z+2])
|
||||||
for (dx=[-ARM_W/4, ARM_W/4])
|
cube([CRADLE_WALL_T+2*e, UWB_W-4, UWB_H-4]);
|
||||||
translate([ARM_W/2 + dx, bk + ARM_L/2, -e])
|
}
|
||||||
cylinder(d=COL_BOLT_D, h=6 + e);
|
for (hx = [-UWB_HOLE_X/2, UWB_HOLE_X/2])
|
||||||
|
for (hy = [(outer_w-UWB_W)/2 + (UWB_W-UWB_HOLE_Y)/2,
|
||||||
|
(outer_w-UWB_W)/2 + (UWB_W-UWB_HOLE_Y)/2 + UWB_HOLE_Y])
|
||||||
|
difference() {
|
||||||
|
translate([hx, hy, CRADLE_FLOOR_T-e])
|
||||||
|
cylinder(d=STANDOFF_OD, h=STANDOFF_H+e);
|
||||||
|
translate([hx, hy, CRADLE_FLOOR_T-2*e])
|
||||||
|
cylinder(d=M2P5_D, h=STANDOFF_H+4);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
// ============================================================
|
||||||
// single_anchor_assembly()
|
// PART 4 -- CABLE CLIP
|
||||||
// ─────────────────────────────────────────────────────────────
|
// ============================================================
|
||||||
module single_anchor_assembly(show_phantom=false) {
|
// Snap-on C-clip retaining USB-C cable along tilt arm outer face.
|
||||||
// Collar
|
// Presses onto ARM_T-wide arm with flexible PETG snap tongues.
|
||||||
color("SteelBlue", 0.9) collar_half("front");
|
// Print x2-3 per anchor, spaced 25mm along arm.
|
||||||
color("CornflowerBlue", 0.9) mirror([0,1,0]) collar_half("rear");
|
//
|
||||||
|
// Print: clip-opening face down, PETG, 3 perims, 20% infill.
|
||||||
// Bracket tilted BRKT_TILT° outward from top of arm boss
|
module cable_clip() {
|
||||||
color("LightSteelBlue", 0.85)
|
ch_r = CLIP_CABLE_D/2 + CLIP_T;
|
||||||
translate([0, COL_OD/2 + ARM_L, COL_H * 0.3])
|
snap_t = 1.6;
|
||||||
rotate([BRKT_TILT, 0, 0])
|
difference() {
|
||||||
translate([-ARM_W/2, 0, 0])
|
union() {
|
||||||
module_bracket();
|
translate([-CLIP_BODY_W/2, 0, 0])
|
||||||
|
cube([CLIP_BODY_W, CLIP_T, CLIP_BODY_H]);
|
||||||
// Phantom UWB PCB
|
translate([0, CLIP_T+ch_r, CLIP_BODY_H/2]) rotate([0,90,0])
|
||||||
if (show_phantom)
|
difference() {
|
||||||
color("ForestGreen", 0.4)
|
cylinder(r=ch_r, h=CLIP_BODY_W, center=true);
|
||||||
translate([-MAWB_L/2,
|
cylinder(r=CLIP_CABLE_D/2, h=CLIP_BODY_W+2*e, center=true);
|
||||||
COL_OD/2 + ARM_L + BRKT_BACK_T,
|
translate([0, ch_r+e, 0])
|
||||||
COL_H * 0.3 + M2_STNDFF])
|
cube([CLIP_CABLE_D*0.85, ch_r*2+2*e, CLIP_BODY_W+2*e],
|
||||||
cube([MAWB_L, MAWB_W, MAWB_H]);
|
center=true);
|
||||||
|
}
|
||||||
|
for (tx = [-CLIP_BODY_W/2+1.5, CLIP_BODY_W/2-1.5-snap_t])
|
||||||
|
translate([tx, -ARM_T-1, 0])
|
||||||
|
cube([snap_t, ARM_T+1+CLIP_T, CLIP_BODY_H]);
|
||||||
|
for (tx = [-CLIP_BODY_W/2+1.5, CLIP_BODY_W/2-1.5-snap_t])
|
||||||
|
translate([tx+snap_t/2, -ARM_T-1, CLIP_BODY_H/2])
|
||||||
|
rotate([0,90,0]) cylinder(d=2, h=snap_t, center=true);
|
||||||
|
}
|
||||||
|
translate([0, -ARM_T-1-e, CLIP_BODY_H/2])
|
||||||
|
cube([CLIP_BODY_W-6, ARM_T+2, CLIP_BODY_H-4], center=true);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
|
||||||
// Render selector
|
|
||||||
// ─────────────────────────────────────────────────────────────
|
|
||||||
if (RENDER == "assembly") {
|
|
||||||
single_anchor_assembly(show_phantom=true);
|
|
||||||
|
|
||||||
} else if (RENDER == "collar_front") {
|
|
||||||
collar_half("front");
|
|
||||||
|
|
||||||
} else if (RENDER == "collar_rear") {
|
|
||||||
collar_half("rear");
|
|
||||||
|
|
||||||
} else if (RENDER == "bracket") {
|
|
||||||
module_bracket();
|
|
||||||
|
|
||||||
} else if (RENDER == "pair") {
|
|
||||||
// Both anchors at 250 mm spacing on a stem stub
|
|
||||||
color("Silver", 0.2)
|
|
||||||
translate([0, 0, -50])
|
|
||||||
cylinder(d=STEM_OD, h=ANCHOR_SPACING + COL_H + 100);
|
|
||||||
|
|
||||||
// Lower anchor (Z = 0)
|
|
||||||
single_anchor_assembly(show_phantom=true);
|
|
||||||
|
|
||||||
// Upper anchor (Z = ANCHOR_SPACING)
|
|
||||||
translate([0, 0, ANCHOR_SPACING])
|
|
||||||
single_anchor_assembly(show_phantom=true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
296
chassis/vesc_mount.scad
Normal file
296
chassis/vesc_mount.scad
Normal file
@ -0,0 +1,296 @@
|
|||||||
|
// ============================================================
|
||||||
|
// vesc_mount.scad — FSESC 6.7 Pro Mini Dual ESC Mount Cradle
|
||||||
|
// Issue #699 / sl-mechanical 2026-03-17
|
||||||
|
// ============================================================
|
||||||
|
// Open-top tray for Flipsky FSESC 6.7 Pro Mini Dual (~100 × 68 × 28 mm).
|
||||||
|
// Attaches to 2020 aluminium T-slot rail via 4× M5 T-nuts
|
||||||
|
// (2× per rail, two parallel rails, 60 mm bolt spacing in X,
|
||||||
|
// 20 mm bolt spacing in Y matching 2020 slot pitch).
|
||||||
|
//
|
||||||
|
// Connector access:
|
||||||
|
// XT60 battery inputs — X− end wall cutouts (2 connectors, side-by-side)
|
||||||
|
// XT30 motor outputs — Y+ and Y− side wall cutouts (2 per side wall)
|
||||||
|
// CAN/UART terminal — X+ end wall cutout (screw terminal, wire exit)
|
||||||
|
//
|
||||||
|
// Ventilation:
|
||||||
|
// Open top face — heatsink fins fully exposed
|
||||||
|
// Floor grille slots — under-board airflow
|
||||||
|
// Side vent louvres — 4 slots on each Y± wall at heatsink height
|
||||||
|
//
|
||||||
|
// Retention: 4× M3 heat-set insert boss in floor — board screws down through
|
||||||
|
// ESC mounting holes via M3×8 FHCS. Board sits on 4 mm raised posts for
|
||||||
|
// under-board airflow.
|
||||||
|
//
|
||||||
|
// ⚠ VERIFY WITH CALIPERS BEFORE PRINTING:
|
||||||
|
// PCB_L, PCB_W board outline
|
||||||
|
// XT60_W, XT60_H XT60 shell at X− edge
|
||||||
|
// XT30_W, XT30_H XT30 shells at Y± edges
|
||||||
|
// TERM_W, TERM_H CAN screw terminal at X+ edge
|
||||||
|
// MOUNT_X1/X2, MOUNT_Y1/Y2 ESC board mounting hole pattern
|
||||||
|
//
|
||||||
|
// Print settings (PETG):
|
||||||
|
// 3 perimeters, 40 % gyroid infill, no supports, 0.2 mm layer
|
||||||
|
// Print orientation: open face UP (as modelled)
|
||||||
|
//
|
||||||
|
// BOM:
|
||||||
|
// 4 × M5×10 BHCS + 4 × M5 slide-in T-nut (2020 rail)
|
||||||
|
// 4 × M3 heat-set insert (Voron-style, OD 4.5 mm × 4 mm deep)
|
||||||
|
// 4 × M3×8 FHCS (board retention)
|
||||||
|
//
|
||||||
|
// Export commands:
|
||||||
|
// openscad -D 'RENDER="mount"' -o vesc_mount.stl vesc_mount.scad
|
||||||
|
// openscad -D 'RENDER="assembly"' -o vesc_assembly.png vesc_mount.scad
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
RENDER = "assembly"; // mount | assembly
|
||||||
|
|
||||||
|
$fn = 48;
|
||||||
|
EPS = 0.01;
|
||||||
|
|
||||||
|
// ── ⚠ Verify before printing ─────────────────────────────────
|
||||||
|
// FSESC 6.7 Pro Mini Dual PCB
|
||||||
|
PCB_L = 100.0; // board length (X: XT60 end → CAN terminal end)
|
||||||
|
PCB_W = 68.0; // board width (Y)
|
||||||
|
PCB_T = 2.0; // board thickness (incl. bottom-side components)
|
||||||
|
COMP_H = 26.0; // tallest component above board top face (heatsink ~26 mm)
|
||||||
|
|
||||||
|
// XT60 battery connectors at X− end (2 connectors, side-by-side)
|
||||||
|
XT60_W = 16.0; // each XT60 shell width (Y)
|
||||||
|
XT60_H = 16.0; // each XT60 shell height (Z) above board surface
|
||||||
|
XT60_Z0 = 0.0; // connector bottom offset above board surface
|
||||||
|
// Y centres of each XT60 measured from PCB Y− edge
|
||||||
|
XT60_Y1 = 16.0;
|
||||||
|
XT60_Y2 = 52.0;
|
||||||
|
|
||||||
|
// XT30 motor output connectors at Y± sides (2 per side)
|
||||||
|
XT30_W = 10.5; // each XT30 shell width (X span)
|
||||||
|
XT30_H = 12.0; // each XT30 shell height (Z) above board surface
|
||||||
|
XT30_Z0 = 0.5; // connector bottom offset above board surface
|
||||||
|
// X centres measured from PCB X− edge (same layout both Y− and Y+ sides)
|
||||||
|
XT30_X1 = 22.0;
|
||||||
|
XT30_X2 = 78.0;
|
||||||
|
|
||||||
|
// CAN / UART screw terminal block at X+ end (3-pos 3.5 mm pitch)
|
||||||
|
TERM_W = 14.0; // terminal block Y span
|
||||||
|
TERM_H = 10.0; // terminal block height above board surface
|
||||||
|
TERM_Z0 = 0.5; // terminal bottom offset above board surface
|
||||||
|
TERM_Y_CTR = PCB_W / 2;
|
||||||
|
|
||||||
|
// ── ESC board mounting hole pattern ──────────────────────────
|
||||||
|
// 4 corner holes, 4 mm inset from each PCB edge
|
||||||
|
MOUNT_INSET = 4.0;
|
||||||
|
MOUNT_X1 = MOUNT_INSET;
|
||||||
|
MOUNT_X2 = PCB_L - MOUNT_INSET;
|
||||||
|
MOUNT_Y1 = MOUNT_INSET;
|
||||||
|
MOUNT_Y2 = PCB_W - MOUNT_INSET;
|
||||||
|
|
||||||
|
M3_INSERT_OD = 4.6; // Voron M3 heat-set insert press-fit OD
|
||||||
|
M3_INSERT_H = 4.0; // insert depth
|
||||||
|
M3_CLEAR_D = 3.4; // M3 clearance bore below insert
|
||||||
|
|
||||||
|
// ── Cradle geometry ──────────────────────────────────────────
|
||||||
|
WALL_T = 2.8; // side / end wall thickness
|
||||||
|
FLOOR_T = 4.5; // floor plate thickness (fits M5 BHCS head pocket)
|
||||||
|
POST_H = 4.0; // standoff post height (board lifts off floor for airflow)
|
||||||
|
CL_SIDE = 0.35; // Y clearance per side
|
||||||
|
CL_END = 0.40; // X clearance per end
|
||||||
|
|
||||||
|
INN_W = PCB_W + 2*CL_SIDE;
|
||||||
|
INN_L = PCB_L + 2*CL_END;
|
||||||
|
INN_H = POST_H + PCB_T + COMP_H + 1.5;
|
||||||
|
|
||||||
|
OTR_W = INN_W + 2*WALL_T;
|
||||||
|
OTR_L = INN_L + 2*WALL_T;
|
||||||
|
OTR_H = FLOOR_T + INN_H;
|
||||||
|
|
||||||
|
PCB_X0 = WALL_T + CL_END;
|
||||||
|
PCB_Y0 = WALL_T + CL_SIDE;
|
||||||
|
PCB_Z0 = FLOOR_T + POST_H;
|
||||||
|
|
||||||
|
// ── M5 T-nut mount (2020 rail) ────────────────────────────────
|
||||||
|
// 4 bolts: 2 columns (X) × 2 rows (Y), centred on body
|
||||||
|
M5_D = 5.3;
|
||||||
|
M5_HEAD_D = 9.5;
|
||||||
|
M5_HEAD_H = 3.0;
|
||||||
|
M5_SPAC_X = 60.0; // X bolt spacing
|
||||||
|
M5_SPAC_Y = 20.0; // Y bolt spacing (2020 T-slot pitch)
|
||||||
|
|
||||||
|
// ── Floor ventilation grille ──────────────────────────────────
|
||||||
|
GRILLE_SLOT_W = 4.0;
|
||||||
|
GRILLE_SLOT_T = FLOOR_T - 1.5;
|
||||||
|
GRILLE_PITCH = 10.0;
|
||||||
|
GRILLE_X0 = WALL_T + 14;
|
||||||
|
GRILLE_X_LEN = OTR_L - 2*WALL_T - 28;
|
||||||
|
GRILLE_N = floor((INN_W - 10) / GRILLE_PITCH);
|
||||||
|
|
||||||
|
// ── Side vent louvres on Y± walls ────────────────────────────
|
||||||
|
LOUV_H = 5.0;
|
||||||
|
LOUV_W = 12.0;
|
||||||
|
LOUV_Z = FLOOR_T + POST_H + PCB_T + 4.0; // mid-heatsink height
|
||||||
|
LOUV_N = 4;
|
||||||
|
LOUV_PITCH = (OTR_L - 2*WALL_T - 20) / max(LOUV_N - 1, 1);
|
||||||
|
|
||||||
|
// ── CAN wire strain relief bosses (X+ end) ───────────────────
|
||||||
|
SR_BOSS_OD = 7.0;
|
||||||
|
SR_BOSS_H = 6.0;
|
||||||
|
SR_SLOT_W = 3.5;
|
||||||
|
SR_SLOT_T = 2.2;
|
||||||
|
SR_Y1 = WALL_T + INN_W * 0.25;
|
||||||
|
SR_Y2 = WALL_T + INN_W * 0.75;
|
||||||
|
SR_X = OTR_L - WALL_T - SR_BOSS_OD/2 - 2.5;
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────
|
||||||
|
module m3_insert_boss() {
|
||||||
|
// Solid post with heat-set insert bore from top
|
||||||
|
post_h = FLOOR_T + POST_H;
|
||||||
|
difference() {
|
||||||
|
cylinder(d = M3_INSERT_OD + 3.2, h = post_h);
|
||||||
|
// Insert bore from top
|
||||||
|
translate([0, 0, post_h - M3_INSERT_H])
|
||||||
|
cylinder(d = M3_INSERT_OD, h = M3_INSERT_H + EPS);
|
||||||
|
// Clearance bore from bottom
|
||||||
|
translate([0, 0, -EPS])
|
||||||
|
cylinder(d = M3_CLEAR_D, h = post_h - M3_INSERT_H + EPS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module vesc_mount() {
|
||||||
|
difference() {
|
||||||
|
union() {
|
||||||
|
// Main body
|
||||||
|
cube([OTR_L, OTR_W, OTR_H]);
|
||||||
|
|
||||||
|
// M3 insert bosses at board mounting corners
|
||||||
|
for (mx = [MOUNT_X1, MOUNT_X2])
|
||||||
|
for (my = [MOUNT_Y1, MOUNT_Y2])
|
||||||
|
translate([PCB_X0 + mx, PCB_Y0 + my, 0])
|
||||||
|
m3_insert_boss();
|
||||||
|
|
||||||
|
// CAN strain relief bosses on X+ end
|
||||||
|
for (sy = [SR_Y1, SR_Y2])
|
||||||
|
translate([SR_X, sy, 0])
|
||||||
|
cylinder(d = SR_BOSS_OD, h = SR_BOSS_H);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Interior cavity (open top) ─────────────────────────
|
||||||
|
translate([WALL_T, WALL_T, FLOOR_T])
|
||||||
|
cube([INN_L, INN_W, INN_H + EPS]);
|
||||||
|
|
||||||
|
// ── XT60 cutouts at X− end (2 connectors) ──────────────
|
||||||
|
for (yc = [XT60_Y1, XT60_Y2])
|
||||||
|
translate([-EPS,
|
||||||
|
PCB_Y0 + yc - (XT60_W + 2.0)/2,
|
||||||
|
PCB_Z0 + XT60_Z0 - 0.5])
|
||||||
|
cube([WALL_T + 2*EPS, XT60_W + 2.0, XT60_H + 3.0]);
|
||||||
|
|
||||||
|
// ── XT30 cutouts at Y− side (2 connectors) ─────────────
|
||||||
|
for (xc = [XT30_X1, XT30_X2])
|
||||||
|
translate([PCB_X0 + xc - (XT30_W + 2.0)/2,
|
||||||
|
-EPS,
|
||||||
|
PCB_Z0 + XT30_Z0 - 0.5])
|
||||||
|
cube([XT30_W + 2.0, WALL_T + 2*EPS, XT30_H + 3.0]);
|
||||||
|
|
||||||
|
// ── XT30 cutouts at Y+ side (2 connectors) ─────────────
|
||||||
|
for (xc = [XT30_X1, XT30_X2])
|
||||||
|
translate([PCB_X0 + xc - (XT30_W + 2.0)/2,
|
||||||
|
OTR_W - WALL_T - EPS,
|
||||||
|
PCB_Z0 + XT30_Z0 - 0.5])
|
||||||
|
cube([XT30_W + 2.0, WALL_T + 2*EPS, XT30_H + 3.0]);
|
||||||
|
|
||||||
|
// ── CAN terminal cutout at X+ end ──────────────────────
|
||||||
|
translate([OTR_L - WALL_T - EPS,
|
||||||
|
PCB_Y0 + TERM_Y_CTR - (TERM_W + 3.0)/2,
|
||||||
|
PCB_Z0 + TERM_Z0 - 0.5])
|
||||||
|
cube([WALL_T + 2*EPS, TERM_W + 3.0, TERM_H + 5.0]);
|
||||||
|
|
||||||
|
// ── Floor ventilation grille ───────────────────────────
|
||||||
|
for (i = [0 : GRILLE_N - 1]) {
|
||||||
|
sy = WALL_T + 5 + i * GRILLE_PITCH;
|
||||||
|
translate([GRILLE_X0, sy, -EPS])
|
||||||
|
cube([GRILLE_X_LEN, GRILLE_SLOT_W, GRILLE_SLOT_T + EPS]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Side vent louvres — Y− wall ────────────────────────
|
||||||
|
for (i = [0 : LOUV_N - 1]) {
|
||||||
|
lx = WALL_T + 10 + i * LOUV_PITCH;
|
||||||
|
translate([lx, -EPS, LOUV_Z])
|
||||||
|
cube([LOUV_W, WALL_T + 2*EPS, LOUV_H]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Side vent louvres — Y+ wall ────────────────────────
|
||||||
|
for (i = [0 : LOUV_N - 1]) {
|
||||||
|
lx = WALL_T + 10 + i * LOUV_PITCH;
|
||||||
|
translate([lx, OTR_W - WALL_T - EPS, LOUV_Z])
|
||||||
|
cube([LOUV_W, WALL_T + 2*EPS, LOUV_H]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── M5 BHCS head pockets (4 bolts, bottom face) ────────
|
||||||
|
for (mx = [OTR_L/2 - M5_SPAC_X/2, OTR_L/2 + M5_SPAC_X/2])
|
||||||
|
for (my = [OTR_W/2 - M5_SPAC_Y/2, OTR_W/2 + M5_SPAC_Y/2])
|
||||||
|
translate([mx, my, -EPS]) {
|
||||||
|
cylinder(d = M5_D, h = FLOOR_T + 2*EPS);
|
||||||
|
cylinder(d = M5_HEAD_D, h = M5_HEAD_H + EPS);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Zip-tie slots through CAN strain relief bosses ─────
|
||||||
|
for (sy = [SR_Y1, SR_Y2])
|
||||||
|
translate([SR_X, sy, SR_BOSS_H/2 - SR_SLOT_T/2])
|
||||||
|
rotate([0, 90, 0])
|
||||||
|
cube([SR_SLOT_T, SR_SLOT_W, SR_BOSS_OD + 2*EPS],
|
||||||
|
center = true);
|
||||||
|
|
||||||
|
// ── Weight-relief pocket in floor underside ─────────────
|
||||||
|
translate([WALL_T + 16, WALL_T + 6, -EPS])
|
||||||
|
cube([OTR_L - 2*WALL_T - 32, OTR_W - 2*WALL_T - 12,
|
||||||
|
FLOOR_T - 2.0 + EPS]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Assembly preview ─────────────────────────────────────────
|
||||||
|
if (RENDER == "assembly") {
|
||||||
|
color("DimGray", 0.93) vesc_mount();
|
||||||
|
|
||||||
|
// Phantom PCB
|
||||||
|
color("ForestGreen", 0.30)
|
||||||
|
translate([PCB_X0, PCB_Y0, PCB_Z0])
|
||||||
|
cube([PCB_L, PCB_W, PCB_T]);
|
||||||
|
|
||||||
|
// Phantom heatsink / component block
|
||||||
|
color("SlateGray", 0.22)
|
||||||
|
translate([PCB_X0, PCB_Y0, PCB_Z0 + PCB_T])
|
||||||
|
cube([PCB_L, PCB_W, COMP_H]);
|
||||||
|
|
||||||
|
// XT60 connector highlights (X− end)
|
||||||
|
for (yc = [XT60_Y1, XT60_Y2])
|
||||||
|
color("Gold", 0.85)
|
||||||
|
translate([-2,
|
||||||
|
PCB_Y0 + yc - XT60_W/2,
|
||||||
|
PCB_Z0 + XT60_Z0])
|
||||||
|
cube([WALL_T + 3, XT60_W, XT60_H]);
|
||||||
|
|
||||||
|
// XT30 connector highlights — Y− side
|
||||||
|
for (xc = [XT30_X1, XT30_X2])
|
||||||
|
color("OrangeRed", 0.80)
|
||||||
|
translate([PCB_X0 + xc - XT30_W/2,
|
||||||
|
-2,
|
||||||
|
PCB_Z0 + XT30_Z0])
|
||||||
|
cube([XT30_W, WALL_T + 3, XT30_H]);
|
||||||
|
|
||||||
|
// XT30 connector highlights — Y+ side
|
||||||
|
for (xc = [XT30_X1, XT30_X2])
|
||||||
|
color("OrangeRed", 0.80)
|
||||||
|
translate([PCB_X0 + xc - XT30_W/2,
|
||||||
|
OTR_W - WALL_T - 1,
|
||||||
|
PCB_Z0 + XT30_Z0])
|
||||||
|
cube([XT30_W, WALL_T + 3, XT30_H]);
|
||||||
|
|
||||||
|
// CAN terminal highlight
|
||||||
|
color("Tomato", 0.75)
|
||||||
|
translate([OTR_L - WALL_T - 1,
|
||||||
|
PCB_Y0 + TERM_Y_CTR - TERM_W/2,
|
||||||
|
PCB_Z0 + TERM_Z0])
|
||||||
|
cube([WALL_T + 3, TERM_W, TERM_H]);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
vesc_mount();
|
||||||
|
}
|
||||||
@ -2,22 +2,44 @@
|
|||||||
|
|
||||||
You're working on **SaltyLab**, a self-balancing two-wheeled indoor robot. Read this entire file before touching anything.
|
You're working on **SaltyLab**, a self-balancing two-wheeled indoor robot. Read this entire file before touching anything.
|
||||||
|
|
||||||
## Project Overview
|
## ⚠️ ARCHITECTURE — SAUL-TEE (finalised 2026-04-04)
|
||||||
|
|
||||||
|
<<<<<<< HEAD
|
||||||
|
Full hardware spec: `docs/SAUL-TEE-SYSTEM-REFERENCE.md` — **read it before writing firmware.**
|
||||||
|
|
||||||
|
| Board | Role |
|
||||||
|
|-------|------|
|
||||||
|
| **ESP32-S3 BALANCE** | Waveshare Touch LCD 1.28 (CH343 USB). QMI8658 IMU, PID loop, CAN→VESC L(68)/R(56), GC9A01 LCD |
|
||||||
|
| **ESP32-S3 IO** | Bare devkit (JTAG USB). TBS Crossfire RC (UART0), ELRS failover (UART2), BTS7960 motors, NFC/baro/ToF, WS2812, buzzer/horn/headlight/fan |
|
||||||
|
| **Jetson Orin** | CANable2 USB→CAN. Cmds on 0x300–0x303, telemetry on 0x400–0x401 |
|
||||||
|
|
||||||
|
```
|
||||||
|
Jetson Orin ──CANable2──► CAN 500kbps ◄───────────────────────┐
|
||||||
|
│ │
|
||||||
|
ESP32-S3 BALANCE ←─UART 460800─► ESP32-S3 IO
|
||||||
|
(QMI8658, PID loop) (BTS7960, RC, sensors)
|
||||||
|
│ CAN 500kbps
|
||||||
|
┌─────────┴──────────┐
|
||||||
|
VESC Left (ID 68) VESC Right (ID 56)
|
||||||
|
=======
|
||||||
A hoverboard-based balancing robot with two compute layers:
|
A hoverboard-based balancing robot with two compute layers:
|
||||||
1. **FC (Flight Controller)** — MAMBA F722S (STM32F722RET6 + MPU6000 IMU). Runs a lean C balance loop at up to 8kHz. Talks UART to the hoverboard ESC. This is the safety-critical layer.
|
1. **ESP32-S3 BALANCE** — ESP32-S3 BALANCE (ESP32-S3RET6 + MPU6000 IMU). Runs a lean C balance loop at up to 8kHz. Talks UART to the hoverboard ESC. This is the safety-critical layer.
|
||||||
2. **Jetson Nano** — AI brain. ROS2, SLAM, person tracking. Sends velocity commands to FC via UART. Not safety-critical — FC operates independently.
|
2. **Jetson Orin Nano Super** — AI brain. ROS2, SLAM, person tracking. Sends velocity commands to FC via UART. Not safety-critical — FC operates independently.
|
||||||
|
|
||||||
```
|
```
|
||||||
Jetson (speed+steer via UART1) ←→ ELRS RC (UART3, kill switch)
|
Jetson (speed+steer via UART1) ←→ ELRS RC (UART3, kill switch)
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
MAMBA F722S (MPU6000 IMU, PID balance)
|
ESP32-S3 BALANCE (MPU6000 IMU, PID balance)
|
||||||
│
|
│
|
||||||
▼ UART2
|
▼ UART2
|
||||||
Hoverboard ESC (FOC) → 2× 8" hub motors
|
Hoverboard ESC (FOC) → 2× 8" hub motors
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Frame: `[0xAA][LEN][TYPE][PAYLOAD][CRC8]`
|
||||||
|
Legacy `src/` STM32 HAL code is **archived — do not extend.**
|
||||||
|
|
||||||
## ⚠️ SAFETY — READ THIS OR PEOPLE GET HURT
|
## ⚠️ SAFETY — READ THIS OR PEOPLE GET HURT
|
||||||
|
|
||||||
This is not a toy. 8" hub motors + 36V battery can crush fingers, break toes, and launch the frame. Every firmware change must preserve these invariants:
|
This is not a toy. 8" hub motors + 36V battery can crush fingers, break toes, and launch the frame. Every firmware change must preserve these invariants:
|
||||||
@ -35,10 +57,14 @@ This is not a toy. 8" hub motors + 36V battery can crush fingers, break toes, an
|
|||||||
## Repository Layout
|
## Repository Layout
|
||||||
|
|
||||||
```
|
```
|
||||||
firmware/ # STM32 HAL firmware (PlatformIO)
|
<<<<<<< HEAD
|
||||||
|
firmware/ # Legacy ESP32/STM32 HAL firmware (PlatformIO, archived)
|
||||||
|
=======
|
||||||
|
firmware/ # ESP-IDF firmware (PlatformIO)
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
├── src/
|
├── src/
|
||||||
│ ├── main.c # Entry point, clock config, main loop
|
│ ├── main.c # Entry point, clock config, main loop
|
||||||
│ ├── icm42688.c # ICM-42688-P SPI driver (backup IMU — currently broken)
|
│ ├── icm42688.c # QMI8658-P SPI driver (backup IMU — currently broken)
|
||||||
│ ├── bmp280.c # Barometer driver (disabled)
|
│ ├── bmp280.c # Barometer driver (disabled)
|
||||||
│ └── status.c # LED + buzzer status patterns
|
│ └── status.c # LED + buzzer status patterns
|
||||||
├── include/
|
├── include/
|
||||||
@ -49,7 +75,7 @@ firmware/ # STM32 HAL firmware (PlatformIO)
|
|||||||
│ ├── crsf.h # ELRS CRSF protocol
|
│ ├── crsf.h # ELRS CRSF protocol
|
||||||
│ ├── bmp280.h
|
│ ├── bmp280.h
|
||||||
│ └── status.h
|
│ └── status.h
|
||||||
├── lib/USB_CDC/ # USB CDC stack (serial over USB)
|
├── lib/USB_CDC/ # USB Serial (CH343) stack (serial over USB)
|
||||||
│ ├── src/ # CDC implementation, USB descriptors, PCD config
|
│ ├── src/ # CDC implementation, USB descriptors, PCD config
|
||||||
│ └── include/
|
│ └── include/
|
||||||
└── platformio.ini # Build config
|
└── platformio.ini # Build config
|
||||||
@ -82,16 +108,24 @@ PLATFORM.md # Hardware platform reference
|
|||||||
|
|
||||||
## Hardware Quick Reference
|
## Hardware Quick Reference
|
||||||
|
|
||||||
### MAMBA F722S Flight Controller
|
<<<<<<< HEAD
|
||||||
|
### ESP32 BALANCE Flight Controller
|
||||||
|
|
||||||
| Spec | Value |
|
| Spec | Value |
|
||||||
|------|-------|
|
|------|-------|
|
||||||
| MCU | STM32F722RET6 (Cortex-M7, 216MHz, 512KB flash, 256KB RAM) |
|
| MCU | ESP32RET6 (Cortex-M7, 216MHz, 512KB flash, 256KB RAM) |
|
||||||
|
=======
|
||||||
|
### ESP32-S3 BALANCE Flight Controller
|
||||||
|
|
||||||
|
| Spec | Value |
|
||||||
|
|------|-------|
|
||||||
|
| MCU | ESP32-S3RET6 (Cortex-M7, 216MHz, 512KB flash, 256KB RAM) |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
| Primary IMU | MPU6000 (WHO_AM_I = 0x68) |
|
| Primary IMU | MPU6000 (WHO_AM_I = 0x68) |
|
||||||
| IMU Bus | SPI1: PA5=SCK, PA6=MISO, PA7=MOSI, CS=PA4 |
|
| IMU Bus | SPI1: PA5=SCK, PA6=MISO, PA7=MOSI, CS=PA4 |
|
||||||
| IMU EXTI | PC4 (data ready interrupt) |
|
| IMU EXTI | PC4 (data ready interrupt) |
|
||||||
| IMU Orientation | CW270 (Betaflight convention) |
|
| IMU Orientation | CW270 (Betaflight convention) |
|
||||||
| Secondary IMU | ICM-42688-P (on same SPI1, CS unknown — currently non-functional) |
|
| Secondary IMU | QMI8658-P (on same SPI1, CS unknown — currently non-functional) |
|
||||||
| Betaflight Target | DIAT-MAMBAF722_2022B |
|
| Betaflight Target | DIAT-MAMBAF722_2022B |
|
||||||
| USB | OTG FS (PA11/PA12), enumerates as /dev/cu.usbmodemSALTY0011 |
|
| USB | OTG FS (PA11/PA12), enumerates as /dev/cu.usbmodemSALTY0011 |
|
||||||
| VID/PID | 0x0483/0x5740 |
|
| VID/PID | 0x0483/0x5740 |
|
||||||
@ -104,7 +138,7 @@ PLATFORM.md # Hardware platform reference
|
|||||||
|
|
||||||
| UART | Pins | Connected To | Baud |
|
| UART | Pins | Connected To | Baud |
|
||||||
|------|------|-------------|------|
|
|------|------|-------------|------|
|
||||||
| USART1 | PA9/PA10 | Jetson Nano | 115200 |
|
| USART1 | PA9/PA10 | Jetson Orin Nano Super | 115200 |
|
||||||
| USART2 | PA2/PA3 | Hoverboard ESC | 115200 |
|
| USART2 | PA2/PA3 | Hoverboard ESC | 115200 |
|
||||||
| USART3 | PB10/PB11 | ELRS Receiver | 420000 (CRSF) |
|
| USART3 | PB10/PB11 | ELRS Receiver | 420000 (CRSF) |
|
||||||
| UART4 | — | Spare | — |
|
| UART4 | — | Spare | — |
|
||||||
@ -125,7 +159,7 @@ PLATFORM.md # Hardware platform reference
|
|||||||
| FC board size | ~36mm square |
|
| FC board size | ~36mm square |
|
||||||
| Hub motor body | Ø200mm (~8") |
|
| Hub motor body | Ø200mm (~8") |
|
||||||
| Motor axle | Ø12mm, 45mm long |
|
| Motor axle | Ø12mm, 45mm long |
|
||||||
| Jetson Nano | 100×80×29mm, M2.5 holes at 86×58mm |
|
| Jetson Orin Nano Super | 100×80×29mm, M2.5 holes at 86×58mm |
|
||||||
| RealSense D435i | 90×25×25mm, 1/4-20 tripod mount |
|
| RealSense D435i | 90×25×25mm, 1/4-20 tripod mount |
|
||||||
| RPLIDAR A1 | Ø70×41mm, 4× M2.5 on Ø67mm circle |
|
| RPLIDAR A1 | Ø70×41mm, 4× M2.5 on Ø67mm circle |
|
||||||
| Kill switch hole | Ø22mm panel mount |
|
| Kill switch hole | Ø22mm panel mount |
|
||||||
@ -160,19 +194,27 @@ PLATFORM.md # Hardware platform reference
|
|||||||
### Critical Lessons Learned (DON'T REPEAT THESE)
|
### Critical Lessons Learned (DON'T REPEAT THESE)
|
||||||
|
|
||||||
1. **SysTick_Handler with HAL_IncTick() is MANDATORY** — without it, HAL_Delay() and every HAL timeout hangs forever. This bricked us multiple times.
|
1. **SysTick_Handler with HAL_IncTick() is MANDATORY** — without it, HAL_Delay() and every HAL timeout hangs forever. This bricked us multiple times.
|
||||||
2. **DCache breaks SPI on STM32F7** — disable DCache or use cache-aligned DMA buffers with clean/invalidate. We disable it.
|
<<<<<<< HEAD
|
||||||
|
2. **DCache breaks SPI on ESP32** — disable DCache or use cache-aligned DMA buffers with clean/invalidate. We disable it.
|
||||||
|
=======
|
||||||
|
2. **DCache breaks SPI on ESP32-S3** — disable DCache or use cache-aligned DMA buffers with clean/invalidate. We disable it.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
3. **`-(int)0 == 0`** — checking `if (-result)` to detect errors doesn't work when result is 0 (success and failure look the same). Always use explicit error codes.
|
3. **`-(int)0 == 0`** — checking `if (-result)` to detect errors doesn't work when result is 0 (success and failure look the same). Always use explicit error codes.
|
||||||
4. **NEVER auto-run untested code on_boot** — we bricked the NSPanel 3x doing this. Test manually first.
|
4. **NEVER auto-run untested code on_boot** — we bricked the NSPanel 3x doing this. Test manually first.
|
||||||
5. **USB CDC needs ReceivePacket() primed in CDC_Init** — without it, the OUT endpoint never starts listening. No data reception.
|
5. **USB Serial (CH343) needs ReceivePacket() primed in CDC_Init** — without it, the OUT endpoint never starts listening. No data reception.
|
||||||
|
|
||||||
### DFU Reboot (Betaflight Method)
|
### DFU Reboot (Betaflight Method)
|
||||||
|
|
||||||
The firmware supports reboot-to-DFU via USB command:
|
The firmware supports reboot-to-DFU via USB command:
|
||||||
1. Send `R` byte over USB CDC
|
1. Send `R` byte over USB Serial (CH343)
|
||||||
2. Firmware writes `0xDEADBEEF` to RTC backup register 0
|
2. Firmware writes `0xDEADBEEF` to RTC backup register 0
|
||||||
3. `NVIC_SystemReset()` — clean hardware reset
|
3. `NVIC_SystemReset()` — clean hardware reset
|
||||||
4. On boot, `checkForBootloader()` (called after `HAL_Init()`) reads the magic
|
4. On boot, `checkForBootloader()` (called after `HAL_Init()`) reads the magic
|
||||||
5. If magic found: clears it, remaps system memory, jumps to STM32 bootloader at `0x1FF00000`
|
<<<<<<< HEAD
|
||||||
|
5. If magic found: clears it, remaps system memory, jumps to ESP32 BALANCE bootloader at `0x1FF00000`
|
||||||
|
=======
|
||||||
|
5. If magic found: clears it, remaps system memory, jumps to ESP32-S3 bootloader at `0x1FF00000`
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
6. Board appears as DFU device, ready for `dfu-util` flash
|
6. Board appears as DFU device, ready for `dfu-util` flash
|
||||||
|
|
||||||
### Build & Flash
|
### Build & Flash
|
||||||
@ -198,14 +240,14 @@ Fallback: HSI 16MHz if HSE fails (PLL M=16)
|
|||||||
## Current Status & Known Issues
|
## Current Status & Known Issues
|
||||||
|
|
||||||
### Working
|
### Working
|
||||||
- USB CDC serial streaming (50Hz JSON: `{"ax":...,"ay":...,"az":...,"gx":...,"gy":...,"gz":...}`)
|
- USB Serial (CH343) serial streaming (50Hz JSON: `{"ax":...,"ay":...,"az":...,"gx":...,"gy":...,"gz":...}`)
|
||||||
- Clock config with HSE + HSI fallback
|
- Clock config with HSE + HSI fallback
|
||||||
- Reboot-to-DFU via USB 'R' command
|
- Reboot-to-DFU via USB 'R' command
|
||||||
- LED status patterns (status.c)
|
- LED status patterns (status.c)
|
||||||
- Web UI with WebSerial + Three.js 3D visualization
|
- Web UI with WebSerial + Three.js 3D visualization
|
||||||
|
|
||||||
### Broken / In Progress
|
### Broken / In Progress
|
||||||
- **ICM-42688-P SPI reads return all zeros** — was the original IMU target, but SPI communication completely non-functional despite correct pin config. May be dead silicon. Switched to MPU6000 as primary.
|
- **QMI8658-P SPI reads return all zeros** — was the original IMU target, but SPI communication completely non-functional despite correct pin config. May be dead silicon. Switched to MPU6000 as primary.
|
||||||
- **MPU6000 driver** — header exists but implementation needs completion
|
- **MPU6000 driver** — header exists but implementation needs completion
|
||||||
- **PID balance loop** — not yet implemented
|
- **PID balance loop** — not yet implemented
|
||||||
- **Hoverboard ESC UART** — protocol defined, driver not written
|
- **Hoverboard ESC UART** — protocol defined, driver not written
|
||||||
@ -243,7 +285,7 @@ T:12.3,P:45,L:100,R:-80,S:3\n
|
|||||||
// T=tilt°, P=PID output, L/R=motor commands, S=state (0-3)
|
// T=tilt°, P=PID output, L/R=motor commands, S=state (0-3)
|
||||||
```
|
```
|
||||||
|
|
||||||
### FC → USB CDC (50Hz JSON)
|
### FC → USB Serial (CH343) (50Hz JSON)
|
||||||
```json
|
```json
|
||||||
{"ax":123,"ay":-456,"az":16384,"gx":10,"gy":-5,"gz":3,"t":250,"p":0,"bt":0}
|
{"ax":123,"ay":-456,"az":16384,"gx":10,"gy":-5,"gz":3,"t":250,"p":0,"bt":0}
|
||||||
// Raw IMU values (int16), t=temp×10, p=pressure, bt=baro temp
|
// Raw IMU values (int16), t=temp×10, p=pressure, bt=baro temp
|
||||||
|
|||||||
@ -1,6 +1,10 @@
|
|||||||
# Face LCD Animation System (Issue #507)
|
# Face LCD Animation System (Issue #507)
|
||||||
|
|
||||||
Implements expressive face animations on an STM32 LCD display with 5 core emotions and smooth transitions.
|
<<<<<<< HEAD
|
||||||
|
Implements expressive face animations on an ESP32 LCD display with 5 core emotions and smooth transitions.
|
||||||
|
=======
|
||||||
|
Implements expressive face animations on an ESP32-S3 LCD display with 5 core emotions and smooth transitions.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
@ -82,7 +86,11 @@ STATUS → Echo current emotion + idle state
|
|||||||
- Colors: Monochrome (1-bit) or RGB565
|
- Colors: Monochrome (1-bit) or RGB565
|
||||||
|
|
||||||
### Microcontroller
|
### Microcontroller
|
||||||
- STM32F7xx (Mamba F722S)
|
<<<<<<< HEAD
|
||||||
|
- ESP32xx (ESP32 BALANCE)
|
||||||
|
=======
|
||||||
|
- ESP32-S3xx (ESP32-S3 BALANCE)
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
- Available UART: USART3 (PB10=TX, PB11=RX)
|
- Available UART: USART3 (PB10=TX, PB11=RX)
|
||||||
- Clock: 216 MHz
|
- Clock: 216 MHz
|
||||||
|
|
||||||
|
|||||||
@ -81,7 +81,7 @@
|
|||||||
│ │
|
│ │
|
||||||
│ [RealSense D435i] │ ← Front-facing, angled down ~10°
|
│ [RealSense D435i] │ ← Front-facing, angled down ~10°
|
||||||
│ │ Height: ~400mm from ground
|
│ │ Height: ~400mm from ground
|
||||||
│ [Jetson Nano] │ ← Center, in ventilated enclosure
|
│ [Jetson Orin Nano Super] │ ← Center, in ventilated enclosure
|
||||||
│ [WiFi/4G module] │ Noctua fan draws air through
|
│ [WiFi/4G module] │ Noctua fan draws air through
|
||||||
│ │
|
│ │
|
||||||
│ [Speaker] [LEDs] │ ← Rear: audio feedback + status
|
│ [Speaker] [LEDs] │ ← Rear: audio feedback + status
|
||||||
@ -173,7 +173,7 @@ PACK1 ═╤═ PACK2 (parallel, XT60)
|
|||||||
│ │
|
│ │
|
||||||
│ └── UART TX/RX ──→ Jetson GPIO
|
│ └── UART TX/RX ──→ Jetson GPIO
|
||||||
│
|
│
|
||||||
├──→ DC-DC 36V→5V ──→ Jetson Nano (barrel jack 5V/4A)
|
├──→ DC-DC 36V→5V ──→ Jetson Orin Nano Super (barrel jack 5V/4A)
|
||||||
│ ──→ USB hub (sensors)
|
│ ──→ USB hub (sensors)
|
||||||
│
|
│
|
||||||
├──→ DC-DC 36V→12V ──→ LED strips
|
├──→ DC-DC 36V→12V ──→ LED strips
|
||||||
|
|||||||
@ -33,7 +33,7 @@ Self-balancing two-wheeled indoor robot with AI brain.
|
|||||||
|
|
||||||
| Component | Voltage | Current | Power (W) | Notes |
|
| Component | Voltage | Current | Power (W) | Notes |
|
||||||
|-----------|---------|---------|-----------|-------|
|
|-----------|---------|---------|-----------|-------|
|
||||||
| Jetson Nano | 5V | 2-4A | 10-20W | AI inference mode: ~15W avg |
|
| Jetson Orin Nano Super | 5V | 2-4A | 10-20W | AI inference mode: ~15W avg |
|
||||||
| RealSense D435i | 5V (USB) | 0.7A | 3.5W | Depth + RGB streaming |
|
| RealSense D435i | 5V (USB) | 0.7A | 3.5W | Depth + RGB streaming |
|
||||||
| RPLIDAR A1M8 | 5V | 0.5A | 2.5W | Spinning at 5.5Hz |
|
| RPLIDAR A1M8 | 5V | 0.5A | 2.5W | Spinning at 5.5Hz |
|
||||||
| BNO055 IMU | 3.3V | 0.01A | 0.04W | Negligible |
|
| BNO055 IMU | 3.3V | 0.01A | 0.04W | Negligible |
|
||||||
@ -80,7 +80,7 @@ Self-balancing two-wheeled indoor robot with AI brain.
|
|||||||
| Battery pack (1x) | 2500 | Estimated, weigh to verify |
|
| Battery pack (1x) | 2500 | Estimated, weigh to verify |
|
||||||
| 2x 8" hub motors | 2400 | ~1200g each with tire |
|
| 2x 8" hub motors | 2400 | ~1200g each with tire |
|
||||||
| ESC board | 150 | Single board |
|
| ESC board | 150 | Single board |
|
||||||
| Jetson Nano + heatsink | 280 | With Noctua fan |
|
| Jetson Orin Nano Super + heatsink | 280 | With Noctua fan |
|
||||||
| RealSense D435i | 72 | Very light |
|
| RealSense D435i | 72 | Very light |
|
||||||
| RPLIDAR A1M8 | 170 | With motor |
|
| RPLIDAR A1M8 | 170 | With motor |
|
||||||
| BNO055 breakout | 5 | Tiny |
|
| BNO055 breakout | 5 | Tiny |
|
||||||
@ -233,7 +233,7 @@ Self-balancing two-wheeled indoor robot with AI brain.
|
|||||||
0mm — Base plate
|
0mm — Base plate
|
||||||
30mm — Battery shelf (holds pack on its side)
|
30mm — Battery shelf (holds pack on its side)
|
||||||
150mm — ESC + DC-DC shelf
|
150mm — ESC + DC-DC shelf
|
||||||
250mm — Jetson Nano shelf
|
250mm — Jetson Orin Nano Super shelf
|
||||||
300mm — BNO055 (attached to spine directly)
|
300mm — BNO055 (attached to spine directly)
|
||||||
370mm — RealSense bracket (front-facing arm)
|
370mm — RealSense bracket (front-facing arm)
|
||||||
420mm — LIDAR standoff begins
|
420mm — LIDAR standoff begins
|
||||||
@ -325,7 +325,7 @@ Self-balancing two-wheeled indoor robot with AI brain.
|
|||||||
- [ ] Assemble spine onto base plate
|
- [ ] Assemble spine onto base plate
|
||||||
- [ ] Mount battery to lowest shelf (velcro straps)
|
- [ ] Mount battery to lowest shelf (velcro straps)
|
||||||
- [ ] Mount ESC + DC-DC converters
|
- [ ] Mount ESC + DC-DC converters
|
||||||
- [ ] Mount Jetson Nano on shelf, connect 5V power
|
- [ ] Mount Jetson Orin Nano Super on shelf, connect 5V power
|
||||||
- [ ] Wire Jetson UART → ESC UART
|
- [ ] Wire Jetson UART → ESC UART
|
||||||
- [ ] Install JetPack 4.6 on Jetson (if not already)
|
- [ ] Install JetPack 4.6 on Jetson (if not already)
|
||||||
- [ ] Write serial bridge: Jetson Python → ESC UART commands
|
- [ ] Write serial bridge: Jetson Python → ESC UART commands
|
||||||
|
|||||||
196
docs/SALTYLAB.md
196
docs/SALTYLAB.md
@ -1,6 +1,6 @@
|
|||||||
# SaltyLab — Self-Balancing Indoor Bot 🔬
|
# SAUL-TEE — Self-Balancing Wagon Robot 🔬
|
||||||
|
|
||||||
Two-wheeled, self-balancing robot for indoor AI/SLAM experiments.
|
Four-wheel wagon (870×510×550 mm, 23 kg). Full spec: `docs/SAUL-TEE-SYSTEM-REFERENCE.md`
|
||||||
|
|
||||||
## ⚠️ SAFETY — TOP PRIORITY
|
## ⚠️ SAFETY — TOP PRIORITY
|
||||||
|
|
||||||
@ -32,8 +32,8 @@ Two-wheeled, self-balancing robot for indoor AI/SLAM experiments.
|
|||||||
|------|--------|
|
|------|--------|
|
||||||
| 2x 8" pneumatic hub motors (36 PSI) | ✅ Have |
|
| 2x 8" pneumatic hub motors (36 PSI) | ✅ Have |
|
||||||
| 1x hoverboard ESC (FOC firmware) | ✅ Have |
|
| 1x hoverboard ESC (FOC firmware) | ✅ Have |
|
||||||
| 1x Drone FC (STM32F745 + MPU-6000) | ✅ Have — balance brain |
|
| 1x Drone FC (ESP32-S3 + QMI8658) | ✅ Have — balance brain |
|
||||||
| 1x Jetson Nano + Noctua fan | ✅ Have |
|
| 1x Jetson Orin Nano Super + Noctua fan | ✅ Have |
|
||||||
| 1x RealSense D435i | ✅ Have |
|
| 1x RealSense D435i | ✅ Have |
|
||||||
| 1x RPLIDAR A1M8 | ✅ Have |
|
| 1x RPLIDAR A1M8 | ✅ Have |
|
||||||
| 1x battery pack (36V) | ✅ Have |
|
| 1x battery pack (36V) | ✅ Have |
|
||||||
@ -49,20 +49,19 @@ Two-wheeled, self-balancing robot for indoor AI/SLAM experiments.
|
|||||||
| 1x BetaFPV ELRS 2.4GHz 1W TX module | ✅ Have — RC control + kill switch |
|
| 1x BetaFPV ELRS 2.4GHz 1W TX module | ✅ Have — RC control + kill switch |
|
||||||
| 1x ELRS receiver (matching) | ✅ Have — mounts on FC UART |
|
| 1x ELRS receiver (matching) | ✅ Have — mounts on FC UART |
|
||||||
|
|
||||||
### Drone FC Details — GEPRC GEP-F7 AIO
|
### ESP32-S3 BALANCE Board Details — Waveshare ESP32-S3 Touch LCD 1.28
|
||||||
- **MCU:** STM32F722RET6 (216MHz Cortex-M7, 512KB flash, 256KB RAM)
|
- **MCU:** ESP32-S3RET6 (Xtensa LX7 dual-core, 240MHz, 8MB Flash, 512KB SRAM)
|
||||||
- **IMU:** TDK ICM-42688-P (6-axis, 32kHz gyro, ultra-low noise, SPI) ← the good one!
|
- **IMU:** QMI8658 (6-axis, 32kHz gyro, ultra-low noise, SPI) ← the good one!
|
||||||
- **Flash:** 8MB Winbond W25Q64 (blackbox, unused)
|
- **Display:** 1.28" round LCD (GC9A01 driver, 240x240)
|
||||||
- **OSD:** AT7456E (unused)
|
- **DFU mode:** Hold BOOT button while plugging USB
|
||||||
- **4-in-1 ESC:** Built into AIO board (unused — we use hoverboard ESC)
|
- **Firmware:** Custom balance firmware (ESP-IDF / Arduino-ESP32)
|
||||||
- **DFU mode:** Hold yellow BOOT button while plugging USB
|
- **USB:** USB Serial via CH343 chip
|
||||||
- **Firmware:** Custom balance firmware (PlatformIO + STM32 HAL)
|
- **UART assignments:**
|
||||||
- **UART pads (confirmed from silkscreen):**
|
- UART0 → USB Serial (CH343) → debug/flash
|
||||||
- T1/R1 (bottom) → USART1 (PA9/PA10) → Jetson
|
- UART1 → Jetson Orin Nano Super
|
||||||
- T2/R2 (right top) → USART2 (PA2/PA3) → Hoverboard ESC
|
- UART2 → Hoverboard ESC
|
||||||
- T3/R3 (bottom) → USART3 (PB10/PB11) → ELRS receiver
|
- UART3 → ELRS receiver
|
||||||
- T4/R4 (bottom) → UART4 → spare
|
- UART4/5 → spare
|
||||||
- T5/R5 (right bottom) → UART5 → spare
|
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@ -74,7 +73,7 @@ Two-wheeled, self-balancing robot for indoor AI/SLAM experiments.
|
|||||||
│ RealSense │ ← Forward-facing depth+RGB
|
│ RealSense │ ← Forward-facing depth+RGB
|
||||||
│ D435i │
|
│ D435i │
|
||||||
├──────────────┤
|
├──────────────┤
|
||||||
│ Jetson Nano │ ← AI brain: navigation, person tracking
|
│ Jetson Orin Nano Super │ ← AI brain: navigation, person tracking
|
||||||
│ │ Sends velocity commands via UART
|
│ │ Sends velocity commands via UART
|
||||||
├──────────────┤
|
├──────────────┤
|
||||||
│ Drone FC │ ← Balance brain: IMU + PID @ 8kHz
|
│ Drone FC │ ← Balance brain: IMU + PID @ 8kHz
|
||||||
@ -92,145 +91,22 @@ Two-wheeled, self-balancing robot for indoor AI/SLAM experiments.
|
|||||||
└─────┘ └─────┘
|
└─────┘ └─────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
## Self-Balancing Control — Custom Firmware on Drone FC
|
## Self-Balancing Control — ESP32-S3 BALANCE Board
|
||||||
|
|
||||||
### Why a Drone FC?
|
> For full system architecture, firmware details, and protocol specs, see
|
||||||
The F745 board is just a premium STM32 dev board with a high-quality IMU (MPU-6000) already soldered on, proper voltage regulation, and multiple UARTs broken out. We write a lean custom balance firmware (~50 lines of C).
|
> **docs/SAUL-TEE-SYSTEM-REFERENCE.md**
|
||||||
|
|
||||||
### Architecture
|
The balance controller runs on the Waveshare ESP32-S3 Touch LCD 1.28 board
|
||||||
```
|
(ESP32-S3 BALANCE). It reads the onboard QMI8658 IMU at 8kHz, runs a PID
|
||||||
Jetson (speed+steer via UART1)
|
balance loop, and drives the hoverboard ESC via UART. Jetson Orin Nano Super
|
||||||
│
|
sends velocity commands over UART1. ELRS receiver on UART3 provides RC
|
||||||
▼
|
override and kill-switch capability.
|
||||||
Drone FC (F745 + MPU-6000)
|
|
||||||
│ - Reads IMU @ 8kHz (SPI)
|
|
||||||
│ - Runs PID balance loop
|
|
||||||
│ - Mixes balance correction + Jetson commands
|
|
||||||
│ - Outputs speed+steer via UART2
|
|
||||||
▼
|
|
||||||
Hoverboard ESC (FOC firmware)
|
|
||||||
│ - Receives UART commands
|
|
||||||
│ - Drives hub motors
|
|
||||||
▼
|
|
||||||
Left + Right wheels
|
|
||||||
```
|
|
||||||
|
|
||||||
- **No motor outputs used** — FC talks UART directly to hoverboard ESC
|
The legacy STM32 firmware (Mamba F722S era) has been archived to
|
||||||
- **Custom firmware only** — no third-party flight software
|
=======
|
||||||
- **Dead motor output irrelevant** — not using any PWM channels
|
The legacy STM32 firmware (STM32 era) has been archived to
|
||||||
|
`legacy/stm32/` and is no longer built or deployed.
|
||||||
### Wiring
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
```
|
|
||||||
Jetson UART1 Drone FC (UART1)
|
|
||||||
──────────── ────────────────
|
|
||||||
TX (Pin 8) ──→ RX
|
|
||||||
RX (Pin 10) ──→ TX
|
|
||||||
GND ──→ GND
|
|
||||||
|
|
||||||
Drone FC (UART2) Hoverboard ESC
|
|
||||||
──────────────── ──────────────
|
|
||||||
TX ──→ RX (serial input)
|
|
||||||
GND ──→ GND
|
|
||||||
5V (BEC) ←── ESC 5V out (powers FC)
|
|
||||||
|
|
||||||
ELRS Receiver Drone FC (UART3)
|
|
||||||
───────────── ────────────────
|
|
||||||
TX ──→ RX
|
|
||||||
RX ←── TX (for telemetry/binding)
|
|
||||||
GND ──→ GND
|
|
||||||
5V ←── 5V
|
|
||||||
```
|
|
||||||
|
|
||||||
### Custom Firmware (STM32 C)
|
|
||||||
|
|
||||||
```c
|
|
||||||
// Core balance loop — runs in timer interrupt @ 1-8kHz
|
|
||||||
void balance_loop(void) {
|
|
||||||
// 1. Read pitch angle from MPU-6000 (complementary filter)
|
|
||||||
float pitch = get_pitch_angle(); // SPI read + filter
|
|
||||||
|
|
||||||
// 2. Get velocity command from Jetson (updated async via UART1 RX)
|
|
||||||
float target_speed = jetson_cmd.speed; // -1000 to 1000
|
|
||||||
float target_steer = jetson_cmd.steer; // -1000 to 1000
|
|
||||||
|
|
||||||
// 3. PID on pitch error
|
|
||||||
// Target angle shifts with speed command (lean forward = go forward)
|
|
||||||
float target_angle = target_speed * SPEED_TO_ANGLE_FACTOR;
|
|
||||||
float error = target_angle - pitch;
|
|
||||||
|
|
||||||
integral += error * dt;
|
|
||||||
integral = clamp(integral, -MAX_I, MAX_I); // anti-windup
|
|
||||||
float derivative = (error - prev_error) / dt;
|
|
||||||
prev_error = error;
|
|
||||||
|
|
||||||
float output = Kp * error + Ki * integral + Kd * derivative;
|
|
||||||
|
|
||||||
// 4. Mix balance + steering → hoverboard ESC UART command
|
|
||||||
int16_t left = clamp(output + target_steer, -1000, 1000);
|
|
||||||
int16_t right = clamp(output - target_steer, -1000, 1000);
|
|
||||||
|
|
||||||
// 5. Send to hoverboard ESC via UART2
|
|
||||||
send_hoverboard_cmd(left, right);
|
|
||||||
|
|
||||||
// 6. Safety: kill motors if tipped beyond recovery
|
|
||||||
if (fabs(pitch) > MAX_TILT_DEG) {
|
|
||||||
send_hoverboard_cmd(0, 0);
|
|
||||||
disarm();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 7. Safety: RC kill switch (ELRS channel, checked every loop)
|
|
||||||
if (rc_channels.arm_switch == DISARMED) {
|
|
||||||
send_hoverboard_cmd(0, 0);
|
|
||||||
disarm();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 8. Safety: kill if Jetson UART heartbeat lost
|
|
||||||
if (millis() - jetson_last_rx > JETSON_TIMEOUT_MS) {
|
|
||||||
send_hoverboard_cmd(0, 0);
|
|
||||||
disarm();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 8. Safety: clamp output to max allowed speed
|
|
||||||
left = clamp(left, -max_speed_limit, max_speed_limit);
|
|
||||||
right = clamp(right, -max_speed_limit, max_speed_limit);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Hoverboard ESC UART Protocol
|
|
||||||
```c
|
|
||||||
typedef struct {
|
|
||||||
uint16_t start; // 0xABCD
|
|
||||||
int16_t speed; // -1000 to 1000 (left)
|
|
||||||
int16_t steer; // -1000 to 1000 (right)
|
|
||||||
uint16_t checksum; // XOR of all bytes
|
|
||||||
} HoverboardCmd;
|
|
||||||
// 115200 baud, send at loop rate
|
|
||||||
```
|
|
||||||
|
|
||||||
### Jetson → FC Protocol (simple custom)
|
|
||||||
```c
|
|
||||||
typedef struct {
|
|
||||||
uint8_t header; // 0xAA
|
|
||||||
int16_t speed; // -1000 to 1000
|
|
||||||
int16_t steer; // -1000 to 1000
|
|
||||||
uint8_t mode; // 0=idle, 1=balance, 2=follow, 3=RC
|
|
||||||
uint8_t checksum;
|
|
||||||
} JetsonCmd;
|
|
||||||
// 115200 baud, ~50Hz from Jetson is plenty
|
|
||||||
```
|
|
||||||
|
|
||||||
### PID Tuning
|
|
||||||
| Param | Starting Value | Notes |
|
|
||||||
|-------|---------------|-------|
|
|
||||||
| Kp | 30-50 | Main balance response |
|
|
||||||
| Ki | 0.5-2 | Drift correction |
|
|
||||||
| Kd | 0.5-2 | Damping oscillation |
|
|
||||||
| Loop rate | 1-8 kHz | Start at 1kHz, increase if needed |
|
|
||||||
| Max tilt | ±25° | Beyond this = cut motors, require re-arm |
|
|
||||||
| JETSON_TIMEOUT_MS | 200 | Kill motors if Jetson stops talking |
|
|
||||||
| max_speed_limit | 100 | Start at 10% (100/1000), increase gradually |
|
|
||||||
| SPEED_TO_ANGLE_FACTOR | 0.01-0.05 | How much lean per speed unit |
|
|
||||||
|
|
||||||
## LED Subsystem (ESP32-C3)
|
## LED Subsystem (ESP32-C3)
|
||||||
|
|
||||||
@ -280,8 +156,8 @@ GND ──→ Common ground
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Dev Tools
|
### Dev Tools
|
||||||
- **Flashing:** STM32CubeProgrammer via USB (DFU mode) or SWD
|
- **Flashing:** ESP32-S3CubeProgrammer via USB (DFU mode) or SWD
|
||||||
- **IDE:** PlatformIO + STM32 HAL, or STM32CubeIDE
|
- **IDE:** PlatformIO + ESP-IDF, or ESP32-S3CubeIDE
|
||||||
- **Debug:** SWD via ST-Link (or use FC's USB as virtual COM for printf debug)
|
- **Debug:** SWD via ST-Link (or use FC's USB as virtual COM for printf debug)
|
||||||
|
|
||||||
## Physical Design
|
## Physical Design
|
||||||
@ -348,7 +224,7 @@ GND ──→ Common ground
|
|||||||
|
|
||||||
## Software Stack
|
## Software Stack
|
||||||
|
|
||||||
### Jetson Nano
|
### Jetson Orin Nano Super
|
||||||
- **OS:** JetPack 4.6.1 (Ubuntu 18.04)
|
- **OS:** JetPack 4.6.1 (Ubuntu 18.04)
|
||||||
- **ROS2 Humble** (or Foxy) for:
|
- **ROS2 Humble** (or Foxy) for:
|
||||||
- `nav2` — navigation stack
|
- `nav2` — navigation stack
|
||||||
@ -375,8 +251,8 @@ GND ──→ Common ground
|
|||||||
- [ ] Install hardware kill switch inline with 36V battery (NC — press to kill)
|
- [ ] Install hardware kill switch inline with 36V battery (NC — press to kill)
|
||||||
- [ ] Set up ceiling tether point above test area (rated for >15kg)
|
- [ ] Set up ceiling tether point above test area (rated for >15kg)
|
||||||
- [ ] Clear test area: 3m radius, no loose items, shoes on
|
- [ ] Clear test area: 3m radius, no loose items, shoes on
|
||||||
- [ ] Set up PlatformIO project for STM32F745 (STM32 HAL)
|
- [ ] Set up PlatformIO project for ESP32-S3 (ESP-IDF)
|
||||||
- [ ] Write MPU-6000 SPI driver (read gyro+accel, complementary filter)
|
- [ ] Write QMI8658 SPI driver (read gyro+accel, complementary filter)
|
||||||
- [ ] Write PID balance loop with ALL safety checks:
|
- [ ] Write PID balance loop with ALL safety checks:
|
||||||
- ±25° tilt cutoff → disarm, require manual re-arm
|
- ±25° tilt cutoff → disarm, require manual re-arm
|
||||||
- Watchdog timer (50ms hardware WDT)
|
- Watchdog timer (50ms hardware WDT)
|
||||||
|
|||||||
222
docs/SAUL-TEE-SYSTEM-REFERENCE.md
Normal file
222
docs/SAUL-TEE-SYSTEM-REFERENCE.md
Normal file
@ -0,0 +1,222 @@
|
|||||||
|
# SAUL-TEE System Reference — SaltyLab ESP32 Architecture
|
||||||
|
*Authoritative source of truth for hardware, pins, protocols, and CAN assignments.*
|
||||||
|
*Spec from hal@Orin, 2026-04-04.*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
| Board | Role | MCU | USB chip |
|
||||||
|
|-------|------|-----|----------|
|
||||||
|
| **ESP32-S3 BALANCE** | PID balance loop, CAN→VESCs, LCD display | ESP32-S3 | CH343 USB-serial |
|
||||||
|
| **ESP32-S3 IO** | RC input, motor drivers, sensors, LEDs, peripherals | ESP32-S3 | JTAG USB (native) |
|
||||||
|
|
||||||
|
**Robot form factor:** 4-wheel wagon — 870 × 510 × 550 mm, ~23 kg
|
||||||
|
**Power:** 36 V LiPo, DC-DC → 5 V and 12 V rails
|
||||||
|
**Orin connection:** CANable2 USB → 500 kbps CAN (same bus as VESCs)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ESP32-S3 BALANCE
|
||||||
|
|
||||||
|
### Board
|
||||||
|
Waveshare ESP32-S3 Touch LCD 1.28
|
||||||
|
- GC9A01 round 240×240 LCD
|
||||||
|
- CST816S capacitive touch
|
||||||
|
- QMI8658 6-axis IMU (accel + gyro, SPI)
|
||||||
|
- CH343 USB-to-serial chip
|
||||||
|
|
||||||
|
### Pin Assignments
|
||||||
|
|
||||||
|
| Function | GPIO | Notes |
|
||||||
|
|----------|------|-------|
|
||||||
|
| **QMI8658 IMU (SPI)** | | |
|
||||||
|
| SCK | IO39 | |
|
||||||
|
| MOSI | IO38 | |
|
||||||
|
| MISO | IO40 | |
|
||||||
|
| CS | IO41 | |
|
||||||
|
| INT1 | IO42 | data-ready interrupt |
|
||||||
|
| **GC9A01 LCD (shares SPI bus)** | | |
|
||||||
|
| CS | IO12 | |
|
||||||
|
| DC | IO11 | |
|
||||||
|
| RST | IO10 | |
|
||||||
|
| BL | IO9 | PWM backlight |
|
||||||
|
| **CST816S Touch (I2C)** | | |
|
||||||
|
| SDA | IO4 | |
|
||||||
|
| SCL | IO5 | |
|
||||||
|
| INT | IO6 | |
|
||||||
|
| RST | IO7 | |
|
||||||
|
| **CAN — SN65HVD230 transceiver** | | 500 kbps |
|
||||||
|
| TX | IO43 | → SN65HVD230 TXD |
|
||||||
|
| RX | IO44 | ← SN65HVD230 RXD |
|
||||||
|
| **Inter-board UART (to IO board)** | | 460800 baud |
|
||||||
|
| TX | IO17 | |
|
||||||
|
| RX | IO18 | |
|
||||||
|
|
||||||
|
### Responsibilities
|
||||||
|
- Read QMI8658 @ 1 kHz (SPI, INT1-driven)
|
||||||
|
- Complementary filter → pitch angle
|
||||||
|
- PID balance loop (configurable Kp / Ki / Kd)
|
||||||
|
- Send VESC speed commands via CAN (ID 68 = left, ID 56 = right)
|
||||||
|
- Receive Orin velocity+mode commands via CAN (0x300–0x303)
|
||||||
|
- Receive IO board status (arming, RC, faults) via UART protocol
|
||||||
|
- Drive GC9A01 LCD: pitch, speed, battery %, error state
|
||||||
|
- Enforce tilt cutoff at ±25°; IWDG 50 ms timeout
|
||||||
|
- Publish telemetry on CAN 0x400–0x401 at 10 Hz
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ESP32-S3 IO
|
||||||
|
|
||||||
|
### Board
|
||||||
|
Bare ESP32-S3 devkit (JTAG USB)
|
||||||
|
|
||||||
|
### Pin Assignments
|
||||||
|
|
||||||
|
| Function | GPIO | Notes |
|
||||||
|
|----------|------|-------|
|
||||||
|
| **TBS Crossfire RC — UART0 (primary)** | | |
|
||||||
|
| RX | IO44 | CRSF frames from Crossfire RX |
|
||||||
|
| TX | IO43 | telemetry to Crossfire TX |
|
||||||
|
| **ELRS failover — UART2** | | active if CRSF absent >100 ms |
|
||||||
|
| RX | IO16 | |
|
||||||
|
| TX | IO17 | |
|
||||||
|
| **BTS7960 Motor Driver — Left** | | |
|
||||||
|
| RPWM | IO1 | forward PWM |
|
||||||
|
| LPWM | IO2 | reverse PWM |
|
||||||
|
| R_EN | IO3 | right enable |
|
||||||
|
| L_EN | IO4 | left enable |
|
||||||
|
| **BTS7960 Motor Driver — Right** | | |
|
||||||
|
| RPWM | IO5 | |
|
||||||
|
| LPWM | IO6 | |
|
||||||
|
| R_EN | IO7 | |
|
||||||
|
| L_EN | IO8 | |
|
||||||
|
| **I2C bus** | | |
|
||||||
|
| SDA | IO11 | |
|
||||||
|
| SCL | IO12 | |
|
||||||
|
| NFC (PN532 or similar) | I2C | |
|
||||||
|
| Barometer (BMP280/BMP388) | I2C | |
|
||||||
|
| ToF (VL53L0X/VL53L1X) | I2C | |
|
||||||
|
| **WS2812B LEDs** | | |
|
||||||
|
| Data | IO13 | |
|
||||||
|
| **Outputs** | | |
|
||||||
|
| Horn / buzzer | IO14 | PWM tone |
|
||||||
|
| Headlight | IO15 | PWM or digital |
|
||||||
|
| Fan | IO16 | (if ELRS not fitted on UART2) |
|
||||||
|
| **Inputs** | | |
|
||||||
|
| Arming button | IO9 | active-low, hold 3 s to arm |
|
||||||
|
| Kill switch sense | IO10 | hardware estop detect |
|
||||||
|
| **Inter-board UART (to BALANCE board)** | | 460800 baud |
|
||||||
|
| TX | IO18 | |
|
||||||
|
| RX | IO21 | |
|
||||||
|
|
||||||
|
### Responsibilities
|
||||||
|
- Parse CRSF frames (TBS Crossfire, primary)
|
||||||
|
- Parse ELRS frames (failover, activates if no CRSF for >100 ms)
|
||||||
|
- Drive BTS7960 left/right PWM motor drivers
|
||||||
|
- Read NFC, barometer, ToF via I2C
|
||||||
|
- Drive WS2812B LEDs (armed/fault/idle patterns)
|
||||||
|
- Control horn, headlight, fan, buzzer
|
||||||
|
- Manage arming: hold button 3 s while upright → send ARM to BALANCE
|
||||||
|
- Monitor kill switch input → immediate motor off + FAULT frame
|
||||||
|
- Forward RC + sensor data to BALANCE via binary UART protocol
|
||||||
|
- Report faults and RC-loss upstream
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Inter-Board Binary Protocol (UART @ 460800 baud)
|
||||||
|
|
||||||
|
```
|
||||||
|
[0xAA][LEN][TYPE][PAYLOAD × LEN bytes][CRC8]
|
||||||
|
```
|
||||||
|
- `0xAA` — start byte
|
||||||
|
- `LEN` — payload length in bytes (uint8)
|
||||||
|
- `TYPE` — message type (uint8)
|
||||||
|
- `CRC8` — CRC-8/MAXIM over TYPE + PAYLOAD bytes
|
||||||
|
|
||||||
|
### IO → BALANCE Messages
|
||||||
|
|
||||||
|
| TYPE | Name | Payload | Description |
|
||||||
|
|------|------|---------|-------------|
|
||||||
|
| 0x01 | RC_CMD | int16 throttle, int16 steer, uint8 flags | flags: bit0=armed, bit1=kill |
|
||||||
|
| 0x02 | SENSOR | uint16 tof_mm, int16 baro_delta_pa, uint8 nfc_present | |
|
||||||
|
| 0x03 | FAULT | uint8 fault_flags | bit0=rc_loss, bit1=motor_fault, bit2=estop |
|
||||||
|
|
||||||
|
### BALANCE → IO Messages
|
||||||
|
|
||||||
|
| TYPE | Name | Payload | Description |
|
||||||
|
|------|------|---------|-------------|
|
||||||
|
| 0x10 | STATE | int16 pitch_x100, int16 pid_out, uint8 error_state | |
|
||||||
|
| 0x11 | LED_CMD | uint8 pattern, uint8 r, uint8 g, uint8 b | |
|
||||||
|
| 0x12 | BUZZER | uint8 tone_id, uint16 duration_ms | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CAN Bus — 500 kbps
|
||||||
|
|
||||||
|
### Node Assignments
|
||||||
|
|
||||||
|
| Node | CAN ID | Role |
|
||||||
|
|------|--------|------|
|
||||||
|
| VESC Left motor | **68** | Receives speed/duty via VESC CAN protocol |
|
||||||
|
| VESC Right motor | **56** | Receives speed/duty via VESC CAN protocol |
|
||||||
|
| ESP32-S3 BALANCE | — | Sends VESC commands; publishes telemetry |
|
||||||
|
| Jetson Orin (CANable2) | — | Sends velocity commands; receives telemetry |
|
||||||
|
|
||||||
|
### Frame Table
|
||||||
|
|
||||||
|
| CAN ID | Direction | Description | Rate |
|
||||||
|
|--------|-----------|-------------|------|
|
||||||
|
| 0x300 | Orin → BALANCE | Velocity cmd: int16 speed_mmps, int16 steer_mrad | 20 Hz |
|
||||||
|
| 0x301 | Orin → BALANCE | PID tuning: float Kp, float Ki, float Kd (3×4B IEEE-754) | on demand |
|
||||||
|
| 0x302 | Orin → BALANCE | Mode: uint8 (0=off, 1=balance, 2=manual, 3=estop) | on demand |
|
||||||
|
| 0x303 | Orin → BALANCE | Config: uint16 tilt_limit_x100, uint16 max_speed_mmps | on demand |
|
||||||
|
| 0x400 | BALANCE → Orin | Telemetry A: int16 pitch_x100, int16 pid_out, int16 speed_mmps, uint8 state | 10 Hz |
|
||||||
|
| 0x401 | BALANCE → Orin | Telemetry B: int16 vesc_l_rpm, int16 vesc_r_rpm, uint16 battery_mv, uint8 faults | 10 Hz |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## RC Channel Mapping (TBS Crossfire / ELRS CRSF)
|
||||||
|
|
||||||
|
| CH | Function | Range (µs) | Notes |
|
||||||
|
|----|----------|------------|-------|
|
||||||
|
| 1 | Steer (Roll) | 988–2012 | ±100% → ±max steer |
|
||||||
|
| 2 | Throttle (Pitch) | 988–2012 | forward / back speed |
|
||||||
|
| 3 | Spare | 988–2012 | |
|
||||||
|
| 4 | Spare | 988–2012 | |
|
||||||
|
| 5 | ARM switch | <1500=disarm, >1500=arm | SB on TX |
|
||||||
|
| 6 | **ESTOP** | <1500=normal, >1500=kill | SC on TX — checked first every loop |
|
||||||
|
| 7 | Speed limit | 988–2012 | maps to 10–100% speed cap |
|
||||||
|
| 8 | Spare | | |
|
||||||
|
|
||||||
|
**RC loss:** No valid CRSF frame >100 ms → IO sends FAULT(rc_loss) → BALANCE cuts motors.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Safety Invariants
|
||||||
|
|
||||||
|
1. **Motors NEVER spin on power-on** — 3 s button hold required while upright
|
||||||
|
2. **Tilt cutoff ±25°** — immediate motor zero, manual re-arm required
|
||||||
|
3. **IWDG 50 ms** — firmware hang → motors cut
|
||||||
|
4. **ESTOP RC channel** checked first in every loop iteration
|
||||||
|
5. **Orin CAN timeout 500 ms** → revert to RC-only mode
|
||||||
|
6. **Speed hard cap** — start at 10%, increase in 10% increments only after stable tethered testing
|
||||||
|
7. **Never untethered** until stable for 5+ continuous minutes tethered
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## USB Debug Commands (both boards, serial console)
|
||||||
|
|
||||||
|
```
|
||||||
|
help list commands
|
||||||
|
status print pitch, PID state, CAN stats, UART stats
|
||||||
|
pid <Kp> <Ki> <Kd> set PID gains
|
||||||
|
arm arm (if upright and safe)
|
||||||
|
disarm disarm immediately
|
||||||
|
estop emergency stop (requires re-arm)
|
||||||
|
tilt_limit <deg> set tilt cutoff angle (default 25)
|
||||||
|
speed_limit <pct> set speed cap percentage (default 10)
|
||||||
|
can_stats CAN bus counters (tx/rx/errors/busoff)
|
||||||
|
uart_stats inter-board UART frame counters
|
||||||
|
reboot soft reboot
|
||||||
|
```
|
||||||
@ -2,7 +2,7 @@
|
|||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<title>GEPRC GEP-F722-45A AIO — Board Layout</title>
|
<title>GEPRC GEP-F722-45A AIO — Board Layout (Legacy / Archived)</title>
|
||||||
<style>
|
<style>
|
||||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
body { background: #1a1a2e; color: #eee; font-family: 'Courier New', monospace; display: flex; flex-direction: column; align-items: center; padding: 20px; }
|
body { background: #1a1a2e; color: #eee; font-family: 'Courier New', monospace; display: flex; flex-direction: column; align-items: center; padding: 20px; }
|
||||||
@ -112,8 +112,13 @@ h1 { color: #e94560; margin-bottom: 5px; font-size: 1.4em; }
|
|||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
<<<<<<< HEAD
|
||||||
|
<h1>🤖 GEPRC GEP-F722-45A AIO — SaltyLab Pinout (Legacy / Archived)</h1>
|
||||||
|
<p class="subtitle">ESP32RET6 + ICM-42688-P | Betaflight target: GEPR-GEPRC_F722_AIO</p>
|
||||||
|
=======
|
||||||
<h1>🤖 GEPRC GEP-F722-45A AIO — SaltyLab Pinout</h1>
|
<h1>🤖 GEPRC GEP-F722-45A AIO — SaltyLab Pinout</h1>
|
||||||
<p class="subtitle">STM32F722RET6 + ICM-42688-P | Betaflight target: GEPR-GEPRC_F722_AIO</p>
|
<p class="subtitle">ESP32-S3RET6 + ICM-42688-P | Betaflight target: GEPR-GEPRC_F722_AIO</p>
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<div class="board-wrap">
|
<div class="board-wrap">
|
||||||
@ -125,7 +130,11 @@ h1 { color: #e94560; margin-bottom: 5px; font-size: 1.4em; }
|
|||||||
<div class="mount br"></div>
|
<div class="mount br"></div>
|
||||||
|
|
||||||
<!-- MCU -->
|
<!-- MCU -->
|
||||||
<div class="mcu"><div class="dot"></div>STM32<br>F722RET6<br>216MHz</div>
|
<<<<<<< HEAD
|
||||||
|
<div class="mcu"><div class="dot"></div>ESP32<br>(legacy:<br>F722RET6)</div>
|
||||||
|
=======
|
||||||
|
<div class="mcu"><div class="dot"></div>ESP32-S3<br>F722RET6<br>216MHz</div>
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
<!-- IMU -->
|
<!-- IMU -->
|
||||||
<div class="imu">ICM<br>42688</div>
|
<div class="imu">ICM<br>42688</div>
|
||||||
@ -206,7 +215,7 @@ h1 { color: #e94560; margin-bottom: 5px; font-size: 1.4em; }
|
|||||||
<h2>🔌 UART Assignments</h2>
|
<h2>🔌 UART Assignments</h2>
|
||||||
<div class="legend-item">
|
<div class="legend-item">
|
||||||
<div class="swatch" style="background:#2196F3"></div>
|
<div class="swatch" style="background:#2196F3"></div>
|
||||||
<span><b>USART1</b> T1/R1 → Jetson Nano</span>
|
<span><b>USART1</b> T1/R1 → Jetson Orin Nano Super</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="legend-item">
|
<div class="legend-item">
|
||||||
<div class="swatch" style="background:#FF9800"></div>
|
<div class="swatch" style="background:#FF9800"></div>
|
||||||
|
|||||||
@ -1,131 +1,155 @@
|
|||||||
# SaltyLab Wiring Diagram
|
# SaltyLab / SAUL-TEE Wiring Reference
|
||||||
|
|
||||||
## System Overview
|
> ⚠️ **ARCHITECTURE CHANGE (2026-04-03):** Mamba F722S / STM32 retired.
|
||||||
|
> New stack: **ESP32-S3 BALANCE** + **ESP32-S3 IO** + VESCs on 500 kbps CAN.
|
||||||
|
> **Authoritative reference:** [`docs/SAUL-TEE-SYSTEM-REFERENCE.md`](SAUL-TEE-SYSTEM-REFERENCE.md)
|
||||||
|
> Historical STM32/Mamba wiring below is **obsolete** — retained for reference only.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ~~System Overview~~ (OBSOLETE — see SAUL-TEE-SYSTEM-REFERENCE.md)
|
||||||
|
|
||||||
```
|
```
|
||||||
┌─────────────────────────────────────────────────────────────────────┐
|
┌─────────────────────────────────────────────────────────────────────┐
|
||||||
│ ORIN NANO SUPER │
|
│ ORIN NANO SUPER │
|
||||||
│ (Top Plate — 25W) │
|
│ (Top Plate — 25W) │
|
||||||
│ │
|
│ │
|
||||||
│ USB-C ──── STM32 CDC (/dev/stm32-bridge, 921600 baud) │
|
<<<<<<< HEAD
|
||||||
|
│ USB-A ──── CANable2 USB-CAN adapter (slcan0, 500 kbps) │
|
||||||
|
│ USB-A ──── ESP32-S3 IO (/dev/esp32-io, 460800 baud) │
|
||||||
|
=======
|
||||||
|
│ USB-C ──── ESP32-S3 CDC (/dev/esp32-bridge, 921600 baud) │
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
│ USB-A1 ─── RealSense D435i (USB 3.1) │
|
│ USB-A1 ─── RealSense D435i (USB 3.1) │
|
||||||
│ USB-A2 ─── RPLIDAR A1M8 (via CP2102 adapter, 115200) │
|
│ USB-A2 ─── RPLIDAR A1M8 (via CP2102 adapter, 115200) │
|
||||||
│ USB-C* ─── SIM7600A 4G/LTE modem (ttyUSB0-2, AT cmds + PPP) │
|
│ USB-C* ─── SIM7600A 4G/LTE modem (ttyUSB0-2, AT cmds + PPP) │
|
||||||
│ USB ─────── Leap Motion Controller (hand/gesture tracking) │
|
│ USB ─────── Leap Motion Controller (hand/gesture tracking) │
|
||||||
│ CSI-A ──── ArduCam adapter → 2× IMX219 (front + left) │
|
│ CSI-A ──── ArduCam adapter → 2x IMX219 (front + left) │
|
||||||
│ CSI-B ──── ArduCam adapter → 2× IMX219 (rear + right) │
|
│ CSI-B ──── ArduCam adapter → 2x IMX219 (rear + right) │
|
||||||
│ M.2 ───── 1TB NVMe SSD │
|
│ M.2 ───── 1TB NVMe SSD │
|
||||||
│ 40-pin ─── ReSpeaker 2-Mic HAT (I2S + I2C, WM8960 codec) │
|
│ 40-pin ─── ReSpeaker 2-Mic HAT (I2S + I2C, WM8960 codec) │
|
||||||
│ Pin 8 ──┐ │
|
│ Pin 8 ──┐ │
|
||||||
│ Pin 10 ─┤ UART fallback to FC (ttyTHS0, 921600) │
|
│ Pin 10 ─┤ UART fallback to ESP32-S3 BALANCE (ttyTHS0, 460800) │
|
||||||
│ Pin 6 ──┘ GND │
|
│ Pin 6 ──┘ GND │
|
||||||
│ │
|
│ │
|
||||||
└─────────────────────────────────────────────────────────────────────┘
|
└─────────────────────────────────────────────────────────────────────┘
|
||||||
│ USB-C (data only) │ UART fallback (3 wires)
|
│ USB-A (CANable2) │ UART fallback (3 wires)
|
||||||
│ 921600 baud │ 921600 baud, 3.3V
|
│ SocketCAN slcan0 │ 460800 baud, 3.3V
|
||||||
|
│ 500 kbps │
|
||||||
▼ ▼
|
▼ ▼
|
||||||
┌─────────────────────────────────────────────────────────────────────┐
|
┌─────────────────────────────────────────────────────────────────────┐
|
||||||
│ MAMBA F722S (FC) │
|
<<<<<<< HEAD
|
||||||
|
│ ESP32-S3 BALANCE │
|
||||||
|
│ (Waveshare Touch LCD 1.28, Middle Plate) │
|
||||||
|
=======
|
||||||
|
│ ESP32-S3 BALANCE (FC) │
|
||||||
│ (Middle Plate — foam mounted) │
|
│ (Middle Plate — foam mounted) │
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
│ │
|
│ │
|
||||||
│ USB-C ──── Orin (CDC serial, primary link) │
|
│ CAN bus ──── CANable2 → Orin (primary link, ISO 11898) │
|
||||||
│ │
|
│ UART0 ──── Orin UART fallback (460800 baud, 3.3V) │
|
||||||
│ USART2 (PA2=TX, PA3=RX) ──── Hoverboard ESC (26400 baud) │
|
│ UART1 ──── VESC Left (CAN ID 56) via UART/CAN bridge │
|
||||||
│ UART4 (PA0=TX, PA1=RX) ──── ELRS RX (CRSF, 420000 baud) │
|
│ UART2 ──── VESC Right (CAN ID 68) via UART/CAN bridge │
|
||||||
│ USART6 (PC6=TX, PC7=RX) ──── Orin UART fallback │
|
│ I2C ──── QMI8658 IMU (onboard, 6-DOF accel+gyro) │
|
||||||
│ UART5 (PC12=TX, PD2=RX) ─── Debug (optional) │
|
│ SPI ──── GC9A01 LCD (onboard, 240x240 round display) │
|
||||||
│ │
|
│ GPIO ──── WS2812B LED strip │
|
||||||
│ SPI1 ─── MPU6000 IMU (on-board, CW270) │
|
│ GPIO ──── Buzzer │
|
||||||
│ I2C1 ─── BMP280 baro (on-board, disabled) │
|
│ ADC ──── Battery voltage divider │
|
||||||
│ ADC ──── Battery voltage (PC1) + Current (PC3) │
|
|
||||||
│ PB3 ──── WS2812B LED strip │
|
|
||||||
│ PB2 ──── Buzzer │
|
|
||||||
│ │
|
│ │
|
||||||
└─────────────────────────────────────────────────────────────────────┘
|
└─────────────────────────────────────────────────────────────────────┘
|
||||||
│ USART2 │ UART4
|
│ CAN bus (ISO 11898) │ UART (460800 baud)
|
||||||
│ PA2=TX → ESC RX │ PA0=TX → ELRS TX
|
│ 500 kbps │
|
||||||
│ PA3=RX ← ESC TX │ PA1=RX ← ELRS RX
|
|
||||||
│ GND ─── GND │ GND ─── GND
|
|
||||||
▼ ▼
|
▼ ▼
|
||||||
┌────────────────────────┐ ┌──────────────────────────┐
|
┌────────────────────────┐ ┌──────────────────────────┐
|
||||||
│ HOVERBOARD ESC │ │ ELRS 2.4GHz RX │
|
│ VESC Left (ID 56) │ │ VESC Right (ID 68) │
|
||||||
│ (Bottom Plate) │ │ (beside FC) │
|
│ (Bottom Plate) │ │ (Bottom Plate) │
|
||||||
|
│ │ │ │
|
||||||
|
│ BLDC hub motor │ │ BLDC hub motor │
|
||||||
|
│ CAN 500 kbps │ │ CAN 500 kbps │
|
||||||
|
│ FOC current control │ │ FOC current control │
|
||||||
|
│ VESC Status 1 (0x900) │ │ VESC Status 1 (0x910) │
|
||||||
│ │ │ │
|
│ │ │ │
|
||||||
│ 2× BLDC hub motors │ │ CRSF protocol │
|
|
||||||
│ 26400 baud UART │ │ 420000 baud │
|
|
||||||
│ Frame: [0xABCD] │ │ BetaFPV 1W TX → RX │
|
|
||||||
│ [steer][speed][csum] │ │ CH3=speed CH4=steer │
|
|
||||||
│ │ │ CH5=arm CH6=mode │
|
|
||||||
└────────────────────────┘ └──────────────────────────┘
|
└────────────────────────┘ └──────────────────────────┘
|
||||||
│
|
│ │
|
||||||
┌────┴────┐
|
LEFT MOTOR RIGHT MOTOR
|
||||||
▼ ▼
|
```
|
||||||
🛞 LEFT RIGHT 🛞
|
|
||||||
MOTOR MOTOR
|
|
||||||
|
|
||||||
|
|
||||||
## Wire-by-Wire Connections
|
## Wire-by-Wire Connections
|
||||||
|
|
||||||
### 1. Orin ↔ FC (Primary: USB CDC)
|
<<<<<<< HEAD
|
||||||
|
### 1. Orin <-> ESP32-S3 BALANCE (Primary: CAN Bus via CANable2)
|
||||||
|
=======
|
||||||
|
### 1. Orin ↔ FC (Primary: USB Serial (CH343))
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
| From | To | Wire Color | Notes |
|
| From | To | Wire | Notes |
|
||||||
|------|----|-----------|-------|
|
|------|----|------|-------|
|
||||||
| Orin USB-C port | FC USB-C port | USB cable | Data only, FC powered from 5V bus |
|
| Orin USB-A | CANable2 USB | USB cable | SocketCAN slcan0 @ 500 kbps |
|
||||||
|
| CANable2 CAN-H | ESP32-S3 BALANCE CAN-H | twisted pair | ISO 11898 differential |
|
||||||
|
| CANable2 CAN-L | ESP32-S3 BALANCE CAN-L | twisted pair | ISO 11898 differential |
|
||||||
|
|
||||||
- Device: `/dev/ttyACM0` → symlink `/dev/stm32-bridge`
|
<<<<<<< HEAD
|
||||||
|
- Interface: SocketCAN `slcan0`, 500 kbps
|
||||||
|
- Device node: `/dev/canable2` (via udev, symlink to ttyUSBx)
|
||||||
|
- Protocol: CAN frames --- ORIN_CMD_DRIVE (0x300), ORIN_CMD_MODE (0x301), ORIN_CMD_ESTOP (0x302)
|
||||||
|
- Telemetry: BALANCE_STATUS (0x400), BALANCE_VESC (0x401), BALANCE_IMU (0x402), BALANCE_BATTERY (0x403)
|
||||||
|
=======
|
||||||
|
- Device: `/dev/ttyACM0` → symlink `/dev/esp32-bridge`
|
||||||
- Baud: 921600, 8N1
|
- Baud: 921600, 8N1
|
||||||
- Protocol: JSON telemetry (FC→Orin), ASCII commands (Orin→FC)
|
- Protocol: JSON telemetry (FC→Orin), ASCII commands (Orin→FC)
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
### 2. Orin ↔ FC (Fallback: Hardware UART)
|
### 2. Orin <-> ESP32-S3 BALANCE (Fallback: Hardware UART)
|
||||||
|
|
||||||
| Orin Pin | Signal | FC Pin | FC Signal |
|
| Orin Pin | Signal | ESP32-S3 Pin | Notes |
|
||||||
|----------|--------|--------|-----------|
|
|----------|--------|--------------|-------|
|
||||||
| Pin 8 | TXD0 | PC7 | USART6 RX |
|
| Pin 8 | TXD0 | GPIO17 (UART0 RX) | Orin TX -> BALANCE RX |
|
||||||
| Pin 10 | RXD0 | PC6 | USART6 TX |
|
| Pin 10 | RXD0 | GPIO18 (UART0 TX) | Orin RX <- BALANCE TX |
|
||||||
| Pin 6 | GND | GND | GND |
|
| Pin 6 | GND | GND | Common ground |
|
||||||
|
|
||||||
- Jetson device: `/dev/ttyTHS0`
|
- Jetson device: `/dev/ttyTHS0`
|
||||||
- Baud: 921600, 8N1
|
- Baud: 460800, 8N1
|
||||||
- Voltage: 3.3V both sides (no level shifter needed)
|
- Voltage: 3.3V both sides (no level shifter needed)
|
||||||
- **Cross-connect:** Orin TX → FC RX, Orin RX ← FC TX
|
- Cross-connect: Orin TX -> BALANCE RX, Orin RX <- BALANCE TX
|
||||||
|
|
||||||
### 3. FC ↔ Hoverboard ESC
|
### 3. Orin <-> ESP32-S3 IO (USB Serial)
|
||||||
|
|
||||||
| FC Pin | Signal | ESC Pin | Notes |
|
| From | To | Notes |
|
||||||
|--------|--------|---------|-------|
|
|------|----|-------|
|
||||||
| PA2 | USART2 TX | RX | FC sends speed/steer commands |
|
| Orin USB-A | ESP32-S3 IO USB-C | USB cable, /dev/esp32-io |
|
||||||
| PA3 | USART2 RX | TX | ESC sends feedback (optional) |
|
|
||||||
|
- Device node: `/dev/esp32-io` (udev symlink)
|
||||||
|
- Baud: 460800, 8N1
|
||||||
|
- Protocol: Binary frames `[0xAA][LEN][TYPE][PAYLOAD][CRC8]`
|
||||||
|
- Use: IO expansion, GPIO control, sensor polling
|
||||||
|
|
||||||
|
### 4. ESP32-S3 BALANCE <-> VESC Motors (CAN Bus)
|
||||||
|
|
||||||
|
| BALANCE Pin | Signal | VESC Pin | Notes |
|
||||||
|
|-------------|--------|----------|-------|
|
||||||
|
| GPIO21 | CAN-H | CAN-H | ISO 11898 differential pair |
|
||||||
|
| GPIO22 | CAN-L | CAN-L | ISO 11898 differential pair |
|
||||||
| GND | GND | GND | Common ground |
|
| GND | GND | GND | Common ground |
|
||||||
|
|
||||||
- Baud: 26400, 8N1
|
- Baud: 500 kbps CAN
|
||||||
- Protocol: Binary frame — `[0xABCD][steer:int16][speed:int16][checksum:uint16]`
|
- VESC Left: CAN ID 56, VESC Right: CAN ID 68
|
||||||
- Speed range: -1000 to +1000
|
- Commands: COMM_SET_RPM, COMM_SET_CURRENT, COMM_SET_DUTY
|
||||||
- **Keep wires short and twisted** (EMI from ESC)
|
- Telemetry: VESC Status 1 at 50 Hz (RPM, current, duty)
|
||||||
|
|
||||||
### 4. FC ↔ ELRS Receiver
|
|
||||||
|
|
||||||
| FC Pin | Signal | ELRS Pin | Notes |
|
|
||||||
|--------|--------|----------|-------|
|
|
||||||
| PA0 | UART4 TX | RX | Telemetry to TX (optional) |
|
|
||||||
| PA1 | UART4 RX | TX | CRSF frames from RX |
|
|
||||||
| GND | GND | GND | Common ground |
|
|
||||||
| 5V | — | VCC | Power ELRS from 5V bus |
|
|
||||||
|
|
||||||
- Baud: 420000 (CRSF protocol)
|
|
||||||
- Failsafe: disarm after 300ms without frame
|
|
||||||
|
|
||||||
### 5. Power Distribution
|
### 5. Power Distribution
|
||||||
|
|
||||||
```
|
```
|
||||||
BATTERY (36V) ──┬── Hoverboard ESC (36V direct)
|
BATTERY (36V) ──┬── VESC Left (36V direct -> BLDC left motor)
|
||||||
|
├── VESC Right (36V direct -> BLDC right motor)
|
||||||
│
|
│
|
||||||
├── 5V BEC/regulator ──┬── Orin (USB-C PD or barrel jack)
|
├── 5V BEC/regulator ──┬── Orin (USB-C PD or barrel jack)
|
||||||
│ ├── FC (via USB or 5V pad)
|
│ ├── ESP32-S3 BALANCE (5V via USB-C)
|
||||||
│ ├── ELRS RX (5V)
|
│ ├── ESP32-S3 IO (5V via USB-C)
|
||||||
│ ├── WS2812B LEDs (5V)
|
│ ├── WS2812B LEDs (5V)
|
||||||
│ └── RPLIDAR (5V via USB)
|
│ └── RPLIDAR (5V via USB)
|
||||||
│
|
│
|
||||||
└── Battery monitor ──── FC ADC (PC1=voltage, PC3=current)
|
└── Battery monitor ──── ESP32-S3 BALANCE ADC (voltage divider)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 6. Sensors on Orin (USB/CSI)
|
### 6. Sensors on Orin (USB/CSI)
|
||||||
@ -136,10 +160,39 @@ BATTERY (36V) ──┬── Hoverboard ESC (36V direct)
|
|||||||
| RPLIDAR A1M8 | USB-UART | USB-A | `/dev/rplidar` |
|
| RPLIDAR A1M8 | USB-UART | USB-A | `/dev/rplidar` |
|
||||||
| IMX219 front+left | MIPI CSI-2 | CSI-A (J5) | `/dev/video0,2` |
|
| IMX219 front+left | MIPI CSI-2 | CSI-A (J5) | `/dev/video0,2` |
|
||||||
| IMX219 rear+right | MIPI CSI-2 | CSI-B (J8) | `/dev/video4,6` |
|
| IMX219 rear+right | MIPI CSI-2 | CSI-B (J8) | `/dev/video4,6` |
|
||||||
| 1TB NVMe | PCIe Gen3 ×4 | M.2 Key M | `/dev/nvme0n1` |
|
| 1TB NVMe | PCIe Gen3 x4 | M.2 Key M | `/dev/nvme0n1` |
|
||||||
|
| CANable2 | USB-CAN | USB-A | `/dev/canable2` -> `slcan0` |
|
||||||
|
|
||||||
|
|
||||||
## FC UART Summary (MAMBA F722S)
|
<<<<<<< HEAD
|
||||||
|
## FC UART Summary (MAMBA F722S — OBSOLETE)
|
||||||
|
|
||||||
|
| Interface | Pins | Baud/Rate | Assignment | Notes |
|
||||||
|
|-----------|------|-----------|------------|-------|
|
||||||
|
| UART0 | GPIO17=RX, GPIO18=TX | 460800 | Orin UART fallback | 3.3V, cross-connect |
|
||||||
|
| UART1 | GPIO19=RX, GPIO20=TX | 115200 | Debug serial | Optional |
|
||||||
|
| CAN (TWAI) | GPIO21=H, GPIO22=L | 500 kbps | CAN bus (VESCs + Orin) | SN65HVD230 transceiver |
|
||||||
|
| I2C | GPIO4=SDA, GPIO5=SCL | 400 kHz | QMI8658 IMU (addr 0x6B) | Onboard |
|
||||||
|
| SPI | GPIO36=MOSI, GPIO37=SCLK, GPIO35=CS | 40 MHz | GC9A01 LCD (onboard) | 240x240 round |
|
||||||
|
| USB CDC | USB-C | 460800 | Orin USB fallback | /dev/esp32-balance |
|
||||||
|
|
||||||
|
## CAN Frame ID Map
|
||||||
|
|
||||||
|
| CAN ID | Direction | Name | Contents |
|
||||||
|
|--------|-----------|------|----------|
|
||||||
|
| 0x300 | Orin -> BALANCE | ORIN_CMD_DRIVE | left_rpm_f32, right_rpm_f32 (8 bytes LE) |
|
||||||
|
| 0x301 | Orin -> BALANCE | ORIN_CMD_MODE | mode byte (0=IDLE, 1=DRIVE, 2=ESTOP) |
|
||||||
|
| 0x302 | Orin -> BALANCE | ORIN_CMD_ESTOP | flags byte (bit0=stop, bit1=clear) |
|
||||||
|
| 0x400 | BALANCE -> Orin | BALANCE_STATUS | pitch x10:i16, motor_cmd:u16, vbat_mv:u16, state:u8, flags:u8 |
|
||||||
|
| 0x401 | BALANCE -> Orin | BALANCE_VESC | l_rpm x10:i16, r_rpm x10:i16, l_cur x10:i16, r_cur x10:i16 |
|
||||||
|
| 0x402 | BALANCE -> Orin | BALANCE_IMU | pitch x100:i16, roll x100:i16, yaw x100:i16, ax x100:i16, ay x100:i16, az x100:i16 |
|
||||||
|
| 0x403 | BALANCE -> Orin | BALANCE_BATTERY | vbat_mv:u16, current_ma:i16, soc_pct:u8 |
|
||||||
|
| 0x900+ID | VESC Left -> | VESC_STATUS_1 | erpm:i32, current x10:i16, duty x1000:i16 |
|
||||||
|
| 0x910+ID | VESC Right -> | VESC_STATUS_1 | erpm:i32, current x10:i16, duty x1000:i16 |
|
||||||
|
|
||||||
|
VESC Left CAN ID = 56 (0x38), VESC Right CAN ID = 68 (0x44).
|
||||||
|
=======
|
||||||
|
## FC UART Summary (ESP32-S3 BALANCE)
|
||||||
|
|
||||||
| UART | Pins | Baud | Assignment | Notes |
|
| UART | Pins | Baud | Assignment | Notes |
|
||||||
|------|------|------|------------|-------|
|
|------|------|------|------------|-------|
|
||||||
@ -149,7 +202,8 @@ BATTERY (36V) ──┬── Hoverboard ESC (36V direct)
|
|||||||
| UART4 | PA0=TX, PA1=RX | 420000 | ELRS RX (CRSF) | RC control |
|
| UART4 | PA0=TX, PA1=RX | 420000 | ELRS RX (CRSF) | RC control |
|
||||||
| UART5 | PC12=TX, PD2=RX | 115200 | Debug serial | Optional |
|
| UART5 | PC12=TX, PD2=RX | 115200 | Debug serial | Optional |
|
||||||
| USART6 | PC6=TX, PC7=RX | 921600 | Jetson UART | Fallback link |
|
| USART6 | PC6=TX, PC7=RX | 921600 | Jetson UART | Fallback link |
|
||||||
| USB CDC | USB-C | 921600 | Jetson primary | `/dev/stm32-bridge` |
|
| USB Serial (CH343) | USB-C | 921600 | Jetson primary | `/dev/esp32-bridge` |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
|
|
||||||
### 7. ReSpeaker 2-Mic HAT (on Orin 40-pin header)
|
### 7. ReSpeaker 2-Mic HAT (on Orin 40-pin header)
|
||||||
@ -167,57 +221,63 @@ BATTERY (36V) ──┬── Hoverboard ESC (36V direct)
|
|||||||
| Pin 2, 4 | 5V | Power |
|
| Pin 2, 4 | 5V | Power |
|
||||||
| Pin 6, 9 | GND | Ground |
|
| Pin 6, 9 | GND | Ground |
|
||||||
|
|
||||||
- **Codec:** Wolfson WM8960 (I2C addr 0x1A)
|
- Codec: Wolfson WM8960 (I2C addr 0x1A)
|
||||||
- **Mics:** 2× MEMS (left + right) — basic stereo / sound localization
|
- Mics: 2x MEMS (left + right) --- basic stereo / sound localization
|
||||||
- **Speaker:** 3W class-D amp output (JST connector)
|
- Speaker: 3W class-D amp output (JST connector)
|
||||||
- **Headset:** 3.5mm TRRS jack
|
- Headset: 3.5mm TRRS jack
|
||||||
- **Requires:** WM8960 device tree overlay for Jetson (community port)
|
- Requires: WM8960 device tree overlay for Jetson (community port)
|
||||||
- **Use:** Voice commands (faster-whisper), wake word (openWakeWord), audio feedback, status announcements
|
- Use: Voice commands (faster-whisper), wake word (openWakeWord), audio feedback, status announcements
|
||||||
|
|
||||||
### 8. SIM7600A 4G/LTE HAT (via USB)
|
### 8. SIM7600A 4G/LTE HAT (via USB)
|
||||||
|
|
||||||
| Connection | Detail |
|
| Connection | Detail |
|
||||||
|-----------|--------|
|
|-----------|--------|
|
||||||
| Interface | USB (micro-B on HAT → USB-A/C on Orin) |
|
| Interface | USB (micro-B on HAT -> USB-A/C on Orin) |
|
||||||
| Device nodes | `/dev/ttyUSB0` (AT), `/dev/ttyUSB1` (PPP/data), `/dev/ttyUSB2` (GPS NMEA) |
|
| Device nodes | `/dev/ttyUSB0` (AT), `/dev/ttyUSB1` (PPP/data), `/dev/ttyUSB2` (GPS NMEA) |
|
||||||
| Power | 5V from USB or separate 5V supply (peak 2A during TX) |
|
| Power | 5V from USB or separate 5V supply (peak 2A during TX) |
|
||||||
| SIM | Nano-SIM slot on HAT |
|
| SIM | Nano-SIM slot on HAT |
|
||||||
| Antenna | 4G LTE + GPS/GNSS (external SMA antennas — mount high on chassis) |
|
| Antenna | 4G LTE + GPS/GNSS (external SMA antennas --- mount high on chassis) |
|
||||||
|
|
||||||
- **Data:** PPP or QMI for internet connectivity
|
- Data: PPP or QMI for internet connectivity
|
||||||
- **GPS/GNSS:** Built-in receiver, NMEA sentences on ttyUSB2 — outdoor positioning
|
- GPS/GNSS: Built-in receiver, NMEA sentences on ttyUSB2 --- outdoor positioning
|
||||||
- **AT commands:** `AT+CGPS=1` (enable GPS), `AT+CGPSINFO` (get fix)
|
- AT commands: `AT+CGPS=1` (enable GPS), `AT+CGPSINFO` (get fix)
|
||||||
- **Connected via USB** (not 40-pin) — avoids UART conflict with FC fallback, flexible antenna placement
|
- Connected via USB (not 40-pin) --- avoids UART conflict with BALANCE fallback, flexible antenna placement
|
||||||
- **Use:** Remote telemetry, 4G connectivity outdoors, GPS positioning, remote SSH/control
|
- Use: Remote telemetry, 4G connectivity outdoors, GPS positioning, remote SSH/control
|
||||||
|
|
||||||
### 10. Leap Motion Controller (USB)
|
### 9. Leap Motion Controller (USB)
|
||||||
|
|
||||||
| Connection | Detail |
|
| Connection | Detail |
|
||||||
|-----------|--------|
|
|-----------|--------|
|
||||||
| Interface | USB 3.0 (micro-B on controller → USB-A on Orin) |
|
| Interface | USB 3.0 (micro-B on controller -> USB-A on Orin) |
|
||||||
| Power | ~0.5W |
|
| Power | ~0.5W |
|
||||||
| Range | ~80cm, 150° FOV |
|
| Range | ~80cm, 150 deg FOV |
|
||||||
| SDK | Ultraleap Gemini V5+ (Linux ARM64 support) |
|
| SDK | Ultraleap Gemini V5+ (Linux ARM64 support) |
|
||||||
| ROS2 | `leap_motion_ros2` wrapper available |
|
| ROS2 | `leap_motion_ros2` wrapper available |
|
||||||
|
|
||||||
- **2× IR cameras + 3× IR LEDs** — tracks all 10 fingers in 3D, sub-mm precision
|
- 2x IR cameras + 3x IR LEDs --- tracks all 10 fingers in 3D, sub-mm precision
|
||||||
- **Mount:** Forward-facing on sensor tower or upward on Orin plate
|
- Mount: Forward-facing on sensor tower or upward on Orin plate
|
||||||
- **Use:** Gesture control (palm=stop, point=go, fist=arm), hand-following mode, demos
|
- Use: Gesture control (palm=stop, point=go, fist=arm), hand-following mode, demos
|
||||||
- **Combined with ReSpeaker:** Voice + gesture control with zero hardware in hand
|
- Combined with ReSpeaker: Voice + gesture control with zero hardware in hand
|
||||||
|
|
||||||
### 11. Power Budget (USB)
|
### 10. Power Budget (USB)
|
||||||
|
|
||||||
| Device | Interface | Power Draw |
|
| Device | Interface | Power Draw |
|
||||||
|--------|-----------|------------|
|
|--------|-----------|------------|
|
||||||
| STM32 FC (CDC) | USB-C | ~0.5W (data only, FC on 5V bus) |
|
<<<<<<< HEAD
|
||||||
|
| CANable2 USB-CAN | USB-A | ~0.5W |
|
||||||
|
| ESP32-S3 BALANCE | USB-C | ~0.8W (WiFi off) |
|
||||||
|
| ESP32-S3 IO | USB-C | ~0.5W |
|
||||||
|
=======
|
||||||
|
| ESP32-S3 FC (CDC) | USB-C | ~0.5W (data only, FC on 5V bus) |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
| RealSense D435i | USB-A | ~1.5W (3.5W peak) |
|
| RealSense D435i | USB-A | ~1.5W (3.5W peak) |
|
||||||
| RPLIDAR A1M8 | USB-A | ~2.6W (motor on) |
|
| RPLIDAR A1M8 | USB-A | ~2.6W (motor on) |
|
||||||
| SIM7600A | USB | ~1W idle, 3W TX peak |
|
| SIM7600A | USB | ~1W idle, 3W TX peak |
|
||||||
| Leap Motion | USB | ~0.5W |
|
| Leap Motion | USB-A | ~0.5W |
|
||||||
| ReSpeaker HAT | 40-pin | ~0.5W |
|
| ReSpeaker HAT | 40-pin | ~0.5W |
|
||||||
| **Total USB** | | **~6.5W typical, ~10.5W peak** |
|
| **Total USB** | | **~7.9W typical, ~11W peak** |
|
||||||
|
|
||||||
Orin Nano Super delivers up to 25W — USB peripherals are well within budget.
|
Orin Nano Super delivers up to 25W --- USB peripherals are well within budget.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -225,38 +285,46 @@ Orin Nano Super delivers up to 25W — USB peripherals are well within budget.
|
|||||||
|
|
||||||
```
|
```
|
||||||
┌──────────────┐
|
┌──────────────┐
|
||||||
│ ELRS TX │ (in your hand)
|
│ RC TX │ (in your hand)
|
||||||
│ (2.4GHz) │
|
│ (2.4GHz) │
|
||||||
└──────┬───────┘
|
└──────┬───────┘
|
||||||
│ radio
|
│ radio
|
||||||
┌──────▼───────┐
|
┌──────▼───────┐
|
||||||
│ ELRS RX │ CRSF 420kbaud
|
│ RC RX │ CRSF 420kbaud (future)
|
||||||
└──────┬───────┘
|
└──────┬───────┘
|
||||||
│ UART4
|
│ UART
|
||||||
┌────────────▼────────────┐
|
┌────────────▼────────────┐
|
||||||
│ MAMBA F722S │
|
<<<<<<< HEAD
|
||||||
|
│ ESP32-S3 BALANCE │
|
||||||
|
│ (Waveshare LCD 1.28) │
|
||||||
|
=======
|
||||||
|
│ ESP32-S3 BALANCE │
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
│ │
|
│ │
|
||||||
│ MPU6000 → Balance PID │
|
│ QMI8658 -> Balance PID │
|
||||||
│ CRSF → Mode Manager │
|
│ RC -> Mode Manager │
|
||||||
│ Safety Monitor │
|
│ Safety Monitor │
|
||||||
│ │
|
│ │
|
||||||
└──┬──────────┬───────────┘
|
└──┬──────────┬───────────┘
|
||||||
USART2 ─────┘ └───── USB CDC / USART6
|
<<<<<<< HEAD
|
||||||
|
CAN 500kbps─┘ └───── CAN bus / UART fallback
|
||||||
|
=======
|
||||||
|
USART2 ─────┘ └───── USB Serial (CH343) / USART6
|
||||||
26400 baud 921600 baud
|
26400 baud 921600 baud
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
│ │
|
│ │
|
||||||
▼ ▼
|
┌────┴────────────┐ ▼
|
||||||
┌────────────────┐ ┌───────────────────┐
|
│ CAN bus (500k) │ ┌───────────────────┐
|
||||||
│ Hoverboard ESC │ │ Orin Nano Super │
|
├─ VESC Left 56 │ │ Orin Nano Super │
|
||||||
│ │ │ │
|
└─ VESC Right 68 │ │ │
|
||||||
│ L motor R motor│ │ SLAM / Nav2 / AI │
|
│ │ │ SLAM / Nav2 / AI │
|
||||||
│ 🛞 🛞 │ │ Person following │
|
▼ ▼ │ Person following │
|
||||||
└────────────────┘ │ Voice commands │
|
LEFT RIGHT │ Voice commands │
|
||||||
│ 4G telemetry │
|
MOTOR MOTOR │ 4G telemetry │
|
||||||
└──┬──────────┬───────┘
|
└──┬──────────┬───────┘
|
||||||
│ │
|
│ │
|
||||||
┌──────────▼─┐ ┌────▼──────────┐
|
┌──────────▼─┐ ┌────▼──────────┐
|
||||||
│ ReSpeaker │ │ SIM7600A │
|
│ ReSpeaker │ │ SIM7600A │
|
||||||
│ 2-Mic HAT │ │ 4G/LTE + GPS │
|
│ 2-Mic HAT │ │ 4G/LTE + GPS │
|
||||||
│ 🎤 🔊 │ │ 📡 🛰️ │
|
|
||||||
└────────────┘ └───────────────┘
|
└────────────┘ └───────────────┘
|
||||||
```
|
```
|
||||||
|
|||||||
30
esp32/uwb_anchor/platformio.ini
Normal file
30
esp32/uwb_anchor/platformio.ini
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
; SaltyBot UWB Anchor Firmware — Issue #544
|
||||||
|
; Target: Makerfabs ESP32 UWB Pro (DW3000 chip)
|
||||||
|
;
|
||||||
|
; Library: Makerfabs MaUWB_DW3000
|
||||||
|
; https://github.com/Makerfabs/MaUWB_DW3000
|
||||||
|
;
|
||||||
|
; Flash:
|
||||||
|
; pio run -e anchor0 --target upload (port-side anchor)
|
||||||
|
; pio run -e anchor1 --target upload (starboard anchor)
|
||||||
|
; Monitor:
|
||||||
|
; pio device monitor -e anchor0 -b 115200
|
||||||
|
|
||||||
|
[common]
|
||||||
|
platform = espressif32
|
||||||
|
board = esp32dev
|
||||||
|
framework = arduino
|
||||||
|
monitor_speed = 115200
|
||||||
|
upload_speed = 921600
|
||||||
|
lib_deps =
|
||||||
|
https://github.com/Makerfabs/MaUWB_DW3000.git
|
||||||
|
build_flags =
|
||||||
|
-DCORE_DEBUG_LEVEL=0
|
||||||
|
|
||||||
|
[env:anchor0]
|
||||||
|
extends = common
|
||||||
|
build_flags = ${common.build_flags} -DANCHOR_ID=0
|
||||||
|
|
||||||
|
[env:anchor1]
|
||||||
|
extends = common
|
||||||
|
build_flags = ${common.build_flags} -DANCHOR_ID=1
|
||||||
542
esp32/uwb_anchor/src/main.cpp
Normal file
542
esp32/uwb_anchor/src/main.cpp
Normal file
@ -0,0 +1,542 @@
|
|||||||
|
/*
|
||||||
|
* uwb_anchor — SaltyBot ESP32 UWB Pro anchor firmware (TWR responder)
|
||||||
|
* Issue #544
|
||||||
|
*
|
||||||
|
* Hardware: Makerfabs ESP32 UWB Pro (DW3000 chip)
|
||||||
|
*
|
||||||
|
* Role
|
||||||
|
* ────
|
||||||
|
* Anchor sits on SaltyBot body, USB-connected to Jetson Orin.
|
||||||
|
* Two anchors per robot (anchor-0 port side, anchor-1 starboard).
|
||||||
|
* Person-worn tags initiate ranging; anchors respond.
|
||||||
|
*
|
||||||
|
* Protocol: Double-Sided TWR (DS-TWR)
|
||||||
|
* ────────────────────────────────────
|
||||||
|
* Tag → Anchor POLL (msg_type 0x01)
|
||||||
|
* Anchor → Tag RESP (msg_type 0x02, payload: T_poll_rx, T_resp_tx)
|
||||||
|
* Tag → Anchor FINAL (msg_type 0x03, payload: Ra, Da, Db timestamps)
|
||||||
|
* Anchor computes range via DS-TWR formula, emits +RANGE on Serial.
|
||||||
|
*
|
||||||
|
* Serial output (115200 8N1, USB-CDC to Jetson)
|
||||||
|
* ──────────────────────────────────────────────
|
||||||
|
* +RANGE:<anchor_id>,<range_mm>,<rssi_dbm>\r\n (on each successful range)
|
||||||
|
*
|
||||||
|
* AT commands (host → anchor)
|
||||||
|
* ───────────────────────────
|
||||||
|
* AT+RANGE? → returns last buffered +RANGE line
|
||||||
|
* AT+RANGE_ADDR=<hex_addr> → pair with specific tag (filter others)
|
||||||
|
* AT+RANGE_ADDR= → clear pairing (accept all tags)
|
||||||
|
* AT+ID? → returns +ID:<anchor_id>
|
||||||
|
* AT+PEER_RANGE=<id> → inter-anchor DS-TWR (for auto-calibration)
|
||||||
|
* → +PEER_RANGE:<my>,<peer>,<mm>,<rssi>
|
||||||
|
*
|
||||||
|
* Pin mapping — Makerfabs ESP32 UWB Pro
|
||||||
|
* ──────────────────────────────────────
|
||||||
|
* SPI SCK 18 SPI MISO 19 SPI MOSI 23
|
||||||
|
* DW CS 21 DW RST 27 DW IRQ 34
|
||||||
|
*
|
||||||
|
* Build
|
||||||
|
* ──────
|
||||||
|
* pio run -e anchor0 --target upload (port side)
|
||||||
|
* pio run -e anchor1 --target upload (starboard)
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <SPI.h>
|
||||||
|
#include <math.h>
|
||||||
|
#include "dw3000.h" // Makerfabs MaUWB_DW3000 library
|
||||||
|
|
||||||
|
/* ── Configurable ───────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
#ifndef ANCHOR_ID
|
||||||
|
# define ANCHOR_ID 0 /* 0 = port, 1 = starboard */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define SERIAL_BAUD 115200
|
||||||
|
|
||||||
|
/* ── Pin map (Makerfabs ESP32 UWB Pro) ─────────────────────────── */
|
||||||
|
|
||||||
|
#define PIN_SCK 18
|
||||||
|
#define PIN_MISO 19
|
||||||
|
#define PIN_MOSI 23
|
||||||
|
#define PIN_CS 21
|
||||||
|
#define PIN_RST 27
|
||||||
|
#define PIN_IRQ 34
|
||||||
|
|
||||||
|
/* ── DW3000 channel / PHY config ───────────────────────────────── */
|
||||||
|
|
||||||
|
static dwt_config_t dw_cfg = {
|
||||||
|
5, /* channel 5 (6.5 GHz, best penetration) */
|
||||||
|
DWT_PLEN_128, /* preamble length */
|
||||||
|
DWT_PAC8, /* PAC size */
|
||||||
|
9, /* TX preamble code */
|
||||||
|
9, /* RX preamble code */
|
||||||
|
1, /* SFD type (IEEE 802.15.4z) */
|
||||||
|
DWT_BR_6M8, /* data rate 6.8 Mbps */
|
||||||
|
DWT_PHR_MODE_STD, /* standard PHR */
|
||||||
|
DWT_PHR_RATE_DATA,
|
||||||
|
(129 + 8 - 8), /* SFD timeout */
|
||||||
|
DWT_STS_MODE_OFF, /* STS off — standard TWR */
|
||||||
|
DWT_STS_LEN_64,
|
||||||
|
DWT_PDOA_M0, /* no PDoA */
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ── Frame format ──────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
/* Byte layout for all frames:
|
||||||
|
* [0] frame_type (FTYPE_*)
|
||||||
|
* [1] src_id (tag 8-bit addr, or ANCHOR_ID)
|
||||||
|
* [2] dst_id
|
||||||
|
* [3..] payload
|
||||||
|
* (FCS appended automatically by DW3000 — 2 bytes)
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define FTYPE_POLL 0x01
|
||||||
|
#define FTYPE_RESP 0x02
|
||||||
|
#define FTYPE_FINAL 0x03
|
||||||
|
|
||||||
|
#define FRAME_HDR 3
|
||||||
|
#define FCS_LEN 2
|
||||||
|
|
||||||
|
/* RESP payload: T_poll_rx(5 B) + T_resp_tx(5 B) */
|
||||||
|
#define RESP_PAYLOAD 10
|
||||||
|
#define RESP_FRAME_LEN (FRAME_HDR + RESP_PAYLOAD + FCS_LEN)
|
||||||
|
|
||||||
|
/* FINAL payload: Ra(5 B) + Da(5 B) + Db(5 B) */
|
||||||
|
#define FINAL_PAYLOAD 15
|
||||||
|
#define FINAL_FRAME_LEN (FRAME_HDR + FINAL_PAYLOAD + FCS_LEN)
|
||||||
|
|
||||||
|
/* ── Timing ────────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
/* Turnaround delay: anchor waits 500 µs after poll_rx before tx_resp.
|
||||||
|
* DW3000 tick = 1/(128×499.2e6) ≈ 15.65 ps → 500 µs = ~31.95M ticks.
|
||||||
|
* Stored as uint32 shifted right 8 bits for dwt_setdelayedtrxtime. */
|
||||||
|
#define RESP_TX_DLY_US 500UL
|
||||||
|
#define DWT_TICKS_PER_US 63898UL /* 1µs in DW3000 ticks (×8 prescaler) */
|
||||||
|
#define RESP_TX_DLY_TICKS (RESP_TX_DLY_US * DWT_TICKS_PER_US)
|
||||||
|
|
||||||
|
/* How long anchor listens for FINAL after sending RESP */
|
||||||
|
#define FINAL_RX_TIMEOUT_US 3000
|
||||||
|
|
||||||
|
/* Speed of light (m/s) */
|
||||||
|
#define SPEED_OF_LIGHT 299702547.0
|
||||||
|
|
||||||
|
/* DW3000 40-bit timestamp mask */
|
||||||
|
#define DWT_TS_MASK 0xFFFFFFFFFFULL
|
||||||
|
|
||||||
|
/* Antenna delay (factory default; calibrate per unit for best accuracy) */
|
||||||
|
#define ANT_DELAY 16385
|
||||||
|
|
||||||
|
/* ── Interrupt flags (set in ISR, polled in main) ──────────────── */
|
||||||
|
|
||||||
|
static volatile bool g_rx_ok = false;
|
||||||
|
static volatile bool g_tx_done = false;
|
||||||
|
static volatile bool g_rx_err = false;
|
||||||
|
static volatile bool g_rx_to = false;
|
||||||
|
|
||||||
|
static uint8_t g_rx_buf[128];
|
||||||
|
static uint32_t g_rx_len = 0;
|
||||||
|
|
||||||
|
/* ── State ──────────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
/* Last successful range (serves AT+RANGE? queries) */
|
||||||
|
static int32_t g_last_range_mm = -1;
|
||||||
|
static char g_last_range_line[72] = {};
|
||||||
|
|
||||||
|
/* Optional tag pairing: 0 = accept all tags */
|
||||||
|
static uint8_t g_paired_tag_id = 0;
|
||||||
|
|
||||||
|
/* ── DW3000 ISR callbacks ───────────────────────────────────────── */
|
||||||
|
|
||||||
|
static void cb_tx_done(const dwt_cb_data_t *) { g_tx_done = true; }
|
||||||
|
|
||||||
|
static void cb_rx_ok(const dwt_cb_data_t *d) {
|
||||||
|
g_rx_len = d->datalength;
|
||||||
|
if (g_rx_len > sizeof(g_rx_buf)) g_rx_len = sizeof(g_rx_buf);
|
||||||
|
dwt_readrxdata(g_rx_buf, g_rx_len, 0);
|
||||||
|
g_rx_ok = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void cb_rx_err(const dwt_cb_data_t *) { g_rx_err = true; }
|
||||||
|
static void cb_rx_to(const dwt_cb_data_t *) { g_rx_to = true; }
|
||||||
|
|
||||||
|
/* ── Timestamp helpers ──────────────────────────────────────────── */
|
||||||
|
|
||||||
|
static uint64_t ts_read(const uint8_t *p) {
|
||||||
|
uint64_t v = 0;
|
||||||
|
for (int i = 4; i >= 0; i--) v = (v << 8) | p[i];
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ts_write(uint8_t *p, uint64_t v) {
|
||||||
|
for (int i = 0; i < 5; i++, v >>= 8) p[i] = (uint8_t)(v & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline uint64_t ts_diff(uint64_t later, uint64_t earlier) {
|
||||||
|
return (later - earlier) & DWT_TS_MASK;
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline double ticks_to_s(uint64_t t) {
|
||||||
|
return (double)t / (128.0 * 499200000.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Estimate receive power from CIR diagnostics (dBm) */
|
||||||
|
static float rx_power_dbm(void) {
|
||||||
|
dwt_rxdiag_t d;
|
||||||
|
dwt_readdiagnostics(&d);
|
||||||
|
if (d.maxGrowthCIR == 0 || d.rxPreamCount == 0) return 0.0f;
|
||||||
|
float f = (float)d.maxGrowthCIR;
|
||||||
|
float n = (float)d.rxPreamCount;
|
||||||
|
return 10.0f * log10f((f * f) / (n * n)) - 121.74f;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Peer-anchor ranging (initiator role, for auto-calibration) ─── */
|
||||||
|
|
||||||
|
/* Timeout waiting for peer's RESP during inter-anchor ranging */
|
||||||
|
#define PEER_RX_RESP_TIMEOUT_US 3500
|
||||||
|
/* Block up to this many ms waiting for the interrupt flags */
|
||||||
|
#define PEER_WAIT_MS 20
|
||||||
|
|
||||||
|
/* Initiate a single DS-TWR exchange toward peer anchor `peer_id`.
|
||||||
|
* Returns range in mm (>=0) on success, or -1 on timeout/error.
|
||||||
|
* RSSI is stored in *rssi_out if non-null.
|
||||||
|
*
|
||||||
|
* Exchange:
|
||||||
|
* This anchor → peer POLL
|
||||||
|
* peer → This RESP (carries T_poll_rx, T_resp_tx)
|
||||||
|
* This anchor → peer FINAL (carries Ra, Da)
|
||||||
|
* This side computes its own range estimate from Ra/Da.
|
||||||
|
*/
|
||||||
|
static int32_t peer_range_once(uint8_t peer_id, float *rssi_out) {
|
||||||
|
/* ── Reset interrupt flags ── */
|
||||||
|
g_tx_done = g_rx_ok = g_rx_err = g_rx_to = false;
|
||||||
|
|
||||||
|
/* ── Build POLL frame ── */
|
||||||
|
uint8_t poll_buf[FRAME_HDR + FCS_LEN] = {
|
||||||
|
FTYPE_POLL,
|
||||||
|
(uint8_t)ANCHOR_ID,
|
||||||
|
peer_id,
|
||||||
|
};
|
||||||
|
|
||||||
|
dwt_writetxdata(sizeof(poll_buf), poll_buf, 0);
|
||||||
|
dwt_writetxfctrl(sizeof(poll_buf), 0, 1);
|
||||||
|
dwt_setrxtimeout(PEER_RX_RESP_TIMEOUT_US);
|
||||||
|
dwt_rxenable(DWT_START_RX_IMMEDIATE);
|
||||||
|
if (dwt_starttx(DWT_START_TX_IMMEDIATE | DWT_RESPONSE_EXPECTED) != DWT_SUCCESS)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
/* Wait for TX done */
|
||||||
|
uint32_t t0 = millis();
|
||||||
|
while (!g_tx_done && !g_rx_err && !g_rx_to) {
|
||||||
|
if (millis() - t0 > (uint32_t)PEER_WAIT_MS) return -1;
|
||||||
|
}
|
||||||
|
if (g_rx_err || g_rx_to) return -1;
|
||||||
|
g_tx_done = false;
|
||||||
|
|
||||||
|
/* Capture T_poll_tx */
|
||||||
|
uint64_t T_poll_tx;
|
||||||
|
dwt_readtxtimestamp((uint8_t *)&T_poll_tx);
|
||||||
|
T_poll_tx &= DWT_TS_MASK;
|
||||||
|
|
||||||
|
/* Wait for RESP */
|
||||||
|
t0 = millis();
|
||||||
|
while (!g_rx_ok && !g_rx_err && !g_rx_to) {
|
||||||
|
if (millis() - t0 > (uint32_t)PEER_WAIT_MS) return -1;
|
||||||
|
}
|
||||||
|
if (!g_rx_ok) return -1;
|
||||||
|
|
||||||
|
/* Validate RESP */
|
||||||
|
if (g_rx_len < (uint32_t)(FRAME_HDR + RESP_PAYLOAD + FCS_LEN)) return -1;
|
||||||
|
if (g_rx_buf[0] != FTYPE_RESP) return -1;
|
||||||
|
if (g_rx_buf[1] != peer_id) return -1;
|
||||||
|
if (g_rx_buf[2] != (uint8_t)ANCHOR_ID) return -1;
|
||||||
|
|
||||||
|
uint64_t T_resp_rx;
|
||||||
|
dwt_readrxtimestamp((uint8_t *)&T_resp_rx);
|
||||||
|
T_resp_rx &= DWT_TS_MASK;
|
||||||
|
|
||||||
|
/* Extract peer timestamps from RESP payload */
|
||||||
|
const uint8_t *pl = g_rx_buf + FRAME_HDR;
|
||||||
|
uint64_t T_poll_rx_peer = ts_read(pl);
|
||||||
|
uint64_t T_resp_tx_peer = ts_read(pl + 5);
|
||||||
|
|
||||||
|
/* DS-TWR Ra, Da */
|
||||||
|
uint64_t Ra = ts_diff(T_resp_rx, T_poll_tx);
|
||||||
|
uint64_t Da = ts_diff(T_resp_tx_peer, T_poll_rx_peer);
|
||||||
|
|
||||||
|
g_rx_ok = g_rx_err = g_rx_to = false;
|
||||||
|
|
||||||
|
/* ── Build FINAL frame ── */
|
||||||
|
uint8_t final_buf[FRAME_HDR + FINAL_PAYLOAD + FCS_LEN];
|
||||||
|
final_buf[0] = FTYPE_FINAL;
|
||||||
|
final_buf[1] = (uint8_t)ANCHOR_ID;
|
||||||
|
final_buf[2] = peer_id;
|
||||||
|
ts_write(final_buf + FRAME_HDR, Ra);
|
||||||
|
ts_write(final_buf + FRAME_HDR + 5, Da);
|
||||||
|
ts_write(final_buf + FRAME_HDR + 10, (uint64_t)0); /* Db placeholder */
|
||||||
|
|
||||||
|
dwt_setrxtimeout(0);
|
||||||
|
dwt_writetxdata(sizeof(final_buf), final_buf, 0);
|
||||||
|
dwt_writetxfctrl(sizeof(final_buf), 0, 1);
|
||||||
|
if (dwt_starttx(DWT_START_TX_IMMEDIATE) != DWT_SUCCESS) return -1;
|
||||||
|
|
||||||
|
t0 = millis();
|
||||||
|
while (!g_tx_done && !g_rx_err) {
|
||||||
|
if (millis() - t0 > (uint32_t)PEER_WAIT_MS) return -1;
|
||||||
|
}
|
||||||
|
g_tx_done = false;
|
||||||
|
|
||||||
|
/* Simplified one-sided range estimate: tof = Ra - Da/2 */
|
||||||
|
double tof_s = ticks_to_s(Ra) - ticks_to_s(Da) / 2.0;
|
||||||
|
if (tof_s < 0.0) tof_s = 0.0;
|
||||||
|
int32_t range_mm = (int32_t)(tof_s * SPEED_OF_LIGHT * 1000.0);
|
||||||
|
|
||||||
|
if (rssi_out) *rssi_out = rx_power_dbm();
|
||||||
|
|
||||||
|
/* Re-enable normal RX for tag ranging */
|
||||||
|
dwt_setrxtimeout(0);
|
||||||
|
dwt_rxenable(DWT_START_RX_IMMEDIATE);
|
||||||
|
|
||||||
|
return range_mm;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── AT command handler ─────────────────────────────────────────── */
|
||||||
|
|
||||||
|
static char g_at_buf[64];
|
||||||
|
static int g_at_idx = 0;
|
||||||
|
|
||||||
|
static void at_dispatch(const char *cmd) {
|
||||||
|
if (strcmp(cmd, "AT+RANGE?") == 0) {
|
||||||
|
if (g_last_range_mm >= 0)
|
||||||
|
Serial.println(g_last_range_line);
|
||||||
|
else
|
||||||
|
Serial.println("+RANGE:NO_DATA");
|
||||||
|
|
||||||
|
} else if (strcmp(cmd, "AT+ID?") == 0) {
|
||||||
|
Serial.printf("+ID:%d\r\n", ANCHOR_ID);
|
||||||
|
|
||||||
|
} else if (strncmp(cmd, "AT+RANGE_ADDR=", 14) == 0) {
|
||||||
|
const char *v = cmd + 14;
|
||||||
|
if (*v == '\0') {
|
||||||
|
g_paired_tag_id = 0;
|
||||||
|
Serial.println("+OK:UNPAIRED");
|
||||||
|
} else {
|
||||||
|
g_paired_tag_id = (uint8_t)strtoul(v, nullptr, 0);
|
||||||
|
Serial.printf("+OK:PAIRED=0x%02X\r\n", g_paired_tag_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (strncmp(cmd, "AT+PEER_RANGE=", 14) == 0) {
|
||||||
|
/* Inter-anchor ranging for calibration.
|
||||||
|
* Usage: AT+PEER_RANGE=<peer_anchor_id>
|
||||||
|
* Response: +PEER_RANGE:<my_id>,<peer_id>,<range_mm>,<rssi_dbm>
|
||||||
|
* or: +PEER_RANGE:ERR,<peer_id>,TIMEOUT
|
||||||
|
*/
|
||||||
|
uint8_t peer_id = (uint8_t)strtoul(cmd + 14, nullptr, 0);
|
||||||
|
float rssi = 0.0f;
|
||||||
|
int32_t mm = peer_range_once(peer_id, &rssi);
|
||||||
|
if (mm >= 0) {
|
||||||
|
Serial.printf("+PEER_RANGE:%d,%d,%ld,%.1f\r\n",
|
||||||
|
ANCHOR_ID, peer_id, mm, (double)rssi);
|
||||||
|
} else {
|
||||||
|
Serial.printf("+PEER_RANGE:ERR,%d,TIMEOUT\r\n", peer_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
Serial.println("+ERR:UNKNOWN_CMD");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void serial_poll(void) {
|
||||||
|
while (Serial.available()) {
|
||||||
|
char c = (char)Serial.read();
|
||||||
|
if (c == '\r') continue;
|
||||||
|
if (c == '\n') {
|
||||||
|
g_at_buf[g_at_idx] = '\0';
|
||||||
|
if (g_at_idx > 0) at_dispatch(g_at_buf);
|
||||||
|
g_at_idx = 0;
|
||||||
|
} else if (g_at_idx < (int)(sizeof(g_at_buf) - 1)) {
|
||||||
|
g_at_buf[g_at_idx++] = c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── DS-TWR anchor state machine ────────────────────────────────── */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* DS-TWR responder (one shot):
|
||||||
|
* 1. Wait for POLL from tag
|
||||||
|
* 2. Delayed-TX RESP (carry T_poll_rx + scheduled T_resp_tx)
|
||||||
|
* 3. Wait for FINAL from tag (tag embeds Ra, Da, Db)
|
||||||
|
* 4. Compute: Rb = T_final_rx − T_resp_tx
|
||||||
|
* tof = (Ra·Rb − Da·Db) / (Ra+Rb+Da+Db)
|
||||||
|
* range_m = tof × c
|
||||||
|
* 5. Print +RANGE line
|
||||||
|
*/
|
||||||
|
static void twr_cycle(void) {
|
||||||
|
|
||||||
|
/* --- 1. Listen for POLL --- */
|
||||||
|
dwt_setrxtimeout(0);
|
||||||
|
dwt_rxenable(DWT_START_RX_IMMEDIATE);
|
||||||
|
|
||||||
|
g_rx_ok = g_rx_err = false;
|
||||||
|
uint32_t deadline = millis() + 2000;
|
||||||
|
while (!g_rx_ok && !g_rx_err) {
|
||||||
|
serial_poll();
|
||||||
|
if (millis() > deadline) {
|
||||||
|
/* restart RX if we've been stuck */
|
||||||
|
dwt_rxenable(DWT_START_RX_IMMEDIATE);
|
||||||
|
deadline = millis() + 2000;
|
||||||
|
}
|
||||||
|
yield();
|
||||||
|
}
|
||||||
|
if (!g_rx_ok || g_rx_len < FRAME_HDR) return;
|
||||||
|
|
||||||
|
/* validate POLL */
|
||||||
|
if (g_rx_buf[0] != FTYPE_POLL) return;
|
||||||
|
uint8_t tag_id = g_rx_buf[1];
|
||||||
|
if (g_paired_tag_id != 0 && tag_id != g_paired_tag_id) return;
|
||||||
|
|
||||||
|
/* --- 2. Record T_poll_rx --- */
|
||||||
|
uint8_t poll_rx_raw[5];
|
||||||
|
dwt_readrxtimestamp(poll_rx_raw);
|
||||||
|
uint64_t T_poll_rx = ts_read(poll_rx_raw);
|
||||||
|
|
||||||
|
/* Compute delayed TX time: poll_rx + turnaround, aligned to 512-tick grid */
|
||||||
|
uint64_t resp_tx_sched = (T_poll_rx + RESP_TX_DLY_TICKS) & ~0x1FFULL;
|
||||||
|
|
||||||
|
/* Build RESP frame */
|
||||||
|
uint8_t resp[RESP_FRAME_LEN];
|
||||||
|
resp[0] = FTYPE_RESP;
|
||||||
|
resp[1] = ANCHOR_ID;
|
||||||
|
resp[2] = tag_id;
|
||||||
|
ts_write(&resp[3], T_poll_rx); /* T_poll_rx (tag uses this) */
|
||||||
|
ts_write(&resp[8], resp_tx_sched); /* scheduled T_resp_tx */
|
||||||
|
|
||||||
|
dwt_writetxdata(RESP_FRAME_LEN - FCS_LEN, resp, 0);
|
||||||
|
dwt_writetxfctrl(RESP_FRAME_LEN, 0, 1 /*ranging*/);
|
||||||
|
dwt_setdelayedtrxtime((uint32_t)(resp_tx_sched >> 8));
|
||||||
|
|
||||||
|
/* Enable RX after TX to receive FINAL */
|
||||||
|
dwt_setrxaftertxdelay(300);
|
||||||
|
dwt_setrxtimeout(FINAL_RX_TIMEOUT_US);
|
||||||
|
|
||||||
|
/* Fire delayed TX */
|
||||||
|
g_tx_done = g_rx_ok = g_rx_err = g_rx_to = false;
|
||||||
|
if (dwt_starttx(DWT_START_TX_DELAYED | DWT_RESPONSE_EXPECTED) != DWT_SUCCESS) {
|
||||||
|
dwt_forcetrxoff();
|
||||||
|
return; /* TX window missed — try next cycle */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Wait for TX done (short wait, ISR fires fast) */
|
||||||
|
uint32_t t0 = millis();
|
||||||
|
while (!g_tx_done && millis() - t0 < 15) { yield(); }
|
||||||
|
|
||||||
|
/* Read actual T_resp_tx */
|
||||||
|
uint8_t resp_tx_raw[5];
|
||||||
|
dwt_readtxtimestamp(resp_tx_raw);
|
||||||
|
uint64_t T_resp_tx = ts_read(resp_tx_raw);
|
||||||
|
|
||||||
|
/* --- 3. Wait for FINAL --- */
|
||||||
|
t0 = millis();
|
||||||
|
while (!g_rx_ok && !g_rx_err && !g_rx_to && millis() - t0 < 60) {
|
||||||
|
serial_poll();
|
||||||
|
yield();
|
||||||
|
}
|
||||||
|
if (!g_rx_ok || g_rx_len < FRAME_HDR + FINAL_PAYLOAD) return;
|
||||||
|
if (g_rx_buf[0] != FTYPE_FINAL) return;
|
||||||
|
if (g_rx_buf[1] != tag_id) return;
|
||||||
|
|
||||||
|
/* Extract DS-TWR timestamps from FINAL payload */
|
||||||
|
uint64_t Ra = ts_read(&g_rx_buf[3]); /* tag: T_resp_rx − T_poll_tx */
|
||||||
|
uint64_t Da = ts_read(&g_rx_buf[8]); /* tag: T_final_tx − T_resp_rx */
|
||||||
|
/* g_rx_buf[13..17] = Db from tag (cross-check, unused here) */
|
||||||
|
|
||||||
|
/* T_final_rx */
|
||||||
|
uint8_t final_rx_raw[5];
|
||||||
|
dwt_readrxtimestamp(final_rx_raw);
|
||||||
|
uint64_t T_final_rx = ts_read(final_rx_raw);
|
||||||
|
|
||||||
|
/* --- 4. DS-TWR formula --- */
|
||||||
|
uint64_t Rb = ts_diff(T_final_rx, T_resp_tx); /* anchor round-trip */
|
||||||
|
uint64_t Db = ts_diff(T_resp_tx, T_poll_rx); /* anchor turnaround */
|
||||||
|
|
||||||
|
double ra = ticks_to_s(Ra), rb = ticks_to_s(Rb);
|
||||||
|
double da = ticks_to_s(Da), db = ticks_to_s(Db);
|
||||||
|
|
||||||
|
double denom = ra + rb + da + db;
|
||||||
|
if (denom < 1e-15) return;
|
||||||
|
|
||||||
|
double tof = (ra * rb - da * db) / denom;
|
||||||
|
double range_m = tof * SPEED_OF_LIGHT;
|
||||||
|
|
||||||
|
/* Validity window: 0.1 m – 130 m */
|
||||||
|
if (range_m < 0.1 || range_m > 130.0) return;
|
||||||
|
|
||||||
|
int32_t range_mm = (int32_t)(range_m * 1000.0 + 0.5);
|
||||||
|
float rssi = rx_power_dbm();
|
||||||
|
|
||||||
|
/* --- 5. Emit +RANGE --- */
|
||||||
|
snprintf(g_last_range_line, sizeof(g_last_range_line),
|
||||||
|
"+RANGE:%d,%ld,%.1f", ANCHOR_ID, (long)range_mm, rssi);
|
||||||
|
g_last_range_mm = range_mm;
|
||||||
|
Serial.println(g_last_range_line);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Arduino setup ──────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
void setup(void) {
|
||||||
|
Serial.begin(SERIAL_BAUD);
|
||||||
|
delay(300);
|
||||||
|
|
||||||
|
Serial.printf("\r\n[uwb_anchor] anchor_id=%d starting\r\n", ANCHOR_ID);
|
||||||
|
|
||||||
|
SPI.begin(PIN_SCK, PIN_MISO, PIN_MOSI, PIN_CS);
|
||||||
|
|
||||||
|
/* Hardware reset */
|
||||||
|
pinMode(PIN_RST, OUTPUT);
|
||||||
|
digitalWrite(PIN_RST, LOW);
|
||||||
|
delay(2);
|
||||||
|
pinMode(PIN_RST, INPUT_PULLUP);
|
||||||
|
delay(5);
|
||||||
|
|
||||||
|
/* DW3000 probe + init (Makerfabs MaUWB_DW3000 library) */
|
||||||
|
if (dwt_probe((struct dwt_probe_s *)&dw3000_probe_interf)) {
|
||||||
|
Serial.println("[uwb_anchor] FATAL: DW3000 probe failed — check SPI wiring");
|
||||||
|
for (;;) delay(1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dwt_initialise(DWT_DW_INIT) != DWT_SUCCESS) {
|
||||||
|
Serial.println("[uwb_anchor] FATAL: dwt_initialise failed");
|
||||||
|
for (;;) delay(1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dwt_configure(&dw_cfg) != DWT_SUCCESS) {
|
||||||
|
Serial.println("[uwb_anchor] FATAL: dwt_configure failed");
|
||||||
|
for (;;) delay(1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
dwt_setrxantennadelay(ANT_DELAY);
|
||||||
|
dwt_settxantennadelay(ANT_DELAY);
|
||||||
|
dwt_settxpower(0x0E080222UL); /* max TX power for 120 m range */
|
||||||
|
|
||||||
|
dwt_setcallbacks(cb_tx_done, cb_rx_ok, cb_rx_to, cb_rx_err,
|
||||||
|
nullptr, nullptr, nullptr);
|
||||||
|
dwt_setinterrupt(
|
||||||
|
DWT_INT_TXFRS | DWT_INT_RFCG | DWT_INT_RFTO |
|
||||||
|
DWT_INT_RFSL | DWT_INT_SFDT | DWT_INT_ARFE | DWT_INT_CPERR,
|
||||||
|
0, DWT_ENABLE_INT_ONLY);
|
||||||
|
|
||||||
|
attachInterrupt(digitalPinToInterrupt(PIN_IRQ),
|
||||||
|
[]() { dwt_isr(); }, RISING);
|
||||||
|
|
||||||
|
Serial.printf("[uwb_anchor] DW3000 ready ch=%d 6.8Mbps id=%d\r\n",
|
||||||
|
dw_cfg.chan, ANCHOR_ID);
|
||||||
|
Serial.println("[uwb_anchor] Listening for tags...");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Arduino loop ───────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
void loop(void) {
|
||||||
|
serial_poll();
|
||||||
|
twr_cycle();
|
||||||
|
}
|
||||||
19
esp32/uwb_anchor/udev/99-uwb-anchors.rules
Normal file
19
esp32/uwb_anchor/udev/99-uwb-anchors.rules
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
# SaltyBot UWB anchor USB-serial persistent symlinks
|
||||||
|
# Install:
|
||||||
|
# sudo cp 99-uwb-anchors.rules /etc/udev/rules.d/
|
||||||
|
# sudo udevadm control --reload && sudo udevadm trigger
|
||||||
|
#
|
||||||
|
# Find serial numbers:
|
||||||
|
# udevadm info -a /dev/ttyUSB0 | grep ATTRS{serial}
|
||||||
|
#
|
||||||
|
# Fill ANCHOR0_SERIAL and ANCHOR1_SERIAL with the values found above.
|
||||||
|
# Anchor 0 = port side → /dev/uwb-anchor0
|
||||||
|
# Anchor 1 = starboard → /dev/uwb-anchor1
|
||||||
|
|
||||||
|
SUBSYSTEM=="tty", ATTRS{idVendor}=="10c4", ATTRS{idProduct}=="ea60", \
|
||||||
|
ATTRS{serial}=="ANCHOR0_SERIAL", \
|
||||||
|
SYMLINK+="uwb-anchor0", MODE="0666"
|
||||||
|
|
||||||
|
SUBSYSTEM=="tty", ATTRS{idVendor}=="10c4", ATTRS{idProduct}=="ea60", \
|
||||||
|
ATTRS{serial}=="ANCHOR1_SERIAL", \
|
||||||
|
SYMLINK+="uwb-anchor1", MODE="0666"
|
||||||
30
esp32/uwb_tag/platformio.ini
Normal file
30
esp32/uwb_tag/platformio.ini
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
; SaltyBot UWB Tag Firmware — Issue #545
|
||||||
|
; Target: Makerfabs ESP32 UWB Pro with Display (DW3000 + SSD1306 OLED)
|
||||||
|
;
|
||||||
|
; The tag is battery-powered, worn by the person being tracked.
|
||||||
|
; It initiates DS-TWR ranging with each anchor in round-robin,
|
||||||
|
; shows status on OLED display, and sends data via ESP-NOW.
|
||||||
|
;
|
||||||
|
; Library: Makerfabs MaUWB_DW3000
|
||||||
|
; https://github.com/Makerfabs/MaUWB_DW3000
|
||||||
|
;
|
||||||
|
; Flash:
|
||||||
|
; pio run -e tag --target upload
|
||||||
|
; Monitor (USB debug):
|
||||||
|
; pio device monitor -b 115200
|
||||||
|
|
||||||
|
[env:tag]
|
||||||
|
platform = espressif32
|
||||||
|
board = esp32dev
|
||||||
|
framework = arduino
|
||||||
|
monitor_speed = 115200
|
||||||
|
upload_speed = 921600
|
||||||
|
lib_deps =
|
||||||
|
https://github.com/Makerfabs/MaUWB_DW3000.git
|
||||||
|
adafruit/Adafruit SSD1306@^2.5.7
|
||||||
|
adafruit/Adafruit GFX Library@^1.11.5
|
||||||
|
build_flags =
|
||||||
|
-DCORE_DEBUG_LEVEL=0
|
||||||
|
-DTAG_ID=0x01 ; unique per tag (0x01–0xFE)
|
||||||
|
-DNUM_ANCHORS=2 ; number of anchors to range with
|
||||||
|
-DRANGE_INTERVAL_MS=50 ; 20 Hz round-robin across anchors
|
||||||
615
esp32/uwb_tag/src/main.cpp
Normal file
615
esp32/uwb_tag/src/main.cpp
Normal file
@ -0,0 +1,615 @@
|
|||||||
|
/*
|
||||||
|
* uwb_tag — SaltyBot ESP32 UWB Pro tag firmware (DS-TWR initiator)
|
||||||
|
* Issue #545 + display/ESP-NOW/e-stop extensions
|
||||||
|
*
|
||||||
|
* Hardware: Makerfabs ESP32 UWB Pro with Display (DW3000 + SSD1306 OLED)
|
||||||
|
*
|
||||||
|
* Role
|
||||||
|
* ────
|
||||||
|
* Tag is worn by a person riding an EUC while SaltyBot follows.
|
||||||
|
* Initiates DS-TWR ranging with 2 anchors on the robot at 20 Hz.
|
||||||
|
* Shows distance/status on OLED. Sends range data via ESP-NOW
|
||||||
|
* (no WiFi AP needed — peer-to-peer, ~1ms latency, works outdoors).
|
||||||
|
* GPIO 0 = emergency stop button (active low).
|
||||||
|
*
|
||||||
|
* Serial output (USB, 115200) — debug
|
||||||
|
* ────────────────────────────────────
|
||||||
|
* +RANGE:<anchor_id>,<range_mm>,<rssi_dbm>\r\n
|
||||||
|
*
|
||||||
|
* ESP-NOW packet (broadcast, 20 bytes)
|
||||||
|
* ─────────────────────────────────────
|
||||||
|
* [0-1] magic 0x5B 0x01
|
||||||
|
* [2] tag_id
|
||||||
|
* [3] msg_type 0x10=range, 0x20=estop, 0x30=heartbeat
|
||||||
|
* [4] anchor_id
|
||||||
|
* [5-8] range_mm (int32_t LE)
|
||||||
|
* [9-12] rssi_dbm (float LE)
|
||||||
|
* [13-16] timestamp (uint32_t millis)
|
||||||
|
* [17] battery_pct (0-100 or 0xFF)
|
||||||
|
* [18] flags bit0=estop_active
|
||||||
|
* [19] seq_num_lo (uint8_t, rolling)
|
||||||
|
*
|
||||||
|
* Pin mapping — Makerfabs ESP32 UWB Pro with Display
|
||||||
|
* ──────────────────────────────────────────────────
|
||||||
|
* SPI SCK 18 SPI MISO 19 SPI MOSI 23
|
||||||
|
* DW CS 21 DW RST 27 DW IRQ 34
|
||||||
|
* I2C SDA 4 I2C SCL 5 OLED addr 0x3C
|
||||||
|
* LED 2 E-STOP 0 (BOOT, active LOW)
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <SPI.h>
|
||||||
|
#include <Wire.h>
|
||||||
|
#include <math.h>
|
||||||
|
#include <WiFi.h>
|
||||||
|
#include <esp_now.h>
|
||||||
|
#include <esp_wifi.h>
|
||||||
|
|
||||||
|
#include "dw3000.h"
|
||||||
|
|
||||||
|
#include <Adafruit_GFX.h>
|
||||||
|
#include <Adafruit_SSD1306.h>
|
||||||
|
|
||||||
|
/* ── Configurable ───────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
#ifndef TAG_ID
|
||||||
|
# define TAG_ID 0x01
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef NUM_ANCHORS
|
||||||
|
# define NUM_ANCHORS 2
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef RANGE_INTERVAL_MS
|
||||||
|
# define RANGE_INTERVAL_MS 50 /* 20 Hz round-robin */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define SERIAL_BAUD 115200
|
||||||
|
|
||||||
|
/* ── Pins ───────────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
#define PIN_SCK 18
|
||||||
|
#define PIN_MISO 19
|
||||||
|
#define PIN_MOSI 23
|
||||||
|
#define PIN_CS 21
|
||||||
|
#define PIN_RST 27
|
||||||
|
#define PIN_IRQ 34
|
||||||
|
|
||||||
|
#define PIN_SDA 4
|
||||||
|
#define PIN_SCL 5
|
||||||
|
|
||||||
|
#define PIN_LED 2
|
||||||
|
#define PIN_ESTOP 0 /* BOOT button, active LOW */
|
||||||
|
|
||||||
|
/* ── OLED ───────────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
#define SCREEN_W 128
|
||||||
|
#define SCREEN_H 64
|
||||||
|
Adafruit_SSD1306 display(SCREEN_W, SCREEN_H, &Wire, -1);
|
||||||
|
|
||||||
|
/* ── ESP-NOW ────────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
#define ESPNOW_MAGIC_0 0x5B /* "SB" */
|
||||||
|
#define ESPNOW_MAGIC_1 0x01 /* v1 */
|
||||||
|
|
||||||
|
#define MSG_RANGE 0x10
|
||||||
|
#define MSG_ESTOP 0x20
|
||||||
|
#define MSG_HEARTBEAT 0x30
|
||||||
|
|
||||||
|
static uint8_t broadcast_mac[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
|
||||||
|
static uint8_t g_seq = 0;
|
||||||
|
|
||||||
|
#pragma pack(push, 1)
|
||||||
|
struct EspNowPacket {
|
||||||
|
uint8_t magic[2];
|
||||||
|
uint8_t tag_id;
|
||||||
|
uint8_t msg_type;
|
||||||
|
uint8_t anchor_id;
|
||||||
|
int32_t range_mm;
|
||||||
|
float rssi_dbm;
|
||||||
|
uint32_t timestamp_ms;
|
||||||
|
uint8_t battery_pct;
|
||||||
|
uint8_t flags;
|
||||||
|
uint8_t seq_num;
|
||||||
|
uint8_t _pad; /* pad to 20 bytes */
|
||||||
|
};
|
||||||
|
#pragma pack(pop)
|
||||||
|
|
||||||
|
static_assert(sizeof(EspNowPacket) == 20, "packet must be 20 bytes");
|
||||||
|
|
||||||
|
/* ── DW3000 PHY config (must match anchor) ──────────────────────── */
|
||||||
|
|
||||||
|
static dwt_config_t dw_cfg = {
|
||||||
|
5, /* channel 5 */
|
||||||
|
DWT_PLEN_128,
|
||||||
|
DWT_PAC8,
|
||||||
|
9, 9, /* TX/RX preamble code */
|
||||||
|
1, /* SFD type */
|
||||||
|
DWT_BR_6M8,
|
||||||
|
DWT_PHR_MODE_STD,
|
||||||
|
DWT_PHR_RATE_DATA,
|
||||||
|
(129 + 8 - 8),
|
||||||
|
DWT_STS_MODE_OFF,
|
||||||
|
DWT_STS_LEN_64,
|
||||||
|
DWT_PDOA_M0,
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ── Frame format ──────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
#define FTYPE_POLL 0x01
|
||||||
|
#define FTYPE_RESP 0x02
|
||||||
|
#define FTYPE_FINAL 0x03
|
||||||
|
|
||||||
|
#define FRAME_HDR 3
|
||||||
|
#define FCS_LEN 2
|
||||||
|
|
||||||
|
#define POLL_FRAME_LEN (FRAME_HDR + FCS_LEN)
|
||||||
|
#define RESP_PAYLOAD 10
|
||||||
|
#define RESP_FRAME_LEN (FRAME_HDR + RESP_PAYLOAD + FCS_LEN)
|
||||||
|
#define FINAL_PAYLOAD 15
|
||||||
|
#define FINAL_FRAME_LEN (FRAME_HDR + FINAL_PAYLOAD + FCS_LEN)
|
||||||
|
|
||||||
|
/* ── Timing ────────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
#define FINAL_TX_DLY_US 500UL
|
||||||
|
#define DWT_TICKS_PER_US 63898UL
|
||||||
|
#define FINAL_TX_DLY_TICKS (FINAL_TX_DLY_US * DWT_TICKS_PER_US)
|
||||||
|
#define RESP_RX_TIMEOUT_US 3000
|
||||||
|
|
||||||
|
#define SPEED_OF_LIGHT 299702547.0
|
||||||
|
#define DWT_TS_MASK 0xFFFFFFFFFFULL
|
||||||
|
#define ANT_DELAY 16385
|
||||||
|
|
||||||
|
/* ── ISR state ──────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
static volatile bool g_rx_ok = false;
|
||||||
|
static volatile bool g_tx_done = false;
|
||||||
|
static volatile bool g_rx_err = false;
|
||||||
|
static volatile bool g_rx_to = false;
|
||||||
|
|
||||||
|
static uint8_t g_rx_buf[128];
|
||||||
|
static uint32_t g_rx_len = 0;
|
||||||
|
|
||||||
|
static void cb_tx_done(const dwt_cb_data_t *) { g_tx_done = true; }
|
||||||
|
static void cb_rx_ok(const dwt_cb_data_t *d) {
|
||||||
|
g_rx_len = d->datalength;
|
||||||
|
if (g_rx_len > sizeof(g_rx_buf)) g_rx_len = sizeof(g_rx_buf);
|
||||||
|
dwt_readrxdata(g_rx_buf, g_rx_len, 0);
|
||||||
|
g_rx_ok = true;
|
||||||
|
}
|
||||||
|
static void cb_rx_err(const dwt_cb_data_t *) { g_rx_err = true; }
|
||||||
|
static void cb_rx_to(const dwt_cb_data_t *) { g_rx_to = true; }
|
||||||
|
|
||||||
|
/* ── Timestamp helpers ──────────────────────────────────────────── */
|
||||||
|
|
||||||
|
static uint64_t ts_read(const uint8_t *p) {
|
||||||
|
uint64_t v = 0;
|
||||||
|
for (int i = 4; i >= 0; i--) v = (v << 8) | p[i];
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ts_write(uint8_t *p, uint64_t v) {
|
||||||
|
for (int i = 0; i < 5; i++, v >>= 8) p[i] = (uint8_t)(v & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline uint64_t ts_diff(uint64_t later, uint64_t earlier) {
|
||||||
|
return (later - earlier) & DWT_TS_MASK;
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline double ticks_to_s(uint64_t t) {
|
||||||
|
return (double)t / (128.0 * 499200000.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static float rx_power_dbm(void) {
|
||||||
|
dwt_rxdiag_t d;
|
||||||
|
dwt_readdiagnostics(&d);
|
||||||
|
if (d.maxGrowthCIR == 0 || d.rxPreamCount == 0) return 0.0f;
|
||||||
|
float f = (float)d.maxGrowthCIR;
|
||||||
|
float n = (float)d.rxPreamCount;
|
||||||
|
return 10.0f * log10f((f * f) / (n * n)) - 121.74f;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Shared state for display ───────────────────────────────────── */
|
||||||
|
|
||||||
|
static int32_t g_anchor_range_mm[NUM_ANCHORS]; /* last range per anchor */
|
||||||
|
static float g_anchor_rssi[NUM_ANCHORS]; /* last RSSI per anchor */
|
||||||
|
static uint32_t g_anchor_last_ok[NUM_ANCHORS]; /* millis() of last good range */
|
||||||
|
static bool g_estop_active = false;
|
||||||
|
|
||||||
|
/* ── ESP-NOW send helper ────────────────────────────────────────── */
|
||||||
|
|
||||||
|
static void espnow_send(uint8_t msg_type, uint8_t anchor_id,
|
||||||
|
int32_t range_mm, float rssi) {
|
||||||
|
EspNowPacket pkt = {};
|
||||||
|
pkt.magic[0] = ESPNOW_MAGIC_0;
|
||||||
|
pkt.magic[1] = ESPNOW_MAGIC_1;
|
||||||
|
pkt.tag_id = TAG_ID;
|
||||||
|
pkt.msg_type = msg_type;
|
||||||
|
pkt.anchor_id = anchor_id;
|
||||||
|
pkt.range_mm = range_mm;
|
||||||
|
pkt.rssi_dbm = rssi;
|
||||||
|
pkt.timestamp_ms = millis();
|
||||||
|
pkt.battery_pct = 0xFF; /* TODO: read ADC battery voltage */
|
||||||
|
pkt.flags = g_estop_active ? 0x01 : 0x00;
|
||||||
|
pkt.seq_num = g_seq++;
|
||||||
|
|
||||||
|
esp_now_send(broadcast_mac, (uint8_t *)&pkt, sizeof(pkt));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── E-Stop handling ────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
static uint32_t g_estop_last_tx = 0;
|
||||||
|
|
||||||
|
static void estop_check(void) {
|
||||||
|
bool pressed = (digitalRead(PIN_ESTOP) == LOW);
|
||||||
|
|
||||||
|
if (pressed && !g_estop_active) {
|
||||||
|
/* Just pressed — enter e-stop */
|
||||||
|
g_estop_active = true;
|
||||||
|
Serial.println("+ESTOP:ACTIVE");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (g_estop_active && pressed) {
|
||||||
|
/* While held: send e-stop at 10 Hz */
|
||||||
|
if (millis() - g_estop_last_tx >= 100) {
|
||||||
|
espnow_send(MSG_ESTOP, 0xFF, 0, 0.0f);
|
||||||
|
g_estop_last_tx = millis();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!pressed && g_estop_active) {
|
||||||
|
/* Released: send 3x clear packets, resume */
|
||||||
|
for (int i = 0; i < 3; i++) {
|
||||||
|
g_estop_active = false; /* clear flag before sending so flags=0 */
|
||||||
|
espnow_send(MSG_ESTOP, 0xFF, 0, 0.0f);
|
||||||
|
delay(10);
|
||||||
|
}
|
||||||
|
g_estop_active = false;
|
||||||
|
Serial.println("+ESTOP:CLEAR");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── OLED display update (5 Hz) ─────────────────────────────────── */
|
||||||
|
|
||||||
|
static uint32_t g_display_last = 0;
|
||||||
|
|
||||||
|
static void display_update(void) {
|
||||||
|
if (millis() - g_display_last < 200) return;
|
||||||
|
g_display_last = millis();
|
||||||
|
|
||||||
|
display.clearDisplay();
|
||||||
|
|
||||||
|
if (g_estop_active) {
|
||||||
|
/* Big E-STOP warning */
|
||||||
|
display.setTextSize(3);
|
||||||
|
display.setTextColor(SSD1306_WHITE);
|
||||||
|
display.setCursor(10, 4);
|
||||||
|
display.println(F("E-STOP"));
|
||||||
|
display.setTextSize(1);
|
||||||
|
display.setCursor(20, 48);
|
||||||
|
display.println(F("RELEASE TO CLEAR"));
|
||||||
|
display.display();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t now = millis();
|
||||||
|
|
||||||
|
/* Find closest anchor */
|
||||||
|
int32_t min_range = INT32_MAX;
|
||||||
|
for (int i = 0; i < NUM_ANCHORS; i++) {
|
||||||
|
if (g_anchor_range_mm[i] > 0 && g_anchor_range_mm[i] < min_range)
|
||||||
|
min_range = g_anchor_range_mm[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Line 1: Big distance to nearest anchor */
|
||||||
|
display.setTextSize(3);
|
||||||
|
display.setTextColor(SSD1306_WHITE);
|
||||||
|
display.setCursor(0, 0);
|
||||||
|
if (min_range < INT32_MAX && min_range > 0) {
|
||||||
|
float m = min_range / 1000.0f;
|
||||||
|
if (m < 10.0f)
|
||||||
|
display.printf("%.1fm", m);
|
||||||
|
else
|
||||||
|
display.printf("%.0fm", m);
|
||||||
|
} else {
|
||||||
|
display.println(F("---"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Line 2: Both anchor ranges */
|
||||||
|
display.setTextSize(1);
|
||||||
|
display.setCursor(0, 30);
|
||||||
|
for (int i = 0; i < NUM_ANCHORS && i < 2; i++) {
|
||||||
|
if (g_anchor_range_mm[i] > 0) {
|
||||||
|
float m = g_anchor_range_mm[i] / 1000.0f;
|
||||||
|
display.printf("A%d:%.1fm ", i, m);
|
||||||
|
} else {
|
||||||
|
display.printf("A%d:--- ", i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Line 3: Connection status */
|
||||||
|
display.setCursor(0, 42);
|
||||||
|
bool any_linked = false;
|
||||||
|
for (int i = 0; i < NUM_ANCHORS; i++) {
|
||||||
|
if (g_anchor_last_ok[i] > 0 && (now - g_anchor_last_ok[i]) < 2000) {
|
||||||
|
any_linked = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (any_linked) {
|
||||||
|
/* RSSI bar: map -90..-30 dBm to 0-5 bars */
|
||||||
|
float best_rssi = -100.0f;
|
||||||
|
for (int i = 0; i < NUM_ANCHORS; i++) {
|
||||||
|
if (g_anchor_rssi[i] > best_rssi) best_rssi = g_anchor_rssi[i];
|
||||||
|
}
|
||||||
|
int bars = constrain((int)((best_rssi + 90.0f) / 12.0f), 0, 5);
|
||||||
|
|
||||||
|
display.print(F("LINKED "));
|
||||||
|
/* Draw signal bars */
|
||||||
|
for (int b = 0; b < 5; b++) {
|
||||||
|
int x = 50 + b * 6;
|
||||||
|
int h = 2 + b * 2;
|
||||||
|
int y = 50 - h;
|
||||||
|
if (b < bars)
|
||||||
|
display.fillRect(x, y, 4, h, SSD1306_WHITE);
|
||||||
|
else
|
||||||
|
display.drawRect(x, y, 4, h, SSD1306_WHITE);
|
||||||
|
}
|
||||||
|
display.printf(" %.0fdB", best_rssi);
|
||||||
|
} else {
|
||||||
|
display.println(F("LOST -- searching --"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Line 4: Uptime */
|
||||||
|
display.setCursor(0, 54);
|
||||||
|
uint32_t secs = now / 1000;
|
||||||
|
display.printf("UP %02d:%02d seq:%d", secs / 60, secs % 60, g_seq);
|
||||||
|
|
||||||
|
display.display();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── DS-TWR initiator (one anchor, one cycle) ───────────────────── */
|
||||||
|
|
||||||
|
static int32_t twr_range_once(uint8_t anchor_id) {
|
||||||
|
|
||||||
|
/* --- 1. TX POLL --- */
|
||||||
|
uint8_t poll[POLL_FRAME_LEN];
|
||||||
|
poll[0] = FTYPE_POLL;
|
||||||
|
poll[1] = TAG_ID;
|
||||||
|
poll[2] = anchor_id;
|
||||||
|
|
||||||
|
dwt_writetxdata(POLL_FRAME_LEN - FCS_LEN, poll, 0);
|
||||||
|
dwt_writetxfctrl(POLL_FRAME_LEN, 0, 1);
|
||||||
|
|
||||||
|
dwt_setrxaftertxdelay(300);
|
||||||
|
dwt_setrxtimeout(RESP_RX_TIMEOUT_US);
|
||||||
|
|
||||||
|
g_tx_done = g_rx_ok = g_rx_err = g_rx_to = false;
|
||||||
|
if (dwt_starttx(DWT_START_TX_IMMEDIATE | DWT_RESPONSE_EXPECTED) != DWT_SUCCESS)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
uint32_t t0 = millis();
|
||||||
|
while (!g_tx_done && millis() - t0 < 15) yield();
|
||||||
|
|
||||||
|
uint8_t poll_tx_raw[5];
|
||||||
|
dwt_readtxtimestamp(poll_tx_raw);
|
||||||
|
uint64_t T_poll_tx = ts_read(poll_tx_raw);
|
||||||
|
|
||||||
|
/* --- 2. Wait for RESP --- */
|
||||||
|
t0 = millis();
|
||||||
|
while (!g_rx_ok && !g_rx_err && !g_rx_to && millis() - t0 < 60) yield();
|
||||||
|
if (!g_rx_ok || g_rx_len < FRAME_HDR + RESP_PAYLOAD) return -1;
|
||||||
|
if (g_rx_buf[0] != FTYPE_RESP) return -1;
|
||||||
|
if (g_rx_buf[2] != TAG_ID) return -1;
|
||||||
|
if (g_rx_buf[1] != anchor_id) return -1;
|
||||||
|
|
||||||
|
uint8_t resp_rx_raw[5];
|
||||||
|
dwt_readrxtimestamp(resp_rx_raw);
|
||||||
|
uint64_t T_resp_rx = ts_read(resp_rx_raw);
|
||||||
|
|
||||||
|
uint64_t T_poll_rx_a = ts_read(&g_rx_buf[3]);
|
||||||
|
uint64_t T_resp_tx_a = ts_read(&g_rx_buf[8]);
|
||||||
|
|
||||||
|
/* --- 3. Compute DS-TWR values for FINAL --- */
|
||||||
|
uint64_t Ra = ts_diff(T_resp_rx, T_poll_tx);
|
||||||
|
uint64_t Db = ts_diff(T_resp_tx_a, T_poll_rx_a);
|
||||||
|
|
||||||
|
uint64_t final_tx_sched = (T_resp_rx + FINAL_TX_DLY_TICKS) & ~0x1FFULL;
|
||||||
|
uint64_t Da = ts_diff(final_tx_sched, T_resp_rx);
|
||||||
|
|
||||||
|
/* --- 4. TX FINAL --- */
|
||||||
|
uint8_t final_buf[FINAL_FRAME_LEN];
|
||||||
|
final_buf[0] = FTYPE_FINAL;
|
||||||
|
final_buf[1] = TAG_ID;
|
||||||
|
final_buf[2] = anchor_id;
|
||||||
|
ts_write(&final_buf[3], Ra);
|
||||||
|
ts_write(&final_buf[8], Da);
|
||||||
|
ts_write(&final_buf[13], Db);
|
||||||
|
|
||||||
|
dwt_writetxdata(FINAL_FRAME_LEN - FCS_LEN, final_buf, 0);
|
||||||
|
dwt_writetxfctrl(FINAL_FRAME_LEN, 0, 1);
|
||||||
|
dwt_setdelayedtrxtime((uint32_t)(final_tx_sched >> 8));
|
||||||
|
|
||||||
|
g_tx_done = false;
|
||||||
|
if (dwt_starttx(DWT_START_TX_DELAYED) != DWT_SUCCESS) {
|
||||||
|
dwt_forcetrxoff();
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
t0 = millis();
|
||||||
|
while (!g_tx_done && millis() - t0 < 15) yield();
|
||||||
|
|
||||||
|
/* --- 5. Local range estimate (debug) --- */
|
||||||
|
uint8_t final_tx_raw[5];
|
||||||
|
dwt_readtxtimestamp(final_tx_raw);
|
||||||
|
/* uint64_t T_final_tx = ts_read(final_tx_raw); -- unused, tag uses SS estimate */
|
||||||
|
|
||||||
|
double ra = ticks_to_s(Ra);
|
||||||
|
double db = ticks_to_s(Db);
|
||||||
|
double tof = (ra - db) / 2.0;
|
||||||
|
double range_m = tof * SPEED_OF_LIGHT;
|
||||||
|
|
||||||
|
if (range_m < 0.1 || range_m > 130.0) return -1;
|
||||||
|
return (int32_t)(range_m * 1000.0 + 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Setup ──────────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
void setup(void) {
|
||||||
|
Serial.begin(SERIAL_BAUD);
|
||||||
|
delay(300);
|
||||||
|
|
||||||
|
/* E-Stop button */
|
||||||
|
pinMode(PIN_ESTOP, INPUT_PULLUP);
|
||||||
|
pinMode(PIN_LED, OUTPUT);
|
||||||
|
digitalWrite(PIN_LED, LOW);
|
||||||
|
|
||||||
|
Serial.printf("\r\n[uwb_tag] tag_id=0x%02X num_anchors=%d starting\r\n",
|
||||||
|
TAG_ID, NUM_ANCHORS);
|
||||||
|
|
||||||
|
/* --- OLED init --- */
|
||||||
|
Wire.begin(PIN_SDA, PIN_SCL);
|
||||||
|
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
|
||||||
|
Serial.println("[uwb_tag] WARN: SSD1306 not found — running headless");
|
||||||
|
} else {
|
||||||
|
display.clearDisplay();
|
||||||
|
display.setTextSize(2);
|
||||||
|
display.setTextColor(SSD1306_WHITE);
|
||||||
|
display.setCursor(0, 0);
|
||||||
|
display.println(F("SaltyBot"));
|
||||||
|
display.setTextSize(1);
|
||||||
|
display.setCursor(0, 20);
|
||||||
|
display.printf("Tag 0x%02X v2.0", TAG_ID);
|
||||||
|
display.setCursor(0, 35);
|
||||||
|
display.println(F("DW3000 DS-TWR + ESP-NOW"));
|
||||||
|
display.setCursor(0, 50);
|
||||||
|
display.println(F("Initializing..."));
|
||||||
|
display.display();
|
||||||
|
Serial.println("[uwb_tag] OLED ok");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- ESP-NOW init --- */
|
||||||
|
WiFi.mode(WIFI_STA);
|
||||||
|
WiFi.disconnect();
|
||||||
|
/* Set WiFi channel to match anchors (default ch 1) */
|
||||||
|
esp_wifi_set_channel(1, WIFI_SECOND_CHAN_NONE);
|
||||||
|
|
||||||
|
if (esp_now_init() != ESP_OK) {
|
||||||
|
Serial.println("[uwb_tag] FATAL: esp_now_init failed");
|
||||||
|
for (;;) delay(1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Add broadcast peer */
|
||||||
|
esp_now_peer_info_t peer = {};
|
||||||
|
memcpy(peer.peer_addr, broadcast_mac, 6);
|
||||||
|
peer.channel = 0; /* use current channel */
|
||||||
|
peer.encrypt = false;
|
||||||
|
esp_now_add_peer(&peer);
|
||||||
|
Serial.println("[uwb_tag] ESP-NOW ok");
|
||||||
|
|
||||||
|
/* --- DW3000 init --- */
|
||||||
|
SPI.begin(PIN_SCK, PIN_MISO, PIN_MOSI, PIN_CS);
|
||||||
|
|
||||||
|
pinMode(PIN_RST, OUTPUT);
|
||||||
|
digitalWrite(PIN_RST, LOW);
|
||||||
|
delay(2);
|
||||||
|
pinMode(PIN_RST, INPUT_PULLUP);
|
||||||
|
delay(5);
|
||||||
|
|
||||||
|
if (dwt_probe((struct dwt_probe_s *)&dw3000_probe_interf)) {
|
||||||
|
Serial.println("[uwb_tag] FATAL: DW3000 probe failed");
|
||||||
|
for (;;) delay(1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dwt_initialise(DWT_DW_INIT) != DWT_SUCCESS) {
|
||||||
|
Serial.println("[uwb_tag] FATAL: dwt_initialise failed");
|
||||||
|
for (;;) delay(1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dwt_configure(&dw_cfg) != DWT_SUCCESS) {
|
||||||
|
Serial.println("[uwb_tag] FATAL: dwt_configure failed");
|
||||||
|
for (;;) delay(1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
dwt_setrxantennadelay(ANT_DELAY);
|
||||||
|
dwt_settxantennadelay(ANT_DELAY);
|
||||||
|
dwt_settxpower(0x0E080222UL);
|
||||||
|
|
||||||
|
dwt_setcallbacks(cb_tx_done, cb_rx_ok, cb_rx_to, cb_rx_err,
|
||||||
|
nullptr, nullptr, nullptr);
|
||||||
|
dwt_setinterrupt(
|
||||||
|
DWT_INT_TXFRS | DWT_INT_RFCG | DWT_INT_RFTO |
|
||||||
|
DWT_INT_RFSL | DWT_INT_SFDT | DWT_INT_ARFE | DWT_INT_CPERR,
|
||||||
|
0, DWT_ENABLE_INT_ONLY);
|
||||||
|
|
||||||
|
attachInterrupt(digitalPinToInterrupt(PIN_IRQ),
|
||||||
|
[]() { dwt_isr(); }, RISING);
|
||||||
|
|
||||||
|
/* Init range state */
|
||||||
|
for (int i = 0; i < NUM_ANCHORS; i++) {
|
||||||
|
g_anchor_range_mm[i] = -1;
|
||||||
|
g_anchor_rssi[i] = -100.0f;
|
||||||
|
g_anchor_last_ok[i] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[uwb_tag] DW3000 ready ch=%d 6.8Mbps tag=0x%02X\r\n",
|
||||||
|
dw_cfg.chan, TAG_ID);
|
||||||
|
Serial.println("[uwb_tag] Ranging + ESP-NOW + display active");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Main loop ──────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
void loop(void) {
|
||||||
|
static uint8_t anchor_idx = 0;
|
||||||
|
static uint32_t last_range_ms = 0;
|
||||||
|
static uint32_t last_hb_ms = 0;
|
||||||
|
|
||||||
|
/* E-Stop always has priority */
|
||||||
|
estop_check();
|
||||||
|
if (g_estop_active) {
|
||||||
|
display_update();
|
||||||
|
return; /* skip ranging while e-stop active */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Heartbeat every 1 second */
|
||||||
|
uint32_t now = millis();
|
||||||
|
if (now - last_hb_ms >= 1000) {
|
||||||
|
espnow_send(MSG_HEARTBEAT, 0xFF, 0, 0.0f);
|
||||||
|
last_hb_ms = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Ranging at configured interval */
|
||||||
|
if (now - last_range_ms >= RANGE_INTERVAL_MS) {
|
||||||
|
last_range_ms = now;
|
||||||
|
|
||||||
|
uint8_t anchor_id = anchor_idx % NUM_ANCHORS;
|
||||||
|
int32_t range_mm = twr_range_once(anchor_id);
|
||||||
|
|
||||||
|
if (range_mm > 0) {
|
||||||
|
float rssi = rx_power_dbm();
|
||||||
|
|
||||||
|
/* Update shared state for display */
|
||||||
|
g_anchor_range_mm[anchor_id] = range_mm;
|
||||||
|
g_anchor_rssi[anchor_id] = rssi;
|
||||||
|
g_anchor_last_ok[anchor_id] = now;
|
||||||
|
|
||||||
|
/* Serial debug */
|
||||||
|
Serial.printf("+RANGE:%d,%ld,%.1f\r\n",
|
||||||
|
anchor_id, (long)range_mm, rssi);
|
||||||
|
|
||||||
|
/* ESP-NOW broadcast */
|
||||||
|
espnow_send(MSG_RANGE, anchor_id, range_mm, rssi);
|
||||||
|
|
||||||
|
/* LED blink */
|
||||||
|
digitalWrite(PIN_LED, HIGH);
|
||||||
|
delay(2);
|
||||||
|
digitalWrite(PIN_LED, LOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
anchor_idx++;
|
||||||
|
if (anchor_idx >= NUM_ANCHORS) anchor_idx = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Display at 5 Hz (non-blocking) */
|
||||||
|
display_update();
|
||||||
|
}
|
||||||
3
esp32s3/balance/CMakeLists.txt
Normal file
3
esp32s3/balance/CMakeLists.txt
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.16)
|
||||||
|
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||||
|
project(esp32s3_balance)
|
||||||
22
esp32s3/balance/main/CMakeLists.txt
Normal file
22
esp32s3/balance/main/CMakeLists.txt
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
idf_component_register(
|
||||||
|
SRCS
|
||||||
|
"main.c"
|
||||||
|
"orin_serial.c"
|
||||||
|
"vesc_can.c"
|
||||||
|
"gitea_ota.c"
|
||||||
|
"ota_self.c"
|
||||||
|
"uart_ota.c"
|
||||||
|
"ota_display.c"
|
||||||
|
INCLUDE_DIRS "."
|
||||||
|
REQUIRES
|
||||||
|
esp_wifi
|
||||||
|
esp_http_client
|
||||||
|
esp_https_ota
|
||||||
|
nvs_flash
|
||||||
|
app_update
|
||||||
|
mbedtls
|
||||||
|
cJSON
|
||||||
|
driver
|
||||||
|
freertos
|
||||||
|
esp_timer
|
||||||
|
)
|
||||||
42
esp32s3/balance/main/config.h
Normal file
42
esp32s3/balance/main/config.h
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
/* ── ESP32-S3 BALANCE board — bd-66hx pin/config definitions ───────────────
|
||||||
|
*
|
||||||
|
* Hardware change from pre-bd-66hx design:
|
||||||
|
* Previously: IO43/IO44 = CAN SN65HVD230 (shared Orin+VESC bus via CANable2)
|
||||||
|
* After bd-66hx: IO43/IO44 = CH343 UART0 (Orin serial comms)
|
||||||
|
* IO2/IO1 = CAN SN65HVD230 rewired (VESC-only bus)
|
||||||
|
*
|
||||||
|
* The SN65HVD230 transceiver physical wiring must be updated from IO43/44
|
||||||
|
* to IO2/IO1 when deploying this firmware. See docs/SAUL-TEE-SYSTEM-REFERENCE.md.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* ── Orin serial (CH343 USB-to-UART, 1a86:55d3 on Orin side) ── */
|
||||||
|
#define ORIN_UART_PORT UART_NUM_0
|
||||||
|
#define ORIN_UART_BAUD 460800
|
||||||
|
#define ORIN_UART_TX_GPIO 43 /* ESP32→CH343 RXD */
|
||||||
|
#define ORIN_UART_RX_GPIO 44 /* CH343 TXD→ESP32 */
|
||||||
|
#define ORIN_UART_RX_BUF 1024
|
||||||
|
#define ORIN_TX_QUEUE_DEPTH 16
|
||||||
|
|
||||||
|
/* ── VESC CAN TWAI (SN65HVD230 transceiver, rewired for bd-66hx) ── */
|
||||||
|
#define VESC_CAN_TX_GPIO 2 /* ESP32 TWAI TX → SN65HVD230 TXD */
|
||||||
|
#define VESC_CAN_RX_GPIO 1 /* SN65HVD230 RXD → ESP32 TWAI RX */
|
||||||
|
#define VESC_CAN_RX_QUEUE 32
|
||||||
|
|
||||||
|
/* VESC node IDs — matched to bd-wim1 TELEM_VESC_LEFT/RIGHT mapping */
|
||||||
|
#define VESC_ID_A 56u /* TELEM_VESC_LEFT (0x81) */
|
||||||
|
#define VESC_ID_B 68u /* TELEM_VESC_RIGHT (0x82) */
|
||||||
|
|
||||||
|
/* ── Safety / timing ── */
|
||||||
|
#define HB_TIMEOUT_MS 500u /* heartbeat watchdog: disarm if exceeded */
|
||||||
|
#define DRIVE_TIMEOUT_MS 500u /* drive command staleness timeout */
|
||||||
|
#define TELEM_STATUS_PERIOD_MS 100u /* 10 Hz status telemetry to Orin */
|
||||||
|
#define TELEM_VESC_PERIOD_MS 100u /* 10 Hz VESC telemetry to Orin */
|
||||||
|
|
||||||
|
/* ── Drive → VESC RPM scaling ── */
|
||||||
|
#define RPM_PER_SPEED_UNIT 5 /* speed_units=1000 → 5000 ERPM */
|
||||||
|
#define RPM_PER_STEER_UNIT 3 /* steer differential scale */
|
||||||
|
|
||||||
|
/* ── Tilt cutoff ── */
|
||||||
|
#define TILT_CUTOFF_DEG 25.0f
|
||||||
285
esp32s3/balance/main/gitea_ota.c
Normal file
285
esp32s3/balance/main/gitea_ota.c
Normal file
@ -0,0 +1,285 @@
|
|||||||
|
/* gitea_ota.c — Gitea version checker (bd-3hte)
|
||||||
|
*
|
||||||
|
* Uses esp_http_client + cJSON to query:
|
||||||
|
* GET /api/v1/repos/{repo}/releases?limit=10
|
||||||
|
* Filters releases by tag prefix, extracts version and download URLs.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "gitea_ota.h"
|
||||||
|
#include "version.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_wifi.h"
|
||||||
|
#include "esp_event.h"
|
||||||
|
#include "esp_netif.h"
|
||||||
|
#include "esp_http_client.h"
|
||||||
|
#include "nvs_flash.h"
|
||||||
|
#include "nvs.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "freertos/event_groups.h"
|
||||||
|
#include "cJSON.h"
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
static const char *TAG = "gitea_ota";
|
||||||
|
|
||||||
|
ota_update_info_t g_balance_update = {0};
|
||||||
|
ota_update_info_t g_io_update = {0};
|
||||||
|
|
||||||
|
/* ── WiFi connection ── */
|
||||||
|
#define WIFI_CONNECTED_BIT BIT0
|
||||||
|
#define WIFI_FAIL_BIT BIT1
|
||||||
|
#define WIFI_MAX_RETRIES 5
|
||||||
|
|
||||||
|
/* Compile-time WiFi fallback (override in NVS "wifi"/"ssid","pass") */
|
||||||
|
#define DEFAULT_WIFI_SSID "saltylab"
|
||||||
|
#define DEFAULT_WIFI_PASS ""
|
||||||
|
|
||||||
|
static EventGroupHandle_t s_wifi_eg;
|
||||||
|
static int s_wifi_retries = 0;
|
||||||
|
|
||||||
|
static void wifi_event_handler(void *arg, esp_event_base_t base,
|
||||||
|
int32_t id, void *data)
|
||||||
|
{
|
||||||
|
if (base == WIFI_EVENT && id == WIFI_EVENT_STA_START) {
|
||||||
|
esp_wifi_connect();
|
||||||
|
} else if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
|
||||||
|
if (s_wifi_retries < WIFI_MAX_RETRIES) {
|
||||||
|
esp_wifi_connect();
|
||||||
|
s_wifi_retries++;
|
||||||
|
} else {
|
||||||
|
xEventGroupSetBits(s_wifi_eg, WIFI_FAIL_BIT);
|
||||||
|
}
|
||||||
|
} else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
|
||||||
|
s_wifi_retries = 0;
|
||||||
|
xEventGroupSetBits(s_wifi_eg, WIFI_CONNECTED_BIT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool wifi_connect(void)
|
||||||
|
{
|
||||||
|
char ssid[64] = DEFAULT_WIFI_SSID;
|
||||||
|
char pass[64] = DEFAULT_WIFI_PASS;
|
||||||
|
|
||||||
|
/* Try to read credentials from NVS */
|
||||||
|
nvs_handle_t nvs;
|
||||||
|
if (nvs_open("wifi", NVS_READONLY, &nvs) == ESP_OK) {
|
||||||
|
size_t sz = sizeof(ssid);
|
||||||
|
nvs_get_str(nvs, "ssid", ssid, &sz);
|
||||||
|
sz = sizeof(pass);
|
||||||
|
nvs_get_str(nvs, "pass", pass, &sz);
|
||||||
|
nvs_close(nvs);
|
||||||
|
}
|
||||||
|
|
||||||
|
s_wifi_eg = xEventGroupCreate();
|
||||||
|
s_wifi_retries = 0;
|
||||||
|
|
||||||
|
ESP_ERROR_CHECK(esp_netif_init());
|
||||||
|
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||||
|
esp_netif_create_default_wifi_sta();
|
||||||
|
|
||||||
|
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||||
|
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||||
|
|
||||||
|
esp_event_handler_instance_t h1, h2;
|
||||||
|
ESP_ERROR_CHECK(esp_event_handler_instance_register(
|
||||||
|
WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_event_handler, NULL, &h1));
|
||||||
|
ESP_ERROR_CHECK(esp_event_handler_instance_register(
|
||||||
|
IP_EVENT, IP_EVENT_STA_GOT_IP, wifi_event_handler, NULL, &h2));
|
||||||
|
|
||||||
|
wifi_config_t wcfg = {0};
|
||||||
|
strlcpy((char *)wcfg.sta.ssid, ssid, sizeof(wcfg.sta.ssid));
|
||||||
|
strlcpy((char *)wcfg.sta.password, pass, sizeof(wcfg.sta.password));
|
||||||
|
|
||||||
|
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||||
|
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wcfg));
|
||||||
|
ESP_ERROR_CHECK(esp_wifi_start());
|
||||||
|
|
||||||
|
EventBits_t bits = xEventGroupWaitBits(s_wifi_eg,
|
||||||
|
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, pdFALSE, pdFALSE,
|
||||||
|
pdMS_TO_TICKS(15000));
|
||||||
|
|
||||||
|
esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, h2);
|
||||||
|
esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, h1);
|
||||||
|
vEventGroupDelete(s_wifi_eg);
|
||||||
|
|
||||||
|
if (bits & WIFI_CONNECTED_BIT) {
|
||||||
|
ESP_LOGI(TAG, "WiFi connected SSID=%s", ssid);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
ESP_LOGW(TAG, "WiFi connect failed SSID=%s", ssid);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── HTTP fetch into a heap buffer ── */
|
||||||
|
#define HTTP_RESP_MAX (8 * 1024)
|
||||||
|
|
||||||
|
typedef struct { char *buf; int len; int cap; } http_buf_t;
|
||||||
|
|
||||||
|
static esp_err_t http_event_cb(esp_http_client_event_t *evt)
|
||||||
|
{
|
||||||
|
http_buf_t *b = (http_buf_t *)evt->user_data;
|
||||||
|
if (evt->event_id == HTTP_EVENT_ON_DATA && b) {
|
||||||
|
if (b->len + evt->data_len < b->cap) {
|
||||||
|
memcpy(b->buf + b->len, evt->data, evt->data_len);
|
||||||
|
b->len += evt->data_len;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
static char *http_get(const char *url)
|
||||||
|
{
|
||||||
|
char *buf = malloc(HTTP_RESP_MAX);
|
||||||
|
if (!buf) return NULL;
|
||||||
|
http_buf_t b = {.buf = buf, .len = 0, .cap = HTTP_RESP_MAX};
|
||||||
|
buf[0] = '\0';
|
||||||
|
|
||||||
|
esp_http_client_config_t cfg = {
|
||||||
|
.url = url,
|
||||||
|
.event_handler = http_event_cb,
|
||||||
|
.user_data = &b,
|
||||||
|
.timeout_ms = GITEA_API_TIMEOUT_MS,
|
||||||
|
.skip_cert_common_name_check = true,
|
||||||
|
};
|
||||||
|
esp_http_client_handle_t client = esp_http_client_init(&cfg);
|
||||||
|
esp_err_t err = esp_http_client_perform(client);
|
||||||
|
int status = esp_http_client_get_status_code(client);
|
||||||
|
esp_http_client_cleanup(client);
|
||||||
|
|
||||||
|
if (err != ESP_OK || status != 200) {
|
||||||
|
ESP_LOGW(TAG, "HTTP GET %s → err=%d status=%d", url, err, status);
|
||||||
|
free(buf);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
buf[b.len] = '\0';
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Version comparison: returns true if remote > local ── */
|
||||||
|
static bool version_newer(const char *local, const char *remote)
|
||||||
|
{
|
||||||
|
int la=0,lb=0,lc=0, ra=0,rb=0,rc=0;
|
||||||
|
sscanf(local, "%d.%d.%d", &la, &lb, &lc);
|
||||||
|
sscanf(remote, "%d.%d.%d", &ra, &rb, &rc);
|
||||||
|
if (ra != la) return ra > la;
|
||||||
|
if (rb != lb) return rb > lb;
|
||||||
|
return rc > lc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Parse releases JSON array, fill ota_update_info_t ── */
|
||||||
|
static void parse_releases(const char *json, const char *tag_prefix,
|
||||||
|
const char *bin_asset, const char *sha_asset,
|
||||||
|
const char *local_version,
|
||||||
|
ota_update_info_t *out)
|
||||||
|
{
|
||||||
|
cJSON *arr = cJSON_Parse(json);
|
||||||
|
if (!arr || !cJSON_IsArray(arr)) {
|
||||||
|
ESP_LOGW(TAG, "JSON parse failed");
|
||||||
|
cJSON_Delete(arr);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
cJSON *rel;
|
||||||
|
cJSON_ArrayForEach(rel, arr) {
|
||||||
|
cJSON *tag_j = cJSON_GetObjectItem(rel, "tag_name");
|
||||||
|
if (!cJSON_IsString(tag_j)) continue;
|
||||||
|
|
||||||
|
const char *tag = tag_j->valuestring;
|
||||||
|
if (strncmp(tag, tag_prefix, strlen(tag_prefix)) != 0) continue;
|
||||||
|
|
||||||
|
/* Extract version after prefix */
|
||||||
|
const char *ver = tag + strlen(tag_prefix);
|
||||||
|
if (*ver == 'v') ver++; /* strip leading 'v' */
|
||||||
|
|
||||||
|
if (!version_newer(local_version, ver)) continue;
|
||||||
|
|
||||||
|
/* Found a newer release — extract asset URLs */
|
||||||
|
cJSON *assets = cJSON_GetObjectItem(rel, "assets");
|
||||||
|
if (!cJSON_IsArray(assets)) continue;
|
||||||
|
|
||||||
|
out->available = false;
|
||||||
|
out->download_url[0] = '\0';
|
||||||
|
out->sha256[0] = '\0';
|
||||||
|
strlcpy(out->version, ver, sizeof(out->version));
|
||||||
|
|
||||||
|
cJSON *asset;
|
||||||
|
cJSON_ArrayForEach(asset, assets) {
|
||||||
|
cJSON *name_j = cJSON_GetObjectItem(asset, "name");
|
||||||
|
cJSON *url_j = cJSON_GetObjectItem(asset, "browser_download_url");
|
||||||
|
if (!cJSON_IsString(name_j) || !cJSON_IsString(url_j)) continue;
|
||||||
|
|
||||||
|
if (strcmp(name_j->valuestring, bin_asset) == 0) {
|
||||||
|
strlcpy(out->download_url, url_j->valuestring,
|
||||||
|
sizeof(out->download_url));
|
||||||
|
out->available = true;
|
||||||
|
} else if (strcmp(name_j->valuestring, sha_asset) == 0) {
|
||||||
|
/* Download the SHA256 asset inline */
|
||||||
|
char *sha = http_get(url_j->valuestring);
|
||||||
|
if (sha) {
|
||||||
|
/* sha file is just hex+newline */
|
||||||
|
size_t n = strspn(sha, "0123456789abcdefABCDEF");
|
||||||
|
if (n == 64) {
|
||||||
|
memcpy(out->sha256, sha, 64);
|
||||||
|
out->sha256[64] = '\0';
|
||||||
|
}
|
||||||
|
free(sha);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (out->available) {
|
||||||
|
ESP_LOGI(TAG, "update: tag=%s ver=%s", tag, out->version);
|
||||||
|
}
|
||||||
|
break; /* use first matching release */
|
||||||
|
}
|
||||||
|
|
||||||
|
cJSON_Delete(arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Main check ── */
|
||||||
|
void gitea_ota_check_now(void)
|
||||||
|
{
|
||||||
|
char url[512];
|
||||||
|
snprintf(url, sizeof(url),
|
||||||
|
"%s/api/v1/repos/%s/releases?limit=10",
|
||||||
|
GITEA_BASE_URL, GITEA_REPO);
|
||||||
|
|
||||||
|
char *json = http_get(url);
|
||||||
|
if (!json) {
|
||||||
|
ESP_LOGW(TAG, "releases fetch failed");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
parse_releases(json, BALANCE_TAG_PREFIX, BALANCE_BIN_ASSET,
|
||||||
|
BALANCE_SHA256_ASSET, BALANCE_FW_VERSION, &g_balance_update);
|
||||||
|
parse_releases(json, IO_TAG_PREFIX, IO_BIN_ASSET,
|
||||||
|
IO_SHA256_ASSET, IO_FW_VERSION, &g_io_update);
|
||||||
|
free(json);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Background task ── */
|
||||||
|
static void version_check_task(void *arg)
|
||||||
|
{
|
||||||
|
/* Initial check immediately after WiFi up */
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||||
|
gitea_ota_check_now();
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(VERSION_CHECK_PERIOD_MS));
|
||||||
|
gitea_ota_check_now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void gitea_ota_init(void)
|
||||||
|
{
|
||||||
|
ESP_ERROR_CHECK(nvs_flash_init());
|
||||||
|
|
||||||
|
if (!wifi_connect()) {
|
||||||
|
ESP_LOGW(TAG, "WiFi unavailable — version checks disabled");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
xTaskCreate(version_check_task, "ver_check", 6144, NULL, 3, NULL);
|
||||||
|
ESP_LOGI(TAG, "version check task started");
|
||||||
|
}
|
||||||
42
esp32s3/balance/main/gitea_ota.h
Normal file
42
esp32s3/balance/main/gitea_ota.h
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
#pragma once
|
||||||
|
/* gitea_ota.h — Gitea release version checker (bd-3hte)
|
||||||
|
*
|
||||||
|
* WiFi task: on boot and every 30 min, queries Gitea releases API,
|
||||||
|
* compares tag version against embedded FW_VERSION, stores update info.
|
||||||
|
*
|
||||||
|
* WiFi credentials read from NVS namespace "wifi" keys "ssid"/"pass".
|
||||||
|
* Fall back to compile-time defaults if NVS is empty.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
/* Gitea instance */
|
||||||
|
#define GITEA_BASE_URL "http://gitea.vayrette.com"
|
||||||
|
#define GITEA_REPO "seb/saltylab-firmware"
|
||||||
|
#define GITEA_API_TIMEOUT_MS 10000
|
||||||
|
|
||||||
|
/* Version check interval */
|
||||||
|
#define VERSION_CHECK_PERIOD_MS (30u * 60u * 1000u) /* 30 minutes */
|
||||||
|
|
||||||
|
/* Max URL/version string lengths */
|
||||||
|
#define OTA_URL_MAX 384
|
||||||
|
#define OTA_VER_MAX 32
|
||||||
|
#define OTA_SHA256_MAX 65
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
bool available;
|
||||||
|
char version[OTA_VER_MAX]; /* remote version string, e.g. "1.2.3" */
|
||||||
|
char download_url[OTA_URL_MAX]; /* direct download URL for .bin */
|
||||||
|
char sha256[OTA_SHA256_MAX]; /* hex SHA256 (from .sha256 asset), or "" */
|
||||||
|
} ota_update_info_t;
|
||||||
|
|
||||||
|
/* Shared state — written by gitea_ota_check_task, read by display/OTA tasks */
|
||||||
|
extern ota_update_info_t g_balance_update;
|
||||||
|
extern ota_update_info_t g_io_update;
|
||||||
|
|
||||||
|
/* Initialize WiFi and start version check task */
|
||||||
|
void gitea_ota_init(void);
|
||||||
|
|
||||||
|
/* One-shot sync check (can be called from any task) */
|
||||||
|
void gitea_ota_check_now(void);
|
||||||
114
esp32s3/balance/main/main.c
Normal file
114
esp32s3/balance/main/main.c
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
/* main.c — ESP32-S3 BALANCE app_main (bd-66hx + OTA beads) */
|
||||||
|
|
||||||
|
#include "orin_serial.h"
|
||||||
|
#include "vesc_can.h"
|
||||||
|
#include "gitea_ota.h"
|
||||||
|
#include "ota_self.h"
|
||||||
|
#include "uart_ota.h"
|
||||||
|
#include "ota_display.h"
|
||||||
|
#include "config.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "freertos/queue.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
static const char *TAG = "main";
|
||||||
|
|
||||||
|
static QueueHandle_t s_orin_tx_q;
|
||||||
|
|
||||||
|
/* ── Telemetry task: sends TELEM_STATUS to Orin at 10 Hz ── */
|
||||||
|
static void telem_task(void *arg)
|
||||||
|
{
|
||||||
|
for (;;) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(TELEM_STATUS_PERIOD_MS));
|
||||||
|
|
||||||
|
uint32_t now_ms = (uint32_t)(esp_timer_get_time() / 1000LL);
|
||||||
|
bool hb_timeout = (now_ms - g_orin_ctrl.hb_last_ms) > HB_TIMEOUT_MS;
|
||||||
|
|
||||||
|
/* Determine balance state for telemetry */
|
||||||
|
bal_state_t state;
|
||||||
|
if (g_orin_ctrl.estop) {
|
||||||
|
state = BAL_ESTOP;
|
||||||
|
} else if (!g_orin_ctrl.armed) {
|
||||||
|
state = BAL_DISARMED;
|
||||||
|
} else {
|
||||||
|
state = BAL_ARMED;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* flags: bit0=estop_active, bit1=heartbeat_timeout */
|
||||||
|
uint8_t flags = (g_orin_ctrl.estop ? 0x01u : 0x00u) |
|
||||||
|
(hb_timeout ? 0x02u : 0x00u);
|
||||||
|
|
||||||
|
/* Battery voltage from VESC_ID_A STATUS_5 (V×10 → mV) */
|
||||||
|
uint16_t vbat_mv = (uint16_t)((int32_t)g_vesc[0].voltage_x10 * 100);
|
||||||
|
|
||||||
|
orin_send_status(s_orin_tx_q,
|
||||||
|
0, /* pitch_x10: stub — full IMU in future bead */
|
||||||
|
0, /* motor_cmd: stub */
|
||||||
|
vbat_mv,
|
||||||
|
state,
|
||||||
|
flags);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Drive task: applies Orin drive commands to VESCs @ 50 Hz ── */
|
||||||
|
static void drive_task(void *arg)
|
||||||
|
{
|
||||||
|
for (;;) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(20)); /* 50 Hz */
|
||||||
|
|
||||||
|
uint32_t now_ms = (uint32_t)(esp_timer_get_time() / 1000LL);
|
||||||
|
bool hb_timeout = (now_ms - g_orin_ctrl.hb_last_ms) > HB_TIMEOUT_MS;
|
||||||
|
bool drive_stale = (now_ms - g_orin_drive.updated_ms) > DRIVE_TIMEOUT_MS;
|
||||||
|
|
||||||
|
int32_t left_erpm = 0;
|
||||||
|
int32_t right_erpm = 0;
|
||||||
|
|
||||||
|
if (g_orin_ctrl.armed && !g_orin_ctrl.estop &&
|
||||||
|
!hb_timeout && !drive_stale) {
|
||||||
|
int32_t spd = (int32_t)g_orin_drive.speed * RPM_PER_SPEED_UNIT;
|
||||||
|
int32_t str = (int32_t)g_orin_drive.steer * RPM_PER_STEER_UNIT;
|
||||||
|
left_erpm = spd + str;
|
||||||
|
right_erpm = spd - str;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* VESC_ID_A (56) = LEFT, VESC_ID_B (68) = RIGHT per bd-wim1 protocol */
|
||||||
|
vesc_can_send_rpm(VESC_ID_A, left_erpm);
|
||||||
|
vesc_can_send_rpm(VESC_ID_B, right_erpm);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void app_main(void)
|
||||||
|
{
|
||||||
|
ESP_LOGI(TAG, "ESP32-S3 BALANCE starting");
|
||||||
|
|
||||||
|
/* OTA rollback health check — must be called within OTA_ROLLBACK_WINDOW_S */
|
||||||
|
ota_self_health_check();
|
||||||
|
|
||||||
|
/* Init peripherals */
|
||||||
|
orin_serial_init();
|
||||||
|
vesc_can_init();
|
||||||
|
|
||||||
|
/* TX queue for outbound serial frames */
|
||||||
|
s_orin_tx_q = xQueueCreate(ORIN_TX_QUEUE_DEPTH, sizeof(orin_tx_frame_t));
|
||||||
|
configASSERT(s_orin_tx_q);
|
||||||
|
|
||||||
|
/* Seed heartbeat timer so we don't immediately timeout */
|
||||||
|
g_orin_ctrl.hb_last_ms = (uint32_t)(esp_timer_get_time() / 1000LL);
|
||||||
|
|
||||||
|
/* Create tasks */
|
||||||
|
xTaskCreate(orin_serial_rx_task, "orin_rx", 4096, s_orin_tx_q, 10, NULL);
|
||||||
|
xTaskCreate(orin_serial_tx_task, "orin_tx", 2048, s_orin_tx_q, 9, NULL);
|
||||||
|
xTaskCreate(vesc_can_rx_task, "vesc_rx", 4096, s_orin_tx_q, 10, NULL);
|
||||||
|
xTaskCreate(telem_task, "telem", 2048, NULL, 5, NULL);
|
||||||
|
xTaskCreate(drive_task, "drive", 2048, NULL, 8, NULL);
|
||||||
|
|
||||||
|
/* OTA subsystem — WiFi version checker + display overlay */
|
||||||
|
gitea_ota_init();
|
||||||
|
ota_display_init();
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "all tasks started");
|
||||||
|
/* app_main returns — FreeRTOS scheduler continues */
|
||||||
|
}
|
||||||
354
esp32s3/balance/main/orin_serial.c
Normal file
354
esp32s3/balance/main/orin_serial.c
Normal file
@ -0,0 +1,354 @@
|
|||||||
|
/* orin_serial.c — Orin↔ESP32-S3 serial protocol (bd-66hx + bd-1s1s OTA cmds) */
|
||||||
|
|
||||||
|
#include "orin_serial.h"
|
||||||
|
#include "config.h"
|
||||||
|
#include "gitea_ota.h"
|
||||||
|
#include "ota_self.h"
|
||||||
|
#include "uart_ota.h"
|
||||||
|
#include "version.h"
|
||||||
|
#include "driver/uart.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/queue.h"
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
static const char *TAG = "orin";
|
||||||
|
|
||||||
|
/* ── Shared state ── */
|
||||||
|
orin_drive_t g_orin_drive = {0};
|
||||||
|
orin_pid_t g_orin_pid = {0};
|
||||||
|
orin_control_t g_orin_ctrl = {.armed = false, .estop = false, .hb_last_ms = 0};
|
||||||
|
|
||||||
|
/* ── CRC8-SMBUS (poly=0x07, init=0x00) ── */
|
||||||
|
static uint8_t crc8(const uint8_t *data, uint8_t len)
|
||||||
|
{
|
||||||
|
uint8_t crc = 0x00u;
|
||||||
|
for (uint8_t i = 0; i < len; i++) {
|
||||||
|
crc ^= data[i];
|
||||||
|
for (uint8_t b = 0; b < 8u; b++) {
|
||||||
|
crc = (crc & 0x80u) ? (uint8_t)((crc << 1u) ^ 0x07u) : (uint8_t)(crc << 1u);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return crc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Frame builder ── */
|
||||||
|
static void build_frame(orin_tx_frame_t *f, uint8_t out[/* ORIN_MAX_PAYLOAD + 4 */], uint8_t *out_len)
|
||||||
|
{
|
||||||
|
/* [SYNC][LEN][TYPE][PAYLOAD...][CRC] */
|
||||||
|
uint8_t crc_buf[2u + ORIN_MAX_PAYLOAD];
|
||||||
|
crc_buf[0] = f->len;
|
||||||
|
crc_buf[1] = f->type;
|
||||||
|
memcpy(&crc_buf[2], f->payload, f->len);
|
||||||
|
uint8_t crc = crc8(crc_buf, (uint8_t)(2u + f->len));
|
||||||
|
|
||||||
|
out[0] = ORIN_SYNC;
|
||||||
|
out[1] = f->len;
|
||||||
|
out[2] = f->type;
|
||||||
|
memcpy(&out[3], f->payload, f->len);
|
||||||
|
out[3u + f->len] = crc;
|
||||||
|
*out_len = (uint8_t)(4u + f->len);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Enqueue helpers ── */
|
||||||
|
static void enqueue(QueueHandle_t q, uint8_t type, const uint8_t *payload, uint8_t len)
|
||||||
|
{
|
||||||
|
orin_tx_frame_t f = {.type = type, .len = len};
|
||||||
|
if (len > 0u && payload) {
|
||||||
|
memcpy(f.payload, payload, len);
|
||||||
|
}
|
||||||
|
if (xQueueSend(q, &f, 0) != pdTRUE) {
|
||||||
|
ESP_LOGW(TAG, "tx queue full, dropped type=0x%02x", type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void orin_send_ack(QueueHandle_t q, uint8_t cmd_type)
|
||||||
|
{
|
||||||
|
enqueue(q, RESP_ACK, &cmd_type, 1u);
|
||||||
|
}
|
||||||
|
|
||||||
|
void orin_send_nack(QueueHandle_t q, uint8_t cmd_type, uint8_t err)
|
||||||
|
{
|
||||||
|
uint8_t p[2] = {cmd_type, err};
|
||||||
|
enqueue(q, RESP_NACK, p, 2u);
|
||||||
|
}
|
||||||
|
|
||||||
|
void orin_send_status(QueueHandle_t q,
|
||||||
|
int16_t pitch_x10, int16_t motor_cmd,
|
||||||
|
uint16_t vbat_mv, bal_state_t state, uint8_t flags)
|
||||||
|
{
|
||||||
|
/* int16 pitch_x10, int16 motor_cmd, uint16 vbat_mv, uint8 state, uint8 flags — BE */
|
||||||
|
uint8_t p[8];
|
||||||
|
p[0] = (uint8_t)((uint16_t)pitch_x10 >> 8u);
|
||||||
|
p[1] = (uint8_t)((uint16_t)pitch_x10);
|
||||||
|
p[2] = (uint8_t)((uint16_t)motor_cmd >> 8u);
|
||||||
|
p[3] = (uint8_t)((uint16_t)motor_cmd);
|
||||||
|
p[4] = (uint8_t)(vbat_mv >> 8u);
|
||||||
|
p[5] = (uint8_t)(vbat_mv);
|
||||||
|
p[6] = (uint8_t)state;
|
||||||
|
p[7] = flags;
|
||||||
|
enqueue(q, TELEM_STATUS, p, 8u);
|
||||||
|
}
|
||||||
|
|
||||||
|
void orin_send_vesc(QueueHandle_t q, uint8_t telem_type,
|
||||||
|
int32_t erpm, uint16_t voltage_mv,
|
||||||
|
int16_t current_ma, uint16_t temp_c_x10)
|
||||||
|
{
|
||||||
|
/* int32 erpm, uint16 voltage_mv, int16 current_ma, uint16 temp_c_x10 — BE */
|
||||||
|
uint8_t p[10];
|
||||||
|
uint32_t u = (uint32_t)erpm;
|
||||||
|
p[0] = (uint8_t)(u >> 24u);
|
||||||
|
p[1] = (uint8_t)(u >> 16u);
|
||||||
|
p[2] = (uint8_t)(u >> 8u);
|
||||||
|
p[3] = (uint8_t)(u);
|
||||||
|
p[4] = (uint8_t)(voltage_mv >> 8u);
|
||||||
|
p[5] = (uint8_t)(voltage_mv);
|
||||||
|
p[6] = (uint8_t)((uint16_t)current_ma >> 8u);
|
||||||
|
p[7] = (uint8_t)((uint16_t)current_ma);
|
||||||
|
p[8] = (uint8_t)(temp_c_x10 >> 8u);
|
||||||
|
p[9] = (uint8_t)(temp_c_x10);
|
||||||
|
enqueue(q, telem_type, p, 10u);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── UART init ── */
|
||||||
|
void orin_serial_init(void)
|
||||||
|
{
|
||||||
|
uart_config_t cfg = {
|
||||||
|
.baud_rate = ORIN_UART_BAUD,
|
||||||
|
.data_bits = UART_DATA_8_BITS,
|
||||||
|
.parity = UART_PARITY_DISABLE,
|
||||||
|
.stop_bits = UART_STOP_BITS_1,
|
||||||
|
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
|
||||||
|
};
|
||||||
|
ESP_ERROR_CHECK(uart_param_config(ORIN_UART_PORT, &cfg));
|
||||||
|
ESP_ERROR_CHECK(uart_set_pin(ORIN_UART_PORT,
|
||||||
|
ORIN_UART_TX_GPIO, ORIN_UART_RX_GPIO,
|
||||||
|
UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
|
||||||
|
ESP_ERROR_CHECK(uart_driver_install(ORIN_UART_PORT, ORIN_UART_RX_BUF, 0,
|
||||||
|
0, NULL, 0));
|
||||||
|
ESP_LOGI(TAG, "UART%d init OK: tx=%d rx=%d baud=%d",
|
||||||
|
ORIN_UART_PORT, ORIN_UART_TX_GPIO, ORIN_UART_RX_GPIO, ORIN_UART_BAUD);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── RX parser state machine ── */
|
||||||
|
typedef enum {
|
||||||
|
WAIT_SYNC,
|
||||||
|
WAIT_LEN,
|
||||||
|
WAIT_TYPE,
|
||||||
|
WAIT_PAYLOAD,
|
||||||
|
WAIT_CRC,
|
||||||
|
} rx_state_t;
|
||||||
|
|
||||||
|
static void dispatch_cmd(uint8_t type, const uint8_t *payload, uint8_t len,
|
||||||
|
QueueHandle_t tx_q)
|
||||||
|
{
|
||||||
|
uint32_t now_ms = (uint32_t)(esp_timer_get_time() / 1000LL);
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case CMD_HEARTBEAT:
|
||||||
|
g_orin_ctrl.hb_last_ms = now_ms;
|
||||||
|
orin_send_ack(tx_q, type);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case CMD_DRIVE:
|
||||||
|
if (len < 4u) { orin_send_nack(tx_q, type, ERR_BAD_LEN); break; }
|
||||||
|
if (g_orin_ctrl.estop) { orin_send_nack(tx_q, type, ERR_ESTOP_ACTIVE); break; }
|
||||||
|
if (!g_orin_ctrl.armed) { orin_send_nack(tx_q, type, ERR_DISARMED); break; }
|
||||||
|
g_orin_drive.speed = (int16_t)(((uint16_t)payload[0] << 8u) | payload[1]);
|
||||||
|
g_orin_drive.steer = (int16_t)(((uint16_t)payload[2] << 8u) | payload[3]);
|
||||||
|
g_orin_drive.updated_ms = now_ms;
|
||||||
|
g_orin_ctrl.hb_last_ms = now_ms; /* drive counts as heartbeat */
|
||||||
|
orin_send_ack(tx_q, type);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case CMD_ESTOP:
|
||||||
|
if (len < 1u) { orin_send_nack(tx_q, type, ERR_BAD_LEN); break; }
|
||||||
|
g_orin_ctrl.estop = (payload[0] != 0u);
|
||||||
|
if (g_orin_ctrl.estop) {
|
||||||
|
g_orin_drive.speed = 0;
|
||||||
|
g_orin_drive.steer = 0;
|
||||||
|
}
|
||||||
|
orin_send_ack(tx_q, type);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case CMD_ARM:
|
||||||
|
if (len < 1u) { orin_send_nack(tx_q, type, ERR_BAD_LEN); break; }
|
||||||
|
if (g_orin_ctrl.estop && payload[0] != 0u) {
|
||||||
|
/* cannot arm while estop is active */
|
||||||
|
orin_send_nack(tx_q, type, ERR_ESTOP_ACTIVE);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
g_orin_ctrl.armed = (payload[0] != 0u);
|
||||||
|
if (!g_orin_ctrl.armed) {
|
||||||
|
g_orin_drive.speed = 0;
|
||||||
|
g_orin_drive.steer = 0;
|
||||||
|
}
|
||||||
|
orin_send_ack(tx_q, type);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case CMD_PID:
|
||||||
|
if (len < 12u) { orin_send_nack(tx_q, type, ERR_BAD_LEN); break; }
|
||||||
|
/* float32 big-endian: copy and swap bytes */
|
||||||
|
{
|
||||||
|
uint32_t raw;
|
||||||
|
raw = ((uint32_t)payload[0] << 24u) | ((uint32_t)payload[1] << 16u) |
|
||||||
|
((uint32_t)payload[2] << 8u) | (uint32_t)payload[3];
|
||||||
|
memcpy((void*)&g_orin_pid.kp, &raw, 4u);
|
||||||
|
raw = ((uint32_t)payload[4] << 24u) | ((uint32_t)payload[5] << 16u) |
|
||||||
|
((uint32_t)payload[6] << 8u) | (uint32_t)payload[7];
|
||||||
|
memcpy((void*)&g_orin_pid.ki, &raw, 4u);
|
||||||
|
raw = ((uint32_t)payload[8] << 24u) | ((uint32_t)payload[9] << 16u) |
|
||||||
|
((uint32_t)payload[10] << 8u) | (uint32_t)payload[11];
|
||||||
|
memcpy((void*)&g_orin_pid.kd, &raw, 4u);
|
||||||
|
g_orin_pid.updated = true;
|
||||||
|
}
|
||||||
|
orin_send_ack(tx_q, type);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case CMD_OTA_CHECK:
|
||||||
|
/* Trigger an immediate Gitea version check */
|
||||||
|
gitea_ota_check_now();
|
||||||
|
orin_send_version_info(tx_q, OTA_TARGET_BALANCE,
|
||||||
|
BALANCE_FW_VERSION,
|
||||||
|
g_balance_update.available
|
||||||
|
? g_balance_update.version : "");
|
||||||
|
orin_send_version_info(tx_q, OTA_TARGET_IO,
|
||||||
|
IO_FW_VERSION,
|
||||||
|
g_io_update.available
|
||||||
|
? g_io_update.version : "");
|
||||||
|
orin_send_ack(tx_q, type);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case CMD_OTA_UPDATE:
|
||||||
|
if (len < 1u) { orin_send_nack(tx_q, type, ERR_BAD_LEN); break; }
|
||||||
|
{
|
||||||
|
uint8_t target = payload[0];
|
||||||
|
bool triggered = false;
|
||||||
|
if (target == OTA_TARGET_IO || target == OTA_TARGET_BOTH) {
|
||||||
|
if (!uart_ota_trigger()) {
|
||||||
|
orin_send_nack(tx_q, type,
|
||||||
|
g_io_update.available ? ERR_OTA_BUSY : ERR_OTA_NO_UPDATE);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
triggered = true;
|
||||||
|
}
|
||||||
|
if (target == OTA_TARGET_BALANCE || target == OTA_TARGET_BOTH) {
|
||||||
|
if (!ota_self_trigger()) {
|
||||||
|
if (!triggered) {
|
||||||
|
orin_send_nack(tx_q, type,
|
||||||
|
g_balance_update.available ? ERR_OTA_BUSY : ERR_OTA_NO_UPDATE);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
orin_send_ack(tx_q, type);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
ESP_LOGW(TAG, "unknown cmd type=0x%02x", type);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void orin_serial_rx_task(void *arg)
|
||||||
|
{
|
||||||
|
QueueHandle_t tx_q = (QueueHandle_t)arg;
|
||||||
|
rx_state_t state = WAIT_SYNC;
|
||||||
|
uint8_t rx_len = 0;
|
||||||
|
uint8_t rx_type = 0;
|
||||||
|
uint8_t payload[ORIN_MAX_PAYLOAD];
|
||||||
|
uint8_t pay_idx = 0;
|
||||||
|
|
||||||
|
uint8_t byte;
|
||||||
|
for (;;) {
|
||||||
|
int r = uart_read_bytes(ORIN_UART_PORT, &byte, 1, pdMS_TO_TICKS(10));
|
||||||
|
if (r <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (state) {
|
||||||
|
case WAIT_SYNC:
|
||||||
|
if (byte == ORIN_SYNC) { state = WAIT_LEN; }
|
||||||
|
break;
|
||||||
|
|
||||||
|
case WAIT_LEN:
|
||||||
|
if (byte > ORIN_MAX_PAYLOAD) {
|
||||||
|
/* oversize — send NACK and reset */
|
||||||
|
orin_send_nack(tx_q, 0x00u, ERR_BAD_LEN);
|
||||||
|
state = WAIT_SYNC;
|
||||||
|
} else {
|
||||||
|
rx_len = byte;
|
||||||
|
state = WAIT_TYPE;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case WAIT_TYPE:
|
||||||
|
rx_type = byte;
|
||||||
|
pay_idx = 0u;
|
||||||
|
state = (rx_len == 0u) ? WAIT_CRC : WAIT_PAYLOAD;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case WAIT_PAYLOAD:
|
||||||
|
payload[pay_idx++] = byte;
|
||||||
|
if (pay_idx == rx_len) { state = WAIT_CRC; }
|
||||||
|
break;
|
||||||
|
|
||||||
|
case WAIT_CRC: {
|
||||||
|
/* Verify CRC over [LEN, TYPE, PAYLOAD] */
|
||||||
|
uint8_t crc_buf[2u + ORIN_MAX_PAYLOAD];
|
||||||
|
crc_buf[0] = rx_len;
|
||||||
|
crc_buf[1] = rx_type;
|
||||||
|
memcpy(&crc_buf[2], payload, rx_len);
|
||||||
|
uint8_t expected = crc8(crc_buf, (uint8_t)(2u + rx_len));
|
||||||
|
if (byte != expected) {
|
||||||
|
ESP_LOGW(TAG, "CRC fail type=0x%02x got=0x%02x exp=0x%02x",
|
||||||
|
rx_type, byte, expected);
|
||||||
|
orin_send_nack(tx_q, rx_type, ERR_BAD_CRC);
|
||||||
|
} else {
|
||||||
|
dispatch_cmd(rx_type, payload, rx_len, tx_q);
|
||||||
|
}
|
||||||
|
state = WAIT_SYNC;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void orin_serial_tx_task(void *arg)
|
||||||
|
{
|
||||||
|
QueueHandle_t tx_q = (QueueHandle_t)arg;
|
||||||
|
orin_tx_frame_t f;
|
||||||
|
uint8_t wire[4u + ORIN_MAX_PAYLOAD];
|
||||||
|
uint8_t wire_len;
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
if (xQueueReceive(tx_q, &f, portMAX_DELAY) == pdTRUE) {
|
||||||
|
build_frame(&f, wire, &wire_len);
|
||||||
|
uart_write_bytes(ORIN_UART_PORT, (const char *)wire, wire_len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── OTA telemetry helpers (bd-1s1s) ── */
|
||||||
|
|
||||||
|
void orin_send_ota_status(QueueHandle_t q, uint8_t target,
|
||||||
|
uint8_t state, uint8_t progress, uint8_t err)
|
||||||
|
{
|
||||||
|
/* TELEM_OTA_STATUS: uint8 target, uint8 state, uint8 progress, uint8 err */
|
||||||
|
uint8_t p[4] = {target, state, progress, err};
|
||||||
|
enqueue(q, TELEM_OTA_STATUS, p, 4u);
|
||||||
|
}
|
||||||
|
|
||||||
|
void orin_send_version_info(QueueHandle_t q, uint8_t target,
|
||||||
|
const char *current, const char *available)
|
||||||
|
{
|
||||||
|
/* TELEM_VERSION_INFO: uint8 target, char current[16], char available[16] */
|
||||||
|
uint8_t p[33];
|
||||||
|
p[0] = target;
|
||||||
|
strncpy((char *)&p[1], current, 16); p[16] = '\0';
|
||||||
|
strncpy((char *)&p[17], available ? available : "", 16); p[32] = '\0';
|
||||||
|
enqueue(q, TELEM_VERSION_INFO, p, 33u);
|
||||||
|
}
|
||||||
113
esp32s3/balance/main/orin_serial.h
Normal file
113
esp32s3/balance/main/orin_serial.h
Normal file
@ -0,0 +1,113 @@
|
|||||||
|
#pragma once
|
||||||
|
/* orin_serial.h — Orin↔ESP32-S3 BALANCE USB/UART serial protocol (bd-66hx)
|
||||||
|
*
|
||||||
|
* Frame layout (matches bd-wim1 esp32_balance_protocol.py exactly):
|
||||||
|
* [0xAA][LEN][TYPE][PAYLOAD × LEN bytes][CRC8-SMBUS]
|
||||||
|
* CRC covers LEN + TYPE + PAYLOAD bytes.
|
||||||
|
* All multi-byte payload fields are big-endian.
|
||||||
|
*
|
||||||
|
* Physical: UART0 → CH343 USB-serial → Orin /dev/esp32-balance @ 460800 baud
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/queue.h"
|
||||||
|
|
||||||
|
/* ── Frame constants ── */
|
||||||
|
#define ORIN_SYNC 0xAAu
|
||||||
|
#define ORIN_MAX_PAYLOAD 62u
|
||||||
|
|
||||||
|
/* ── Command types: Orin → ESP32 ── */
|
||||||
|
#define CMD_HEARTBEAT 0x01u
|
||||||
|
#define CMD_DRIVE 0x02u /* int16 speed + int16 steer, BE */
|
||||||
|
#define CMD_ESTOP 0x03u /* uint8: 1=assert, 0=clear */
|
||||||
|
#define CMD_ARM 0x04u /* uint8: 1=arm, 0=disarm */
|
||||||
|
#define CMD_PID 0x05u /* float32 kp, ki, kd, BE */
|
||||||
|
|
||||||
|
/* ── Telemetry types: ESP32 → Orin ── */
|
||||||
|
#define TELEM_STATUS 0x80u /* status @ 10 Hz */
|
||||||
|
#define TELEM_VESC_LEFT 0x81u /* VESC ID 56 telemetry @ 10 Hz */
|
||||||
|
#define TELEM_VESC_RIGHT 0x82u /* VESC ID 68 telemetry @ 10 Hz */
|
||||||
|
#define TELEM_OTA_STATUS 0x83u /* OTA state + progress (bd-1s1s) */
|
||||||
|
#define TELEM_VERSION_INFO 0x84u /* firmware version report (bd-1s1s) */
|
||||||
|
#define RESP_ACK 0xA0u
|
||||||
|
#define RESP_NACK 0xA1u
|
||||||
|
|
||||||
|
/* ── OTA commands (Orin → ESP32, bd-1s1s) ── */
|
||||||
|
#define CMD_OTA_CHECK 0x10u /* no payload: trigger Gitea version check */
|
||||||
|
#define CMD_OTA_UPDATE 0x11u /* uint8 target: 0=balance, 1=io, 2=both */
|
||||||
|
|
||||||
|
/* ── OTA target constants ── */
|
||||||
|
#define OTA_TARGET_BALANCE 0x00u
|
||||||
|
#define OTA_TARGET_IO 0x01u
|
||||||
|
#define OTA_TARGET_BOTH 0x02u
|
||||||
|
|
||||||
|
/* ── NACK error codes ── */
|
||||||
|
#define ERR_BAD_CRC 0x01u
|
||||||
|
#define ERR_BAD_LEN 0x02u
|
||||||
|
#define ERR_ESTOP_ACTIVE 0x03u
|
||||||
|
#define ERR_DISARMED 0x04u
|
||||||
|
#define ERR_OTA_BUSY 0x05u
|
||||||
|
#define ERR_OTA_NO_UPDATE 0x06u
|
||||||
|
|
||||||
|
/* ── Balance state (mirrored from TELEM_STATUS.balance_state) ── */
|
||||||
|
typedef enum {
|
||||||
|
BAL_DISARMED = 0,
|
||||||
|
BAL_ARMED = 1,
|
||||||
|
BAL_TILT_FAULT = 2,
|
||||||
|
BAL_ESTOP = 3,
|
||||||
|
} bal_state_t;
|
||||||
|
|
||||||
|
/* ── Shared state written by RX task, consumed by main/vesc tasks ── */
|
||||||
|
typedef struct {
|
||||||
|
volatile int16_t speed; /* -1000..+1000 */
|
||||||
|
volatile int16_t steer; /* -1000..+1000 */
|
||||||
|
volatile uint32_t updated_ms; /* esp_timer tick at last CMD_DRIVE */
|
||||||
|
} orin_drive_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
volatile float kp, ki, kd;
|
||||||
|
volatile bool updated;
|
||||||
|
} orin_pid_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
volatile bool armed;
|
||||||
|
volatile bool estop;
|
||||||
|
volatile uint32_t hb_last_ms; /* esp_timer tick at last CMD_HEARTBEAT/CMD_DRIVE */
|
||||||
|
} orin_control_t;
|
||||||
|
|
||||||
|
/* ── TX frame queue item ── */
|
||||||
|
typedef struct {
|
||||||
|
uint8_t type;
|
||||||
|
uint8_t len;
|
||||||
|
uint8_t payload[ORIN_MAX_PAYLOAD];
|
||||||
|
} orin_tx_frame_t;
|
||||||
|
|
||||||
|
/* ── Globals (defined in orin_serial.c, extern here) ── */
|
||||||
|
extern orin_drive_t g_orin_drive;
|
||||||
|
extern orin_pid_t g_orin_pid;
|
||||||
|
extern orin_control_t g_orin_ctrl;
|
||||||
|
|
||||||
|
/* ── API ── */
|
||||||
|
void orin_serial_init(void);
|
||||||
|
|
||||||
|
/* Tasks — pass tx_queue as arg to both */
|
||||||
|
void orin_serial_rx_task(void *arg); /* arg = QueueHandle_t tx_queue */
|
||||||
|
void orin_serial_tx_task(void *arg); /* arg = QueueHandle_t tx_queue */
|
||||||
|
|
||||||
|
/* Enqueue outbound frames */
|
||||||
|
void orin_send_status(QueueHandle_t q,
|
||||||
|
int16_t pitch_x10, int16_t motor_cmd,
|
||||||
|
uint16_t vbat_mv, bal_state_t state, uint8_t flags);
|
||||||
|
void orin_send_vesc(QueueHandle_t q, uint8_t telem_type,
|
||||||
|
int32_t erpm, uint16_t voltage_mv,
|
||||||
|
int16_t current_ma, uint16_t temp_c_x10);
|
||||||
|
void orin_send_ack(QueueHandle_t q, uint8_t cmd_type);
|
||||||
|
void orin_send_nack(QueueHandle_t q, uint8_t cmd_type, uint8_t err);
|
||||||
|
|
||||||
|
/* OTA telemetry helpers (bd-1s1s) */
|
||||||
|
void orin_send_ota_status(QueueHandle_t q, uint8_t target,
|
||||||
|
uint8_t state, uint8_t progress, uint8_t err);
|
||||||
|
void orin_send_version_info(QueueHandle_t q, uint8_t target,
|
||||||
|
const char *current, const char *available);
|
||||||
150
esp32s3/balance/main/ota_display.c
Normal file
150
esp32s3/balance/main/ota_display.c
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
/* ota_display.c — OTA notification/progress UI on GC9A01 (bd-1yr8)
|
||||||
|
*
|
||||||
|
* Renders OTA state overlaid on the 240×240 round HUD display:
|
||||||
|
* - BADGE: small dot on top-right when update available (idle state)
|
||||||
|
* - UPDATE SCREEN: version compare, Update Balance / Update IO / Update All
|
||||||
|
* - PROGRESS: arc around display perimeter + % + status text
|
||||||
|
* - ERROR: red banner + "RETRY" prompt
|
||||||
|
*
|
||||||
|
* The display_draw_* primitives must be provided by the GC9A01 driver.
|
||||||
|
* Actual SPI driver implementation is in a separate driver bead.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "ota_display.h"
|
||||||
|
#include "gitea_ota.h"
|
||||||
|
#include "version.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
static const char *TAG = "ota_disp";
|
||||||
|
|
||||||
|
/* Display centre and radius for the 240×240 GC9A01 */
|
||||||
|
#define CX 120
|
||||||
|
#define CY 120
|
||||||
|
#define RAD 110
|
||||||
|
|
||||||
|
/* ── Availability badge: 8×8 dot at top-right of display ── */
|
||||||
|
static void draw_badge(bool balance_avail, bool io_avail)
|
||||||
|
{
|
||||||
|
uint16_t col = (balance_avail || io_avail) ? COL_ORANGE : COL_BG;
|
||||||
|
display_fill_rect(200, 15, 12, 12, col);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Progress arc: sweeps 0→360° proportional to progress% ── */
|
||||||
|
static void draw_progress_arc(uint8_t pct, uint16_t color)
|
||||||
|
{
|
||||||
|
int end_deg = (int)(360 * pct / 100);
|
||||||
|
display_draw_arc(CX, CY, RAD, 0, end_deg, 6, color);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Status banner: 2 lines of text centred on display ── */
|
||||||
|
static void draw_status(const char *line1, const char *line2,
|
||||||
|
uint16_t fg, uint16_t bg)
|
||||||
|
{
|
||||||
|
display_fill_rect(20, 90, 200, 60, bg);
|
||||||
|
if (line1 && line1[0])
|
||||||
|
display_draw_string(CX - (int)(strlen(line1) * 6 / 2), 96,
|
||||||
|
line1, fg, bg);
|
||||||
|
if (line2 && line2[0])
|
||||||
|
display_draw_string(CX - (int)(strlen(line2) * 6 / 2), 116,
|
||||||
|
line2, fg, bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Main render logic ── */
|
||||||
|
void ota_display_update(void)
|
||||||
|
{
|
||||||
|
/* Determine dominant OTA state */
|
||||||
|
ota_self_state_t self = g_ota_self_state;
|
||||||
|
uart_ota_send_state_t io_s = g_uart_ota_state;
|
||||||
|
|
||||||
|
switch (self) {
|
||||||
|
case OTA_SELF_DOWNLOADING:
|
||||||
|
case OTA_SELF_VERIFYING:
|
||||||
|
case OTA_SELF_APPLYING: {
|
||||||
|
/* Balance self-update in progress */
|
||||||
|
char pct_str[16];
|
||||||
|
snprintf(pct_str, sizeof(pct_str), "%d%%", g_ota_self_progress);
|
||||||
|
const char *phase = (self == OTA_SELF_VERIFYING) ? "Verifying..." :
|
||||||
|
(self == OTA_SELF_APPLYING) ? "Applying..." :
|
||||||
|
"Downloading...";
|
||||||
|
draw_progress_arc(g_ota_self_progress, COL_BLUE);
|
||||||
|
draw_status("Updating Balance", pct_str, COL_WHITE, COL_BG);
|
||||||
|
ESP_LOGD(TAG, "balance OTA %s %d%%", phase, g_ota_self_progress);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case OTA_SELF_REBOOTING:
|
||||||
|
draw_status("Update complete", "Rebooting...", COL_GREEN, COL_BG);
|
||||||
|
return;
|
||||||
|
case OTA_SELF_FAILED:
|
||||||
|
draw_progress_arc(0, COL_RED);
|
||||||
|
draw_status("Balance update", "FAILED RETRY?", COL_RED, COL_BG);
|
||||||
|
return;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (io_s) {
|
||||||
|
case UART_OTA_S_DOWNLOADING:
|
||||||
|
draw_progress_arc(g_uart_ota_progress, COL_YELLOW);
|
||||||
|
draw_status("Downloading IO", "firmware...", COL_WHITE, COL_BG);
|
||||||
|
return;
|
||||||
|
case UART_OTA_S_SENDING: {
|
||||||
|
char pct_str[16];
|
||||||
|
snprintf(pct_str, sizeof(pct_str), "%d%%", g_uart_ota_progress);
|
||||||
|
draw_progress_arc(g_uart_ota_progress, COL_YELLOW);
|
||||||
|
draw_status("Updating IO", pct_str, COL_WHITE, COL_BG);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case UART_OTA_S_DONE:
|
||||||
|
draw_status("IO update done", "", COL_GREEN, COL_BG);
|
||||||
|
return;
|
||||||
|
case UART_OTA_S_FAILED:
|
||||||
|
draw_progress_arc(0, COL_RED);
|
||||||
|
draw_status("IO update", "FAILED RETRY?", COL_RED, COL_BG);
|
||||||
|
return;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Idle — show badge if update available */
|
||||||
|
bool bal_avail = g_balance_update.available;
|
||||||
|
bool io_avail = g_io_update.available;
|
||||||
|
draw_badge(bal_avail, io_avail);
|
||||||
|
|
||||||
|
if (bal_avail || io_avail) {
|
||||||
|
/* Show available versions on display when idle */
|
||||||
|
char verline[32];
|
||||||
|
if (bal_avail) {
|
||||||
|
snprintf(verline, sizeof(verline), "Bal v%s rdy",
|
||||||
|
g_balance_update.version);
|
||||||
|
draw_status(verline, io_avail ? "IO update rdy" : "",
|
||||||
|
COL_ORANGE, COL_BG);
|
||||||
|
} else if (io_avail) {
|
||||||
|
snprintf(verline, sizeof(verline), "IO v%s rdy",
|
||||||
|
g_io_update.version);
|
||||||
|
draw_status(verline, "", COL_ORANGE, COL_BG);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
/* Clear OTA overlay area */
|
||||||
|
display_fill_rect(20, 90, 200, 60, COL_BG);
|
||||||
|
draw_badge(false, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Background display task (5 Hz) ── */
|
||||||
|
static void ota_display_task(void *arg)
|
||||||
|
{
|
||||||
|
for (;;) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(200));
|
||||||
|
ota_display_update();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ota_display_init(void)
|
||||||
|
{
|
||||||
|
xTaskCreate(ota_display_task, "ota_disp", 2048, NULL, 3, NULL);
|
||||||
|
ESP_LOGI(TAG, "OTA display task started");
|
||||||
|
}
|
||||||
33
esp32s3/balance/main/ota_display.h
Normal file
33
esp32s3/balance/main/ota_display.h
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
#pragma once
|
||||||
|
/* ota_display.h — OTA notification UI on GC9A01 round LCD (bd-1yr8)
|
||||||
|
*
|
||||||
|
* GC9A01 240×240 round display via SPI (IO12 CS, IO11 DC, IO10 RST, IO9 BL).
|
||||||
|
* Calls into display_draw_* primitives (provided by display driver layer).
|
||||||
|
* This module owns the "OTA notification overlay" rendered over the HUD.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include "ota_self.h"
|
||||||
|
#include "uart_ota.h"
|
||||||
|
|
||||||
|
/* ── Display primitives API (must be provided by display driver) ── */
|
||||||
|
void display_fill_rect(int x, int y, int w, int h, uint16_t rgb565);
|
||||||
|
void display_draw_string(int x, int y, const char *str, uint16_t fg, uint16_t bg);
|
||||||
|
void display_draw_arc(int cx, int cy, int r, int start_deg, int end_deg,
|
||||||
|
int thickness, uint16_t color);
|
||||||
|
|
||||||
|
/* ── Colour palette (RGB565) ── */
|
||||||
|
#define COL_BG 0x0000u /* black */
|
||||||
|
#define COL_WHITE 0xFFFFu
|
||||||
|
#define COL_GREEN 0x07E0u
|
||||||
|
#define COL_YELLOW 0xFFE0u
|
||||||
|
#define COL_RED 0xF800u
|
||||||
|
#define COL_BLUE 0x001Fu
|
||||||
|
#define COL_ORANGE 0xFD20u
|
||||||
|
|
||||||
|
/* ── OTA display task: runs at 5 Hz, overlays OTA state on HUD ── */
|
||||||
|
void ota_display_init(void);
|
||||||
|
|
||||||
|
/* Called from main loop or display task to render the OTA overlay */
|
||||||
|
void ota_display_update(void);
|
||||||
183
esp32s3/balance/main/ota_self.c
Normal file
183
esp32s3/balance/main/ota_self.c
Normal file
@ -0,0 +1,183 @@
|
|||||||
|
/* ota_self.c — Balance self-OTA (bd-18nb)
|
||||||
|
*
|
||||||
|
* Uses esp_https_ota / esp_ota_ops to download from Gitea release URL,
|
||||||
|
* stream-verify SHA256 with mbedTLS, set new boot partition, and reboot.
|
||||||
|
* CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE in sdkconfig allows auto-rollback
|
||||||
|
* if the new image doesn't call esp_ota_mark_app_valid_cancel_rollback()
|
||||||
|
* within OTA_ROLLBACK_WINDOW_S seconds.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "ota_self.h"
|
||||||
|
#include "gitea_ota.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_ota_ops.h"
|
||||||
|
#include "esp_http_client.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "mbedtls/sha256.h"
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
static const char *TAG = "ota_self";
|
||||||
|
|
||||||
|
volatile ota_self_state_t g_ota_self_state = OTA_SELF_IDLE;
|
||||||
|
volatile uint8_t g_ota_self_progress = 0;
|
||||||
|
|
||||||
|
#define OTA_CHUNK_SIZE 4096
|
||||||
|
|
||||||
|
/* ── SHA256 verify helper ── */
|
||||||
|
static bool sha256_matches(const uint8_t *digest, const char *expected_hex)
|
||||||
|
{
|
||||||
|
if (!expected_hex || expected_hex[0] == '\0') {
|
||||||
|
ESP_LOGW(TAG, "no SHA256 to verify — skipping");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
char got[65] = {0};
|
||||||
|
for (int i = 0; i < 32; i++) {
|
||||||
|
snprintf(&got[i*2], 3, "%02x", digest[i]);
|
||||||
|
}
|
||||||
|
bool ok = (strncasecmp(got, expected_hex, 64) == 0);
|
||||||
|
if (!ok) {
|
||||||
|
ESP_LOGE(TAG, "SHA256 mismatch: got=%s exp=%s", got, expected_hex);
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── OTA download + flash task ── */
|
||||||
|
static void ota_self_task(void *arg)
|
||||||
|
{
|
||||||
|
const char *url = g_balance_update.download_url;
|
||||||
|
const char *sha256 = g_balance_update.sha256;
|
||||||
|
|
||||||
|
g_ota_self_state = OTA_SELF_DOWNLOADING;
|
||||||
|
g_ota_self_progress = 0;
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "OTA start: %s", url);
|
||||||
|
|
||||||
|
esp_ota_handle_t handle = 0;
|
||||||
|
const esp_partition_t *ota_part = esp_ota_get_next_update_partition(NULL);
|
||||||
|
if (!ota_part) {
|
||||||
|
ESP_LOGE(TAG, "no OTA partition");
|
||||||
|
g_ota_self_state = OTA_SELF_FAILED;
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t err = esp_ota_begin(ota_part, OTA_WITH_SEQUENTIAL_WRITES, &handle);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "ota_begin: %s", esp_err_to_name(err));
|
||||||
|
g_ota_self_state = OTA_SELF_FAILED;
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Setup HTTP client */
|
||||||
|
esp_http_client_config_t hcfg = {
|
||||||
|
.url = url,
|
||||||
|
.timeout_ms = 30000,
|
||||||
|
.buffer_size = OTA_CHUNK_SIZE,
|
||||||
|
.skip_cert_common_name_check = true,
|
||||||
|
};
|
||||||
|
esp_http_client_handle_t client = esp_http_client_init(&hcfg);
|
||||||
|
err = esp_http_client_open(client, 0);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "http_open: %s", esp_err_to_name(err));
|
||||||
|
esp_ota_abort(handle);
|
||||||
|
esp_http_client_cleanup(client);
|
||||||
|
g_ota_self_state = OTA_SELF_FAILED;
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int content_len = esp_http_client_fetch_headers(client);
|
||||||
|
ESP_LOGI(TAG, "content-length: %d", content_len);
|
||||||
|
|
||||||
|
mbedtls_sha256_context sha_ctx;
|
||||||
|
mbedtls_sha256_init(&sha_ctx);
|
||||||
|
mbedtls_sha256_starts(&sha_ctx, 0); /* 0 = SHA-256 */
|
||||||
|
|
||||||
|
static uint8_t buf[OTA_CHUNK_SIZE];
|
||||||
|
int total = 0;
|
||||||
|
int rd;
|
||||||
|
while ((rd = esp_http_client_read(client, (char *)buf, sizeof(buf))) > 0) {
|
||||||
|
mbedtls_sha256_update(&sha_ctx, buf, rd);
|
||||||
|
err = esp_ota_write(handle, buf, rd);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "ota_write: %s", esp_err_to_name(err));
|
||||||
|
esp_ota_abort(handle);
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
total += rd;
|
||||||
|
if (content_len > 0) {
|
||||||
|
g_ota_self_progress = (uint8_t)((total * 100) / content_len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
esp_http_client_close(client);
|
||||||
|
|
||||||
|
/* Verify SHA256 */
|
||||||
|
g_ota_self_state = OTA_SELF_VERIFYING;
|
||||||
|
uint8_t digest[32];
|
||||||
|
mbedtls_sha256_finish(&sha_ctx, digest);
|
||||||
|
if (!sha256_matches(digest, sha256)) {
|
||||||
|
ESP_LOGE(TAG, "SHA256 verification failed");
|
||||||
|
esp_ota_abort(handle);
|
||||||
|
g_ota_self_state = OTA_SELF_FAILED;
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Finalize + set boot partition */
|
||||||
|
g_ota_self_state = OTA_SELF_APPLYING;
|
||||||
|
err = esp_ota_end(handle);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "ota_end: %s", esp_err_to_name(err));
|
||||||
|
g_ota_self_state = OTA_SELF_FAILED;
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
|
||||||
|
err = esp_ota_set_boot_partition(ota_part);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "set_boot_partition: %s", esp_err_to_name(err));
|
||||||
|
g_ota_self_state = OTA_SELF_FAILED;
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
|
||||||
|
g_ota_self_state = OTA_SELF_REBOOTING;
|
||||||
|
g_ota_self_progress = 100;
|
||||||
|
ESP_LOGI(TAG, "OTA success — rebooting");
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(500));
|
||||||
|
esp_restart();
|
||||||
|
|
||||||
|
cleanup:
|
||||||
|
mbedtls_sha256_free(&sha_ctx);
|
||||||
|
esp_http_client_cleanup(client);
|
||||||
|
handle = 0;
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ota_self_trigger(void)
|
||||||
|
{
|
||||||
|
if (!g_balance_update.available) {
|
||||||
|
ESP_LOGW(TAG, "no update available");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (g_ota_self_state != OTA_SELF_IDLE) {
|
||||||
|
ESP_LOGW(TAG, "OTA already in progress (state=%d)", g_ota_self_state);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
xTaskCreate(ota_self_task, "ota_self", 8192, NULL, 5, NULL);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ota_self_health_check(void)
|
||||||
|
{
|
||||||
|
/* Mark running image as valid — prevents rollback */
|
||||||
|
esp_err_t err = esp_ota_mark_app_valid_cancel_rollback();
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
ESP_LOGI(TAG, "image marked valid");
|
||||||
|
} else if (err == ESP_ERR_NOT_SUPPORTED) {
|
||||||
|
/* Not an OTA image (e.g., flashed via JTAG) — ignore */
|
||||||
|
} else {
|
||||||
|
ESP_LOGW(TAG, "mark_valid: %s", esp_err_to_name(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
34
esp32s3/balance/main/ota_self.h
Normal file
34
esp32s3/balance/main/ota_self.h
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
#pragma once
|
||||||
|
/* ota_self.h — Balance self-OTA (bd-18nb)
|
||||||
|
*
|
||||||
|
* Downloads balance-firmware.bin from Gitea release URL to the inactive
|
||||||
|
* OTA partition, verifies SHA256, sets boot partition, reboots.
|
||||||
|
* Auto-rollback if health check not called within ROLLBACK_WINDOW_S seconds.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
#define OTA_ROLLBACK_WINDOW_S 30
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
OTA_SELF_IDLE = 0,
|
||||||
|
OTA_SELF_CHECKING, /* (unused — gitea_ota handles this) */
|
||||||
|
OTA_SELF_DOWNLOADING,
|
||||||
|
OTA_SELF_VERIFYING,
|
||||||
|
OTA_SELF_APPLYING,
|
||||||
|
OTA_SELF_REBOOTING,
|
||||||
|
OTA_SELF_FAILED,
|
||||||
|
} ota_self_state_t;
|
||||||
|
|
||||||
|
extern volatile ota_self_state_t g_ota_self_state;
|
||||||
|
extern volatile uint8_t g_ota_self_progress; /* 0-100 % */
|
||||||
|
|
||||||
|
/* Trigger a Balance self-update.
|
||||||
|
* Uses g_balance_update (from gitea_ota). Non-blocking: starts in a task.
|
||||||
|
* Returns false if no update available or OTA already in progress. */
|
||||||
|
bool ota_self_trigger(void);
|
||||||
|
|
||||||
|
/* Called from app_main after boot to mark the running image as valid.
|
||||||
|
* Must be called within OTA_ROLLBACK_WINDOW_S after boot or rollback fires. */
|
||||||
|
void ota_self_health_check(void);
|
||||||
241
esp32s3/balance/main/uart_ota.c
Normal file
241
esp32s3/balance/main/uart_ota.c
Normal file
@ -0,0 +1,241 @@
|
|||||||
|
/* uart_ota.c — UART OTA sender: Balance→IO board (bd-21hv)
|
||||||
|
*
|
||||||
|
* Downloads io-firmware.bin from Gitea, then sends to IO board via UART1.
|
||||||
|
* IO board must update itself BEFORE Balance self-update (per spec).
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "uart_ota.h"
|
||||||
|
#include "gitea_ota.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_http_client.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "mbedtls/sha256.h"
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
static const char *TAG = "uart_ota";
|
||||||
|
|
||||||
|
volatile uart_ota_send_state_t g_uart_ota_state = UART_OTA_S_IDLE;
|
||||||
|
volatile uint8_t g_uart_ota_progress = 0;
|
||||||
|
|
||||||
|
/* ── CRC8-SMBUS ── */
|
||||||
|
static uint8_t crc8(const uint8_t *d, uint16_t len)
|
||||||
|
{
|
||||||
|
uint8_t crc = 0;
|
||||||
|
for (uint16_t i = 0; i < len; i++) {
|
||||||
|
crc ^= d[i];
|
||||||
|
for (uint8_t b = 0; b < 8; b++)
|
||||||
|
crc = (crc & 0x80u) ? (uint8_t)((crc << 1u) ^ 0x07u) : (uint8_t)(crc << 1u);
|
||||||
|
}
|
||||||
|
return crc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Build and send one UART OTA frame ── */
|
||||||
|
static void send_frame(uint8_t type, uint16_t seq,
|
||||||
|
const uint8_t *payload, uint16_t plen)
|
||||||
|
{
|
||||||
|
/* [TYPE:1][SEQ:2 BE][LEN:2 BE][PAYLOAD][CRC8:1] */
|
||||||
|
uint8_t hdr[5];
|
||||||
|
hdr[0] = type;
|
||||||
|
hdr[1] = (uint8_t)(seq >> 8u);
|
||||||
|
hdr[2] = (uint8_t)(seq);
|
||||||
|
hdr[3] = (uint8_t)(plen >> 8u);
|
||||||
|
hdr[4] = (uint8_t)(plen);
|
||||||
|
|
||||||
|
/* CRC over hdr + payload */
|
||||||
|
uint8_t crc_buf[5 + OTA_UART_CHUNK_SIZE];
|
||||||
|
memcpy(crc_buf, hdr, 5);
|
||||||
|
if (plen > 0 && payload) memcpy(crc_buf + 5, payload, plen);
|
||||||
|
uint8_t crc = crc8(crc_buf, (uint16_t)(5 + plen));
|
||||||
|
|
||||||
|
uart_write_bytes(UART_OTA_PORT, (char *)hdr, 5);
|
||||||
|
if (plen > 0 && payload)
|
||||||
|
uart_write_bytes(UART_OTA_PORT, (char *)payload, plen);
|
||||||
|
uart_write_bytes(UART_OTA_PORT, (char *)&crc, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Wait for ACK/NACK from IO board ── */
|
||||||
|
static bool wait_ack(uint16_t expected_seq)
|
||||||
|
{
|
||||||
|
/* Response frame: [TYPE:1][SEQ:2][LEN:2][PAYLOAD][CRC:1] */
|
||||||
|
uint8_t buf[16];
|
||||||
|
int timeout = OTA_UART_ACK_TIMEOUT_MS;
|
||||||
|
int got = 0;
|
||||||
|
|
||||||
|
while (timeout > 0 && got < 6) {
|
||||||
|
int r = uart_read_bytes(UART_OTA_PORT, buf + got, 1, pdMS_TO_TICKS(50));
|
||||||
|
if (r > 0) got++;
|
||||||
|
else timeout -= 50;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (got < 3) return false;
|
||||||
|
|
||||||
|
uint8_t type = buf[0];
|
||||||
|
uint16_t seq = (uint16_t)((buf[1] << 8u) | buf[2]);
|
||||||
|
|
||||||
|
if (type == UART_OTA_ACK && seq == expected_seq) return true;
|
||||||
|
if (type == UART_OTA_NACK) {
|
||||||
|
uint8_t err = (got >= 6) ? buf[5] : 0;
|
||||||
|
ESP_LOGW(TAG, "NACK seq=%u err=%u", seq, err);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Download firmware to RAM buffer (max 1.75 MB) ── */
|
||||||
|
static uint8_t *download_io_firmware(uint32_t *out_size)
|
||||||
|
{
|
||||||
|
const char *url = g_io_update.download_url;
|
||||||
|
ESP_LOGI(TAG, "downloading IO fw: %s", url);
|
||||||
|
|
||||||
|
esp_http_client_config_t cfg = {
|
||||||
|
.url = url, .timeout_ms = 30000,
|
||||||
|
.skip_cert_common_name_check = true,
|
||||||
|
};
|
||||||
|
esp_http_client_handle_t client = esp_http_client_init(&cfg);
|
||||||
|
if (esp_http_client_open(client, 0) != ESP_OK) {
|
||||||
|
esp_http_client_cleanup(client);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
int content_len = esp_http_client_fetch_headers(client);
|
||||||
|
if (content_len <= 0 || content_len > (int)(0x1B0000)) {
|
||||||
|
ESP_LOGE(TAG, "bad content-length: %d", content_len);
|
||||||
|
esp_http_client_cleanup(client);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t *buf = malloc(content_len);
|
||||||
|
if (!buf) {
|
||||||
|
ESP_LOGE(TAG, "malloc %d failed", content_len);
|
||||||
|
esp_http_client_cleanup(client);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
int total = 0, rd;
|
||||||
|
while ((rd = esp_http_client_read(client, (char *)buf + total,
|
||||||
|
content_len - total)) > 0) {
|
||||||
|
total += rd;
|
||||||
|
g_uart_ota_progress = (uint8_t)((total * 50) / content_len); /* 0-50% for download */
|
||||||
|
}
|
||||||
|
esp_http_client_cleanup(client);
|
||||||
|
|
||||||
|
if (total != content_len) {
|
||||||
|
free(buf);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
*out_size = (uint32_t)total;
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── UART OTA send task ── */
|
||||||
|
static void uart_ota_task(void *arg)
|
||||||
|
{
|
||||||
|
g_uart_ota_state = UART_OTA_S_DOWNLOADING;
|
||||||
|
g_uart_ota_progress = 0;
|
||||||
|
|
||||||
|
uint32_t fw_size = 0;
|
||||||
|
uint8_t *fw = download_io_firmware(&fw_size);
|
||||||
|
if (!fw) {
|
||||||
|
ESP_LOGE(TAG, "download failed");
|
||||||
|
g_uart_ota_state = UART_OTA_S_FAILED;
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Compute SHA256 of downloaded firmware */
|
||||||
|
uint8_t digest[32];
|
||||||
|
mbedtls_sha256_context sha;
|
||||||
|
mbedtls_sha256_init(&sha);
|
||||||
|
mbedtls_sha256_starts(&sha, 0);
|
||||||
|
mbedtls_sha256_update(&sha, fw, fw_size);
|
||||||
|
mbedtls_sha256_finish(&sha, digest);
|
||||||
|
mbedtls_sha256_free(&sha);
|
||||||
|
|
||||||
|
g_uart_ota_state = UART_OTA_S_SENDING;
|
||||||
|
|
||||||
|
/* Send OTA_BEGIN: uint32 size + uint8[32] sha256 */
|
||||||
|
uint8_t begin_payload[36];
|
||||||
|
begin_payload[0] = (uint8_t)(fw_size >> 24u);
|
||||||
|
begin_payload[1] = (uint8_t)(fw_size >> 16u);
|
||||||
|
begin_payload[2] = (uint8_t)(fw_size >> 8u);
|
||||||
|
begin_payload[3] = (uint8_t)(fw_size);
|
||||||
|
memcpy(&begin_payload[4], digest, 32);
|
||||||
|
|
||||||
|
for (int retry = 0; retry < OTA_UART_MAX_RETRIES; retry++) {
|
||||||
|
send_frame(UART_OTA_BEGIN, 0, begin_payload, 36);
|
||||||
|
if (wait_ack(0)) goto send_data;
|
||||||
|
ESP_LOGW(TAG, "BEGIN retry %d", retry);
|
||||||
|
}
|
||||||
|
ESP_LOGE(TAG, "BEGIN failed");
|
||||||
|
free(fw);
|
||||||
|
g_uart_ota_state = UART_OTA_S_FAILED;
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
|
||||||
|
send_data: {
|
||||||
|
uint32_t offset = 0;
|
||||||
|
uint16_t seq = 1;
|
||||||
|
while (offset < fw_size) {
|
||||||
|
uint16_t chunk = (uint16_t)((fw_size - offset) < OTA_UART_CHUNK_SIZE
|
||||||
|
? (fw_size - offset) : OTA_UART_CHUNK_SIZE);
|
||||||
|
bool acked = false;
|
||||||
|
for (int retry = 0; retry < OTA_UART_MAX_RETRIES; retry++) {
|
||||||
|
send_frame(UART_OTA_DATA, seq, fw + offset, chunk);
|
||||||
|
if (wait_ack(seq)) { acked = true; break; }
|
||||||
|
ESP_LOGW(TAG, "DATA seq=%u retry=%d", seq, retry);
|
||||||
|
}
|
||||||
|
if (!acked) {
|
||||||
|
ESP_LOGE(TAG, "DATA seq=%u failed", seq);
|
||||||
|
send_frame(UART_OTA_ABORT, seq, NULL, 0);
|
||||||
|
free(fw);
|
||||||
|
g_uart_ota_state = UART_OTA_S_FAILED;
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
offset += chunk;
|
||||||
|
seq++;
|
||||||
|
/* 50-100% for sending phase */
|
||||||
|
g_uart_ota_progress = (uint8_t)(50u + (offset * 50u) / fw_size);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Send OTA_END */
|
||||||
|
for (int retry = 0; retry < OTA_UART_MAX_RETRIES; retry++) {
|
||||||
|
send_frame(UART_OTA_END, seq, NULL, 0);
|
||||||
|
if (wait_ack(seq)) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
free(fw);
|
||||||
|
g_uart_ota_progress = 100;
|
||||||
|
g_uart_ota_state = UART_OTA_S_DONE;
|
||||||
|
ESP_LOGI(TAG, "IO OTA complete — %lu bytes sent", (unsigned long)fw_size);
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool uart_ota_trigger(void)
|
||||||
|
{
|
||||||
|
if (!g_io_update.available) {
|
||||||
|
ESP_LOGW(TAG, "no IO update available");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (g_uart_ota_state != UART_OTA_S_IDLE) {
|
||||||
|
ESP_LOGW(TAG, "UART OTA busy (state=%d)", g_uart_ota_state);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
/* Init UART1 for OTA */
|
||||||
|
uart_config_t ucfg = {
|
||||||
|
.baud_rate = UART_OTA_BAUD,
|
||||||
|
.data_bits = UART_DATA_8_BITS,
|
||||||
|
.parity = UART_PARITY_DISABLE,
|
||||||
|
.stop_bits = UART_STOP_BITS_1,
|
||||||
|
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
|
||||||
|
};
|
||||||
|
uart_param_config(UART_OTA_PORT, &ucfg);
|
||||||
|
uart_set_pin(UART_OTA_PORT, UART_OTA_TX_GPIO, UART_OTA_RX_GPIO,
|
||||||
|
UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
|
||||||
|
uart_driver_install(UART_OTA_PORT, 2048, 0, 0, NULL, 0);
|
||||||
|
|
||||||
|
xTaskCreate(uart_ota_task, "uart_ota", 16384, NULL, 4, NULL);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
64
esp32s3/balance/main/uart_ota.h
Normal file
64
esp32s3/balance/main/uart_ota.h
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
#pragma once
|
||||||
|
/* uart_ota.h — UART OTA protocol for Balance→IO firmware update (bd-21hv)
|
||||||
|
*
|
||||||
|
* Balance downloads io-firmware.bin from Gitea, then streams it to the IO
|
||||||
|
* board over UART1 (GPIO17/18, 460800 baud) in 1 KB chunks with ACK.
|
||||||
|
*
|
||||||
|
* Protocol frame format (both directions):
|
||||||
|
* [TYPE:1][SEQ:2 BE][LEN:2 BE][PAYLOAD:LEN][CRC8:1]
|
||||||
|
* CRC8-SMBUS over TYPE+SEQ+LEN+PAYLOAD.
|
||||||
|
*
|
||||||
|
* Balance→IO:
|
||||||
|
* OTA_BEGIN (0xC0) payload: uint32 total_size BE + uint8[32] sha256
|
||||||
|
* OTA_DATA (0xC1) payload: uint8[] chunk (up to 1024 bytes)
|
||||||
|
* OTA_END (0xC2) no payload
|
||||||
|
* OTA_ABORT (0xC3) no payload
|
||||||
|
*
|
||||||
|
* IO→Balance:
|
||||||
|
* OTA_ACK (0xC4) payload: uint16 acked_seq BE
|
||||||
|
* OTA_NACK (0xC5) payload: uint16 failed_seq BE + uint8 err_code
|
||||||
|
* OTA_STATUS (0xC6) payload: uint8 state + uint8 progress%
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
/* UART for Balance→IO OTA */
|
||||||
|
#include "driver/uart.h"
|
||||||
|
#define UART_OTA_PORT UART_NUM_1
|
||||||
|
#define UART_OTA_BAUD 460800
|
||||||
|
#define UART_OTA_TX_GPIO 17
|
||||||
|
#define UART_OTA_RX_GPIO 18
|
||||||
|
|
||||||
|
#define OTA_UART_CHUNK_SIZE 1024
|
||||||
|
#define OTA_UART_ACK_TIMEOUT_MS 3000
|
||||||
|
#define OTA_UART_MAX_RETRIES 3
|
||||||
|
|
||||||
|
/* Frame type bytes */
|
||||||
|
#define UART_OTA_BEGIN 0xC0u
|
||||||
|
#define UART_OTA_DATA 0xC1u
|
||||||
|
#define UART_OTA_END 0xC2u
|
||||||
|
#define UART_OTA_ABORT 0xC3u
|
||||||
|
#define UART_OTA_ACK 0xC4u
|
||||||
|
#define UART_OTA_NACK 0xC5u
|
||||||
|
#define UART_OTA_STATUS 0xC6u
|
||||||
|
|
||||||
|
/* NACK error codes */
|
||||||
|
#define OTA_ERR_BAD_CRC 0x01u
|
||||||
|
#define OTA_ERR_WRITE 0x02u
|
||||||
|
#define OTA_ERR_SIZE 0x03u
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
UART_OTA_S_IDLE = 0,
|
||||||
|
UART_OTA_S_DOWNLOADING, /* downloading from Gitea */
|
||||||
|
UART_OTA_S_SENDING, /* sending to IO board */
|
||||||
|
UART_OTA_S_DONE,
|
||||||
|
UART_OTA_S_FAILED,
|
||||||
|
} uart_ota_send_state_t;
|
||||||
|
|
||||||
|
extern volatile uart_ota_send_state_t g_uart_ota_state;
|
||||||
|
extern volatile uint8_t g_uart_ota_progress;
|
||||||
|
|
||||||
|
/* Trigger IO firmware update. Uses g_io_update (from gitea_ota).
|
||||||
|
* Downloads bin, then streams via UART. Returns false if busy or no update. */
|
||||||
|
bool uart_ota_trigger(void);
|
||||||
14
esp32s3/balance/main/version.h
Normal file
14
esp32s3/balance/main/version.h
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
#pragma once
|
||||||
|
/* Embedded firmware version — bump on each release */
|
||||||
|
#define BALANCE_FW_VERSION "1.0.0"
|
||||||
|
#define IO_FW_VERSION "1.0.0"
|
||||||
|
|
||||||
|
/* Gitea release tag prefixes */
|
||||||
|
#define BALANCE_TAG_PREFIX "esp32-balance/"
|
||||||
|
#define IO_TAG_PREFIX "esp32-io/"
|
||||||
|
|
||||||
|
/* Gitea release asset filenames */
|
||||||
|
#define BALANCE_BIN_ASSET "balance-firmware.bin"
|
||||||
|
#define IO_BIN_ASSET "io-firmware.bin"
|
||||||
|
#define BALANCE_SHA256_ASSET "balance-firmware.sha256"
|
||||||
|
#define IO_SHA256_ASSET "io-firmware.sha256"
|
||||||
119
esp32s3/balance/main/vesc_can.c
Normal file
119
esp32s3/balance/main/vesc_can.c
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
/* vesc_can.c — VESC CAN TWAI driver (bd-66hx)
|
||||||
|
*
|
||||||
|
* Receives VESC STATUS/4/5 frames via TWAI, proxies to Orin over serial.
|
||||||
|
* Transmits SET_RPM commands from Orin drive requests.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "vesc_can.h"
|
||||||
|
#include "orin_serial.h"
|
||||||
|
#include "config.h"
|
||||||
|
#include "driver/twai.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
static const char *TAG = "vesc_can";
|
||||||
|
|
||||||
|
vesc_state_t g_vesc[2] = {0};
|
||||||
|
|
||||||
|
/* Index for a given VESC node ID: 0=VESC_ID_A, 1=VESC_ID_B */
|
||||||
|
static int vesc_idx(uint8_t id)
|
||||||
|
{
|
||||||
|
if (id == VESC_ID_A) return 0;
|
||||||
|
if (id == VESC_ID_B) return 1;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
void vesc_can_init(void)
|
||||||
|
{
|
||||||
|
twai_general_config_t gcfg = TWAI_GENERAL_CONFIG_DEFAULT(
|
||||||
|
(gpio_num_t)VESC_CAN_TX_GPIO,
|
||||||
|
(gpio_num_t)VESC_CAN_RX_GPIO,
|
||||||
|
TWAI_MODE_NORMAL);
|
||||||
|
gcfg.rx_queue_len = VESC_CAN_RX_QUEUE;
|
||||||
|
|
||||||
|
twai_timing_config_t tcfg = TWAI_TIMING_CONFIG_500KBITS();
|
||||||
|
twai_filter_config_t fcfg = TWAI_FILTER_CONFIG_ACCEPT_ALL();
|
||||||
|
|
||||||
|
ESP_ERROR_CHECK(twai_driver_install(&gcfg, &tcfg, &fcfg));
|
||||||
|
ESP_ERROR_CHECK(twai_start());
|
||||||
|
ESP_LOGI(TAG, "TWAI init OK: tx=%d rx=%d 500kbps", VESC_CAN_TX_GPIO, VESC_CAN_RX_GPIO);
|
||||||
|
}
|
||||||
|
|
||||||
|
void vesc_can_send_rpm(uint8_t vesc_id, int32_t erpm)
|
||||||
|
{
|
||||||
|
uint32_t ext_id = ((uint32_t)VESC_PKT_SET_RPM << 8u) | vesc_id;
|
||||||
|
twai_message_t msg = {
|
||||||
|
.extd = 1,
|
||||||
|
.identifier = ext_id,
|
||||||
|
.data_length_code = 4,
|
||||||
|
};
|
||||||
|
uint32_t u = (uint32_t)erpm;
|
||||||
|
msg.data[0] = (uint8_t)(u >> 24u);
|
||||||
|
msg.data[1] = (uint8_t)(u >> 16u);
|
||||||
|
msg.data[2] = (uint8_t)(u >> 8u);
|
||||||
|
msg.data[3] = (uint8_t)(u);
|
||||||
|
twai_transmit(&msg, pdMS_TO_TICKS(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
void vesc_can_rx_task(void *arg)
|
||||||
|
{
|
||||||
|
QueueHandle_t tx_q = (QueueHandle_t)arg;
|
||||||
|
twai_message_t msg;
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
if (twai_receive(&msg, pdMS_TO_TICKS(50)) != ESP_OK) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!msg.extd) {
|
||||||
|
continue; /* ignore standard frames */
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t pkt_type = (uint8_t)(msg.identifier >> 8u);
|
||||||
|
uint8_t vesc_id = (uint8_t)(msg.identifier & 0xFFu);
|
||||||
|
int idx = vesc_idx(vesc_id);
|
||||||
|
if (idx < 0) {
|
||||||
|
continue; /* not our VESC */
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t now_ms = (uint32_t)(esp_timer_get_time() / 1000LL);
|
||||||
|
vesc_state_t *s = &g_vesc[idx];
|
||||||
|
|
||||||
|
switch (pkt_type) {
|
||||||
|
case VESC_PKT_STATUS:
|
||||||
|
if (msg.data_length_code < 8u) { break; }
|
||||||
|
s->erpm = (int32_t)(
|
||||||
|
((uint32_t)msg.data[0] << 24u) | ((uint32_t)msg.data[1] << 16u) |
|
||||||
|
((uint32_t)msg.data[2] << 8u) | (uint32_t)msg.data[3]);
|
||||||
|
s->current_x10 = (int16_t)(((uint16_t)msg.data[4] << 8u) | msg.data[5]);
|
||||||
|
s->last_rx_ms = now_ms;
|
||||||
|
/* Proxy to Orin: voltage from STATUS_5 (may be zero until received) */
|
||||||
|
{
|
||||||
|
uint8_t ttype = (vesc_id == VESC_ID_A) ? TELEM_VESC_LEFT : TELEM_VESC_RIGHT;
|
||||||
|
/* voltage_mv: V×10 → mV (/10 * 1000 = *100); current_ma: A×10 → mA (*100) */
|
||||||
|
uint16_t vmv = (uint16_t)((int32_t)s->voltage_x10 * 100);
|
||||||
|
int16_t ima = (int16_t)((int32_t)s->current_x10 * 100);
|
||||||
|
orin_send_vesc(tx_q, ttype, s->erpm, vmv, ima,
|
||||||
|
(uint16_t)s->temp_mot_x10);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case VESC_PKT_STATUS_4:
|
||||||
|
if (msg.data_length_code < 6u) { break; }
|
||||||
|
/* T_fet×10, T_mot×10, I_in×10 */
|
||||||
|
s->temp_mot_x10 = (int16_t)(((uint16_t)msg.data[2] << 8u) | msg.data[3]);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case VESC_PKT_STATUS_5:
|
||||||
|
if (msg.data_length_code < 6u) { break; }
|
||||||
|
/* int32 tacho (ignored), int16 V_in×10 */
|
||||||
|
s->voltage_x10 = (int16_t)(((uint16_t)msg.data[4] << 8u) | msg.data[5]);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
36
esp32s3/balance/main/vesc_can.h
Normal file
36
esp32s3/balance/main/vesc_can.h
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
#pragma once
|
||||||
|
/* vesc_can.h — VESC CAN TWAI driver for ESP32-S3 BALANCE (bd-66hx)
|
||||||
|
*
|
||||||
|
* VESC extended CAN ID: (packet_type << 8) | vesc_node_id
|
||||||
|
* Physical layer: TWAI peripheral → SN65HVD230 → 500 kbps shared bus
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/queue.h"
|
||||||
|
|
||||||
|
/* ── VESC packet types ── */
|
||||||
|
#define VESC_PKT_SET_RPM 3u
|
||||||
|
#define VESC_PKT_STATUS 9u /* int32 erpm, int16 I×10, int16 duty×1000 */
|
||||||
|
#define VESC_PKT_STATUS_4 16u /* int16 T_fet×10, T_mot×10, I_in×10 */
|
||||||
|
#define VESC_PKT_STATUS_5 27u /* int32 tacho, int16 V_in×10 */
|
||||||
|
|
||||||
|
/* ── VESC telemetry snapshot ── */
|
||||||
|
typedef struct {
|
||||||
|
int32_t erpm; /* electrical RPM (STATUS) */
|
||||||
|
int16_t current_x10; /* phase current A×10 (STATUS) */
|
||||||
|
int16_t voltage_x10; /* bus voltage V×10 (STATUS_5) */
|
||||||
|
int16_t temp_mot_x10; /* motor temp °C×10 (STATUS_4) */
|
||||||
|
uint32_t last_rx_ms; /* esp_timer ms of last STATUS frame */
|
||||||
|
} vesc_state_t;
|
||||||
|
|
||||||
|
/* ── Globals (two VESC nodes: index 0 = VESC_ID_A=56, 1 = VESC_ID_B=68) ── */
|
||||||
|
extern vesc_state_t g_vesc[2];
|
||||||
|
|
||||||
|
/* ── API ── */
|
||||||
|
void vesc_can_init(void);
|
||||||
|
void vesc_can_send_rpm(uint8_t vesc_id, int32_t erpm);
|
||||||
|
|
||||||
|
/* RX task — pass tx_queue as arg; forwards STATUS frames to Orin over serial */
|
||||||
|
void vesc_can_rx_task(void *arg); /* arg = QueueHandle_t orin_tx_queue */
|
||||||
7
esp32s3/balance/partitions.csv
Normal file
7
esp32s3/balance/partitions.csv
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
# ESP32-S3 BALANCE — 4 MB flash, dual OTA partitions
|
||||||
|
# Name, Type, SubType, Offset, Size
|
||||||
|
nvs, data, nvs, 0x9000, 0x5000,
|
||||||
|
otadata, data, ota, 0xe000, 0x2000,
|
||||||
|
app0, app, ota_0, 0x10000, 0x1B0000,
|
||||||
|
app1, app, ota_1, 0x1C0000, 0x1B0000,
|
||||||
|
nvs_user, data, nvs, 0x370000, 0x50000,
|
||||||
|
19
esp32s3/balance/sdkconfig.defaults
Normal file
19
esp32s3/balance/sdkconfig.defaults
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
CONFIG_IDF_TARGET="esp32s3"
|
||||||
|
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||||
|
CONFIG_FREERTOS_HZ=1000
|
||||||
|
CONFIG_ESP_TASK_WDT_EN=y
|
||||||
|
CONFIG_ESP_TASK_WDT_TIMEOUT_S=5
|
||||||
|
CONFIG_TWAI_ISR_IN_IRAM=y
|
||||||
|
CONFIG_UART_ISR_IN_IRAM=y
|
||||||
|
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
|
||||||
|
CONFIG_ESP_CONSOLE_UART_NUM=0
|
||||||
|
CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200
|
||||||
|
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
|
||||||
|
|
||||||
|
# OTA — bd-3gwo: dual OTA partitions + rollback
|
||||||
|
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||||
|
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||||
|
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y
|
||||||
|
CONFIG_OTA_ALLOW_HTTP=y
|
||||||
|
CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP=y
|
||||||
|
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y
|
||||||
3
esp32s3/io/CMakeLists.txt
Normal file
3
esp32s3/io/CMakeLists.txt
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.16)
|
||||||
|
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||||
|
project(esp32s3_io)
|
||||||
10
esp32s3/io/main/CMakeLists.txt
Normal file
10
esp32s3/io/main/CMakeLists.txt
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
idf_component_register(
|
||||||
|
SRCS "main.c" "uart_ota_recv.c"
|
||||||
|
INCLUDE_DIRS "."
|
||||||
|
REQUIRES
|
||||||
|
app_update
|
||||||
|
mbedtls
|
||||||
|
driver
|
||||||
|
freertos
|
||||||
|
esp_timer
|
||||||
|
)
|
||||||
35
esp32s3/io/main/config.h
Normal file
35
esp32s3/io/main/config.h
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
#pragma once
|
||||||
|
/* ESP32-S3 IO board — pin assignments (SAUL-TEE-SYSTEM-REFERENCE.md) */
|
||||||
|
|
||||||
|
/* ── Inter-board UART (to/from BALANCE board) ── */
|
||||||
|
#define IO_UART_PORT UART_NUM_0
|
||||||
|
#define IO_UART_BAUD 460800
|
||||||
|
#define IO_UART_TX_GPIO 43 /* IO board UART0_TXD → BALANCE RX */
|
||||||
|
#define IO_UART_RX_GPIO 44 /* IO board UART0_RXD ← BALANCE TX */
|
||||||
|
/* Note: SAUL-TEE spec says IO TX=IO18, RX=IO21; BALANCE TX=IO17, RX=IO18.
|
||||||
|
* This is UART0 on the IO devkit (GPIO43/44). Adjust to match actual wiring. */
|
||||||
|
|
||||||
|
/* ── BTS7960 Left motor driver ── */
|
||||||
|
#define MOTOR_L_RPWM 1
|
||||||
|
#define MOTOR_L_LPWM 2
|
||||||
|
#define MOTOR_L_EN_R 3
|
||||||
|
#define MOTOR_L_EN_L 4
|
||||||
|
|
||||||
|
/* ── BTS7960 Right motor driver ── */
|
||||||
|
#define MOTOR_R_RPWM 5
|
||||||
|
#define MOTOR_R_LPWM 6
|
||||||
|
#define MOTOR_R_EN_R 7
|
||||||
|
#define MOTOR_R_EN_L 8
|
||||||
|
|
||||||
|
/* ── Arming button / kill switch ── */
|
||||||
|
#define ARM_BTN_GPIO 9
|
||||||
|
#define KILL_GPIO 10
|
||||||
|
|
||||||
|
/* ── WS2812B LED strip ── */
|
||||||
|
#define LED_DATA_GPIO 13
|
||||||
|
|
||||||
|
/* ── OTA UART — receives firmware from BALANCE (bd-21hv) ── */
|
||||||
|
/* Uses same IO_UART_PORT since Balance drives OTA over the inter-board link */
|
||||||
|
|
||||||
|
/* ── Firmware version ── */
|
||||||
|
#define IO_FW_VERSION "1.0.0"
|
||||||
42
esp32s3/io/main/main.c
Normal file
42
esp32s3/io/main/main.c
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
/* main.c — ESP32-S3 IO board app_main */
|
||||||
|
|
||||||
|
#include "uart_ota_recv.h"
|
||||||
|
#include "config.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_ota_ops.h"
|
||||||
|
#include "driver/uart.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
|
||||||
|
static const char *TAG = "io_main";
|
||||||
|
|
||||||
|
static void uart_init(void)
|
||||||
|
{
|
||||||
|
uart_config_t cfg = {
|
||||||
|
.baud_rate = IO_UART_BAUD,
|
||||||
|
.data_bits = UART_DATA_8_BITS,
|
||||||
|
.parity = UART_PARITY_DISABLE,
|
||||||
|
.stop_bits = UART_STOP_BITS_1,
|
||||||
|
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
|
||||||
|
};
|
||||||
|
uart_param_config(IO_UART_PORT, &cfg);
|
||||||
|
uart_set_pin(IO_UART_PORT, IO_UART_TX_GPIO, IO_UART_RX_GPIO,
|
||||||
|
UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
|
||||||
|
uart_driver_install(IO_UART_PORT, 4096, 0, 0, NULL, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
void app_main(void)
|
||||||
|
{
|
||||||
|
ESP_LOGI(TAG, "ESP32-S3 IO v%s starting", IO_FW_VERSION);
|
||||||
|
|
||||||
|
/* Mark running image valid (OTA rollback support) */
|
||||||
|
esp_ota_mark_app_valid_cancel_rollback();
|
||||||
|
|
||||||
|
uart_init();
|
||||||
|
uart_ota_recv_init();
|
||||||
|
|
||||||
|
/* IO board main loop placeholder — RC/motor/sensor tasks added in later beads */
|
||||||
|
while (1) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||||
|
}
|
||||||
|
}
|
||||||
210
esp32s3/io/main/uart_ota_recv.c
Normal file
210
esp32s3/io/main/uart_ota_recv.c
Normal file
@ -0,0 +1,210 @@
|
|||||||
|
/* uart_ota_recv.c — IO board OTA receiver (bd-21hv)
|
||||||
|
*
|
||||||
|
* Listens on UART0 for OTA frames from Balance board.
|
||||||
|
* Writes incoming chunks to the inactive OTA partition, verifies SHA256,
|
||||||
|
* then reboots into new firmware.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "uart_ota_recv.h"
|
||||||
|
#include "config.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_ota_ops.h"
|
||||||
|
#include "driver/uart.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "mbedtls/sha256.h"
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
static const char *TAG = "io_ota";
|
||||||
|
|
||||||
|
volatile io_ota_state_t g_io_ota_state = IO_OTA_IDLE;
|
||||||
|
volatile uint8_t g_io_ota_progress = 0;
|
||||||
|
|
||||||
|
/* Frame type bytes (same as uart_ota.h sender side) */
|
||||||
|
#define OTA_BEGIN 0xC0u
|
||||||
|
#define OTA_DATA 0xC1u
|
||||||
|
#define OTA_END 0xC2u
|
||||||
|
#define OTA_ABORT 0xC3u
|
||||||
|
#define OTA_ACK 0xC4u
|
||||||
|
#define OTA_NACK 0xC5u
|
||||||
|
|
||||||
|
#define CHUNK_MAX 1024
|
||||||
|
|
||||||
|
static uint8_t crc8(const uint8_t *d, uint16_t len)
|
||||||
|
{
|
||||||
|
uint8_t crc = 0;
|
||||||
|
for (uint16_t i = 0; i < len; i++) {
|
||||||
|
crc ^= d[i];
|
||||||
|
for (uint8_t b = 0; b < 8; b++)
|
||||||
|
crc = (crc & 0x80u) ? (uint8_t)((crc << 1u) ^ 0x07u) : (uint8_t)(crc << 1u);
|
||||||
|
}
|
||||||
|
return crc;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void send_ack(uint16_t seq)
|
||||||
|
{
|
||||||
|
uint8_t frame[6];
|
||||||
|
frame[0] = OTA_ACK;
|
||||||
|
frame[1] = (uint8_t)(seq >> 8u);
|
||||||
|
frame[2] = (uint8_t)(seq);
|
||||||
|
frame[3] = 0; frame[4] = 0; /* LEN=0 */
|
||||||
|
uint8_t crc = crc8(frame, 5);
|
||||||
|
frame[5] = crc;
|
||||||
|
uart_write_bytes(IO_UART_PORT, (char *)frame, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void send_nack(uint16_t seq, uint8_t err)
|
||||||
|
{
|
||||||
|
uint8_t frame[8];
|
||||||
|
frame[0] = OTA_NACK;
|
||||||
|
frame[1] = (uint8_t)(seq >> 8u);
|
||||||
|
frame[2] = (uint8_t)(seq);
|
||||||
|
frame[3] = 0; frame[4] = 1; /* LEN=1 */
|
||||||
|
frame[5] = err;
|
||||||
|
uint8_t crc = crc8(frame, 6);
|
||||||
|
frame[6] = crc;
|
||||||
|
uart_write_bytes(IO_UART_PORT, (char *)frame, 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Read exact n bytes with timeout */
|
||||||
|
static bool uart_read_exact(uint8_t *buf, int n, int timeout_ms)
|
||||||
|
{
|
||||||
|
int got = 0;
|
||||||
|
while (got < n && timeout_ms > 0) {
|
||||||
|
int r = uart_read_bytes(IO_UART_PORT, buf + got, n - got,
|
||||||
|
pdMS_TO_TICKS(50));
|
||||||
|
if (r > 0) got += r;
|
||||||
|
else timeout_ms -= 50;
|
||||||
|
}
|
||||||
|
return got == n;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ota_recv_task(void *arg)
|
||||||
|
{
|
||||||
|
esp_ota_handle_t handle = 0;
|
||||||
|
const esp_partition_t *ota_part = esp_ota_get_next_update_partition(NULL);
|
||||||
|
mbedtls_sha256_context sha;
|
||||||
|
mbedtls_sha256_init(&sha);
|
||||||
|
uint32_t expected_size = 0;
|
||||||
|
uint8_t expected_digest[32] = {0};
|
||||||
|
uint32_t received = 0;
|
||||||
|
bool ota_started = false;
|
||||||
|
static uint8_t payload[CHUNK_MAX];
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
/* Read frame header: TYPE(1) + SEQ(2) + LEN(2) = 5 bytes */
|
||||||
|
uint8_t hdr[5];
|
||||||
|
if (!uart_read_exact(hdr, 5, 5000)) continue;
|
||||||
|
|
||||||
|
uint8_t type = hdr[0];
|
||||||
|
uint16_t seq = (uint16_t)((hdr[1] << 8u) | hdr[2]);
|
||||||
|
uint16_t plen = (uint16_t)((hdr[3] << 8u) | hdr[4]);
|
||||||
|
|
||||||
|
if (plen > CHUNK_MAX + 36) {
|
||||||
|
ESP_LOGW(TAG, "oversized frame plen=%u", plen);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Read payload + CRC */
|
||||||
|
if (plen > 0 && !uart_read_exact(payload, plen, 2000)) continue;
|
||||||
|
uint8_t crc_rx;
|
||||||
|
if (!uart_read_exact(&crc_rx, 1, 500)) continue;
|
||||||
|
|
||||||
|
/* Verify CRC over hdr+payload */
|
||||||
|
uint8_t crc_buf[5 + CHUNK_MAX + 36];
|
||||||
|
memcpy(crc_buf, hdr, 5);
|
||||||
|
if (plen > 0) memcpy(crc_buf + 5, payload, plen);
|
||||||
|
uint8_t expected_crc = crc8(crc_buf, (uint16_t)(5 + plen));
|
||||||
|
if (crc_rx != expected_crc) {
|
||||||
|
ESP_LOGW(TAG, "CRC fail seq=%u", seq);
|
||||||
|
send_nack(seq, 0x01u); /* OTA_ERR_BAD_CRC */
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case OTA_BEGIN:
|
||||||
|
if (plen < 36) { send_nack(seq, 0x03u); break; }
|
||||||
|
expected_size = ((uint32_t)payload[0] << 24u) |
|
||||||
|
((uint32_t)payload[1] << 16u) |
|
||||||
|
((uint32_t)payload[2] << 8u) |
|
||||||
|
(uint32_t)payload[3];
|
||||||
|
memcpy(expected_digest, &payload[4], 32);
|
||||||
|
|
||||||
|
if (!ota_part || esp_ota_begin(ota_part, OTA_WITH_SEQUENTIAL_WRITES,
|
||||||
|
&handle) != ESP_OK) {
|
||||||
|
send_nack(seq, 0x02u);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
mbedtls_sha256_starts(&sha, 0);
|
||||||
|
received = 0;
|
||||||
|
ota_started = true;
|
||||||
|
g_io_ota_state = IO_OTA_RECEIVING;
|
||||||
|
g_io_ota_progress = 0;
|
||||||
|
ESP_LOGI(TAG, "OTA begin: %lu bytes", (unsigned long)expected_size);
|
||||||
|
send_ack(seq);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case OTA_DATA:
|
||||||
|
if (!ota_started) { send_nack(seq, 0x02u); break; }
|
||||||
|
if (esp_ota_write(handle, payload, plen) != ESP_OK) {
|
||||||
|
send_nack(seq, 0x02u);
|
||||||
|
esp_ota_abort(handle);
|
||||||
|
ota_started = false;
|
||||||
|
g_io_ota_state = IO_OTA_FAILED;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
mbedtls_sha256_update(&sha, payload, plen);
|
||||||
|
received += plen;
|
||||||
|
if (expected_size > 0)
|
||||||
|
g_io_ota_progress = (uint8_t)((received * 100u) / expected_size);
|
||||||
|
send_ack(seq);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case OTA_END: {
|
||||||
|
if (!ota_started) { send_nack(seq, 0x02u); break; }
|
||||||
|
g_io_ota_state = IO_OTA_VERIFYING;
|
||||||
|
|
||||||
|
uint8_t digest[32];
|
||||||
|
mbedtls_sha256_finish(&sha, digest);
|
||||||
|
if (memcmp(digest, expected_digest, 32) != 0) {
|
||||||
|
ESP_LOGE(TAG, "SHA256 mismatch");
|
||||||
|
esp_ota_abort(handle);
|
||||||
|
send_nack(seq, 0x01u);
|
||||||
|
g_io_ota_state = IO_OTA_FAILED;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (esp_ota_end(handle) != ESP_OK ||
|
||||||
|
esp_ota_set_boot_partition(ota_part) != ESP_OK) {
|
||||||
|
send_nack(seq, 0x02u);
|
||||||
|
g_io_ota_state = IO_OTA_FAILED;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
g_io_ota_state = IO_OTA_REBOOTING;
|
||||||
|
g_io_ota_progress = 100;
|
||||||
|
ESP_LOGI(TAG, "OTA done — rebooting");
|
||||||
|
send_ack(seq);
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(500));
|
||||||
|
esp_restart();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case OTA_ABORT:
|
||||||
|
if (ota_started) { esp_ota_abort(handle); ota_started = false; }
|
||||||
|
g_io_ota_state = IO_OTA_IDLE;
|
||||||
|
ESP_LOGW(TAG, "OTA aborted");
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void uart_ota_recv_init(void)
|
||||||
|
{
|
||||||
|
/* UART0 already initialized for inter-board comms; just create the task */
|
||||||
|
xTaskCreate(ota_recv_task, "io_ota_recv", 8192, NULL, 6, NULL);
|
||||||
|
ESP_LOGI(TAG, "OTA receiver task started");
|
||||||
|
}
|
||||||
20
esp32s3/io/main/uart_ota_recv.h
Normal file
20
esp32s3/io/main/uart_ota_recv.h
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
#pragma once
|
||||||
|
/* uart_ota_recv.h — IO board: receives OTA firmware from Balance (bd-21hv) */
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
IO_OTA_IDLE = 0,
|
||||||
|
IO_OTA_RECEIVING,
|
||||||
|
IO_OTA_VERIFYING,
|
||||||
|
IO_OTA_APPLYING,
|
||||||
|
IO_OTA_REBOOTING,
|
||||||
|
IO_OTA_FAILED,
|
||||||
|
} io_ota_state_t;
|
||||||
|
|
||||||
|
extern volatile io_ota_state_t g_io_ota_state;
|
||||||
|
extern volatile uint8_t g_io_ota_progress;
|
||||||
|
|
||||||
|
/* Start listening for OTA frames on UART0 */
|
||||||
|
void uart_ota_recv_init(void);
|
||||||
7
esp32s3/io/partitions.csv
Normal file
7
esp32s3/io/partitions.csv
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
# ESP32-S3 IO — 4 MB flash, dual OTA partitions
|
||||||
|
# Name, Type, SubType, Offset, Size
|
||||||
|
nvs, data, nvs, 0x9000, 0x5000,
|
||||||
|
otadata, data, ota, 0xe000, 0x2000,
|
||||||
|
app0, app, ota_0, 0x10000, 0x1B0000,
|
||||||
|
app1, app, ota_1, 0x1C0000, 0x1B0000,
|
||||||
|
nvs_user, data, nvs, 0x370000, 0x50000,
|
||||||
|
13
esp32s3/io/sdkconfig.defaults
Normal file
13
esp32s3/io/sdkconfig.defaults
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
CONFIG_IDF_TARGET="esp32s3"
|
||||||
|
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||||
|
CONFIG_FREERTOS_HZ=1000
|
||||||
|
CONFIG_ESP_TASK_WDT_EN=y
|
||||||
|
CONFIG_ESP_TASK_WDT_TIMEOUT_S=5
|
||||||
|
CONFIG_UART_ISR_IN_IRAM=y
|
||||||
|
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
|
||||||
|
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
|
||||||
|
|
||||||
|
# OTA — bd-3gwo: dual OTA partitions + rollback
|
||||||
|
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||||
|
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||||
|
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y
|
||||||
193
include/jlink.h
193
include/jlink.h
@ -1,193 +0,0 @@
|
|||||||
#ifndef JLINK_H
|
|
||||||
#define JLINK_H
|
|
||||||
|
|
||||||
#include <stdint.h>
|
|
||||||
#include <stdbool.h>
|
|
||||||
|
|
||||||
/*
|
|
||||||
* JLink — Jetson serial binary protocol over USART1 (PB6=TX, PB7=RX).
|
|
||||||
*
|
|
||||||
* Issue #120: replaces jetson_cmd ASCII-over-USB-CDC with a dedicated
|
|
||||||
* hardware UART at 921600 baud using DMA circular RX and IDLE interrupt.
|
|
||||||
*
|
|
||||||
* Frame format (both directions):
|
|
||||||
* [STX=0x02][LEN][CMD][PAYLOAD...][CRC16_hi][CRC16_lo][ETX=0x03]
|
|
||||||
*
|
|
||||||
* STX : frame start sentinel (0x02)
|
|
||||||
* LEN : count of CMD + PAYLOAD bytes (1 + payload_len)
|
|
||||||
* CMD : command/telemetry type byte
|
|
||||||
* PAYLOAD: 0..N bytes depending on CMD
|
|
||||||
* CRC16 : CRC16-XModem over CMD+PAYLOAD (poly 0x1021, init 0), big-endian
|
|
||||||
* ETX : frame end sentinel (0x03)
|
|
||||||
*
|
|
||||||
* Jetson to STM32 commands:
|
|
||||||
* 0x01 HEARTBEAT - no payload; refreshes heartbeat timer
|
|
||||||
* 0x02 DRIVE - int16 speed (-1000..+1000), int16 steer (-1000..+1000)
|
|
||||||
* 0x03 ARM - no payload; request arm (same interlock as CDC 'A')
|
|
||||||
* 0x04 DISARM - no payload; disarm immediately
|
|
||||||
* 0x05 PID_SET - float kp, float ki, float kd (12 bytes, IEEE-754 LE)
|
|
||||||
* 0x06 DFU_ENTER - no payload; request OTA DFU reboot (denied while armed)
|
|
||||||
* 0x07 ESTOP - no payload; engage emergency stop
|
|
||||||
* 0x0A PID_SAVE - no payload; save current Kp/Ki/Kd to flash (Issue #531)
|
|
||||||
*
|
|
||||||
* STM32 to Jetson telemetry:
|
|
||||||
* 0x80 STATUS - jlink_tlm_status_t (20 bytes), sent at JLINK_TLM_HZ
|
|
||||||
* 0x81 POWER - jlink_tlm_power_t (11 bytes), sent at PM_TLM_HZ
|
|
||||||
* 0x83 PID_RESULT - jlink_tlm_pid_result_t (13 bytes), sent after PID_SAVE (Issue #531)
|
|
||||||
*
|
|
||||||
* Priority: CRSF RC always takes precedence. Jetson steer/speed only applied
|
|
||||||
* when mode_manager_active() == MODE_AUTONOMOUS (CH6 high). In RC_MANUAL and
|
|
||||||
* RC_ASSISTED modes the Jetson speed offset and steer are injected via
|
|
||||||
* mode_manager_set_auto_cmd() and blended per the existing blend ramp.
|
|
||||||
*
|
|
||||||
* Heartbeat: if no valid frame arrives within JLINK_HB_TIMEOUT_MS (1000ms),
|
|
||||||
* jlink_is_active() returns false and the main loop clears the auto command.
|
|
||||||
*/
|
|
||||||
|
|
||||||
/* ---- Frame constants ---- */
|
|
||||||
#define JLINK_STX 0x02u
|
|
||||||
#define JLINK_ETX 0x03u
|
|
||||||
|
|
||||||
/* ---- Command IDs (Jetson to STM32) ---- */
|
|
||||||
#define JLINK_CMD_HEARTBEAT 0x01u
|
|
||||||
#define JLINK_CMD_DRIVE 0x02u
|
|
||||||
#define JLINK_CMD_ARM 0x03u
|
|
||||||
#define JLINK_CMD_DISARM 0x04u
|
|
||||||
#define JLINK_CMD_PID_SET 0x05u
|
|
||||||
#define JLINK_CMD_DFU_ENTER 0x06u
|
|
||||||
#define JLINK_CMD_ESTOP 0x07u
|
|
||||||
#define JLINK_CMD_AUDIO 0x08u /* PCM audio chunk: int16 samples, up to 126 */
|
|
||||||
#define JLINK_CMD_SLEEP 0x09u /* no payload; request STOP-mode sleep */
|
|
||||||
#define JLINK_CMD_PID_SAVE 0x0Au /* no payload; save Kp/Ki/Kd to flash (Issue #531) */
|
|
||||||
|
|
||||||
/* ---- Telemetry IDs (STM32 to Jetson) ---- */
|
|
||||||
#define JLINK_TLM_STATUS 0x80u
|
|
||||||
#define JLINK_TLM_POWER 0x81u /* jlink_tlm_power_t (11 bytes) */
|
|
||||||
#define JLINK_TLM_BATTERY 0x82u /* jlink_tlm_battery_t (10 bytes, Issue #533) */
|
|
||||||
#define JLINK_TLM_PID_RESULT 0x83u /* jlink_tlm_pid_result_t (13 bytes) Issue #531 */
|
|
||||||
|
|
||||||
/* ---- Telemetry STATUS payload (20 bytes, packed) ---- */
|
|
||||||
typedef struct __attribute__((packed)) {
|
|
||||||
int16_t pitch_x10; /* pitch degrees x10 */
|
|
||||||
int16_t roll_x10; /* roll degrees x10 */
|
|
||||||
int16_t yaw_x10; /* yaw degrees x10 (gyro-integrated) */
|
|
||||||
int16_t motor_cmd; /* ESC output -1000..+1000 */
|
|
||||||
uint16_t vbat_mv; /* battery millivolts */
|
|
||||||
int8_t rssi_dbm; /* CRSF RSSI (dBm, negative) */
|
|
||||||
uint8_t link_quality; /* CRSF LQ 0-100 */
|
|
||||||
uint8_t balance_state; /* 0=DISARMED, 1=ARMED, 2=TILT_FAULT */
|
|
||||||
uint8_t rc_armed; /* crsf_state.armed (1=armed) */
|
|
||||||
uint8_t mode; /* robot_mode_t: 0=RC_MANUAL,1=ASSISTED,2=AUTONOMOUS */
|
|
||||||
uint8_t estop; /* EstopSource value */
|
|
||||||
uint8_t soc_pct; /* state-of-charge 0-100, 255=unknown */
|
|
||||||
uint8_t fw_major;
|
|
||||||
uint8_t fw_minor;
|
|
||||||
uint8_t fw_patch;
|
|
||||||
} jlink_tlm_status_t; /* 20 bytes */
|
|
||||||
|
|
||||||
/* ---- Telemetry POWER payload (11 bytes, packed) ---- */
|
|
||||||
typedef struct __attribute__((packed)) {
|
|
||||||
uint8_t power_state; /* PowerState: 0=ACTIVE,1=SLEEP_PENDING,2=SLEEPING,3=WAKING */
|
|
||||||
uint16_t est_total_ma; /* estimated total current draw (mA) */
|
|
||||||
uint16_t est_audio_ma; /* estimated I2S3+amp current (mA); 0 if gated */
|
|
||||||
uint16_t est_osd_ma; /* estimated OSD SPI2 current (mA); 0 if gated */
|
|
||||||
uint32_t idle_ms; /* ms since last cmd_vel activity */
|
|
||||||
} jlink_tlm_power_t; /* 11 bytes */
|
|
||||||
|
|
||||||
/* ---- Telemetry BATTERY payload (10 bytes, packed) — Issue #533 ---- */
|
|
||||||
typedef struct __attribute__((packed)) {
|
|
||||||
uint16_t vbat_mv; /* DMA-sampled LPF-filtered Vbat (mV) */
|
|
||||||
int16_t ibat_ma; /* DMA-sampled LPF-filtered Ibat (mA, + = discharge) */
|
|
||||||
uint16_t vbat_raw_mv; /* unfiltered last-tick average (mV) */
|
|
||||||
uint8_t flags; /* bit0=low, bit1=critical, bit2=4S, bit3=adc_ready */
|
|
||||||
int8_t cal_offset; /* vbat_offset_mv / 4 (±127 → ±508 mV) */
|
|
||||||
uint8_t lpf_shift; /* IIR shift factor (α = 1/2^lpf_shift) */
|
|
||||||
uint8_t soc_pct; /* voltage-based SoC 0–100, 255 = unknown */
|
|
||||||
} jlink_tlm_battery_t; /* 10 bytes */
|
|
||||||
|
|
||||||
/* ---- Telemetry PID_RESULT payload (13 bytes, packed) Issue #531 ---- */
|
|
||||||
/* Sent after JLINK_CMD_PID_SAVE is processed; confirms gains written to flash. */
|
|
||||||
typedef struct __attribute__((packed)) {
|
|
||||||
float kp; /* Kp saved */
|
|
||||||
float ki; /* Ki saved */
|
|
||||||
float kd; /* Kd saved */
|
|
||||||
uint8_t saved_ok; /* 1 = flash write verified, 0 = write failed */
|
|
||||||
} jlink_tlm_pid_result_t; /* 13 bytes */
|
|
||||||
|
|
||||||
/* ---- Volatile state (read from main loop) ---- */
|
|
||||||
typedef struct {
|
|
||||||
/* Drive command - updated on JLINK_CMD_DRIVE */
|
|
||||||
volatile int16_t speed; /* -1000..+1000 */
|
|
||||||
volatile int16_t steer; /* -1000..+1000 */
|
|
||||||
|
|
||||||
/* Heartbeat timer - updated on any valid frame */
|
|
||||||
volatile uint32_t last_rx_ms; /* HAL_GetTick() of last valid frame; 0=none */
|
|
||||||
|
|
||||||
/* One-shot request flags - set by parser, cleared by main loop */
|
|
||||||
volatile uint8_t arm_req;
|
|
||||||
volatile uint8_t disarm_req;
|
|
||||||
volatile uint8_t estop_req;
|
|
||||||
|
|
||||||
/* PID update - set by parser, cleared by main loop */
|
|
||||||
volatile uint8_t pid_updated;
|
|
||||||
volatile float pid_kp;
|
|
||||||
volatile float pid_ki;
|
|
||||||
volatile float pid_kd;
|
|
||||||
|
|
||||||
/* DFU reboot request - set by parser, cleared by main loop */
|
|
||||||
volatile uint8_t dfu_req;
|
|
||||||
/* Sleep request - set by JLINK_CMD_SLEEP, cleared by main loop */
|
|
||||||
volatile uint8_t sleep_req;
|
|
||||||
/* PID save request - set by JLINK_CMD_PID_SAVE, cleared by main loop (Issue #531) */
|
|
||||||
volatile uint8_t pid_save_req;
|
|
||||||
} JLinkState;
|
|
||||||
|
|
||||||
extern volatile JLinkState jlink_state;
|
|
||||||
|
|
||||||
/* ---- API ---- */
|
|
||||||
|
|
||||||
/*
|
|
||||||
* jlink_init() - configure USART1 (PB6=TX, PB7=RX) at 921600 baud with
|
|
||||||
* DMA2_Stream2_Channel4 circular RX (128-byte buffer) and IDLE interrupt.
|
|
||||||
* Call once before safety_init().
|
|
||||||
*/
|
|
||||||
void jlink_init(void);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* jlink_is_active(now_ms) - returns true if a valid frame arrived within
|
|
||||||
* JLINK_HB_TIMEOUT_MS. Returns false if no frame ever received.
|
|
||||||
*/
|
|
||||||
bool jlink_is_active(uint32_t now_ms);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* jlink_send_telemetry(status) - build and transmit a JLINK_TLM_STATUS frame
|
|
||||||
* over USART1 TX (blocking, ~0.2ms at 921600). Call at JLINK_TLM_HZ.
|
|
||||||
*/
|
|
||||||
void jlink_send_telemetry(const jlink_tlm_status_t *status);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* jlink_process() - drain DMA circular buffer and parse frames.
|
|
||||||
* Call from main loop every iteration (not ISR). Lightweight: O(bytes_pending).
|
|
||||||
*/
|
|
||||||
void jlink_process(void);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* jlink_send_power_telemetry(power) - build and transmit a JLINK_TLM_POWER
|
|
||||||
* frame (17 bytes) at PM_TLM_HZ. Call from main loop when not in STOP mode.
|
|
||||||
*/
|
|
||||||
void jlink_send_power_telemetry(const jlink_tlm_power_t *power);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* jlink_send_pid_result(result) - build and transmit a JLINK_TLM_PID_RESULT
|
|
||||||
* frame (19 bytes) to confirm PID flash save outcome (Issue #531).
|
|
||||||
*/
|
|
||||||
void jlink_send_pid_result(const jlink_tlm_pid_result_t *result);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* jlink_send_battery_telemetry(batt) - build and transmit JLINK_TLM_BATTERY
|
|
||||||
* (0x82) frame (16 bytes) at BATTERY_ADC_PUBLISH_HZ (1 Hz).
|
|
||||||
* Called by battery_adc_publish(); not normally called directly.
|
|
||||||
*/
|
|
||||||
void jlink_send_battery_telemetry(const jlink_tlm_battery_t *batt);
|
|
||||||
|
|
||||||
#endif /* JLINK_H */
|
|
||||||
@ -1,48 +0,0 @@
|
|||||||
#ifndef PID_FLASH_H
|
|
||||||
#define PID_FLASH_H
|
|
||||||
|
|
||||||
#include <stdint.h>
|
|
||||||
#include <stdbool.h>
|
|
||||||
|
|
||||||
/*
|
|
||||||
* pid_flash — persistent PID storage for Issue #531 (auto-tune).
|
|
||||||
*
|
|
||||||
* Stores Kp, Ki, Kd in the last 64 bytes of STM32F722 flash sector 7
|
|
||||||
* (0x0807FFC0). Magic word validates presence of saved params.
|
|
||||||
* Sector 7 is 128KB starting at 0x08060000; firmware never exceeds sector 6.
|
|
||||||
*
|
|
||||||
* Flash writes require an erase of the full sector (128KB) before re-writing.
|
|
||||||
* The store address is the very last 64-byte block so future expansion can
|
|
||||||
* grow toward lower addresses within sector 7 without conflict.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#define PID_FLASH_SECTOR FLASH_SECTOR_7
|
|
||||||
#define PID_FLASH_SECTOR_VOLTAGE VOLTAGE_RANGE_3 /* 2.7V-3.6V, 32-bit parallelism */
|
|
||||||
|
|
||||||
/* Sector 7: 128KB at 0x08060000; store in last 64 bytes */
|
|
||||||
#define PID_FLASH_STORE_ADDR 0x0807FFC0UL
|
|
||||||
#define PID_FLASH_MAGIC 0x534C5401UL /* 'SLT\x01' — version 1 */
|
|
||||||
|
|
||||||
typedef struct __attribute__((packed)) {
|
|
||||||
uint32_t magic; /* PID_FLASH_MAGIC when valid */
|
|
||||||
float kp;
|
|
||||||
float ki;
|
|
||||||
float kd;
|
|
||||||
uint8_t _pad[48]; /* padding to 64 bytes */
|
|
||||||
} pid_flash_t;
|
|
||||||
|
|
||||||
/*
|
|
||||||
* pid_flash_load() — read saved PID from flash.
|
|
||||||
* Returns true and fills *kp/*ki/*kd if magic is valid.
|
|
||||||
* Returns false if no valid params stored (caller keeps defaults).
|
|
||||||
*/
|
|
||||||
bool pid_flash_load(float *kp, float *ki, float *kd);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* pid_flash_save() — erase sector 7 and write Kp/Ki/Kd.
|
|
||||||
* Must not be called while armed (flash erase takes ~1s and stalls the CPU).
|
|
||||||
* Returns true on success.
|
|
||||||
*/
|
|
||||||
bool pid_flash_save(float kp, float ki, float kd);
|
|
||||||
|
|
||||||
#endif /* PID_FLASH_H */
|
|
||||||
@ -2,7 +2,7 @@
|
|||||||
# Base: JetPack 6 (L4T R36.2.0) + CUDA 12.x / Ubuntu 22.04
|
# Base: JetPack 6 (L4T R36.2.0) + CUDA 12.x / Ubuntu 22.04
|
||||||
#
|
#
|
||||||
# Hardware: Jetson Orin Nano Super 8GB (67 TOPS, 1024-core Ampere)
|
# Hardware: Jetson Orin Nano Super 8GB (67 TOPS, 1024-core Ampere)
|
||||||
# Previous: Jetson Nano 4GB (JetPack 4.6 / L4T R32.6.1) — see git history
|
# Previous: Jetson Orin Nano Super 4GB (JetPack 4.6 / L4T R32.6.1) — see git history
|
||||||
|
|
||||||
FROM nvcr.io/nvidia/l4t-jetpack:r36.2.0
|
FROM nvcr.io/nvidia/l4t-jetpack:r36.2.0
|
||||||
|
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
# Jetson Nano — AI/SLAM Platform Setup
|
# Jetson Orin Nano Super — AI/SLAM Platform Setup
|
||||||
|
|
||||||
Self-balancing robot: Jetson Nano dev environment for ROS2 Humble + SLAM stack.
|
Self-balancing robot: Jetson Orin Nano Super dev environment for ROS2 Humble + SLAM stack.
|
||||||
|
|
||||||
## Stack
|
## Stack
|
||||||
|
|
||||||
| Component | Version / Part |
|
| Component | Version / Part |
|
||||||
|-----------|---------------|
|
|-----------|---------------|
|
||||||
| Platform | Jetson Nano 4GB |
|
| Platform | Jetson Orin Nano Super 4GB |
|
||||||
| JetPack | 4.6 (L4T R32.6.1, CUDA 10.2) |
|
| JetPack | 4.6 (L4T R32.6.1, CUDA 10.2) |
|
||||||
| ROS2 | Humble Hawksbill |
|
| ROS2 | Humble Hawksbill |
|
||||||
| DDS | CycloneDDS |
|
| DDS | CycloneDDS |
|
||||||
@ -14,7 +14,11 @@ Self-balancing robot: Jetson Nano dev environment for ROS2 Humble + SLAM stack.
|
|||||||
| Nav | Nav2 |
|
| Nav | Nav2 |
|
||||||
| Depth camera | Intel RealSense D435i |
|
| Depth camera | Intel RealSense D435i |
|
||||||
| LiDAR | RPLIDAR A1M8 |
|
| LiDAR | RPLIDAR A1M8 |
|
||||||
| MCU bridge | STM32F722 (USB CDC @ 921600) |
|
<<<<<<< HEAD
|
||||||
|
| MCU bridge | ESP32 (USB CDC @ 921600) |
|
||||||
|
=======
|
||||||
|
| MCU bridge | ESP32-S3 (USB Serial (CH343) @ 921600) |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
@ -42,7 +46,11 @@ bash scripts/build-and-run.sh shell
|
|||||||
```
|
```
|
||||||
jetson/
|
jetson/
|
||||||
├── Dockerfile # L4T base + ROS2 Humble + SLAM packages
|
├── Dockerfile # L4T base + ROS2 Humble + SLAM packages
|
||||||
├── docker-compose.yml # Multi-service stack (ROS2, RPLIDAR, D435i, STM32)
|
<<<<<<< HEAD
|
||||||
|
├── docker-compose.yml # Multi-service stack (ROS2, RPLIDAR, D435i, ESP32 BALANCE)
|
||||||
|
=======
|
||||||
|
├── docker-compose.yml # Multi-service stack (ROS2, RPLIDAR, D435i, ESP32-S3)
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
├── README.md # This file
|
├── README.md # This file
|
||||||
├── docs/
|
├── docs/
|
||||||
│ ├── pinout.md # GPIO/I2C/UART pinout reference
|
│ ├── pinout.md # GPIO/I2C/UART pinout reference
|
||||||
|
|||||||
@ -34,7 +34,11 @@ Recovery behaviors are triggered when Nav2 encounters navigation failures (path
|
|||||||
|
|
||||||
The emergency stop system (Issue #459, `saltybot_emergency` package) runs independently of Nav2 and takes absolute priority.
|
The emergency stop system (Issue #459, `saltybot_emergency` package) runs independently of Nav2 and takes absolute priority.
|
||||||
|
|
||||||
Recovery behaviors cannot interfere with E-stop because the emergency system operates at the motor driver level on the STM32 firmware.
|
<<<<<<< HEAD
|
||||||
|
Recovery behaviors cannot interfere with E-stop because the emergency system operates at the motor driver level on the ESP32 BALANCE firmware.
|
||||||
|
=======
|
||||||
|
Recovery behaviors cannot interfere with E-stop because the emergency system operates at the motor driver level on the ESP32-S3 firmware.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
## Behavior Tree Sequence
|
## Behavior Tree Sequence
|
||||||
|
|
||||||
|
|||||||
@ -12,7 +12,11 @@
|
|||||||
# /scan — RPLIDAR A1M8 (obstacle layer)
|
# /scan — RPLIDAR A1M8 (obstacle layer)
|
||||||
# /camera/depth/color/points — RealSense D435i (voxel layer)
|
# /camera/depth/color/points — RealSense D435i (voxel layer)
|
||||||
#
|
#
|
||||||
# Output: /cmd_vel (Twist) — STM32 bridge consumes this topic.
|
<<<<<<< HEAD
|
||||||
|
# Output: /cmd_vel (Twist) — ESP32 bridge consumes this topic.
|
||||||
|
=======
|
||||||
|
# Output: /cmd_vel (Twist) — ESP32-S3 bridge consumes this topic.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
bt_navigator:
|
bt_navigator:
|
||||||
ros__parameters:
|
ros__parameters:
|
||||||
|
|||||||
@ -31,7 +31,7 @@ services:
|
|||||||
- ./config:/config:ro
|
- ./config:/config:ro
|
||||||
devices:
|
devices:
|
||||||
- /dev/rplidar:/dev/rplidar
|
- /dev/rplidar:/dev/rplidar
|
||||||
- /dev/stm32-bridge:/dev/stm32-bridge
|
- /dev/esp32-bridge:/dev/esp32-bridge
|
||||||
- /dev/bus/usb:/dev/bus/usb
|
- /dev/bus/usb:/dev/bus/usb
|
||||||
- /dev/i2c-7:/dev/i2c-7
|
- /dev/i2c-7:/dev/i2c-7
|
||||||
- /dev/video0:/dev/video0
|
- /dev/video0:/dev/video0
|
||||||
@ -97,13 +97,17 @@ services:
|
|||||||
rgb_camera.profile:=640x480x30
|
rgb_camera.profile:=640x480x30
|
||||||
"
|
"
|
||||||
|
|
||||||
# ── STM32 bridge node (bidirectional serial<->ROS2) ────────────────────────
|
<<<<<<< HEAD
|
||||||
stm32-bridge:
|
# ── ESP32 bridge node (bidirectional serial<->ROS2) ────────────────────────
|
||||||
|
=======
|
||||||
|
# ── ESP32-S3 bridge node (bidirectional serial<->ROS2) ────────────────────────
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
esp32-bridge:
|
||||||
image: saltybot/ros2-humble:jetson-orin
|
image: saltybot/ros2-humble:jetson-orin
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
container_name: saltybot-stm32-bridge
|
container_name: saltybot-esp32-bridge
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
runtime: nvidia
|
runtime: nvidia
|
||||||
network_mode: host
|
network_mode: host
|
||||||
@ -111,13 +115,13 @@ services:
|
|||||||
- ROS_DOMAIN_ID=42
|
- ROS_DOMAIN_ID=42
|
||||||
- RMW_IMPLEMENTATION=rmw_cyclonedds_cpp
|
- RMW_IMPLEMENTATION=rmw_cyclonedds_cpp
|
||||||
devices:
|
devices:
|
||||||
- /dev/stm32-bridge:/dev/stm32-bridge
|
- /dev/esp32-bridge:/dev/esp32-bridge
|
||||||
command: >
|
command: >
|
||||||
bash -c "
|
bash -c "
|
||||||
source /opt/ros/humble/setup.bash &&
|
source /opt/ros/humble/setup.bash &&
|
||||||
ros2 launch saltybot_bridge bridge.launch.py
|
ros2 launch saltybot_bridge bridge.launch.py
|
||||||
mode:=bidirectional
|
mode:=bidirectional
|
||||||
serial_port:=/dev/stm32-bridge
|
serial_port:=/dev/esp32-bridge
|
||||||
"
|
"
|
||||||
|
|
||||||
# ── 4x IMX219 CSI cameras ──────────────────────────────────────────────────
|
# ── 4x IMX219 CSI cameras ──────────────────────────────────────────────────
|
||||||
@ -192,7 +196,7 @@ services:
|
|||||||
network_mode: host
|
network_mode: host
|
||||||
depends_on:
|
depends_on:
|
||||||
- saltybot-ros2
|
- saltybot-ros2
|
||||||
- stm32-bridge
|
- esp32-bridge
|
||||||
- csi-cameras
|
- csi-cameras
|
||||||
environment:
|
environment:
|
||||||
- ROS_DOMAIN_ID=42
|
- ROS_DOMAIN_ID=42
|
||||||
@ -208,8 +212,13 @@ services:
|
|||||||
"
|
"
|
||||||
|
|
||||||
|
|
||||||
# -- Remote e-stop bridge (MQTT over 4G -> STM32 CDC) ----------------------
|
<<<<<<< HEAD
|
||||||
# Subscribes to saltybot/estop MQTT topic. {"kill":true} -> 'E\r\n' to STM32.
|
# -- Remote e-stop bridge (MQTT over 4G -> ESP32 CDC) ----------------------
|
||||||
|
# Subscribes to saltybot/estop MQTT topic. {"kill":true} -> 'E\r\n' to ESP32 BALANCE.
|
||||||
|
=======
|
||||||
|
# -- Remote e-stop bridge (MQTT over 4G -> ESP32-S3 CDC) ----------------------
|
||||||
|
# Subscribes to saltybot/estop MQTT topic. {"kill":true} -> 'E\r\n' to ESP32-S3.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
# Cellular watchdog: 5s MQTT drop in AUTO mode -> 'F\r\n' (ESTOP_CELLULAR_TIMEOUT).
|
# Cellular watchdog: 5s MQTT drop in AUTO mode -> 'F\r\n' (ESTOP_CELLULAR_TIMEOUT).
|
||||||
remote-estop:
|
remote-estop:
|
||||||
image: saltybot/ros2-humble:jetson-orin
|
image: saltybot/ros2-humble:jetson-orin
|
||||||
@ -221,12 +230,12 @@ services:
|
|||||||
runtime: nvidia
|
runtime: nvidia
|
||||||
network_mode: host
|
network_mode: host
|
||||||
depends_on:
|
depends_on:
|
||||||
- stm32-bridge
|
- esp32-bridge
|
||||||
environment:
|
environment:
|
||||||
- ROS_DOMAIN_ID=42
|
- ROS_DOMAIN_ID=42
|
||||||
- RMW_IMPLEMENTATION=rmw_cyclonedds_cpp
|
- RMW_IMPLEMENTATION=rmw_cyclonedds_cpp
|
||||||
devices:
|
devices:
|
||||||
- /dev/stm32-bridge:/dev/stm32-bridge
|
- /dev/esp32-bridge:/dev/esp32-bridge
|
||||||
volumes:
|
volumes:
|
||||||
- ./ros2_ws/src:/ros2_ws/src:rw
|
- ./ros2_ws/src:/ros2_ws/src:rw
|
||||||
- ./config:/config:ro
|
- ./config:/config:ro
|
||||||
@ -316,7 +325,7 @@ services:
|
|||||||
runtime: nvidia
|
runtime: nvidia
|
||||||
network_mode: host
|
network_mode: host
|
||||||
depends_on:
|
depends_on:
|
||||||
- stm32-bridge
|
- esp32-bridge
|
||||||
environment:
|
environment:
|
||||||
- NVIDIA_VISIBLE_DEVICES=all
|
- NVIDIA_VISIBLE_DEVICES=all
|
||||||
- NVIDIA_DRIVER_CAPABILITIES=all,audio
|
- NVIDIA_DRIVER_CAPABILITIES=all,audio
|
||||||
|
|||||||
@ -1,5 +1,9 @@
|
|||||||
# Jetson Orin Nano Super — GPIO / I2C / UART / CSI Pinout Reference
|
# Jetson Orin Nano Super — GPIO / I2C / UART / CSI Pinout Reference
|
||||||
## Self-Balancing Robot: STM32F722 Bridge + RealSense D435i + RPLIDAR A1M8 + 4× IMX219
|
<<<<<<< HEAD
|
||||||
|
## Self-Balancing Robot: ESP32 Bridge + RealSense D435i + RPLIDAR A1M8 + 4× IMX219
|
||||||
|
=======
|
||||||
|
## Self-Balancing Robot: ESP32-S3 Bridge + RealSense D435i + RPLIDAR A1M8 + 4× IMX219
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
Last updated: 2026-02-28
|
Last updated: 2026-02-28
|
||||||
JetPack version: 6.x (L4T R36.x / Ubuntu 22.04)
|
JetPack version: 6.x (L4T R36.x / Ubuntu 22.04)
|
||||||
@ -43,21 +47,37 @@ i2cdetect -l
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. STM32F722 Bridge (USB CDC — Primary)
|
<<<<<<< HEAD
|
||||||
|
## 1. ESP32 Bridge (USB CDC — Primary)
|
||||||
|
|
||||||
The STM32 acts as a real-time motor + IMU controller. Communication is via **USB CDC serial**.
|
The ESP32 BALANCE acts as a real-time motor + IMU controller. Communication is via **USB CDC serial**.
|
||||||
|
=======
|
||||||
|
## 1. ESP32-S3 Bridge (USB Serial (CH343) — Primary)
|
||||||
|
|
||||||
### USB CDC Connection
|
The ESP32-S3 acts as a real-time motor + IMU controller. Communication is via **USB Serial (CH343) serial**.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
|
### USB Serial (CH343) Connection
|
||||||
| Connection | Detail |
|
| Connection | Detail |
|
||||||
|-----------|--------|
|
|-----------|--------|
|
||||||
| Interface | USB Micro-B on STM32 dev board → USB-A on Jetson |
|
<<<<<<< HEAD
|
||||||
| Device node | `/dev/ttyACM0` → symlink `/dev/stm32-bridge` (via udev) |
|
| Interface | USB on ESP32 BALANCE board → USB-A on Jetson |
|
||||||
| Baud rate | 921600 (configured in STM32 firmware) |
|
| Device node | `/dev/ttyACM0` → symlink `/dev/esp32-bridge` (via udev) |
|
||||||
|
| Baud rate | 921600 (configured in ESP32 BALANCE firmware) |
|
||||||
|
=======
|
||||||
|
| Interface | USB Micro-B on ESP32-S3 dev board → USB-A on Jetson |
|
||||||
|
| Device node | `/dev/ttyACM0` → symlink `/dev/esp32-bridge` (via udev) |
|
||||||
|
| Baud rate | 921600 (configured in ESP32-S3 firmware) |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
| Protocol | JSON telemetry RX + ASCII command TX (see bridge docs) |
|
| Protocol | JSON telemetry RX + ASCII command TX (see bridge docs) |
|
||||||
| Power | Powered via robot 5V bus (data-only via USB) |
|
| Power | Powered via robot 5V bus (data-only via USB) |
|
||||||
|
|
||||||
### Hardware UART (Fallback — 40-pin header)
|
### Hardware UART (Fallback — 40-pin header)
|
||||||
| Jetson Pin | Signal | STM32 Pin | Notes |
|
<<<<<<< HEAD
|
||||||
|
| Jetson Pin | Signal | ESP32 Pin | Notes |
|
||||||
|
=======
|
||||||
|
| Jetson Pin | Signal | ESP32-S3 Pin | Notes |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|-----------|--------|-----------|-------|
|
|-----------|--------|-----------|-------|
|
||||||
| Pin 8 (TXD0) | TX → | PA10 (UART1 RX) | Cross-connect TX→RX |
|
| Pin 8 (TXD0) | TX → | PA10 (UART1 RX) | Cross-connect TX→RX |
|
||||||
| Pin 10 (RXD0) | RX ← | PA9 (UART1 TX) | Cross-connect RX→TX |
|
| Pin 10 (RXD0) | RX ← | PA9 (UART1 TX) | Cross-connect RX→TX |
|
||||||
@ -65,7 +85,11 @@ The STM32 acts as a real-time motor + IMU controller. Communication is via **USB
|
|||||||
|
|
||||||
**Jetson device node:** `/dev/ttyTHS0`
|
**Jetson device node:** `/dev/ttyTHS0`
|
||||||
**Baud rate:** 921600, 8N1
|
**Baud rate:** 921600, 8N1
|
||||||
**Voltage level:** 3.3V — both Jetson Orin and STM32F722 are 3.3V GPIO
|
<<<<<<< HEAD
|
||||||
|
**Voltage level:** 3.3V — both Jetson Orin and ESP32 are 3.3V GPIO
|
||||||
|
=======
|
||||||
|
**Voltage level:** 3.3V — both Jetson Orin and ESP32-S3 are 3.3V GPIO
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Verify UART
|
# Verify UART
|
||||||
@ -75,13 +99,23 @@ sudo usermod -aG dialout $USER
|
|||||||
picocom -b 921600 /dev/ttyTHS0
|
picocom -b 921600 /dev/ttyTHS0
|
||||||
```
|
```
|
||||||
|
|
||||||
**ROS2 topics (STM32 bridge node):**
|
<<<<<<< HEAD
|
||||||
|
**ROS2 topics (ESP32 bridge node):**
|
||||||
| ROS2 Topic | Direction | Content |
|
| ROS2 Topic | Direction | Content |
|
||||||
|-----------|-----------|---------
|
|-----------|-----------|---------
|
||||||
| `/saltybot/imu` | STM32→Jetson | IMU data (accel, gyro) at 50Hz |
|
| `/saltybot/imu` | ESP32 BALANCE→Jetson | IMU data (accel, gyro) at 50Hz |
|
||||||
| `/saltybot/balance_state` | STM32→Jetson | Motor cmd, pitch, state |
|
| `/saltybot/balance_state` | ESP32 BALANCE→Jetson | Motor cmd, pitch, state |
|
||||||
| `/cmd_vel` | Jetson→STM32 | Velocity commands → `C<spd>,<str>\n` |
|
| `/cmd_vel` | Jetson→ESP32 BALANCE | Velocity commands → `C<spd>,<str>\n` |
|
||||||
| `/saltybot/estop` | Jetson→STM32 | Emergency stop |
|
| `/saltybot/estop` | Jetson→ESP32 BALANCE | Emergency stop |
|
||||||
|
=======
|
||||||
|
**ROS2 topics (ESP32-S3 bridge node):**
|
||||||
|
| ROS2 Topic | Direction | Content |
|
||||||
|
|-----------|-----------|---------
|
||||||
|
| `/saltybot/imu` | ESP32-S3→Jetson | IMU data (accel, gyro) at 50Hz |
|
||||||
|
| `/saltybot/balance_state` | ESP32-S3→Jetson | Motor cmd, pitch, state |
|
||||||
|
| `/cmd_vel` | Jetson→ESP32-S3 | Velocity commands → `C<spd>,<str>\n` |
|
||||||
|
| `/saltybot/estop` | Jetson→ESP32-S3 | Emergency stop |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -266,7 +300,11 @@ sudo mkdir -p /mnt/nvme
|
|||||||
|------|------|----------|
|
|------|------|----------|
|
||||||
| USB-A (top, blue) | USB 3.1 Gen 1 | RealSense D435i |
|
| USB-A (top, blue) | USB 3.1 Gen 1 | RealSense D435i |
|
||||||
| USB-A (bottom) | USB 2.0 | RPLIDAR (via USB-UART adapter) |
|
| USB-A (bottom) | USB 2.0 | RPLIDAR (via USB-UART adapter) |
|
||||||
| USB-C | USB 3.1 Gen 1 (+ DP) | STM32 CDC or host flash |
|
<<<<<<< HEAD
|
||||||
|
| USB-C | USB 3.1 Gen 1 (+ DP) | ESP32 CDC or host flash |
|
||||||
|
=======
|
||||||
|
| USB-C | USB 3.1 Gen 1 (+ DP) | ESP32-S3 CDC or host flash |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
| Micro-USB | Debug/flash | JetPack flash only |
|
| Micro-USB | Debug/flash | JetPack flash only |
|
||||||
|
|
||||||
---
|
---
|
||||||
@ -277,10 +315,17 @@ sudo mkdir -p /mnt/nvme
|
|||||||
|-------------|----------|---------|----------|
|
|-------------|----------|---------|----------|
|
||||||
| 3 | SDA1 | 3.3V | I2C data (i2c-7) |
|
| 3 | SDA1 | 3.3V | I2C data (i2c-7) |
|
||||||
| 5 | SCL1 | 3.3V | I2C clock (i2c-7) |
|
| 5 | SCL1 | 3.3V | I2C clock (i2c-7) |
|
||||||
| 8 | TXD0 | 3.3V | UART TX → STM32 (fallback) |
|
<<<<<<< HEAD
|
||||||
| 10 | RXD0 | 3.3V | UART RX ← STM32 (fallback) |
|
| 8 | TXD0 | 3.3V | UART TX → ESP32 BALANCE (fallback) |
|
||||||
|
| 10 | RXD0 | 3.3V | UART RX ← ESP32 BALANCE (fallback) |
|
||||||
| USB-A ×2 | — | 5V | D435i, RPLIDAR |
|
| USB-A ×2 | — | 5V | D435i, RPLIDAR |
|
||||||
| USB-C | — | 5V | STM32 CDC |
|
| USB-C | — | 5V | ESP32 CDC |
|
||||||
|
=======
|
||||||
|
| 8 | TXD0 | 3.3V | UART TX → ESP32-S3 (fallback) |
|
||||||
|
| 10 | RXD0 | 3.3V | UART RX ← ESP32-S3 (fallback) |
|
||||||
|
| USB-A ×2 | — | 5V | D435i, RPLIDAR |
|
||||||
|
| USB-C | — | 5V | ESP32-S3 CDC |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
| CSI-A (J5) | MIPI CSI-2 | — | Cameras front + left |
|
| CSI-A (J5) | MIPI CSI-2 | — | Cameras front + left |
|
||||||
| CSI-B (J8) | MIPI CSI-2 | — | Cameras rear + right |
|
| CSI-B (J8) | MIPI CSI-2 | — | Cameras rear + right |
|
||||||
| M.2 Key M | PCIe Gen3 ×4 | — | NVMe SSD |
|
| M.2 Key M | PCIe Gen3 ×4 | — | NVMe SSD |
|
||||||
@ -298,9 +343,13 @@ Apply stable device names:
|
|||||||
KERNEL=="ttyUSB*", ATTRS{idVendor}=="10c4", ATTRS{idProduct}=="ea60", \
|
KERNEL=="ttyUSB*", ATTRS{idVendor}=="10c4", ATTRS{idProduct}=="ea60", \
|
||||||
SYMLINK+="rplidar", MODE="0666"
|
SYMLINK+="rplidar", MODE="0666"
|
||||||
|
|
||||||
# STM32 USB CDC (STMicroelectronics)
|
<<<<<<< HEAD
|
||||||
|
# ESP32 USB CDC (STMicroelectronics)
|
||||||
|
=======
|
||||||
|
# ESP32-S3 USB Serial (CH343) (STMicroelectronics)
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
KERNEL=="ttyACM*", ATTRS{idVendor}=="0483", ATTRS{idProduct}=="5740", \
|
KERNEL=="ttyACM*", ATTRS{idVendor}=="0483", ATTRS{idProduct}=="5740", \
|
||||||
SYMLINK+="stm32-bridge", MODE="0666"
|
SYMLINK+="esp32-bridge", MODE="0666"
|
||||||
|
|
||||||
# Intel RealSense D435i
|
# Intel RealSense D435i
|
||||||
SUBSYSTEM=="usb", ATTRS{idVendor}=="8086", ATTRS{idProduct}=="0b3a", \
|
SUBSYSTEM=="usb", ATTRS{idVendor}=="8086", ATTRS{idProduct}=="0b3a", \
|
||||||
|
|||||||
@ -56,7 +56,11 @@ sudo jtop
|
|||||||
|-----------|----------|------------|----------|-----------|-------|
|
|-----------|----------|------------|----------|-----------|-------|
|
||||||
| RealSense D435i | 0.3 | 1.5 | 3.5 | USB 3.1 | Peak during boot/init |
|
| RealSense D435i | 0.3 | 1.5 | 3.5 | USB 3.1 | Peak during boot/init |
|
||||||
| RPLIDAR A1M8 | 0.4 | 2.6 | 3.0 | USB (UART adapter) | Motor spinning |
|
| RPLIDAR A1M8 | 0.4 | 2.6 | 3.0 | USB (UART adapter) | Motor spinning |
|
||||||
| STM32F722 bridge | 0.0 | 0.0 | 0.0 | USB CDC | Self-powered from robot 5V |
|
<<<<<<< HEAD
|
||||||
|
| ESP32 bridge | 0.0 | 0.0 | 0.0 | USB CDC | Self-powered from robot 5V |
|
||||||
|
=======
|
||||||
|
| ESP32-S3 bridge | 0.0 | 0.0 | 0.0 | USB Serial (CH343) | Self-powered from robot 5V |
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
| 4× IMX219 cameras | 0.2 | 2.0 | 2.4 | MIPI CSI-2 | ~0.5W per camera active |
|
| 4× IMX219 cameras | 0.2 | 2.0 | 2.4 | MIPI CSI-2 | ~0.5W per camera active |
|
||||||
| **Peripheral Subtotal** | **0.9** | **6.1** | **8.9** | | |
|
| **Peripheral Subtotal** | **0.9** | **6.1** | **8.9** | | |
|
||||||
|
|
||||||
@ -72,7 +76,7 @@ sudo jtop
|
|||||||
|
|
||||||
## Budget Analysis vs Previous Platform
|
## Budget Analysis vs Previous Platform
|
||||||
|
|
||||||
| Metric | Jetson Nano | Jetson Orin Nano Super |
|
| Metric | Jetson Orin Nano Super | Jetson Orin Nano Super |
|
||||||
|--------|------------|------------------------|
|
|--------|------------|------------------------|
|
||||||
| TDP | 10W | 25W |
|
| TDP | 10W | 25W |
|
||||||
| CPU | 4× Cortex-A57 @ 1.43GHz | 6× A78AE @ 1.5GHz |
|
| CPU | 4× Cortex-A57 @ 1.43GHz | 6× A78AE @ 1.5GHz |
|
||||||
@ -151,7 +155,11 @@ LiPo 4S (16.8V max)
|
|||||||
├─► DC-DC Buck → 5V 6A ──► Jetson Orin barrel jack (30W)
|
├─► DC-DC Buck → 5V 6A ──► Jetson Orin barrel jack (30W)
|
||||||
│ (e.g., XL4016E1)
|
│ (e.g., XL4016E1)
|
||||||
│
|
│
|
||||||
├─► DC-DC Buck → 5V 3A ──► STM32 + logic 5V rail
|
<<<<<<< HEAD
|
||||||
|
├─► DC-DC Buck → 5V 3A ──► ESP32 + logic 5V rail
|
||||||
|
=======
|
||||||
|
├─► DC-DC Buck → 5V 3A ──► ESP32-S3 + logic 5V rail
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
│
|
│
|
||||||
└─► Hoverboard ESC ──► Hub motors (48V loop)
|
└─► Hoverboard ESC ──► Hub motors (48V loop)
|
||||||
```
|
```
|
||||||
|
|||||||
@ -0,0 +1,34 @@
|
|||||||
|
aruco_detect:
|
||||||
|
ros__parameters:
|
||||||
|
# ── Marker specification ─────────────────────────────────────────────────
|
||||||
|
marker_size_m: 0.10 # physical side length of printed ArUco markers (m)
|
||||||
|
# measure the black border edge-to-edge
|
||||||
|
|
||||||
|
# ── Dock target filter ───────────────────────────────────────────────────
|
||||||
|
# dock_marker_ids: IDs that may serve as dock target.
|
||||||
|
# - Empty list [] → any detected marker is a dock candidate (closest wins)
|
||||||
|
# - Non-empty → only listed IDs are candidates; others still appear in
|
||||||
|
# /saltybot/aruco/markers but not in dock_target
|
||||||
|
# The saltybot dock uses marker ID 42 on the charging face by convention.
|
||||||
|
dock_marker_ids: [42]
|
||||||
|
|
||||||
|
# Maximum distance to consider a marker as dock target (m)
|
||||||
|
max_dock_range_m: 3.0
|
||||||
|
|
||||||
|
# ── ArUco dictionary ─────────────────────────────────────────────────────
|
||||||
|
aruco_dict: DICT_4X4_50 # cv2.aruco constant name
|
||||||
|
|
||||||
|
# Corner sub-pixel refinement (improves pose accuracy at close range)
|
||||||
|
# CORNER_REFINE_NONE — fastest, no refinement
|
||||||
|
# CORNER_REFINE_SUBPIX — best for high-contrast markers (recommended)
|
||||||
|
# CORNER_REFINE_CONTOUR — good for blurry or low-res images
|
||||||
|
corner_refinement: CORNER_REFINE_SUBPIX
|
||||||
|
|
||||||
|
# ── Frame / topic config ─────────────────────────────────────────────────
|
||||||
|
camera_frame: camera_color_optical_frame
|
||||||
|
|
||||||
|
# ── Debug image output (disabled by default) ─────────────────────────────
|
||||||
|
# When true, publishes annotated BGR image with markers + axes drawn.
|
||||||
|
# Useful for tuning but costs ~10 ms/frame encoding overhead.
|
||||||
|
draw_debug_image: false
|
||||||
|
debug_image_topic: /saltybot/aruco/debug_image
|
||||||
@ -0,0 +1,29 @@
|
|||||||
|
"""aruco_detect.launch.py — ArUco marker detection for docking (Issue #627)."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from ament_index_python.packages import get_package_share_directory
|
||||||
|
from launch import LaunchDescription
|
||||||
|
from launch.actions import DeclareLaunchArgument
|
||||||
|
from launch.substitutions import LaunchConfiguration
|
||||||
|
from launch_ros.actions import Node
|
||||||
|
|
||||||
|
|
||||||
|
def generate_launch_description():
|
||||||
|
pkg_share = get_package_share_directory('saltybot_aruco_detect')
|
||||||
|
default_params = os.path.join(pkg_share, 'config', 'aruco_detect_params.yaml')
|
||||||
|
|
||||||
|
params_arg = DeclareLaunchArgument(
|
||||||
|
'params_file',
|
||||||
|
default_value=default_params,
|
||||||
|
description='Path to aruco_detect_params.yaml',
|
||||||
|
)
|
||||||
|
|
||||||
|
aruco_node = Node(
|
||||||
|
package='saltybot_aruco_detect',
|
||||||
|
executable='aruco_detect',
|
||||||
|
name='aruco_detect',
|
||||||
|
output='screen',
|
||||||
|
parameters=[LaunchConfiguration('params_file')],
|
||||||
|
)
|
||||||
|
|
||||||
|
return LaunchDescription([params_arg, aruco_node])
|
||||||
37
jetson/ros2_ws/src/saltybot_aruco_detect/package.xml
Normal file
37
jetson/ros2_ws/src/saltybot_aruco_detect/package.xml
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
|
||||||
|
<package format="3">
|
||||||
|
<name>saltybot_aruco_detect</name>
|
||||||
|
<version>0.1.0</version>
|
||||||
|
<description>
|
||||||
|
ArUco marker detection for docking alignment (Issue #627).
|
||||||
|
Detects all DICT_4X4_50 markers from RealSense D435i RGB, estimates 6-DOF
|
||||||
|
pose with estimatePoseSingleMarkers, publishes PoseArray on
|
||||||
|
/saltybot/aruco/markers and closest dock-candidate marker on
|
||||||
|
/saltybot/aruco/dock_target (PoseStamped) with RViz MarkerArray and
|
||||||
|
JSON status.
|
||||||
|
</description>
|
||||||
|
<maintainer email="sl-perception@saltylab.local">sl-perception</maintainer>
|
||||||
|
<license>MIT</license>
|
||||||
|
|
||||||
|
<buildtool_depend>ament_python</buildtool_depend>
|
||||||
|
|
||||||
|
<depend>rclpy</depend>
|
||||||
|
<depend>std_msgs</depend>
|
||||||
|
<depend>sensor_msgs</depend>
|
||||||
|
<depend>geometry_msgs</depend>
|
||||||
|
<depend>visualization_msgs</depend>
|
||||||
|
<depend>cv_bridge</depend>
|
||||||
|
|
||||||
|
<exec_depend>python3-numpy</exec_depend>
|
||||||
|
<exec_depend>python3-opencv</exec_depend>
|
||||||
|
|
||||||
|
<test_depend>ament_copyright</test_depend>
|
||||||
|
<test_depend>ament_flake8</test_depend>
|
||||||
|
<test_depend>ament_pep257</test_depend>
|
||||||
|
<test_depend>python3-pytest</test_depend>
|
||||||
|
|
||||||
|
<export>
|
||||||
|
<build_type>ament_python</build_type>
|
||||||
|
</export>
|
||||||
|
</package>
|
||||||
@ -0,0 +1,518 @@
|
|||||||
|
"""
|
||||||
|
aruco_detect_node.py — ArUco marker detection for docking alignment (Issue #627).
|
||||||
|
|
||||||
|
Detects all DICT_4X4_50 ArUco markers visible in the RealSense D435i RGB stream,
|
||||||
|
estimates their 6-DOF poses relative to the camera using estimatePoseSingleMarkers,
|
||||||
|
and publishes:
|
||||||
|
|
||||||
|
/saltybot/aruco/markers geometry_msgs/PoseArray — all detected markers
|
||||||
|
/saltybot/aruco/dock_target geometry_msgs/PoseStamped — closest dock marker
|
||||||
|
/saltybot/aruco/viz visualization_msgs/MarkerArray — RViz axes overlays
|
||||||
|
/saltybot/aruco/status std_msgs/String — JSON summary (10 Hz)
|
||||||
|
|
||||||
|
Coordinate frame
|
||||||
|
────────────────
|
||||||
|
All poses are expressed in camera_color_optical_frame (ROS optical convention):
|
||||||
|
+X = right, +Y = down, +Z = forward (into scene)
|
||||||
|
|
||||||
|
The dock_target pose gives the docking controller everything it needs:
|
||||||
|
position.z — forward distance to dock (m) → throttle target
|
||||||
|
position.x — lateral offset (m) → steer target
|
||||||
|
orientation — marker orientation for final align → yaw servo
|
||||||
|
|
||||||
|
Dock target selection
|
||||||
|
─────────────────────
|
||||||
|
dock_marker_ids list[int] [] — empty = accept any detected marker
|
||||||
|
non-empty = only these IDs are candidates
|
||||||
|
closest_wins bool true — among candidates, prefer the nearest
|
||||||
|
max_dock_range_m float 3.0 — ignore markers beyond this distance
|
||||||
|
|
||||||
|
estimatePoseSingleMarkers API
|
||||||
|
──────────────────────────────
|
||||||
|
Uses cv2.aruco.estimatePoseSingleMarkers (legacy OpenCV API still present in
|
||||||
|
4.x with a deprecation notice). Falls back to per-marker cv2.solvePnP with
|
||||||
|
SOLVEPNP_IPPE_SQUARE if the legacy function is unavailable.
|
||||||
|
Both paths use the same camera_matrix / dist_coeffs from CameraInfo.
|
||||||
|
|
||||||
|
Subscribes
|
||||||
|
──────────
|
||||||
|
/camera/color/image_raw sensor_msgs/Image 30 Hz (BGR8)
|
||||||
|
/camera/color/camera_info sensor_msgs/CameraInfo (latched, once)
|
||||||
|
|
||||||
|
Publishes
|
||||||
|
─────────
|
||||||
|
/saltybot/aruco/markers geometry_msgs/PoseArray
|
||||||
|
/saltybot/aruco/dock_target geometry_msgs/PoseStamped
|
||||||
|
/saltybot/aruco/viz visualization_msgs/MarkerArray
|
||||||
|
/saltybot/aruco/status std_msgs/String (JSON, 10 Hz)
|
||||||
|
|
||||||
|
Parameters (see config/aruco_detect_params.yaml)
|
||||||
|
────────────────────────────────────────────────
|
||||||
|
marker_size_m float 0.10 physical side length of printed markers (m)
|
||||||
|
dock_marker_ids int[] [] IDs to accept as dock targets (empty = all)
|
||||||
|
max_dock_range_m float 3.0 ignore candidates beyond this (m)
|
||||||
|
aruco_dict str DICT_4X4_50
|
||||||
|
corner_refinement str CORNER_REFINE_SUBPIX
|
||||||
|
camera_frame str camera_color_optical_frame
|
||||||
|
draw_debug_image bool false publish annotated image for debugging
|
||||||
|
debug_image_topic str /saltybot/aruco/debug_image
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
|
||||||
|
import rclpy
|
||||||
|
from rclpy.node import Node
|
||||||
|
from rclpy.qos import (
|
||||||
|
QoSProfile, ReliabilityPolicy, HistoryPolicy, DurabilityPolicy
|
||||||
|
)
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import cv2
|
||||||
|
from cv_bridge import CvBridge
|
||||||
|
|
||||||
|
from geometry_msgs.msg import (
|
||||||
|
Pose, PoseArray, PoseStamped, Point, Quaternion, Vector3, TransformStamped
|
||||||
|
)
|
||||||
|
from sensor_msgs.msg import Image, CameraInfo
|
||||||
|
from std_msgs.msg import Header, String, ColorRGBA
|
||||||
|
from visualization_msgs.msg import Marker, MarkerArray
|
||||||
|
|
||||||
|
from .aruco_math import MarkerPose, rvec_to_quat, tvec_distance
|
||||||
|
|
||||||
|
|
||||||
|
# ── QoS ───────────────────────────────────────────────────────────────────────
|
||||||
|
_SENSOR_QOS = QoSProfile(
|
||||||
|
reliability=ReliabilityPolicy.BEST_EFFORT,
|
||||||
|
history=HistoryPolicy.KEEP_LAST,
|
||||||
|
depth=5,
|
||||||
|
)
|
||||||
|
_LATCHED_QOS = QoSProfile(
|
||||||
|
reliability=ReliabilityPolicy.RELIABLE,
|
||||||
|
history=HistoryPolicy.KEEP_LAST,
|
||||||
|
depth=1,
|
||||||
|
durability=DurabilityPolicy.TRANSIENT_LOCAL,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ArUco axis length for viz (fraction of marker size)
|
||||||
|
_AXIS_LEN_FRAC = 0.5
|
||||||
|
|
||||||
|
|
||||||
|
class ArucoDetectNode(Node):
|
||||||
|
"""ArUco marker detection + pose estimation node — see module docstring."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__('aruco_detect')
|
||||||
|
|
||||||
|
# ── Parameters ────────────────────────────────────────────────────────
|
||||||
|
self.declare_parameter('marker_size_m', 0.10)
|
||||||
|
self.declare_parameter('dock_marker_ids', []) # empty list = all
|
||||||
|
self.declare_parameter('max_dock_range_m', 3.0)
|
||||||
|
self.declare_parameter('aruco_dict', 'DICT_4X4_50')
|
||||||
|
self.declare_parameter('corner_refinement', 'CORNER_REFINE_SUBPIX')
|
||||||
|
self.declare_parameter('camera_frame', 'camera_color_optical_frame')
|
||||||
|
self.declare_parameter('draw_debug_image', False)
|
||||||
|
self.declare_parameter('debug_image_topic', '/saltybot/aruco/debug_image')
|
||||||
|
|
||||||
|
self._marker_size = self.get_parameter('marker_size_m').value
|
||||||
|
self._dock_ids = set(self.get_parameter('dock_marker_ids').value)
|
||||||
|
self._max_range = self.get_parameter('max_dock_range_m').value
|
||||||
|
self._cam_frame = self.get_parameter('camera_frame').value
|
||||||
|
self._draw_debug = self.get_parameter('draw_debug_image').value
|
||||||
|
self._debug_topic = self.get_parameter('debug_image_topic').value
|
||||||
|
|
||||||
|
aruco_dict_name = self.get_parameter('aruco_dict').value
|
||||||
|
refine_name = self.get_parameter('corner_refinement').value
|
||||||
|
|
||||||
|
# ── ArUco detector setup ──────────────────────────────────────────────
|
||||||
|
dict_id = getattr(cv2.aruco, aruco_dict_name, cv2.aruco.DICT_4X4_50)
|
||||||
|
params = cv2.aruco.DetectorParameters()
|
||||||
|
# Apply corner refinement
|
||||||
|
refine_id = getattr(cv2.aruco, refine_name, cv2.aruco.CORNER_REFINE_SUBPIX)
|
||||||
|
params.cornerRefinementMethod = refine_id
|
||||||
|
|
||||||
|
aruco_dict = cv2.aruco.getPredefinedDictionary(dict_id)
|
||||||
|
self._detector = cv2.aruco.ArucoDetector(aruco_dict, params)
|
||||||
|
|
||||||
|
# Object points for solvePnP fallback (counter-clockwise from top-left)
|
||||||
|
half = self._marker_size / 2.0
|
||||||
|
self._obj_pts = np.array([
|
||||||
|
[-half, half, 0.0],
|
||||||
|
[ half, half, 0.0],
|
||||||
|
[ half, -half, 0.0],
|
||||||
|
[-half, -half, 0.0],
|
||||||
|
], dtype=np.float64)
|
||||||
|
|
||||||
|
# ── Camera intrinsics (set on first CameraInfo) ───────────────────────
|
||||||
|
self._K: np.ndarray | None = None
|
||||||
|
self._dist: np.ndarray | None = None
|
||||||
|
self._bridge = CvBridge()
|
||||||
|
|
||||||
|
# ── Publishers ─────────────────────────────────────────────────────────
|
||||||
|
self._pose_array_pub = self.create_publisher(
|
||||||
|
PoseArray, '/saltybot/aruco/markers', 10
|
||||||
|
)
|
||||||
|
self._dock_pub = self.create_publisher(
|
||||||
|
PoseStamped, '/saltybot/aruco/dock_target', 10
|
||||||
|
)
|
||||||
|
self._viz_pub = self.create_publisher(
|
||||||
|
MarkerArray, '/saltybot/aruco/viz', 10
|
||||||
|
)
|
||||||
|
self._status_pub = self.create_publisher(
|
||||||
|
String, '/saltybot/aruco/status', 10
|
||||||
|
)
|
||||||
|
if self._draw_debug:
|
||||||
|
self._debug_pub = self.create_publisher(
|
||||||
|
Image, self._debug_topic, 5
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._debug_pub = None
|
||||||
|
|
||||||
|
# ── Subscriptions ──────────────────────────────────────────────────────
|
||||||
|
self.create_subscription(
|
||||||
|
CameraInfo,
|
||||||
|
'/camera/color/camera_info',
|
||||||
|
self._on_camera_info,
|
||||||
|
_LATCHED_QOS,
|
||||||
|
)
|
||||||
|
self.create_subscription(
|
||||||
|
Image,
|
||||||
|
'/camera/color/image_raw',
|
||||||
|
self._on_image,
|
||||||
|
_SENSOR_QOS,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Status timer (10 Hz) ────────────────────────────────────────────────
|
||||||
|
self._last_detections: list[MarkerPose] = []
|
||||||
|
self.create_timer(0.1, self._on_status_timer)
|
||||||
|
|
||||||
|
self.get_logger().info(
|
||||||
|
f'aruco_detect ready — '
|
||||||
|
f'dict={aruco_dict_name} '
|
||||||
|
f'marker_size={self._marker_size * 100:.0f}cm '
|
||||||
|
f'dock_ids={list(self._dock_ids) if self._dock_ids else "any"} '
|
||||||
|
f'max_range={self._max_range}m'
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Camera info ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _on_camera_info(self, msg: CameraInfo) -> None:
|
||||||
|
if self._K is not None:
|
||||||
|
return
|
||||||
|
self._K = np.array(msg.k, dtype=np.float64).reshape(3, 3)
|
||||||
|
self._dist = np.array(msg.d, dtype=np.float64).reshape(1, -1)
|
||||||
|
self.get_logger().info(
|
||||||
|
f'camera_info received — '
|
||||||
|
f'fx={self._K[0,0]:.1f} fy={self._K[1,1]:.1f}'
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Image callback ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _on_image(self, msg: Image) -> None:
|
||||||
|
if self._K is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
# ── Decode ────────────────────────────────────────────────────────────
|
||||||
|
try:
|
||||||
|
bgr = self._bridge.imgmsg_to_cv2(msg, desired_encoding='bgr8')
|
||||||
|
except Exception as exc:
|
||||||
|
self.get_logger().warning(f'image decode error: {exc}',
|
||||||
|
throttle_duration_sec=5.0)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Convert to greyscale for detection (faster, same accuracy)
|
||||||
|
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
|
||||||
|
|
||||||
|
stamp = msg.header.stamp
|
||||||
|
|
||||||
|
# ── Detect markers ────────────────────────────────────────────────────
|
||||||
|
corners, ids, _ = self._detector.detectMarkers(gray)
|
||||||
|
|
||||||
|
if ids is None or len(ids) == 0:
|
||||||
|
self._last_detections = []
|
||||||
|
self._publish_empty(stamp)
|
||||||
|
return
|
||||||
|
|
||||||
|
ids_flat = ids.flatten().tolist()
|
||||||
|
|
||||||
|
# ── Pose estimation ───────────────────────────────────────────────────
|
||||||
|
detections = self._estimate_poses(corners, ids_flat)
|
||||||
|
|
||||||
|
# Filter by range
|
||||||
|
detections = [d for d in detections if d.distance_m <= self._max_range]
|
||||||
|
|
||||||
|
self._last_detections = detections
|
||||||
|
|
||||||
|
# ── Publish ───────────────────────────────────────────────────────────
|
||||||
|
self._publish_pose_array(detections, stamp)
|
||||||
|
self._publish_dock_target(detections, stamp)
|
||||||
|
self._publish_viz(detections, stamp)
|
||||||
|
|
||||||
|
# Debug image
|
||||||
|
if self._debug_pub is not None:
|
||||||
|
self._publish_debug(bgr, corners, ids, detections, stamp)
|
||||||
|
|
||||||
|
# ── Pose estimation ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _estimate_poses(
|
||||||
|
self,
|
||||||
|
corners: list,
|
||||||
|
ids: list[int],
|
||||||
|
) -> list[MarkerPose]:
|
||||||
|
"""
|
||||||
|
Estimate 6-DOF pose for each detected marker.
|
||||||
|
|
||||||
|
Uses estimatePoseSingleMarkers (legacy API, still present in cv2 4.x).
|
||||||
|
Falls back to per-marker solvePnP(IPPE_SQUARE) if unavailable.
|
||||||
|
"""
|
||||||
|
results: list[MarkerPose] = []
|
||||||
|
|
||||||
|
# ── Try legacy estimatePoseSingleMarkers ──────────────────────────────
|
||||||
|
if hasattr(cv2.aruco, 'estimatePoseSingleMarkers'):
|
||||||
|
try:
|
||||||
|
rvecs, tvecs, _ = cv2.aruco.estimatePoseSingleMarkers(
|
||||||
|
corners, self._marker_size, self._K, self._dist
|
||||||
|
)
|
||||||
|
for i, mid in enumerate(ids):
|
||||||
|
rvec = rvecs[i].ravel().astype(np.float64)
|
||||||
|
tvec = tvecs[i].ravel().astype(np.float64)
|
||||||
|
results.append(MarkerPose(
|
||||||
|
marker_id = int(mid),
|
||||||
|
tvec = tvec,
|
||||||
|
rvec = rvec,
|
||||||
|
corners = corners[i].reshape(4, 2).astype(np.float64),
|
||||||
|
))
|
||||||
|
return results
|
||||||
|
except Exception as exc:
|
||||||
|
self.get_logger().debug(
|
||||||
|
f'estimatePoseSingleMarkers failed ({exc}), '
|
||||||
|
'falling back to solvePnP'
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Fallback: per-marker solvePnP ─────────────────────────────────────
|
||||||
|
for i, mid in enumerate(ids):
|
||||||
|
img_pts = corners[i].reshape(4, 2).astype(np.float64)
|
||||||
|
ok, rvec, tvec = cv2.solvePnP(
|
||||||
|
self._obj_pts, img_pts,
|
||||||
|
self._K, self._dist,
|
||||||
|
flags=cv2.SOLVEPNP_IPPE_SQUARE,
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
continue
|
||||||
|
results.append(MarkerPose(
|
||||||
|
marker_id = int(mid),
|
||||||
|
tvec = tvec.ravel().astype(np.float64),
|
||||||
|
rvec = rvec.ravel().astype(np.float64),
|
||||||
|
corners = img_pts,
|
||||||
|
))
|
||||||
|
return results
|
||||||
|
|
||||||
|
# ── Dock target selection ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _select_dock_target(
|
||||||
|
self,
|
||||||
|
detections: list[MarkerPose],
|
||||||
|
) -> MarkerPose | None:
|
||||||
|
"""Select the closest marker that matches dock_marker_ids filter."""
|
||||||
|
candidates = [
|
||||||
|
d for d in detections
|
||||||
|
if not self._dock_ids or d.marker_id in self._dock_ids
|
||||||
|
]
|
||||||
|
if not candidates:
|
||||||
|
return None
|
||||||
|
return min(candidates, key=lambda d: d.distance_m)
|
||||||
|
|
||||||
|
# ── Publishers ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _publish_pose_array(
|
||||||
|
self,
|
||||||
|
detections: list[MarkerPose],
|
||||||
|
stamp,
|
||||||
|
) -> None:
|
||||||
|
pa = PoseArray()
|
||||||
|
pa.header.stamp = stamp
|
||||||
|
pa.header.frame_id = self._cam_frame
|
||||||
|
|
||||||
|
for d in detections:
|
||||||
|
qx, qy, qz, qw = d.quat
|
||||||
|
pose = Pose()
|
||||||
|
pose.position = Point(x=float(d.tvec[0]),
|
||||||
|
y=float(d.tvec[1]),
|
||||||
|
z=float(d.tvec[2]))
|
||||||
|
pose.orientation = Quaternion(x=qx, y=qy, z=qz, w=qw)
|
||||||
|
pa.poses.append(pose)
|
||||||
|
|
||||||
|
self._pose_array_pub.publish(pa)
|
||||||
|
|
||||||
|
def _publish_dock_target(
|
||||||
|
self,
|
||||||
|
detections: list[MarkerPose],
|
||||||
|
stamp,
|
||||||
|
) -> None:
|
||||||
|
target = self._select_dock_target(detections)
|
||||||
|
if target is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
qx, qy, qz, qw = target.quat
|
||||||
|
ps = PoseStamped()
|
||||||
|
ps.header.stamp = stamp
|
||||||
|
ps.header.frame_id = self._cam_frame
|
||||||
|
ps.pose.position = Point(x=float(target.tvec[0]),
|
||||||
|
y=float(target.tvec[1]),
|
||||||
|
z=float(target.tvec[2]))
|
||||||
|
ps.pose.orientation = Quaternion(x=qx, y=qy, z=qz, w=qw)
|
||||||
|
self._dock_pub.publish(ps)
|
||||||
|
|
||||||
|
def _publish_viz(
|
||||||
|
self,
|
||||||
|
detections: list[MarkerPose],
|
||||||
|
stamp,
|
||||||
|
) -> None:
|
||||||
|
"""Publish coordinate-axes MarkerArray for each detected marker."""
|
||||||
|
ma = MarkerArray()
|
||||||
|
lifetime = _ros_duration(0.2)
|
||||||
|
|
||||||
|
# Delete-all
|
||||||
|
dm = Marker()
|
||||||
|
dm.action = Marker.DELETEALL
|
||||||
|
dm.header.stamp = stamp
|
||||||
|
dm.header.frame_id = self._cam_frame
|
||||||
|
ma.markers.append(dm)
|
||||||
|
|
||||||
|
target = self._select_dock_target(detections)
|
||||||
|
axis_len = self._marker_size * _AXIS_LEN_FRAC
|
||||||
|
|
||||||
|
for idx, d in enumerate(detections):
|
||||||
|
is_target = (target is not None and d.marker_id == target.marker_id)
|
||||||
|
cx, cy, cz = float(d.tvec[0]), float(d.tvec[1]), float(d.tvec[2])
|
||||||
|
qx, qy, qz, qw = d.quat
|
||||||
|
base_id = idx * 10
|
||||||
|
|
||||||
|
# Sphere at marker centre
|
||||||
|
sph = Marker()
|
||||||
|
sph.header.stamp = stamp
|
||||||
|
sph.header.frame_id = self._cam_frame
|
||||||
|
sph.ns = 'aruco_centers'
|
||||||
|
sph.id = base_id
|
||||||
|
sph.type = Marker.SPHERE
|
||||||
|
sph.action = Marker.ADD
|
||||||
|
sph.pose.position = Point(x=cx, y=cy, z=cz)
|
||||||
|
sph.pose.orientation = Quaternion(x=qx, y=qy, z=qz, w=qw)
|
||||||
|
r_s = 0.015 if not is_target else 0.025
|
||||||
|
sph.scale = Vector3(x=r_s * 2, y=r_s * 2, z=r_s * 2)
|
||||||
|
sph.color = (
|
||||||
|
ColorRGBA(r=1.0, g=0.2, b=0.2, a=1.0) if is_target else
|
||||||
|
ColorRGBA(r=0.2, g=0.8, b=1.0, a=0.9)
|
||||||
|
)
|
||||||
|
sph.lifetime = lifetime
|
||||||
|
ma.markers.append(sph)
|
||||||
|
|
||||||
|
# Text label: ID + distance
|
||||||
|
txt = Marker()
|
||||||
|
txt.header.stamp = stamp
|
||||||
|
txt.header.frame_id = self._cam_frame
|
||||||
|
txt.ns = 'aruco_labels'
|
||||||
|
txt.id = base_id + 1
|
||||||
|
txt.type = Marker.TEXT_VIEW_FACING
|
||||||
|
txt.action = Marker.ADD
|
||||||
|
txt.pose.position = Point(x=cx, y=cy - 0.08, z=cz)
|
||||||
|
txt.pose.orientation.w = 1.0
|
||||||
|
txt.scale.z = 0.06
|
||||||
|
txt.color = ColorRGBA(r=1.0, g=1.0, b=0.0, a=1.0)
|
||||||
|
txt.text = f'ID={d.marker_id}\n{d.distance_m:.2f}m'
|
||||||
|
if is_target:
|
||||||
|
txt.text += '\n[DOCK]'
|
||||||
|
txt.lifetime = lifetime
|
||||||
|
ma.markers.append(txt)
|
||||||
|
|
||||||
|
self._viz_pub.publish(ma)
|
||||||
|
|
||||||
|
def _publish_empty(self, stamp) -> None:
|
||||||
|
pa = PoseArray()
|
||||||
|
pa.header.stamp = stamp
|
||||||
|
pa.header.frame_id = self._cam_frame
|
||||||
|
self._pose_array_pub.publish(pa)
|
||||||
|
self._publish_viz([], stamp)
|
||||||
|
|
||||||
|
def _publish_debug(self, bgr, corners, ids, detections, stamp) -> None:
|
||||||
|
"""Annotate and publish debug image with detected markers drawn."""
|
||||||
|
debug = bgr.copy()
|
||||||
|
if ids is not None and len(ids) > 0:
|
||||||
|
cv2.aruco.drawDetectedMarkers(debug, corners, ids)
|
||||||
|
|
||||||
|
# Draw axes for each detection using the estimated poses
|
||||||
|
for d in detections:
|
||||||
|
try:
|
||||||
|
cv2.drawFrameAxes(
|
||||||
|
debug, self._K, self._dist,
|
||||||
|
d.rvec.reshape(3, 1),
|
||||||
|
d.tvec.reshape(3, 1),
|
||||||
|
self._marker_size * _AXIS_LEN_FRAC,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
img_msg = self._bridge.cv2_to_imgmsg(debug, encoding='bgr8')
|
||||||
|
img_msg.header.stamp = stamp
|
||||||
|
img_msg.header.frame_id = self._cam_frame
|
||||||
|
self._debug_pub.publish(img_msg)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# ── Status timer ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _on_status_timer(self) -> None:
|
||||||
|
detections = self._last_detections
|
||||||
|
target = self._select_dock_target(detections)
|
||||||
|
|
||||||
|
markers_info = [
|
||||||
|
{
|
||||||
|
'id': d.marker_id,
|
||||||
|
'distance_m': round(d.distance_m, 3),
|
||||||
|
'yaw_deg': round(math.degrees(d.yaw_rad), 2),
|
||||||
|
'lateral_m': round(d.lateral_m, 3),
|
||||||
|
'forward_m': round(d.forward_m, 3),
|
||||||
|
'is_target': target is not None and d.marker_id == target.marker_id,
|
||||||
|
}
|
||||||
|
for d in detections
|
||||||
|
]
|
||||||
|
|
||||||
|
status = {
|
||||||
|
'detected_count': len(detections),
|
||||||
|
'dock_target_id': target.marker_id if target else None,
|
||||||
|
'dock_distance_m': round(target.distance_m, 3) if target else None,
|
||||||
|
'dock_yaw_deg': round(math.degrees(target.yaw_rad), 2) if target else None,
|
||||||
|
'dock_lateral_m': round(target.lateral_m, 3) if target else None,
|
||||||
|
'markers': markers_info,
|
||||||
|
}
|
||||||
|
msg = String()
|
||||||
|
msg.data = json.dumps(status)
|
||||||
|
self._status_pub.publish(msg)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helpers ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _ros_duration(seconds: float):
|
||||||
|
from rclpy.duration import Duration
|
||||||
|
sec = int(seconds)
|
||||||
|
nsec = int((seconds - sec) * 1e9)
|
||||||
|
return Duration(seconds=sec, nanoseconds=nsec).to_msg()
|
||||||
|
|
||||||
|
|
||||||
|
def main(args=None) -> None:
|
||||||
|
rclpy.init(args=args)
|
||||||
|
node = ArucoDetectNode()
|
||||||
|
try:
|
||||||
|
rclpy.spin(node)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
node.destroy_node()
|
||||||
|
rclpy.try_shutdown()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@ -0,0 +1,156 @@
|
|||||||
|
"""
|
||||||
|
aruco_math.py — Pure-math helpers for ArUco detection (Issue #627).
|
||||||
|
|
||||||
|
No ROS2 dependencies — importable in unit tests without a ROS2 install.
|
||||||
|
|
||||||
|
Provides:
|
||||||
|
rot_mat_to_quat(R) → (qx, qy, qz, qw)
|
||||||
|
rvec_to_quat(rvec) → (qx, qy, qz, qw) [via cv2.Rodrigues]
|
||||||
|
tvec_distance(tvec) → float (Euclidean norm)
|
||||||
|
tvec_yaw_rad(tvec) → float (atan2(tx, tz) — lateral bearing error)
|
||||||
|
MarkerPose dataclass — per-marker detection result
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import List, Optional, Tuple
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
# ── Rotation helpers ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def rot_mat_to_quat(R: np.ndarray) -> Tuple[float, float, float, float]:
|
||||||
|
"""
|
||||||
|
Convert a 3×3 rotation matrix to quaternion (qx, qy, qz, qw).
|
||||||
|
|
||||||
|
Uses Shepperd's method for numerical stability.
|
||||||
|
R must be a valid rotation matrix (‖R‖₂ = 1, det R = +1).
|
||||||
|
"""
|
||||||
|
R = np.asarray(R, dtype=np.float64)
|
||||||
|
trace = R[0, 0] + R[1, 1] + R[2, 2]
|
||||||
|
|
||||||
|
if trace > 0.0:
|
||||||
|
s = 0.5 / math.sqrt(trace + 1.0)
|
||||||
|
w = 0.25 / s
|
||||||
|
x = (R[2, 1] - R[1, 2]) * s
|
||||||
|
y = (R[0, 2] - R[2, 0]) * s
|
||||||
|
z = (R[1, 0] - R[0, 1]) * s
|
||||||
|
elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
|
||||||
|
s = 2.0 * math.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2])
|
||||||
|
w = (R[2, 1] - R[1, 2]) / s
|
||||||
|
x = 0.25 * s
|
||||||
|
y = (R[0, 1] + R[1, 0]) / s
|
||||||
|
z = (R[0, 2] + R[2, 0]) / s
|
||||||
|
elif R[1, 1] > R[2, 2]:
|
||||||
|
s = 2.0 * math.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2])
|
||||||
|
w = (R[0, 2] - R[2, 0]) / s
|
||||||
|
x = (R[0, 1] + R[1, 0]) / s
|
||||||
|
y = 0.25 * s
|
||||||
|
z = (R[1, 2] + R[2, 1]) / s
|
||||||
|
else:
|
||||||
|
s = 2.0 * math.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1])
|
||||||
|
w = (R[1, 0] - R[0, 1]) / s
|
||||||
|
x = (R[0, 2] + R[2, 0]) / s
|
||||||
|
y = (R[1, 2] + R[2, 1]) / s
|
||||||
|
z = 0.25 * s
|
||||||
|
|
||||||
|
# Normalise
|
||||||
|
norm = math.sqrt(x * x + y * y + z * z + w * w)
|
||||||
|
if norm < 1e-10:
|
||||||
|
return 0.0, 0.0, 0.0, 1.0
|
||||||
|
inv = 1.0 / norm
|
||||||
|
return x * inv, y * inv, z * inv, w * inv
|
||||||
|
|
||||||
|
|
||||||
|
def rvec_to_quat(rvec: np.ndarray) -> Tuple[float, float, float, float]:
|
||||||
|
"""
|
||||||
|
Convert a Rodrigues rotation vector (3,) or (1,3) to quaternion.
|
||||||
|
|
||||||
|
Requires cv2 for cv2.Rodrigues(); falls back to manual exponential map
|
||||||
|
if cv2 is unavailable.
|
||||||
|
"""
|
||||||
|
vec = np.asarray(rvec, dtype=np.float64).ravel()
|
||||||
|
try:
|
||||||
|
import cv2
|
||||||
|
R, _ = cv2.Rodrigues(vec)
|
||||||
|
except ImportError:
|
||||||
|
# Manual Rodrigues exponential map
|
||||||
|
angle = float(np.linalg.norm(vec))
|
||||||
|
if angle < 1e-12:
|
||||||
|
return 0.0, 0.0, 0.0, 1.0
|
||||||
|
axis = vec / angle
|
||||||
|
K = np.array([
|
||||||
|
[ 0.0, -axis[2], axis[1]],
|
||||||
|
[ axis[2], 0.0, -axis[0]],
|
||||||
|
[-axis[1], axis[0], 0.0],
|
||||||
|
])
|
||||||
|
R = np.eye(3) + math.sin(angle) * K + (1.0 - math.cos(angle)) * K @ K
|
||||||
|
|
||||||
|
return rot_mat_to_quat(R)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Metric helpers ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def tvec_distance(tvec: np.ndarray) -> float:
|
||||||
|
"""Euclidean distance from camera to marker (m)."""
|
||||||
|
t = np.asarray(tvec, dtype=np.float64).ravel()
|
||||||
|
return float(math.sqrt(t[0] ** 2 + t[1] ** 2 + t[2] ** 2))
|
||||||
|
|
||||||
|
|
||||||
|
def tvec_yaw_rad(tvec: np.ndarray) -> float:
|
||||||
|
"""
|
||||||
|
Horizontal bearing error to marker (rad).
|
||||||
|
|
||||||
|
atan2(tx, tz): +ve when marker is to the right of the camera optical axis.
|
||||||
|
Zero when the marker is directly in front.
|
||||||
|
"""
|
||||||
|
t = np.asarray(tvec, dtype=np.float64).ravel()
|
||||||
|
return float(math.atan2(t[0], t[2]))
|
||||||
|
|
||||||
|
|
||||||
|
# ── Per-marker result ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class MarkerPose:
|
||||||
|
"""Pose result for a single detected ArUco marker."""
|
||||||
|
marker_id: int
|
||||||
|
tvec: np.ndarray # (3,) translation in camera optical frame (m)
|
||||||
|
rvec: np.ndarray # (3,) Rodrigues rotation vector
|
||||||
|
corners: np.ndarray # (4, 2) image-plane corner coordinates (px)
|
||||||
|
|
||||||
|
# Derived (computed lazily)
|
||||||
|
_distance_m: Optional[float] = field(default=None, repr=False)
|
||||||
|
_yaw_rad: Optional[float] = field(default=None, repr=False)
|
||||||
|
_quat: Optional[Tuple[float, float, float, float]] = field(default=None, repr=False)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def distance_m(self) -> float:
|
||||||
|
if self._distance_m is None:
|
||||||
|
self._distance_m = tvec_distance(self.tvec)
|
||||||
|
return self._distance_m
|
||||||
|
|
||||||
|
@property
|
||||||
|
def yaw_rad(self) -> float:
|
||||||
|
if self._yaw_rad is None:
|
||||||
|
self._yaw_rad = tvec_yaw_rad(self.tvec)
|
||||||
|
return self._yaw_rad
|
||||||
|
|
||||||
|
@property
|
||||||
|
def lateral_m(self) -> float:
|
||||||
|
"""Lateral offset (m); +ve = marker is to the right."""
|
||||||
|
return float(self.tvec[0])
|
||||||
|
|
||||||
|
@property
|
||||||
|
def forward_m(self) -> float:
|
||||||
|
"""Forward distance (Z component in camera frame, m)."""
|
||||||
|
return float(self.tvec[2])
|
||||||
|
|
||||||
|
@property
|
||||||
|
def quat(self) -> Tuple[float, float, float, float]:
|
||||||
|
"""Quaternion (qx, qy, qz, qw) from rvec."""
|
||||||
|
if self._quat is None:
|
||||||
|
self._quat = rvec_to_quat(self.rvec)
|
||||||
|
return self._quat
|
||||||
5
jetson/ros2_ws/src/saltybot_aruco_detect/setup.cfg
Normal file
5
jetson/ros2_ws/src/saltybot_aruco_detect/setup.cfg
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
[develop]
|
||||||
|
script_dir=$base/lib/saltybot_aruco_detect
|
||||||
|
|
||||||
|
[install]
|
||||||
|
install_scripts=$base/lib/saltybot_aruco_detect
|
||||||
30
jetson/ros2_ws/src/saltybot_aruco_detect/setup.py
Normal file
30
jetson/ros2_ws/src/saltybot_aruco_detect/setup.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
import os
|
||||||
|
from glob import glob
|
||||||
|
from setuptools import setup
|
||||||
|
|
||||||
|
package_name = 'saltybot_aruco_detect'
|
||||||
|
|
||||||
|
setup(
|
||||||
|
name=package_name,
|
||||||
|
version='0.1.0',
|
||||||
|
packages=[package_name],
|
||||||
|
data_files=[
|
||||||
|
('share/ament_index/resource_index/packages',
|
||||||
|
['resource/' + package_name]),
|
||||||
|
('share/' + package_name, ['package.xml']),
|
||||||
|
(os.path.join('share', package_name, 'launch'), glob('launch/*.py')),
|
||||||
|
(os.path.join('share', package_name, 'config'), glob('config/*.yaml')),
|
||||||
|
],
|
||||||
|
install_requires=['setuptools'],
|
||||||
|
zip_safe=True,
|
||||||
|
maintainer='sl-perception',
|
||||||
|
maintainer_email='sl-perception@saltylab.local',
|
||||||
|
description='ArUco marker detection for docking alignment (Issue #627)',
|
||||||
|
license='MIT',
|
||||||
|
tests_require=['pytest'],
|
||||||
|
entry_points={
|
||||||
|
'console_scripts': [
|
||||||
|
'aruco_detect = saltybot_aruco_detect.aruco_detect_node:main',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
)
|
||||||
206
jetson/ros2_ws/src/saltybot_aruco_detect/test/test_aruco_math.py
Normal file
206
jetson/ros2_ws/src/saltybot_aruco_detect/test/test_aruco_math.py
Normal file
@ -0,0 +1,206 @@
|
|||||||
|
"""Unit tests for aruco_math.py — no ROS2, no live camera required."""
|
||||||
|
|
||||||
|
import math
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from saltybot_aruco_detect.aruco_math import (
|
||||||
|
rot_mat_to_quat,
|
||||||
|
rvec_to_quat,
|
||||||
|
tvec_distance,
|
||||||
|
tvec_yaw_rad,
|
||||||
|
MarkerPose,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helpers ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _quat_norm(q):
|
||||||
|
return math.sqrt(sum(x * x for x in q))
|
||||||
|
|
||||||
|
|
||||||
|
def _quat_rotate(q, v):
|
||||||
|
"""Rotate vector v by quaternion q (qx, qy, qz, qw)."""
|
||||||
|
qx, qy, qz, qw = q
|
||||||
|
# Quaternion product: q * (0,v) * q^-1
|
||||||
|
# Using formula: v' = v + 2qw(q × v) + 2(q × (q × v))
|
||||||
|
qvec = np.array([qx, qy, qz])
|
||||||
|
t = 2.0 * np.cross(qvec, v)
|
||||||
|
return v + qw * t + np.cross(qvec, t)
|
||||||
|
|
||||||
|
|
||||||
|
# ── rot_mat_to_quat ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_identity_rotation():
|
||||||
|
R = np.eye(3)
|
||||||
|
q = rot_mat_to_quat(R)
|
||||||
|
assert abs(q[3] - 1.0) < 1e-9 # w = 1 for identity
|
||||||
|
assert abs(q[0]) < 1e-9
|
||||||
|
assert abs(q[1]) < 1e-9
|
||||||
|
assert abs(q[2]) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
def test_90deg_yaw():
|
||||||
|
"""90° rotation about Z axis."""
|
||||||
|
angle = math.pi / 2
|
||||||
|
R = np.array([
|
||||||
|
[math.cos(angle), -math.sin(angle), 0],
|
||||||
|
[math.sin(angle), math.cos(angle), 0],
|
||||||
|
[0, 0, 1],
|
||||||
|
])
|
||||||
|
qx, qy, qz, qw = rot_mat_to_quat(R)
|
||||||
|
# For 90° Z rotation: q = (0, 0, sin45°, cos45°)
|
||||||
|
assert abs(qx) < 1e-6
|
||||||
|
assert abs(qy) < 1e-6
|
||||||
|
assert abs(qz - math.sin(angle / 2)) < 1e-6
|
||||||
|
assert abs(qw - math.cos(angle / 2)) < 1e-6
|
||||||
|
|
||||||
|
|
||||||
|
def test_unit_norm():
|
||||||
|
for yaw in [0, 0.5, 1.0, 2.0, math.pi]:
|
||||||
|
R = np.array([
|
||||||
|
[math.cos(yaw), -math.sin(yaw), 0],
|
||||||
|
[math.sin(yaw), math.cos(yaw), 0],
|
||||||
|
[0, 0, 1],
|
||||||
|
])
|
||||||
|
q = rot_mat_to_quat(R)
|
||||||
|
assert abs(_quat_norm(q) - 1.0) < 1e-9, f"yaw={yaw}: norm={_quat_norm(q)}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_roundtrip_rotation_matrix():
|
||||||
|
"""Rotating a vector with the matrix and quaternion should give same result."""
|
||||||
|
angle = 1.23
|
||||||
|
R = np.array([
|
||||||
|
[math.cos(angle), -math.sin(angle), 0],
|
||||||
|
[math.sin(angle), math.cos(angle), 0],
|
||||||
|
[0, 0, 1],
|
||||||
|
])
|
||||||
|
q = rot_mat_to_quat(R)
|
||||||
|
v = np.array([1.0, 0.0, 0.0])
|
||||||
|
v_R = R @ v
|
||||||
|
v_q = _quat_rotate(q, v)
|
||||||
|
np.testing.assert_allclose(v_R, v_q, atol=1e-9)
|
||||||
|
|
||||||
|
|
||||||
|
def test_180deg_pitch():
|
||||||
|
"""180° rotation about Y axis."""
|
||||||
|
R = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, -1]], dtype=float)
|
||||||
|
q = rot_mat_to_quat(R)
|
||||||
|
assert abs(_quat_norm(q) - 1.0) < 1e-9
|
||||||
|
# For 180° Y: q = (0, 1, 0, 0) or (0, -1, 0, 0)
|
||||||
|
assert abs(abs(q[1]) - 1.0) < 1e-6
|
||||||
|
|
||||||
|
|
||||||
|
# ── rvec_to_quat ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_rvec_zero_is_identity():
|
||||||
|
q = rvec_to_quat(np.array([0.0, 0.0, 0.0]))
|
||||||
|
assert abs(_quat_norm(q) - 1.0) < 1e-6
|
||||||
|
assert abs(q[3] - 1.0) < 1e-6 # w = 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_rvec_unit_norm():
|
||||||
|
for rvec in [
|
||||||
|
[0.1, 0.0, 0.0],
|
||||||
|
[0.0, 0.5, 0.0],
|
||||||
|
[0.0, 0.0, 1.57],
|
||||||
|
[0.3, 0.4, 0.5],
|
||||||
|
]:
|
||||||
|
q = rvec_to_quat(np.array(rvec))
|
||||||
|
assert abs(_quat_norm(q) - 1.0) < 1e-9, f"rvec={rvec}: norm={_quat_norm(q)}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_rvec_z_rotation_matches_rot_mat():
|
||||||
|
"""rvec=[0,0,π/3] should match 60° Z rotation matrix quaternion."""
|
||||||
|
angle = math.pi / 3
|
||||||
|
rvec = np.array([0.0, 0.0, angle])
|
||||||
|
R = np.array([
|
||||||
|
[math.cos(angle), -math.sin(angle), 0],
|
||||||
|
[math.sin(angle), math.cos(angle), 0],
|
||||||
|
[0, 0, 1],
|
||||||
|
])
|
||||||
|
q_rvec = rvec_to_quat(rvec)
|
||||||
|
q_R = rot_mat_to_quat(R)
|
||||||
|
# Allow sign flip (q and -q represent the same rotation)
|
||||||
|
diff = min(
|
||||||
|
abs(_quat_norm(np.array(q_rvec) - np.array(q_R))),
|
||||||
|
abs(_quat_norm(np.array(q_rvec) + np.array(q_R))),
|
||||||
|
)
|
||||||
|
assert diff < 1e-6, f"rvec q={q_rvec}, mat q={q_R}"
|
||||||
|
|
||||||
|
|
||||||
|
# ── tvec_distance ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_tvec_distance_basic():
|
||||||
|
assert abs(tvec_distance(np.array([3.0, 4.0, 0.0])) - 5.0) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
def test_tvec_distance_zero():
|
||||||
|
assert tvec_distance(np.array([0.0, 0.0, 0.0])) == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_tvec_distance_forward():
|
||||||
|
assert abs(tvec_distance(np.array([0.0, 0.0, 2.5])) - 2.5) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
def test_tvec_distance_3d():
|
||||||
|
t = np.array([1.0, 2.0, 3.0])
|
||||||
|
expected = math.sqrt(14.0)
|
||||||
|
assert abs(tvec_distance(t) - expected) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
# ── tvec_yaw_rad ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_yaw_zero_when_centred():
|
||||||
|
"""Marker directly in front: tx=0 → yaw=0."""
|
||||||
|
assert abs(tvec_yaw_rad(np.array([0.0, 0.0, 2.0]))) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
def test_yaw_positive_right():
|
||||||
|
"""Marker to the right (tx>0) → positive yaw."""
|
||||||
|
assert tvec_yaw_rad(np.array([1.0, 0.0, 2.0])) > 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_yaw_negative_left():
|
||||||
|
"""Marker to the left (tx<0) → negative yaw."""
|
||||||
|
assert tvec_yaw_rad(np.array([-1.0, 0.0, 2.0])) < 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_yaw_45deg():
|
||||||
|
"""tx=tz → 45°."""
|
||||||
|
assert abs(tvec_yaw_rad(np.array([1.0, 0.0, 1.0])) - math.pi / 4) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
# ── MarkerPose ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _make_marker(mid=42, tx=0.0, ty=0.0, tz=2.0):
|
||||||
|
rvec = np.array([0.0, 0.0, 0.1])
|
||||||
|
tvec = np.array([tx, ty, tz])
|
||||||
|
corners = np.zeros((4, 2))
|
||||||
|
return MarkerPose(marker_id=mid, tvec=tvec, rvec=rvec, corners=corners)
|
||||||
|
|
||||||
|
|
||||||
|
def test_marker_distance_cached():
|
||||||
|
m = _make_marker(tz=3.0)
|
||||||
|
d1 = m.distance_m
|
||||||
|
d2 = m.distance_m
|
||||||
|
assert d1 == d2
|
||||||
|
|
||||||
|
|
||||||
|
def test_marker_lateral_and_forward():
|
||||||
|
m = _make_marker(tx=0.5, tz=2.0)
|
||||||
|
assert abs(m.lateral_m - 0.5) < 1e-9
|
||||||
|
assert abs(m.forward_m - 2.0) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
def test_marker_quat_unit_norm():
|
||||||
|
m = _make_marker()
|
||||||
|
q = m.quat
|
||||||
|
assert abs(_quat_norm(q) - 1.0) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
def test_marker_yaw_sign():
|
||||||
|
m_right = _make_marker(tx=+0.3, tz=1.0)
|
||||||
|
m_left = _make_marker(tx=-0.3, tz=1.0)
|
||||||
|
assert m_right.yaw_rad > 0
|
||||||
|
assert m_left.yaw_rad < 0
|
||||||
@ -1,28 +1,33 @@
|
|||||||
|
# bag_recorder.yaml — Bag recording manager config (Issue #615).
|
||||||
bag_recorder:
|
bag_recorder:
|
||||||
ros__parameters:
|
ros__parameters:
|
||||||
# Path where bags are stored (Issue #488: mission logging)
|
storage_paths:
|
||||||
bag_dir: '~/saltybot-data/bags'
|
- '/media/usb0'
|
||||||
|
- '/media/usb1'
|
||||||
# Topics to record for mission logging (Issue #488)
|
- '/mnt/nvme/saltybot-bags'
|
||||||
|
- '~/saltybot-data/bags'
|
||||||
topics:
|
topics:
|
||||||
- '/scan'
|
- '/scan'
|
||||||
- '/cmd_vel'
|
- '/cmd_vel'
|
||||||
- '/odom'
|
- '/odom'
|
||||||
- '/tf'
|
- '/tf'
|
||||||
- '/camera/color/image_raw/compressed'
|
- '/tf_static'
|
||||||
|
- '/saltybot/pose/fused_cov'
|
||||||
- '/saltybot/diagnostics'
|
- '/saltybot/diagnostics'
|
||||||
|
- '/saltybot/sensor_health'
|
||||||
# Rotation interval: save new bag every N minutes (Issue #488: 30 min)
|
- '/saltybot/battery'
|
||||||
buffer_duration_minutes: 30
|
- '/saltybot/motor_daemon/status'
|
||||||
|
- '/camera/color/image_raw/compressed'
|
||||||
# Storage management (Issue #488: FIFO 20GB limit)
|
- '/camera/depth/image_rect_raw/compressed'
|
||||||
storage_ttl_days: 7 # Remove bags older than 7 days
|
- '/imu/data'
|
||||||
max_storage_gb: 20 # Enforce 20GB FIFO quota
|
motion_trigger: true
|
||||||
|
idle_timeout_s: 30.0
|
||||||
# Storage format (Issue #488: prefer MCAP)
|
split_size_gb: 1.0
|
||||||
storage_format: 'mcap' # Options: mcap, sqlite3
|
split_duration_min: 10.0
|
||||||
|
storage_format: 'mcap'
|
||||||
# NAS sync (optional)
|
warn_disk_pct: 70.0
|
||||||
enable_rsync: false
|
cleanup_disk_pct: 80.0
|
||||||
rsync_destination: ''
|
cleanup_age_days: 7
|
||||||
# rsync_destination: 'user@nas:/path/to/backups/'
|
min_free_gb: 2.0
|
||||||
|
status_hz: 1.0
|
||||||
|
check_hz: 0.033
|
||||||
|
|||||||
@ -0,0 +1,293 @@
|
|||||||
|
"""bag_policy.py — Pure-Python recording policy logic (Issue #615).
|
||||||
|
|
||||||
|
No ROS2 dependencies — importable and fully unit-testable without a live
|
||||||
|
ROS2 install.
|
||||||
|
|
||||||
|
Classes
|
||||||
|
───────
|
||||||
|
MotionState — tracks /cmd_vel activity and idle timeout
|
||||||
|
DiskInfo — disk-usage snapshot with threshold helpers
|
||||||
|
StorageSelector — picks the best storage path from a priority list
|
||||||
|
BagPolicy — decides when to start/stop/split/clean up
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
import shutil
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional, Tuple
|
||||||
|
|
||||||
|
|
||||||
|
# ── Motion tracking ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class MotionState:
|
||||||
|
"""Tracks /cmd_vel activity and determines idle timeout.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
ms = MotionState(idle_timeout_s=30.0)
|
||||||
|
ms.update(linear_x=0.5, angular_z=0.0, now=time.monotonic())
|
||||||
|
if ms.should_start_recording(now):
|
||||||
|
...
|
||||||
|
if ms.should_stop_recording(now):
|
||||||
|
...
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, idle_timeout_s: float = 30.0) -> None:
|
||||||
|
if idle_timeout_s <= 0:
|
||||||
|
raise ValueError(f"idle_timeout_s must be > 0, got {idle_timeout_s!r}")
|
||||||
|
self._idle_timeout = idle_timeout_s
|
||||||
|
self._last_motion_t: Optional[float] = None
|
||||||
|
self._ever_moved: bool = False
|
||||||
|
|
||||||
|
# ── Mutators ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def update(self, linear_x: float, angular_z: float, now: float) -> None:
|
||||||
|
"""Feed the latest cmd_vel values. Non-zero → reset idle timer."""
|
||||||
|
if abs(linear_x) > 1e-3 or abs(angular_z) > 1e-3:
|
||||||
|
self._last_motion_t = now
|
||||||
|
self._ever_moved = True
|
||||||
|
|
||||||
|
def reset(self) -> None:
|
||||||
|
"""Forget all motion history (e.g. after a recording session ends)."""
|
||||||
|
self._last_motion_t = None
|
||||||
|
self._ever_moved = False
|
||||||
|
|
||||||
|
# ── Queries ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def idle_seconds(self, now: float) -> float:
|
||||||
|
"""Seconds since last non-zero cmd_vel (inf if never moved)."""
|
||||||
|
if self._last_motion_t is None:
|
||||||
|
return math.inf
|
||||||
|
return now - self._last_motion_t
|
||||||
|
|
||||||
|
def is_idle(self, now: float) -> bool:
|
||||||
|
"""True if idle_timeout has elapsed since last non-zero cmd_vel."""
|
||||||
|
return self.idle_seconds(now) >= self._idle_timeout
|
||||||
|
|
||||||
|
def is_moving(self, now: float) -> bool:
|
||||||
|
"""True if non-zero cmd_vel was received within the idle window."""
|
||||||
|
return self._ever_moved and not self.is_idle(now)
|
||||||
|
|
||||||
|
def should_start_recording(self, now: float) -> bool:
|
||||||
|
"""True when motion is detected (used to trigger auto-record start)."""
|
||||||
|
return self._ever_moved and not self.is_idle(now)
|
||||||
|
|
||||||
|
def should_stop_recording(self, now: float) -> bool:
|
||||||
|
"""True when idle timeout has elapsed after motion (trigger auto-stop)."""
|
||||||
|
return self._ever_moved and self.is_idle(now)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ever_moved(self) -> bool:
|
||||||
|
return self._ever_moved
|
||||||
|
|
||||||
|
@property
|
||||||
|
def idle_timeout_s(self) -> float:
|
||||||
|
return self._idle_timeout
|
||||||
|
|
||||||
|
|
||||||
|
# ── Disk information ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DiskInfo:
|
||||||
|
"""Snapshot of disk usage for a single mount point.
|
||||||
|
|
||||||
|
Construct with :meth:`DiskInfo.from_path` for live data or build
|
||||||
|
directly from known values for unit tests.
|
||||||
|
"""
|
||||||
|
|
||||||
|
path: str
|
||||||
|
total_bytes: int
|
||||||
|
used_bytes: int
|
||||||
|
free_bytes: int
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_path(cls, path: str) -> "DiskInfo":
|
||||||
|
"""Read live disk usage from the OS."""
|
||||||
|
u = shutil.disk_usage(path)
|
||||||
|
return cls(path=path, total_bytes=u.total,
|
||||||
|
used_bytes=u.used, free_bytes=u.free)
|
||||||
|
|
||||||
|
# ── Derived properties ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def used_pct(self) -> float:
|
||||||
|
"""Percentage of disk space used (0–100)."""
|
||||||
|
if self.total_bytes == 0:
|
||||||
|
return 100.0
|
||||||
|
return self.used_bytes / self.total_bytes * 100.0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def free_pct(self) -> float:
|
||||||
|
return 100.0 - self.used_pct
|
||||||
|
|
||||||
|
@property
|
||||||
|
def free_gb(self) -> float:
|
||||||
|
return self.free_bytes / (1024 ** 3)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def used_gb(self) -> float:
|
||||||
|
return self.used_bytes / (1024 ** 3)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def total_gb(self) -> float:
|
||||||
|
return self.total_bytes / (1024 ** 3)
|
||||||
|
|
||||||
|
# ── Threshold helpers ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def exceeds_pct(self, threshold_pct: float) -> bool:
|
||||||
|
return self.used_pct >= threshold_pct
|
||||||
|
|
||||||
|
def has_min_free(self, min_free_gb: float) -> bool:
|
||||||
|
return self.free_gb >= min_free_gb
|
||||||
|
|
||||||
|
def summary(self) -> str:
|
||||||
|
return (f"{self.path}: {self.used_gb:.1f}/{self.total_gb:.1f} GB "
|
||||||
|
f"({self.used_pct:.1f}% used, {self.free_gb:.1f} GB free)")
|
||||||
|
|
||||||
|
|
||||||
|
# ── Storage path selection ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class StorageSelector:
|
||||||
|
"""Selects the best storage path from a priority-ordered list.
|
||||||
|
|
||||||
|
Paths are tried in order; the first accessible path with at least
|
||||||
|
``min_free_gb`` of free space is returned. Typical priority order:
|
||||||
|
USB → NVMe → internal home directory.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
sel = StorageSelector(['/media/usb0', '/mnt/nvme', '~/bags'])
|
||||||
|
path = sel.select() # e.g. '/media/usb0'
|
||||||
|
"""
|
||||||
|
|
||||||
|
DEFAULT_MIN_FREE_GB = 2.0
|
||||||
|
|
||||||
|
def __init__(self,
|
||||||
|
paths: List[str],
|
||||||
|
min_free_gb: float = DEFAULT_MIN_FREE_GB) -> None:
|
||||||
|
if not paths:
|
||||||
|
raise ValueError("paths list must not be empty")
|
||||||
|
self._paths = [str(Path(p).expanduser()) for p in paths]
|
||||||
|
self._min_free_gb = min_free_gb
|
||||||
|
|
||||||
|
def select(self) -> Optional[str]:
|
||||||
|
"""Return the best available storage path, or None if none qualify."""
|
||||||
|
for path in self._paths:
|
||||||
|
p = Path(path)
|
||||||
|
if not p.exists():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
info = DiskInfo.from_path(path)
|
||||||
|
if info.has_min_free(self._min_free_gb):
|
||||||
|
return path
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
def select_or_default(self, default: str) -> str:
|
||||||
|
"""Return the best path, falling back to ``default`` if none qualify."""
|
||||||
|
return self.select() or default
|
||||||
|
|
||||||
|
def disk_infos(self) -> List[DiskInfo]:
|
||||||
|
"""Return DiskInfo for all accessible paths (for status publishing)."""
|
||||||
|
result = []
|
||||||
|
for path in self._paths:
|
||||||
|
if Path(path).exists():
|
||||||
|
try:
|
||||||
|
result.append(DiskInfo.from_path(path))
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
# ── Recording policy ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class BagPolicy:
|
||||||
|
"""Encapsulates all recording policy thresholds (Issue #615).
|
||||||
|
|
||||||
|
Separates business logic from ROS2 so it can be unit-tested without a
|
||||||
|
live ROS2 install.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
──────────
|
||||||
|
split_size_gb float Split bag when it reaches this size. Default 1.0
|
||||||
|
split_duration_min float Split bag after this many minutes. Default 10.0
|
||||||
|
cleanup_age_days int Bags older than this are cleanup candidates. Default 7
|
||||||
|
cleanup_disk_pct float Trigger cleanup when disk exceeds this %. Default 80.0
|
||||||
|
warn_disk_pct float Log a warning when disk exceeds this %. Default 70.0
|
||||||
|
min_free_gb float Minimum free space to start recording. Default 2.0
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
split_size_gb: float = 1.0,
|
||||||
|
split_duration_min: float = 10.0,
|
||||||
|
cleanup_age_days: int = 7,
|
||||||
|
cleanup_disk_pct: float = 80.0,
|
||||||
|
warn_disk_pct: float = 70.0,
|
||||||
|
min_free_gb: float = 2.0,
|
||||||
|
) -> None:
|
||||||
|
if split_size_gb <= 0:
|
||||||
|
raise ValueError(f"split_size_gb must be > 0, got {split_size_gb!r}")
|
||||||
|
if split_duration_min <= 0:
|
||||||
|
raise ValueError(f"split_duration_min must be > 0, got {split_duration_min!r}")
|
||||||
|
if cleanup_age_days < 1:
|
||||||
|
raise ValueError(f"cleanup_age_days must be >= 1, got {cleanup_age_days!r}")
|
||||||
|
if not (0 < warn_disk_pct < cleanup_disk_pct <= 100):
|
||||||
|
raise ValueError(
|
||||||
|
f"Must have 0 < warn_disk_pct({warn_disk_pct}) "
|
||||||
|
f"< cleanup_disk_pct({cleanup_disk_pct}) <= 100"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.split_size_bytes = int(split_size_gb * 1024 ** 3)
|
||||||
|
self.split_duration_s = split_duration_min * 60.0
|
||||||
|
self.cleanup_age_days = cleanup_age_days
|
||||||
|
self.cleanup_disk_pct = cleanup_disk_pct
|
||||||
|
self.warn_disk_pct = warn_disk_pct
|
||||||
|
self.min_free_gb = min_free_gb
|
||||||
|
|
||||||
|
# ── Split decision ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def needs_split(
|
||||||
|
self,
|
||||||
|
bag_size_bytes: int,
|
||||||
|
bag_duration_s: float,
|
||||||
|
) -> Tuple[bool, str]:
|
||||||
|
"""Return (True, reason) if the active bag segment should be split."""
|
||||||
|
if bag_size_bytes >= self.split_size_bytes:
|
||||||
|
size_gb = bag_size_bytes / 1024 ** 3
|
||||||
|
lim_gb = self.split_size_bytes / 1024 ** 3
|
||||||
|
return True, f"size {size_gb:.2f} GB ≥ {lim_gb:.1f} GB"
|
||||||
|
if bag_duration_s >= self.split_duration_s:
|
||||||
|
return True, (
|
||||||
|
f"duration {bag_duration_s / 60:.1f} min "
|
||||||
|
f"≥ {self.split_duration_s / 60:.0f} min"
|
||||||
|
)
|
||||||
|
return False, ""
|
||||||
|
|
||||||
|
# ── Disk thresholds ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def needs_cleanup(self, disk: DiskInfo) -> bool:
|
||||||
|
"""True if disk is full enough to warrant deleting old bags."""
|
||||||
|
return disk.exceeds_pct(self.cleanup_disk_pct)
|
||||||
|
|
||||||
|
def should_warn_disk(self, disk: DiskInfo) -> bool:
|
||||||
|
"""True if disk usage deserves a warning log."""
|
||||||
|
return disk.exceeds_pct(self.warn_disk_pct)
|
||||||
|
|
||||||
|
def can_record(self, disk: DiskInfo) -> bool:
|
||||||
|
"""True if there is enough free space to start/continue recording."""
|
||||||
|
return disk.has_min_free(self.min_free_gb)
|
||||||
|
|
||||||
|
# ── Age-based cleanup ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def bag_is_expired(self, bag_age_days: float) -> bool:
|
||||||
|
"""True if a bag is old enough to be a cleanup candidate."""
|
||||||
|
return bag_age_days >= self.cleanup_age_days
|
||||||
|
|
||||||
|
def bag_age_days(self, bag_mtime: float, now: float) -> float:
|
||||||
|
"""Compute bag age in fractional days from mtime and current time."""
|
||||||
|
return (now - bag_mtime) / 86400.0
|
||||||
@ -1,265 +1,383 @@
|
|||||||
#!/usr/bin/env python3
|
"""bag_recorder_node.py — ROS2 bag recording manager (Issue #615).
|
||||||
|
|
||||||
import os
|
Upgrades the Issue #488 basic recorder with:
|
||||||
import signal
|
• Motion-triggered auto-record (/cmd_vel non-zero → start, 30s idle → stop)
|
||||||
import shutil
|
• Auto-split at 1 GB or 10 min
|
||||||
import subprocess
|
• USB/NVMe storage path selection with disk monitoring
|
||||||
import threading
|
• Disk-usage-triggered cleanup (>80% → delete bags >7 days old)
|
||||||
import time
|
• JSON status topic at 1 Hz
|
||||||
|
|
||||||
|
Services (Trigger):
|
||||||
|
/saltybot/bag_recorder/start /saltybot/bag_recorder/stop
|
||||||
|
/saltybot/bag_recorder/split (plus legacy /saltybot/start_recording etc.)
|
||||||
|
|
||||||
|
Topics:
|
||||||
|
SUB /cmd_vel (geometry_msgs/Twist)
|
||||||
|
PUB /saltybot/bag_recorder/status (std_msgs/String, JSON)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json, os, shutil, signal, subprocess, threading, time
|
||||||
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from datetime import datetime, timedelta
|
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
import rclpy
|
import rclpy
|
||||||
from rclpy.node import Node
|
from rclpy.node import Node
|
||||||
from std_srvs.srv import Trigger
|
from geometry_msgs.msg import Twist
|
||||||
from std_msgs.msg import String
|
from std_msgs.msg import String
|
||||||
|
from std_srvs.srv import Trigger
|
||||||
|
|
||||||
|
from saltybot_bag_recorder.bag_policy import BagPolicy, DiskInfo, MotionState, StorageSelector
|
||||||
|
|
||||||
|
|
||||||
|
class _BagSession:
|
||||||
|
"""Tracks one recording session (possibly multiple split segments)."""
|
||||||
|
|
||||||
|
def __init__(self, bag_dir: Path, session_name: str) -> None:
|
||||||
|
self.bag_dir = bag_dir
|
||||||
|
self.session_name = session_name
|
||||||
|
self.start_time = time.monotonic()
|
||||||
|
self.split_count = 0
|
||||||
|
self.proc: Optional[subprocess.Popen] = None
|
||||||
|
self.segment_start = time.monotonic()
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
|
def segment_name(self) -> str:
|
||||||
|
return f"{self.session_name}_s{self.split_count:03d}"
|
||||||
|
|
||||||
|
def segment_path(self) -> Path:
|
||||||
|
return self.bag_dir / self.segment_name()
|
||||||
|
|
||||||
|
def segment_size_bytes(self) -> int:
|
||||||
|
p = self.segment_path()
|
||||||
|
if not p.exists():
|
||||||
|
return 0
|
||||||
|
return sum(f.stat().st_size for f in p.rglob("*") if f.is_file())
|
||||||
|
|
||||||
|
def segment_duration_s(self) -> float:
|
||||||
|
return time.monotonic() - self.segment_start
|
||||||
|
|
||||||
|
def session_duration_s(self) -> float:
|
||||||
|
return time.monotonic() - self.start_time
|
||||||
|
|
||||||
|
def is_alive(self) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
return self.proc is not None and self.proc.poll() is None
|
||||||
|
|
||||||
|
def stop_proc(self, timeout: float = 5.0) -> None:
|
||||||
|
with self._lock:
|
||||||
|
if self.proc is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
self.proc.send_signal(signal.SIGINT)
|
||||||
|
self.proc.wait(timeout=timeout)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
self.proc.kill()
|
||||||
|
self.proc.wait()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
self.proc = None
|
||||||
|
|
||||||
|
|
||||||
class BagRecorderNode(Node):
|
class BagRecorderNode(Node):
|
||||||
"""ROS2 bag recording service for mission logging (Issue #488)."""
|
"""ROS2 bag recording manager with motion trigger and disk monitoring (Issue #615)."""
|
||||||
|
|
||||||
def __init__(self):
|
DEFAULT_TOPICS: List[str] = [
|
||||||
super().__init__('saltybot_bag_recorder')
|
"/scan", "/cmd_vel", "/odom", "/tf", "/tf_static",
|
||||||
|
"/saltybot/pose/fused_cov", "/saltybot/diagnostics",
|
||||||
|
"/saltybot/sensor_health", "/saltybot/battery",
|
||||||
|
"/saltybot/motor_daemon/status",
|
||||||
|
"/camera/color/image_raw/compressed",
|
||||||
|
"/camera/depth/image_rect_raw/compressed",
|
||||||
|
"/imu/data",
|
||||||
|
]
|
||||||
|
|
||||||
# Configuration (Issue #488: mission logging)
|
DEFAULT_STORAGE_PATHS: List[str] = [
|
||||||
default_bag_dir = str(Path.home() / 'saltybot-data' / 'bags')
|
"/media/usb0", "/media/usb1",
|
||||||
self.declare_parameter('bag_dir', default_bag_dir)
|
"/mnt/nvme/saltybot-bags",
|
||||||
self.declare_parameter('topics', [
|
"~/saltybot-data/bags",
|
||||||
'/scan',
|
]
|
||||||
'/cmd_vel',
|
|
||||||
'/odom',
|
|
||||||
'/tf',
|
|
||||||
'/camera/color/image_raw/compressed',
|
|
||||||
'/saltybot/diagnostics'
|
|
||||||
])
|
|
||||||
self.declare_parameter('buffer_duration_minutes', 30)
|
|
||||||
self.declare_parameter('storage_ttl_days', 7)
|
|
||||||
self.declare_parameter('max_storage_gb', 20)
|
|
||||||
self.declare_parameter('enable_rsync', False)
|
|
||||||
self.declare_parameter('rsync_destination', '')
|
|
||||||
self.declare_parameter('storage_format', 'mcap')
|
|
||||||
|
|
||||||
self.bag_dir = Path(self.get_parameter('bag_dir').value)
|
def __init__(self) -> None:
|
||||||
self.topics = self.get_parameter('topics').value
|
super().__init__("bag_recorder")
|
||||||
self.buffer_duration = self.get_parameter('buffer_duration_minutes').value * 60
|
|
||||||
self.storage_ttl_days = self.get_parameter('storage_ttl_days').value
|
|
||||||
self.max_storage_gb = self.get_parameter('max_storage_gb').value
|
|
||||||
self.enable_rsync = self.get_parameter('enable_rsync').value
|
|
||||||
self.rsync_destination = self.get_parameter('rsync_destination').value
|
|
||||||
self.storage_format = self.get_parameter('storage_format').value
|
|
||||||
|
|
||||||
self.bag_dir.mkdir(parents=True, exist_ok=True)
|
self.declare_parameter("storage_paths", self.DEFAULT_STORAGE_PATHS)
|
||||||
|
self.declare_parameter("topics", self.DEFAULT_TOPICS)
|
||||||
|
self.declare_parameter("motion_trigger", True)
|
||||||
|
self.declare_parameter("idle_timeout_s", 30.0)
|
||||||
|
self.declare_parameter("split_size_gb", 1.0)
|
||||||
|
self.declare_parameter("split_duration_min", 10.0)
|
||||||
|
self.declare_parameter("storage_format", "mcap")
|
||||||
|
self.declare_parameter("warn_disk_pct", 70.0)
|
||||||
|
self.declare_parameter("cleanup_disk_pct", 80.0)
|
||||||
|
self.declare_parameter("cleanup_age_days", 7)
|
||||||
|
self.declare_parameter("min_free_gb", 2.0)
|
||||||
|
self.declare_parameter("status_hz", 1.0)
|
||||||
|
self.declare_parameter("check_hz", 0.033)
|
||||||
|
|
||||||
# Recording state
|
self._topics = list(self.get_parameter("topics").value)
|
||||||
self.is_recording = False
|
self._motion_trigger = self.get_parameter("motion_trigger").value
|
||||||
self.current_bag_process = None
|
self._storage_fmt = self.get_parameter("storage_format").value
|
||||||
self.current_bag_name = None
|
|
||||||
self.buffer_bags: List[str] = []
|
|
||||||
self.recording_lock = threading.Lock()
|
|
||||||
|
|
||||||
# Services
|
self._policy = BagPolicy(
|
||||||
self.save_service = self.create_service(Trigger, '/saltybot/save_bag', self.save_bag_callback)
|
split_size_gb = self.get_parameter("split_size_gb").value,
|
||||||
self.start_service = self.create_service(Trigger, '/saltybot/start_recording', self.start_recording_callback)
|
split_duration_min = self.get_parameter("split_duration_min").value,
|
||||||
self.stop_service = self.create_service(Trigger, '/saltybot/stop_recording', self.stop_recording_callback)
|
cleanup_age_days = int(self.get_parameter("cleanup_age_days").value),
|
||||||
|
cleanup_disk_pct = self.get_parameter("cleanup_disk_pct").value,
|
||||||
# Watchdog to handle crash recovery
|
warn_disk_pct = self.get_parameter("warn_disk_pct").value,
|
||||||
self.setup_signal_handlers()
|
min_free_gb = self.get_parameter("min_free_gb").value,
|
||||||
|
)
|
||||||
# Start recording
|
self._motion = MotionState(
|
||||||
self.start_recording()
|
idle_timeout_s = self.get_parameter("idle_timeout_s").value,
|
||||||
|
)
|
||||||
# Periodic maintenance (cleanup old bags, manage storage)
|
self._selector = StorageSelector(
|
||||||
self.maintenance_timer = self.create_timer(300.0, self.maintenance_callback)
|
paths = list(self.get_parameter("storage_paths").value),
|
||||||
|
min_free_gb = self.get_parameter("min_free_gb").value,
|
||||||
self.get_logger().info(
|
|
||||||
f'Bag recorder initialized: {self.bag_dir}, format={self.storage_format}, '
|
|
||||||
f'buffer={self.buffer_duration}s, max={self.max_storage_gb}GB, topics={len(self.topics)}'
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def setup_signal_handlers(self):
|
self._bag_dir: Optional[Path] = None
|
||||||
"""Setup signal handlers for graceful shutdown and crash recovery."""
|
self._session: Optional[_BagSession] = None
|
||||||
def signal_handler(sig, frame):
|
self._lock: threading.Lock = threading.Lock()
|
||||||
self.get_logger().warn(f'Signal {sig} received, saving current bag')
|
self._recording: bool = False
|
||||||
self.stop_recording(save=True)
|
|
||||||
self.cleanup()
|
|
||||||
rclpy.shutdown()
|
|
||||||
|
|
||||||
signal.signal(signal.SIGINT, signal_handler)
|
self._status_pub = self.create_publisher(
|
||||||
signal.signal(signal.SIGTERM, signal_handler)
|
String, "/saltybot/bag_recorder/status", 10)
|
||||||
|
|
||||||
def start_recording(self):
|
self.create_service(Trigger, "/saltybot/bag_recorder/start", self._svc_start)
|
||||||
"""Start bag recording in the background."""
|
self.create_service(Trigger, "/saltybot/bag_recorder/stop", self._svc_stop)
|
||||||
with self.recording_lock:
|
self.create_service(Trigger, "/saltybot/bag_recorder/split", self._svc_split)
|
||||||
if self.is_recording:
|
# Legacy (Issue #488 compatibility)
|
||||||
|
self.create_service(Trigger, "/saltybot/start_recording", self._svc_start)
|
||||||
|
self.create_service(Trigger, "/saltybot/stop_recording", self._svc_stop)
|
||||||
|
self.create_service(Trigger, "/saltybot/save_bag", self._svc_split)
|
||||||
|
|
||||||
|
if self._motion_trigger:
|
||||||
|
self.create_subscription(Twist, "/cmd_vel", self._on_cmd_vel, 10)
|
||||||
|
|
||||||
|
hz = self.get_parameter("status_hz").value
|
||||||
|
self.create_timer(1.0 / hz, self._publish_status)
|
||||||
|
chz = self.get_parameter("check_hz").value
|
||||||
|
self.create_timer(1.0 / chz, self._periodic_check)
|
||||||
|
self.create_timer(60.0, self._disk_maintenance)
|
||||||
|
|
||||||
|
self.get_logger().info(
|
||||||
|
f"BagRecorder ready | motion={self._motion_trigger} "
|
||||||
|
f"idle={self._motion.idle_timeout_s:.0f}s "
|
||||||
|
f"split={self._policy.split_size_bytes//1024**3}GB/"
|
||||||
|
f"{int(self._policy.split_duration_s//60)}min "
|
||||||
|
f"fmt={self._storage_fmt} topics={len(self._topics)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _on_cmd_vel(self, msg: Twist) -> None:
|
||||||
|
now = time.monotonic()
|
||||||
|
self._motion.update(msg.linear.x, msg.angular.z, now)
|
||||||
|
with self._lock:
|
||||||
|
if not self._recording and self._motion.should_start_recording(now):
|
||||||
|
self.get_logger().info("Motion detected — auto-starting bag recording")
|
||||||
|
self._start_recording_locked()
|
||||||
|
|
||||||
|
def _svc_start(self, _req, resp):
|
||||||
|
with self._lock:
|
||||||
|
if self._recording:
|
||||||
|
resp.success = False
|
||||||
|
resp.message = f"Already recording: {self._session.session_name}"
|
||||||
|
return resp
|
||||||
|
ok, msg = self._start_recording_locked()
|
||||||
|
resp.success = ok
|
||||||
|
resp.message = msg
|
||||||
|
return resp
|
||||||
|
|
||||||
|
def _svc_stop(self, _req, resp):
|
||||||
|
with self._lock:
|
||||||
|
if not self._recording:
|
||||||
|
resp.success = False
|
||||||
|
resp.message = "Not recording"
|
||||||
|
return resp
|
||||||
|
_, ok, msg = self._stop_recording_locked()
|
||||||
|
resp.success = ok
|
||||||
|
resp.message = msg
|
||||||
|
return resp
|
||||||
|
|
||||||
|
def _svc_split(self, _req, resp):
|
||||||
|
with self._lock:
|
||||||
|
if not self._recording:
|
||||||
|
resp.success = False
|
||||||
|
resp.message = "Not recording — nothing to split"
|
||||||
|
return resp
|
||||||
|
ok, msg = self._split_locked()
|
||||||
|
resp.success = ok
|
||||||
|
resp.message = msg
|
||||||
|
return resp
|
||||||
|
|
||||||
|
def _periodic_check(self) -> None:
|
||||||
|
now = time.monotonic()
|
||||||
|
with self._lock:
|
||||||
|
if self._recording and self._motion_trigger:
|
||||||
|
if self._motion.should_stop_recording(now):
|
||||||
|
self.get_logger().info(
|
||||||
|
f"Idle {self._motion.idle_seconds(now):.0f}s — auto-stopping")
|
||||||
|
self._stop_recording_locked()
|
||||||
return
|
return
|
||||||
|
if self._recording and self._session is not None:
|
||||||
|
size = self._session.segment_size_bytes()
|
||||||
|
dur = self._session.segment_duration_s()
|
||||||
|
split, reason = self._policy.needs_split(size, dur)
|
||||||
|
if split:
|
||||||
|
self.get_logger().info(f"Auto-split: {reason}")
|
||||||
|
self._split_locked()
|
||||||
|
|
||||||
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
def _disk_maintenance(self) -> None:
|
||||||
self.current_bag_name = f'saltybot_{timestamp}'
|
if self._bag_dir is None:
|
||||||
bag_path = self.bag_dir / self.current_bag_name
|
sel = self._selector.select()
|
||||||
|
if sel is None:
|
||||||
try:
|
|
||||||
# Build rosbag2 record command
|
|
||||||
cmd = ['ros2', 'bag', 'record', '--output', str(bag_path), '--storage', self.storage_format]
|
|
||||||
|
|
||||||
# Add compression for sqlite3 format
|
|
||||||
if self.storage_format == 'sqlite3':
|
|
||||||
cmd.extend(['--compression-format', 'zstd', '--compression-mode', 'file'])
|
|
||||||
|
|
||||||
# Add topics (required for mission logging)
|
|
||||||
if self.topics and self.topics[0]:
|
|
||||||
cmd.extend(self.topics)
|
|
||||||
else:
|
|
||||||
cmd.extend(['/scan', '/cmd_vel', '/odom', '/tf', '/camera/color/image_raw/compressed', '/saltybot/diagnostics'])
|
|
||||||
|
|
||||||
self.current_bag_process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
||||||
self.is_recording = True
|
|
||||||
self.buffer_bags.append(self.current_bag_name)
|
|
||||||
self.get_logger().info(f'Started recording: {self.current_bag_name}')
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
self.get_logger().error(f'Failed to start recording: {e}')
|
|
||||||
|
|
||||||
def save_bag_callback(self, request, response):
|
|
||||||
"""Service callback to manually trigger bag save."""
|
|
||||||
try:
|
|
||||||
self.stop_recording(save=True)
|
|
||||||
self.start_recording()
|
|
||||||
response.success = True
|
|
||||||
response.message = f'Saved: {self.current_bag_name}'
|
|
||||||
self.get_logger().info(response.message)
|
|
||||||
except Exception as e:
|
|
||||||
response.success = False
|
|
||||||
response.message = f'Failed to save bag: {e}'
|
|
||||||
self.get_logger().error(response.message)
|
|
||||||
return response
|
|
||||||
|
|
||||||
def start_recording_callback(self, request, response):
|
|
||||||
"""Service callback to start recording."""
|
|
||||||
if self.is_recording:
|
|
||||||
response.success = False
|
|
||||||
response.message = 'Recording already in progress'
|
|
||||||
return response
|
|
||||||
try:
|
|
||||||
self.start_recording()
|
|
||||||
response.success = True
|
|
||||||
response.message = f'Recording started: {self.current_bag_name}'
|
|
||||||
self.get_logger().info(response.message)
|
|
||||||
except Exception as e:
|
|
||||||
response.success = False
|
|
||||||
response.message = f'Failed to start recording: {e}'
|
|
||||||
self.get_logger().error(response.message)
|
|
||||||
return response
|
|
||||||
|
|
||||||
def stop_recording_callback(self, request, response):
|
|
||||||
"""Service callback to stop recording."""
|
|
||||||
if not self.is_recording:
|
|
||||||
response.success = False
|
|
||||||
response.message = 'No recording in progress'
|
|
||||||
return response
|
|
||||||
try:
|
|
||||||
self.stop_recording(save=True)
|
|
||||||
response.success = True
|
|
||||||
response.message = f'Recording stopped and saved: {self.current_bag_name}'
|
|
||||||
self.get_logger().info(response.message)
|
|
||||||
except Exception as e:
|
|
||||||
response.success = False
|
|
||||||
response.message = f'Failed to stop recording: {e}'
|
|
||||||
self.get_logger().error(response.message)
|
|
||||||
return response
|
|
||||||
|
|
||||||
def stop_recording(self, save: bool = False):
|
|
||||||
"""Stop the current bag recording."""
|
|
||||||
with self.recording_lock:
|
|
||||||
if not self.is_recording or not self.current_bag_process:
|
|
||||||
return
|
return
|
||||||
|
self._bag_dir = Path(sel)
|
||||||
try:
|
try:
|
||||||
self.current_bag_process.send_signal(signal.SIGINT)
|
disk = DiskInfo.from_path(str(self._bag_dir))
|
||||||
self.current_bag_process.wait(timeout=5.0)
|
except OSError as exc:
|
||||||
except subprocess.TimeoutExpired:
|
self.get_logger().warn(f"Disk check failed: {exc}")
|
||||||
self.get_logger().warn(f'Force terminating {self.current_bag_name}')
|
|
||||||
self.current_bag_process.kill()
|
|
||||||
self.current_bag_process.wait()
|
|
||||||
except Exception as e:
|
|
||||||
self.get_logger().error(f'Error stopping recording: {e}')
|
|
||||||
self.is_recording = False
|
|
||||||
self.get_logger().info(f'Stopped recording: {self.current_bag_name}')
|
|
||||||
if save:
|
|
||||||
self.apply_compression()
|
|
||||||
|
|
||||||
def apply_compression(self):
|
|
||||||
"""Compress the current bag using zstd."""
|
|
||||||
if not self.current_bag_name:
|
|
||||||
return
|
return
|
||||||
bag_path = self.bag_dir / self.current_bag_name
|
if self._policy.should_warn_disk(disk):
|
||||||
try:
|
self.get_logger().warn(
|
||||||
tar_path = f'{bag_path}.tar.zst'
|
f"Disk {disk.used_pct:.1f}% > {self._policy.warn_disk_pct:.0f}%")
|
||||||
if bag_path.exists():
|
if self._policy.needs_cleanup(disk):
|
||||||
cmd = ['tar', '-I', 'zstd', '-cf', tar_path, '-C', str(self.bag_dir), self.current_bag_name]
|
self.get_logger().warn(
|
||||||
subprocess.run(cmd, check=True, capture_output=True, timeout=60)
|
f"Disk {disk.used_pct:.1f}% >= {self._policy.cleanup_disk_pct:.0f}% — cleaning")
|
||||||
self.get_logger().info(f'Compressed: {tar_path}')
|
self._cleanup_expired_bags()
|
||||||
except Exception as e:
|
|
||||||
self.get_logger().warn(f'Compression skipped: {e}')
|
|
||||||
|
|
||||||
def maintenance_callback(self):
|
def _start_recording_locked(self):
|
||||||
"""Periodic maintenance: cleanup old bags and manage storage."""
|
sel = self._selector.select()
|
||||||
self.cleanup_expired_bags()
|
if sel is None:
|
||||||
self.enforce_storage_quota()
|
msg = f"No storage path with >={self._policy.min_free_gb:.1f}GB free"
|
||||||
if self.enable_rsync and self.rsync_destination:
|
self.get_logger().error(msg)
|
||||||
self.rsync_bags()
|
return False, msg
|
||||||
|
self._bag_dir = Path(sel)
|
||||||
|
self._bag_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
self._session = _BagSession(self._bag_dir, f"saltybot_{ts}")
|
||||||
|
ok, msg = self._launch_ros2bag_locked()
|
||||||
|
if ok:
|
||||||
|
self._recording = True
|
||||||
|
self.get_logger().info(
|
||||||
|
f"Recording: {self._session.segment_name()} -> {self._bag_dir}")
|
||||||
|
return ok, msg
|
||||||
|
|
||||||
def cleanup_expired_bags(self):
|
def _stop_recording_locked(self):
|
||||||
"""Remove bags older than TTL."""
|
if self._session is None:
|
||||||
try:
|
return None, False, "No active session"
|
||||||
cutoff_time = datetime.now() - timedelta(days=self.storage_ttl_days)
|
name = self._session.session_name
|
||||||
for item in self.bag_dir.iterdir():
|
self._session.stop_proc()
|
||||||
if item.is_dir() and item.name.startswith('saltybot_'):
|
self._recording = False
|
||||||
try:
|
self.get_logger().info(f"Stopped: {name}")
|
||||||
timestamp_str = item.name.replace('saltybot_', '')
|
return name, True, f"Stopped: {name}"
|
||||||
item_time = datetime.strptime(timestamp_str, '%Y%m%d_%H%M%S')
|
|
||||||
if item_time < cutoff_time:
|
|
||||||
shutil.rmtree(item, ignore_errors=True)
|
|
||||||
self.get_logger().info(f'Removed expired bag: {item.name}')
|
|
||||||
except (ValueError, OSError) as e:
|
|
||||||
self.get_logger().warn(f'Error processing {item.name}: {e}')
|
|
||||||
except Exception as e:
|
|
||||||
self.get_logger().error(f'Cleanup failed: {e}')
|
|
||||||
|
|
||||||
def enforce_storage_quota(self):
|
def _split_locked(self):
|
||||||
"""Remove oldest bags if total size exceeds quota (FIFO)."""
|
if self._session is None:
|
||||||
|
return False, "No active session"
|
||||||
|
old = self._session.segment_name()
|
||||||
|
self._session.stop_proc()
|
||||||
|
self._session.split_count += 1
|
||||||
|
self._session.segment_start = time.monotonic()
|
||||||
|
ok, msg = self._launch_ros2bag_locked()
|
||||||
|
if ok:
|
||||||
|
self.get_logger().info(f"Split: {old} -> {self._session.segment_name()}")
|
||||||
|
return True, f"Split: {old} -> {self._session.segment_name()}"
|
||||||
|
return ok, msg
|
||||||
|
|
||||||
|
def _launch_ros2bag_locked(self):
|
||||||
|
seg_path = self._session.segment_path()
|
||||||
|
cmd = ["ros2", "bag", "record",
|
||||||
|
"--output", str(seg_path),
|
||||||
|
"--storage", self._storage_fmt]
|
||||||
|
if self._storage_fmt == "sqlite3":
|
||||||
|
cmd += ["--compression-format", "zstd", "--compression-mode", "file"]
|
||||||
|
cmd += self._topics
|
||||||
try:
|
try:
|
||||||
total_size = sum(f.stat().st_size for f in self.bag_dir.rglob('*') if f.is_file()) / (1024 ** 3)
|
self._session.proc = subprocess.Popen(
|
||||||
if total_size > self.max_storage_gb:
|
cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
|
||||||
self.get_logger().warn(f'Storage quota exceeded: {total_size:.2f}GB > {self.max_storage_gb}GB')
|
preexec_fn=os.setsid)
|
||||||
bags = sorted([d for d in self.bag_dir.iterdir() if d.is_dir() and d.name.startswith('saltybot_')], key=lambda x: x.stat().st_mtime)
|
return True, f"Recording: {self._session.segment_name()}"
|
||||||
for bag in bags:
|
except Exception as exc:
|
||||||
if total_size <= self.max_storage_gb:
|
msg = f"Failed to launch ros2 bag record: {exc}"
|
||||||
|
self.get_logger().error(msg)
|
||||||
|
return False, msg
|
||||||
|
|
||||||
|
def _cleanup_expired_bags(self) -> None:
|
||||||
|
if self._bag_dir is None or not self._bag_dir.exists():
|
||||||
|
return
|
||||||
|
now = time.time()
|
||||||
|
for item in sorted(self._bag_dir.iterdir(),
|
||||||
|
key=lambda p: p.stat().st_mtime):
|
||||||
|
if not item.is_dir() or not item.name.startswith("saltybot_"):
|
||||||
|
continue
|
||||||
|
if (self._session and
|
||||||
|
item.name.startswith(self._session.session_name)):
|
||||||
|
continue
|
||||||
|
age = self._policy.bag_age_days(item.stat().st_mtime, now)
|
||||||
|
if self._policy.bag_is_expired(age):
|
||||||
|
try:
|
||||||
|
shutil.rmtree(item)
|
||||||
|
self.get_logger().info(
|
||||||
|
f"Cleanup: removed {item.name} (age {age:.1f}d)")
|
||||||
|
try:
|
||||||
|
disk = DiskInfo.from_path(str(self._bag_dir))
|
||||||
|
if not self._policy.needs_cleanup(disk):
|
||||||
break
|
break
|
||||||
bag_size = sum(f.stat().st_size for f in bag.rglob('*') if f.is_file()) / (1024 ** 3)
|
except OSError:
|
||||||
shutil.rmtree(bag, ignore_errors=True)
|
break
|
||||||
total_size -= bag_size
|
except OSError as exc:
|
||||||
self.get_logger().info(f'Removed bag to enforce quota: {bag.name}')
|
self.get_logger().warn(f"Cleanup failed {item.name}: {exc}")
|
||||||
except Exception as e:
|
|
||||||
self.get_logger().error(f'Storage quota enforcement failed: {e}')
|
|
||||||
|
|
||||||
def rsync_bags(self):
|
def _publish_status(self) -> None:
|
||||||
"""Optional: rsync bags to NAS."""
|
with self._lock:
|
||||||
|
s_name = self._session.session_name if self._session else None
|
||||||
|
seg = self._session.segment_name() if self._session else None
|
||||||
|
splits = self._session.split_count if self._session else 0
|
||||||
|
seg_sz = self._session.segment_size_bytes() if self._session else 0
|
||||||
|
s_dur = self._session.session_duration_s() if self._session else 0.0
|
||||||
|
seg_dur = self._session.segment_duration_s() if self._session else 0.0
|
||||||
|
rec = self._recording
|
||||||
|
bdir = str(self._bag_dir) if self._bag_dir else None
|
||||||
|
now = time.monotonic()
|
||||||
|
idle = self._motion.idle_seconds(now)
|
||||||
|
disk_status = {}
|
||||||
|
if self._bag_dir and self._bag_dir.exists():
|
||||||
try:
|
try:
|
||||||
cmd = ['rsync', '-avz', '--delete', f'{self.bag_dir}/', self.rsync_destination]
|
di = DiskInfo.from_path(str(self._bag_dir))
|
||||||
subprocess.run(cmd, check=False, timeout=300)
|
disk_status = {
|
||||||
self.get_logger().info(f'Synced bags to NAS: {self.rsync_destination}')
|
"path": bdir,
|
||||||
except subprocess.TimeoutExpired:
|
"used_pct": round(di.used_pct, 1),
|
||||||
self.get_logger().warn('Rsync timed out')
|
"free_gb": round(di.free_gb, 2),
|
||||||
except Exception as e:
|
"total_gb": round(di.total_gb, 2),
|
||||||
self.get_logger().error(f'Rsync failed: {e}')
|
"warn": self._policy.should_warn_disk(di),
|
||||||
|
"cleanup": self._policy.needs_cleanup(di),
|
||||||
|
}
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
payload = {
|
||||||
|
"recording": rec,
|
||||||
|
"session": s_name,
|
||||||
|
"segment": seg,
|
||||||
|
"split_count": splits,
|
||||||
|
"segment_size_mb": round(seg_sz / 1e6, 1),
|
||||||
|
"session_dur_s": round(s_dur, 1),
|
||||||
|
"segment_dur_s": round(seg_dur, 1),
|
||||||
|
"motion_idle_s": round(idle, 1) if idle != float("inf") else None,
|
||||||
|
"motion_trigger": self._motion_trigger,
|
||||||
|
"bag_dir": bdir,
|
||||||
|
"disk": disk_status,
|
||||||
|
}
|
||||||
|
self._status_pub.publish(String(data=json.dumps(payload)))
|
||||||
|
|
||||||
def cleanup(self):
|
def _shutdown(self) -> None:
|
||||||
"""Cleanup resources."""
|
with self._lock:
|
||||||
self.stop_recording(save=True)
|
if self._recording:
|
||||||
self.get_logger().info('Bag recorder shutdown complete')
|
self._stop_recording_locked()
|
||||||
|
|
||||||
|
|
||||||
def main(args=None):
|
def main(args=None) -> None:
|
||||||
rclpy.init(args=args)
|
rclpy.init(args=args)
|
||||||
node = BagRecorderNode()
|
node = BagRecorderNode()
|
||||||
try:
|
try:
|
||||||
@ -267,10 +385,6 @@ def main(args=None):
|
|||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
pass
|
pass
|
||||||
finally:
|
finally:
|
||||||
node.cleanup()
|
node._shutdown()
|
||||||
node.destroy_node()
|
node.destroy_node()
|
||||||
rclpy.shutdown()
|
rclpy.try_shutdown()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
main()
|
|
||||||
|
|||||||
379
jetson/ros2_ws/src/saltybot_bag_recorder/test/test_bag_policy.py
Normal file
379
jetson/ros2_ws/src/saltybot_bag_recorder/test/test_bag_policy.py
Normal file
@ -0,0 +1,379 @@
|
|||||||
|
"""test_bag_policy.py — Unit tests for bag recording policy (Issue #615).
|
||||||
|
|
||||||
|
ROS2-free. Run with:
|
||||||
|
python3 -m pytest \
|
||||||
|
jetson/ros2_ws/src/saltybot_bag_recorder/test/test_bag_policy.py -v
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..",
|
||||||
|
"saltybot_bag_recorder"))
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from bag_policy import BagPolicy, DiskInfo, MotionState, StorageSelector
|
||||||
|
|
||||||
|
|
||||||
|
# ─── MotionState ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class TestMotionStateInit:
|
||||||
|
def test_default_idle_timeout(self):
|
||||||
|
assert MotionState().idle_timeout_s == 30.0
|
||||||
|
|
||||||
|
def test_custom_idle_timeout(self):
|
||||||
|
assert MotionState(idle_timeout_s=60.0).idle_timeout_s == 60.0
|
||||||
|
|
||||||
|
def test_zero_timeout_raises(self):
|
||||||
|
with pytest.raises(ValueError, match="idle_timeout_s"):
|
||||||
|
MotionState(idle_timeout_s=0.0)
|
||||||
|
|
||||||
|
def test_negative_timeout_raises(self):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
MotionState(idle_timeout_s=-5.0)
|
||||||
|
|
||||||
|
def test_initial_not_ever_moved(self):
|
||||||
|
assert not MotionState().ever_moved
|
||||||
|
|
||||||
|
def test_initial_idle_seconds_inf(self):
|
||||||
|
assert MotionState().idle_seconds(1000.0) == math.inf
|
||||||
|
|
||||||
|
def test_initial_is_idle(self):
|
||||||
|
assert MotionState().is_idle(1000.0)
|
||||||
|
|
||||||
|
def test_initial_not_moving(self):
|
||||||
|
assert not MotionState().is_moving(1000.0)
|
||||||
|
|
||||||
|
|
||||||
|
class TestMotionStateUpdate:
|
||||||
|
def setup_method(self):
|
||||||
|
self.ms = MotionState(idle_timeout_s=30.0)
|
||||||
|
|
||||||
|
def test_nonzero_linear_sets_moved(self):
|
||||||
|
self.ms.update(0.5, 0.0, 100.0)
|
||||||
|
assert self.ms.ever_moved
|
||||||
|
|
||||||
|
def test_nonzero_angular_sets_moved(self):
|
||||||
|
self.ms.update(0.0, 0.3, 100.0)
|
||||||
|
assert self.ms.ever_moved
|
||||||
|
|
||||||
|
def test_zero_cmd_vel_does_not_set_moved(self):
|
||||||
|
self.ms.update(0.0, 0.0, 100.0)
|
||||||
|
assert not self.ms.ever_moved
|
||||||
|
|
||||||
|
def test_noise_below_threshold_ignored(self):
|
||||||
|
self.ms.update(0.0005, 0.0005, 100.0)
|
||||||
|
assert not self.ms.ever_moved
|
||||||
|
|
||||||
|
def test_idle_seconds_after_motion(self):
|
||||||
|
self.ms.update(0.5, 0.0, 100.0)
|
||||||
|
assert abs(self.ms.idle_seconds(105.0) - 5.0) < 1e-9
|
||||||
|
|
||||||
|
def test_not_idle_immediately(self):
|
||||||
|
self.ms.update(0.5, 0.0, 100.0)
|
||||||
|
assert not self.ms.is_idle(100.0)
|
||||||
|
|
||||||
|
def test_not_idle_within_timeout(self):
|
||||||
|
self.ms.update(0.5, 0.0, 100.0)
|
||||||
|
assert not self.ms.is_idle(129.9)
|
||||||
|
|
||||||
|
def test_idle_at_boundary(self):
|
||||||
|
self.ms.update(0.5, 0.0, 100.0)
|
||||||
|
assert self.ms.is_idle(130.0)
|
||||||
|
|
||||||
|
def test_idle_after_timeout(self):
|
||||||
|
self.ms.update(0.5, 0.0, 100.0)
|
||||||
|
assert self.ms.is_idle(200.0)
|
||||||
|
|
||||||
|
def test_moving_within_window(self):
|
||||||
|
self.ms.update(0.5, 0.0, 100.0)
|
||||||
|
assert self.ms.is_moving(115.0)
|
||||||
|
|
||||||
|
def test_not_moving_after_timeout(self):
|
||||||
|
self.ms.update(0.5, 0.0, 100.0)
|
||||||
|
assert not self.ms.is_moving(200.0)
|
||||||
|
|
||||||
|
def test_second_motion_resets_timer(self):
|
||||||
|
self.ms.update(0.5, 0.0, 100.0)
|
||||||
|
self.ms.update(0.5, 0.0, 125.0)
|
||||||
|
assert not self.ms.is_idle(150.0) # 25s since last motion
|
||||||
|
assert self.ms.is_idle(160.0) # 35s since last motion
|
||||||
|
|
||||||
|
|
||||||
|
class TestMotionStateAutoDecisions:
|
||||||
|
def setup_method(self):
|
||||||
|
self.ms = MotionState(idle_timeout_s=30.0)
|
||||||
|
|
||||||
|
def test_no_start_before_motion(self):
|
||||||
|
assert not self.ms.should_start_recording(1000.0)
|
||||||
|
|
||||||
|
def test_start_after_motion(self):
|
||||||
|
self.ms.update(0.5, 0.0, 1000.0)
|
||||||
|
assert self.ms.should_start_recording(1001.0)
|
||||||
|
|
||||||
|
def test_no_start_after_idle(self):
|
||||||
|
self.ms.update(0.5, 0.0, 1000.0)
|
||||||
|
assert not self.ms.should_start_recording(1040.0)
|
||||||
|
|
||||||
|
def test_no_stop_before_motion(self):
|
||||||
|
assert not self.ms.should_stop_recording(1000.0)
|
||||||
|
|
||||||
|
def test_no_stop_while_active(self):
|
||||||
|
self.ms.update(0.5, 0.0, 1000.0)
|
||||||
|
assert not self.ms.should_stop_recording(1010.0)
|
||||||
|
|
||||||
|
def test_stop_after_idle(self):
|
||||||
|
self.ms.update(0.5, 0.0, 1000.0)
|
||||||
|
assert self.ms.should_stop_recording(1035.0)
|
||||||
|
|
||||||
|
|
||||||
|
class TestMotionStateReset:
|
||||||
|
def test_reset_clears_motion(self):
|
||||||
|
ms = MotionState()
|
||||||
|
ms.update(1.0, 0.0, 100.0)
|
||||||
|
ms.reset()
|
||||||
|
assert not ms.ever_moved
|
||||||
|
assert ms.idle_seconds(200.0) == math.inf
|
||||||
|
|
||||||
|
|
||||||
|
# ─── DiskInfo ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _disk(total_gb=100.0, free_gb=50.0, path="/fake"):
|
||||||
|
total = int(total_gb * 1024**3)
|
||||||
|
free = int(free_gb * 1024**3)
|
||||||
|
used = total - free
|
||||||
|
return DiskInfo(path=path, total_bytes=total, used_bytes=used, free_bytes=free)
|
||||||
|
|
||||||
|
|
||||||
|
class TestDiskInfo:
|
||||||
|
def test_used_pct_50(self):
|
||||||
|
assert abs(_disk(100, 50).used_pct - 50.0) < 0.01
|
||||||
|
|
||||||
|
def test_used_pct_100(self):
|
||||||
|
assert _disk(100, 0).used_pct == 100.0
|
||||||
|
|
||||||
|
def test_used_pct_0(self):
|
||||||
|
assert abs(_disk(100, 100).used_pct) < 0.01
|
||||||
|
|
||||||
|
def test_free_pct(self):
|
||||||
|
assert abs(_disk(100, 30).free_pct - 30.0) < 0.01
|
||||||
|
|
||||||
|
def test_free_gb(self):
|
||||||
|
assert abs(_disk(100, 20).free_gb - 20.0) < 0.01
|
||||||
|
|
||||||
|
def test_total_gb(self):
|
||||||
|
assert abs(_disk(250, 100).total_gb - 250.0) < 0.01
|
||||||
|
|
||||||
|
def test_used_gb(self):
|
||||||
|
assert abs(_disk(100, 30).used_gb - 70.0) < 0.01
|
||||||
|
|
||||||
|
def test_exceeds_pct_true(self):
|
||||||
|
assert _disk(100, 10).exceeds_pct(80.0) # 90% used
|
||||||
|
|
||||||
|
def test_exceeds_pct_false(self):
|
||||||
|
assert not _disk(100, 50).exceeds_pct(80.0) # 50% used
|
||||||
|
|
||||||
|
def test_exceeds_pct_boundary(self):
|
||||||
|
assert _disk(100, 20).exceeds_pct(80.0) # exactly 80%
|
||||||
|
|
||||||
|
def test_has_min_free_true(self):
|
||||||
|
assert _disk(100, 10).has_min_free(2.0)
|
||||||
|
|
||||||
|
def test_has_min_free_false(self):
|
||||||
|
assert not _disk(100, 1).has_min_free(2.0)
|
||||||
|
|
||||||
|
def test_zero_total_is_100pct(self):
|
||||||
|
di = DiskInfo(path="/", total_bytes=0, used_bytes=0, free_bytes=0)
|
||||||
|
assert di.used_pct == 100.0
|
||||||
|
|
||||||
|
def test_summary_has_path(self):
|
||||||
|
di = _disk(path="/media/usb0")
|
||||||
|
assert "/media/usb0" in di.summary()
|
||||||
|
|
||||||
|
|
||||||
|
# ─── StorageSelector ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class TestStorageSelector:
|
||||||
|
def test_empty_paths_raises(self):
|
||||||
|
with pytest.raises(ValueError, match="paths"):
|
||||||
|
StorageSelector([])
|
||||||
|
|
||||||
|
def test_select_none_when_no_paths_exist(self):
|
||||||
|
sel = StorageSelector(["/nonexistent/a", "/nonexistent/b"])
|
||||||
|
assert sel.select() is None
|
||||||
|
|
||||||
|
def test_select_first_accessible(self, tmp_path):
|
||||||
|
p1 = tmp_path / "p1"; p1.mkdir()
|
||||||
|
p2 = tmp_path / "p2"; p2.mkdir()
|
||||||
|
sel = StorageSelector([str(p1), str(p2)], min_free_gb=0.0)
|
||||||
|
assert sel.select() == str(p1)
|
||||||
|
|
||||||
|
def test_select_skips_insufficient_free(self, tmp_path):
|
||||||
|
small = tmp_path / "small"; small.mkdir()
|
||||||
|
large = tmp_path / "large"; large.mkdir()
|
||||||
|
|
||||||
|
def fake_from(path):
|
||||||
|
if "small" in path:
|
||||||
|
return DiskInfo(path=path, total_bytes=10*1024**3,
|
||||||
|
used_bytes=9*1024**3, free_bytes=1*1024**3)
|
||||||
|
return DiskInfo(path=path, total_bytes=100*1024**3,
|
||||||
|
used_bytes=10*1024**3, free_bytes=90*1024**3)
|
||||||
|
|
||||||
|
with patch("bag_policy.DiskInfo.from_path", side_effect=fake_from):
|
||||||
|
sel = StorageSelector([str(small), str(large)], min_free_gb=2.0)
|
||||||
|
assert sel.select() == str(large)
|
||||||
|
|
||||||
|
def test_select_or_default_fallback(self):
|
||||||
|
sel = StorageSelector(["/nonexistent"], min_free_gb=1.0)
|
||||||
|
assert sel.select_or_default("/fb") == "/fb"
|
||||||
|
|
||||||
|
def test_disk_infos_empty_nonexistent(self):
|
||||||
|
sel = StorageSelector(["/nonexistent"])
|
||||||
|
assert sel.disk_infos() == []
|
||||||
|
|
||||||
|
|
||||||
|
# ─── BagPolicy constructor ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class TestBagPolicyConstructor:
|
||||||
|
def test_defaults(self):
|
||||||
|
p = BagPolicy()
|
||||||
|
assert p.split_size_bytes == 1 * 1024**3
|
||||||
|
assert p.split_duration_s == 600.0
|
||||||
|
assert p.cleanup_age_days == 7
|
||||||
|
assert p.cleanup_disk_pct == 80.0
|
||||||
|
assert p.warn_disk_pct == 70.0
|
||||||
|
|
||||||
|
def test_size_stored_as_bytes(self):
|
||||||
|
assert BagPolicy(split_size_gb=2.0).split_size_bytes == 2 * 1024**3
|
||||||
|
|
||||||
|
def test_duration_stored_as_seconds(self):
|
||||||
|
assert BagPolicy(split_duration_min=5.0).split_duration_s == 300.0
|
||||||
|
|
||||||
|
def test_zero_size_raises(self):
|
||||||
|
with pytest.raises(ValueError, match="split_size_gb"):
|
||||||
|
BagPolicy(split_size_gb=0.0)
|
||||||
|
|
||||||
|
def test_negative_size_raises(self):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
BagPolicy(split_size_gb=-1.0)
|
||||||
|
|
||||||
|
def test_zero_duration_raises(self):
|
||||||
|
with pytest.raises(ValueError, match="split_duration_min"):
|
||||||
|
BagPolicy(split_duration_min=0.0)
|
||||||
|
|
||||||
|
def test_cleanup_age_zero_raises(self):
|
||||||
|
with pytest.raises(ValueError, match="cleanup_age_days"):
|
||||||
|
BagPolicy(cleanup_age_days=0)
|
||||||
|
|
||||||
|
def test_warn_above_cleanup_raises(self):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
BagPolicy(warn_disk_pct=85.0, cleanup_disk_pct=80.0)
|
||||||
|
|
||||||
|
def test_equal_warn_cleanup_raises(self):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
BagPolicy(warn_disk_pct=80.0, cleanup_disk_pct=80.0)
|
||||||
|
|
||||||
|
|
||||||
|
# ─── BagPolicy split ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class TestBagPolicySplit:
|
||||||
|
def setup_method(self):
|
||||||
|
self.p = BagPolicy(split_size_gb=1.0, split_duration_min=10.0)
|
||||||
|
|
||||||
|
def test_no_split_small_short(self):
|
||||||
|
split, reason = self.p.needs_split(100*1024**2, 60)
|
||||||
|
assert not split and reason == ""
|
||||||
|
|
||||||
|
def test_split_at_size_boundary(self):
|
||||||
|
split, reason = self.p.needs_split(1024**3, 60)
|
||||||
|
assert split
|
||||||
|
assert "size" in reason.lower() or "gb" in reason.lower()
|
||||||
|
|
||||||
|
def test_split_over_size(self):
|
||||||
|
split, _ = self.p.needs_split(int(1.5*1024**3), 60)
|
||||||
|
assert split
|
||||||
|
|
||||||
|
def test_split_at_duration_boundary(self):
|
||||||
|
split, reason = self.p.needs_split(100*1024**2, 600)
|
||||||
|
assert split
|
||||||
|
assert "min" in reason.lower() or "duration" in reason.lower()
|
||||||
|
|
||||||
|
def test_split_over_duration(self):
|
||||||
|
split, _ = self.p.needs_split(100*1024**2, 700)
|
||||||
|
assert split
|
||||||
|
|
||||||
|
def test_just_below_both(self):
|
||||||
|
split, _ = self.p.needs_split(1024**3 - 1, 599)
|
||||||
|
assert not split
|
||||||
|
|
||||||
|
def test_both_exceeded_still_splits(self):
|
||||||
|
split, _ = self.p.needs_split(2*1024**3, 700)
|
||||||
|
assert split
|
||||||
|
|
||||||
|
|
||||||
|
# ─── BagPolicy disk thresholds ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class TestBagPolicyDisk:
|
||||||
|
def setup_method(self):
|
||||||
|
self.p = BagPolicy(warn_disk_pct=70.0, cleanup_disk_pct=80.0,
|
||||||
|
min_free_gb=2.0)
|
||||||
|
|
||||||
|
def test_no_warn_below(self):
|
||||||
|
assert not self.p.should_warn_disk(_disk(100, 40)) # 60% used
|
||||||
|
|
||||||
|
def test_warn_at_boundary(self):
|
||||||
|
assert self.p.should_warn_disk(_disk(100, 30)) # 70% used
|
||||||
|
|
||||||
|
def test_warn_above(self):
|
||||||
|
assert self.p.should_warn_disk(_disk(100, 25)) # 75% used
|
||||||
|
|
||||||
|
def test_no_cleanup_at_warn(self):
|
||||||
|
assert not self.p.needs_cleanup(_disk(100, 30)) # 70% used
|
||||||
|
|
||||||
|
def test_cleanup_at_boundary(self):
|
||||||
|
assert self.p.needs_cleanup(_disk(100, 20)) # 80% used
|
||||||
|
|
||||||
|
def test_cleanup_above(self):
|
||||||
|
assert self.p.needs_cleanup(_disk(100, 5)) # 95% used
|
||||||
|
|
||||||
|
def test_can_record_exact_min_free(self):
|
||||||
|
total = 100 * 1024**3
|
||||||
|
free = int(2.0 * 1024**3)
|
||||||
|
di = DiskInfo(path="/", total_bytes=total,
|
||||||
|
used_bytes=total-free, free_bytes=free)
|
||||||
|
assert self.p.can_record(di)
|
||||||
|
|
||||||
|
def test_cannot_record_below_min_free(self):
|
||||||
|
total = 100 * 1024**3
|
||||||
|
free = int(1.0 * 1024**3)
|
||||||
|
di = DiskInfo(path="/", total_bytes=total,
|
||||||
|
used_bytes=total-free, free_bytes=free)
|
||||||
|
assert not self.p.can_record(di)
|
||||||
|
|
||||||
|
|
||||||
|
# ─── BagPolicy age ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class TestBagPolicyAge:
|
||||||
|
def setup_method(self):
|
||||||
|
self.p = BagPolicy(cleanup_age_days=7)
|
||||||
|
|
||||||
|
def test_fresh_not_expired(self):
|
||||||
|
assert not self.p.bag_is_expired(1.0)
|
||||||
|
|
||||||
|
def test_at_boundary_expired(self):
|
||||||
|
assert self.p.bag_is_expired(7.0)
|
||||||
|
|
||||||
|
def test_old_expired(self):
|
||||||
|
assert self.p.bag_is_expired(30.0)
|
||||||
|
|
||||||
|
def test_age_computation(self):
|
||||||
|
mtime = 1000.0
|
||||||
|
age = self.p.bag_age_days(mtime, mtime + 8 * 86400)
|
||||||
|
assert abs(age - 8.0) < 1e-9
|
||||||
|
|
||||||
|
def test_age_zero(self):
|
||||||
|
assert self.p.bag_age_days(5000.0, 5000.0) == 0.0
|
||||||
@ -2,7 +2,7 @@
|
|||||||
# Used by both serial_bridge_node (RX-only) and saltybot_cmd_node (bidirectional)
|
# Used by both serial_bridge_node (RX-only) and saltybot_cmd_node (bidirectional)
|
||||||
|
|
||||||
# ── Serial ─────────────────────────────────────────────────────────────────────
|
# ── Serial ─────────────────────────────────────────────────────────────────────
|
||||||
# Use /dev/stm32-bridge if udev rule from jetson/docs/pinout.md is applied.
|
# Use /dev/esp32-bridge if udev rule from jetson/docs/pinout.md is applied.
|
||||||
serial_port: /dev/ttyACM0
|
serial_port: /dev/ttyACM0
|
||||||
baud_rate: 921600
|
baud_rate: 921600
|
||||||
timeout: 0.05 # serial readline timeout (seconds)
|
timeout: 0.05 # serial readline timeout (seconds)
|
||||||
@ -11,7 +11,11 @@ reconnect_delay: 2.0 # seconds between reconnect attempts on serial disconne
|
|||||||
# ── saltybot_cmd_node (bidirectional) only ─────────────────────────────────────
|
# ── saltybot_cmd_node (bidirectional) only ─────────────────────────────────────
|
||||||
|
|
||||||
# Heartbeat: H\n sent every heartbeat_period seconds.
|
# Heartbeat: H\n sent every heartbeat_period seconds.
|
||||||
# STM32 reverts steer to 0 after JETSON_HB_TIMEOUT_MS (500ms) without heartbeat.
|
<<<<<<< HEAD
|
||||||
|
# ESP32 BALANCE reverts steer to 0 after JETSON_HB_TIMEOUT_MS (500ms) without heartbeat.
|
||||||
|
=======
|
||||||
|
# ESP32-S3 reverts steer to 0 after JETSON_HB_TIMEOUT_MS (500ms) without heartbeat.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
heartbeat_period: 0.2 # seconds (= 200ms)
|
heartbeat_period: 0.2 # seconds (= 200ms)
|
||||||
|
|
||||||
# Twist → ESC command scaling
|
# Twist → ESC command scaling
|
||||||
|
|||||||
@ -1,5 +1,9 @@
|
|||||||
# cmd_vel_bridge_params.yaml
|
# cmd_vel_bridge_params.yaml
|
||||||
# Configuration for cmd_vel_bridge_node — Nav2 /cmd_vel → STM32 autonomous drive.
|
<<<<<<< HEAD
|
||||||
|
# Configuration for cmd_vel_bridge_node — Nav2 /cmd_vel → ESP32 BALANCE autonomous drive.
|
||||||
|
=======
|
||||||
|
# Configuration for cmd_vel_bridge_node — Nav2 /cmd_vel → ESP32-S3 autonomous drive.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
#
|
#
|
||||||
# Run with:
|
# Run with:
|
||||||
# ros2 launch saltybot_bridge cmd_vel_bridge.launch.py
|
# ros2 launch saltybot_bridge cmd_vel_bridge.launch.py
|
||||||
@ -7,14 +11,18 @@
|
|||||||
# ros2 launch saltybot_bridge cmd_vel_bridge.launch.py max_linear_vel:=0.3
|
# ros2 launch saltybot_bridge cmd_vel_bridge.launch.py max_linear_vel:=0.3
|
||||||
|
|
||||||
# ── Serial ─────────────────────────────────────────────────────────────────────
|
# ── Serial ─────────────────────────────────────────────────────────────────────
|
||||||
# Use /dev/stm32-bridge if udev rule from jetson/docs/pinout.md is applied.
|
# Use /dev/esp32-bridge if udev rule from jetson/docs/pinout.md is applied.
|
||||||
serial_port: /dev/ttyACM0
|
serial_port: /dev/ttyACM0
|
||||||
baud_rate: 921600
|
baud_rate: 921600
|
||||||
timeout: 0.05 # serial readline timeout (s)
|
timeout: 0.05 # serial readline timeout (s)
|
||||||
reconnect_delay: 2.0 # seconds between reconnect attempts
|
reconnect_delay: 2.0 # seconds between reconnect attempts
|
||||||
|
|
||||||
# ── Heartbeat ──────────────────────────────────────────────────────────────────
|
# ── Heartbeat ──────────────────────────────────────────────────────────────────
|
||||||
# STM32 jetson_cmd module reverts steer to 0 after JETSON_HB_TIMEOUT_MS (500ms).
|
<<<<<<< HEAD
|
||||||
|
# ESP32 BALANCE jetson_cmd module reverts steer to 0 after JETSON_HB_TIMEOUT_MS (500ms).
|
||||||
|
=======
|
||||||
|
# ESP32-S3 jetson_cmd module reverts steer to 0 after JETSON_HB_TIMEOUT_MS (500ms).
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
# Keep heartbeat well below that threshold.
|
# Keep heartbeat well below that threshold.
|
||||||
heartbeat_period: 0.2 # seconds (200ms)
|
heartbeat_period: 0.2 # seconds (200ms)
|
||||||
|
|
||||||
@ -50,5 +58,9 @@ ramp_rate: 500 # ESC units/second
|
|||||||
# ── Deadman switch ─────────────────────────────────────────────────────────────
|
# ── Deadman switch ─────────────────────────────────────────────────────────────
|
||||||
# If /cmd_vel is not received for this many seconds, target speed/steer are
|
# If /cmd_vel is not received for this many seconds, target speed/steer are
|
||||||
# zeroed immediately. The ramp then drives the robot to a stop.
|
# zeroed immediately. The ramp then drives the robot to a stop.
|
||||||
# 500ms matches the STM32 jetson heartbeat timeout for consistency.
|
<<<<<<< HEAD
|
||||||
|
# 500ms matches the ESP32 BALANCE jetson heartbeat timeout for consistency.
|
||||||
|
=======
|
||||||
|
# 500ms matches the ESP32-S3 jetson heartbeat timeout for consistency.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
cmd_vel_timeout: 0.5 # seconds
|
cmd_vel_timeout: 0.5 # seconds
|
||||||
|
|||||||
@ -0,0 +1,49 @@
|
|||||||
|
<<<<<<< HEAD:jetson/ros2_ws/src/saltybot_bridge/config/stm32_cmd_params.yaml
|
||||||
|
# stm32_cmd_params.yaml — Configuration for stm32_cmd_node (ESP32-S3 IO bridge)
|
||||||
|
# Connects to ESP32-S3 IO board via USB-CDC @ 460800 baud.
|
||||||
|
# Frame format: [0xAA][LEN][TYPE][PAYLOAD][CRC8]
|
||||||
|
# Spec: docs/SAUL-TEE-SYSTEM-REFERENCE.md §5
|
||||||
|
|
||||||
|
# ── Serial port ────────────────────────────────────────────────────────────────
|
||||||
|
# Use /dev/esp32-io if udev rule is applied (see jetson/docs/udev-rules.md).
|
||||||
|
# ESP32-S3 IO appears as USB-JTAG/Serial device; no external UART bridge needed.
|
||||||
|
serial_port: /dev/esp32-io
|
||||||
|
baud_rate: 460800
|
||||||
|
reconnect_delay: 2.0 # seconds between reconnect attempts
|
||||||
|
|
||||||
|
# ── Heartbeat ─────────────────────────────────────────────────────────────────
|
||||||
|
# HEARTBEAT (0x20) sent every heartbeat_period.
|
||||||
|
# ESP32 IO watchdog fires if no heartbeat for ~500 ms.
|
||||||
|
heartbeat_period: 0.2 # 200 ms → well within 500 ms watchdog
|
||||||
|
=======
|
||||||
|
# esp32_cmd_params.yaml — Configuration for esp32_cmd_node (Issue #119)
|
||||||
|
# Binary-framed Jetson↔ESP32-S3 bridge at 921600 baud.
|
||||||
|
|
||||||
|
# ── Serial port ────────────────────────────────────────────────────────────────
|
||||||
|
# Use /dev/esp32-bridge if the udev rule is applied:
|
||||||
|
# SUBSYSTEM=="tty", ATTRS{idVendor}=="0483", ATTRS{idProduct}=="5740",
|
||||||
|
# SYMLINK+="esp32-bridge", MODE="0660", GROUP="dialout"
|
||||||
|
serial_port: /dev/ttyACM0
|
||||||
|
baud_rate: 921600
|
||||||
|
reconnect_delay: 2.0 # seconds between USB reconnect attempts
|
||||||
|
|
||||||
|
# ── Heartbeat ─────────────────────────────────────────────────────────────────
|
||||||
|
# HEARTBEAT frame sent every heartbeat_period seconds.
|
||||||
|
# ESP32-S3 fires watchdog and reverts to safe state if no frame received for 500ms.
|
||||||
|
heartbeat_period: 0.2 # 200ms → well within 500ms ESP32-S3 watchdog
|
||||||
|
|
||||||
|
# ── Watchdog (Jetson-side) ────────────────────────────────────────────────────
|
||||||
|
# If no /cmd_vel message received for watchdog_timeout seconds,
|
||||||
|
# send SPEED_STEER(0,0) to stop the robot.
|
||||||
|
watchdog_timeout: 0.5 # 500ms
|
||||||
|
|
||||||
|
# ── Twist velocity scaling ────────────────────────────────────────────────────
|
||||||
|
# speed = clamp(linear.x * speed_scale, -1000, 1000) (m/s → ESC units)
|
||||||
|
# steer = clamp(angular.z * steer_scale, -1000, 1000) (rad/s → ESC units)
|
||||||
|
#
|
||||||
|
# Default: 1 m/s → 1000 ESC units, ±2 rad/s → ±1000 steer.
|
||||||
|
# Negative steer_scale flips ROS2 CCW+ convention to match ESC steer direction.
|
||||||
|
# Tune speed_scale to set the physical top speed.
|
||||||
|
speed_scale: 1000.0
|
||||||
|
steer_scale: -500.0
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only):jetson/ros2_ws/src/saltybot_bridge/config/esp32_cmd_params.yaml
|
||||||
@ -1,6 +1,6 @@
|
|||||||
remote_estop_node:
|
remote_estop_node:
|
||||||
ros__parameters:
|
ros__parameters:
|
||||||
serial_port: /dev/stm32-bridge
|
serial_port: /dev/esp32-bridge
|
||||||
baud_rate: 921600
|
baud_rate: 921600
|
||||||
mqtt_host: "mqtt.example.com"
|
mqtt_host: "mqtt.example.com"
|
||||||
mqtt_port: 1883
|
mqtt_port: 1883
|
||||||
|
|||||||
@ -1,30 +0,0 @@
|
|||||||
# stm32_cmd_params.yaml — Configuration for stm32_cmd_node (Issue #119)
|
|
||||||
# Binary-framed Jetson↔STM32 bridge at 921600 baud.
|
|
||||||
|
|
||||||
# ── Serial port ────────────────────────────────────────────────────────────────
|
|
||||||
# Use /dev/stm32-bridge if the udev rule is applied:
|
|
||||||
# SUBSYSTEM=="tty", ATTRS{idVendor}=="0483", ATTRS{idProduct}=="5740",
|
|
||||||
# SYMLINK+="stm32-bridge", MODE="0660", GROUP="dialout"
|
|
||||||
serial_port: /dev/ttyACM0
|
|
||||||
baud_rate: 921600
|
|
||||||
reconnect_delay: 2.0 # seconds between USB reconnect attempts
|
|
||||||
|
|
||||||
# ── Heartbeat ─────────────────────────────────────────────────────────────────
|
|
||||||
# HEARTBEAT frame sent every heartbeat_period seconds.
|
|
||||||
# STM32 fires watchdog and reverts to safe state if no frame received for 500ms.
|
|
||||||
heartbeat_period: 0.2 # 200ms → well within 500ms STM32 watchdog
|
|
||||||
|
|
||||||
# ── Watchdog (Jetson-side) ────────────────────────────────────────────────────
|
|
||||||
# If no /cmd_vel message received for watchdog_timeout seconds,
|
|
||||||
# send SPEED_STEER(0,0) to stop the robot.
|
|
||||||
watchdog_timeout: 0.5 # 500ms
|
|
||||||
|
|
||||||
# ── Twist velocity scaling ────────────────────────────────────────────────────
|
|
||||||
# speed = clamp(linear.x * speed_scale, -1000, 1000) (m/s → ESC units)
|
|
||||||
# steer = clamp(angular.z * steer_scale, -1000, 1000) (rad/s → ESC units)
|
|
||||||
#
|
|
||||||
# Default: 1 m/s → 1000 ESC units, ±2 rad/s → ±1000 steer.
|
|
||||||
# Negative steer_scale flips ROS2 CCW+ convention to match ESC steer direction.
|
|
||||||
# Tune speed_scale to set the physical top speed.
|
|
||||||
speed_scale: 1000.0
|
|
||||||
steer_scale: -500.0
|
|
||||||
@ -6,7 +6,11 @@ Two deployment modes:
|
|||||||
1. Full bidirectional (recommended for Nav2):
|
1. Full bidirectional (recommended for Nav2):
|
||||||
ros2 launch saltybot_bridge bridge.launch.py mode:=bidirectional
|
ros2 launch saltybot_bridge bridge.launch.py mode:=bidirectional
|
||||||
Starts saltybot_cmd_node — owns serial port, handles both RX telemetry
|
Starts saltybot_cmd_node — owns serial port, handles both RX telemetry
|
||||||
and TX /cmd_vel → STM32 commands + heartbeat.
|
<<<<<<< HEAD
|
||||||
|
and TX /cmd_vel → ESP32 BALANCE commands + heartbeat.
|
||||||
|
=======
|
||||||
|
and TX /cmd_vel → ESP32-S3 commands + heartbeat.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
2. RX-only (telemetry monitor, no drive commands):
|
2. RX-only (telemetry monitor, no drive commands):
|
||||||
ros2 launch saltybot_bridge bridge.launch.py mode:=rx_only
|
ros2 launch saltybot_bridge bridge.launch.py mode:=rx_only
|
||||||
@ -40,7 +44,7 @@ def _launch_nodes(context, *args, **kwargs):
|
|||||||
return [Node(
|
return [Node(
|
||||||
package="saltybot_bridge",
|
package="saltybot_bridge",
|
||||||
executable="serial_bridge_node",
|
executable="serial_bridge_node",
|
||||||
name="stm32_serial_bridge",
|
name="esp32_serial_bridge",
|
||||||
output="screen",
|
output="screen",
|
||||||
parameters=[params],
|
parameters=[params],
|
||||||
)]
|
)]
|
||||||
@ -65,7 +69,11 @@ def generate_launch_description():
|
|||||||
DeclareLaunchArgument("mode", default_value="bidirectional",
|
DeclareLaunchArgument("mode", default_value="bidirectional",
|
||||||
description="bidirectional | rx_only"),
|
description="bidirectional | rx_only"),
|
||||||
DeclareLaunchArgument("serial_port", default_value="/dev/ttyACM0",
|
DeclareLaunchArgument("serial_port", default_value="/dev/ttyACM0",
|
||||||
description="STM32 USB CDC device node"),
|
<<<<<<< HEAD
|
||||||
|
description="ESP32 USB CDC device node"),
|
||||||
|
=======
|
||||||
|
description="ESP32-S3 USB CDC device node"),
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
DeclareLaunchArgument("baud_rate", default_value="921600"),
|
DeclareLaunchArgument("baud_rate", default_value="921600"),
|
||||||
DeclareLaunchArgument("speed_scale", default_value="1000.0",
|
DeclareLaunchArgument("speed_scale", default_value="1000.0",
|
||||||
description="m/s → ESC units (linear.x scale)"),
|
description="m/s → ESC units (linear.x scale)"),
|
||||||
|
|||||||
@ -1,10 +1,18 @@
|
|||||||
"""
|
"""
|
||||||
cmd_vel_bridge.launch.py — Nav2 cmd_vel → STM32 autonomous drive bridge.
|
<<<<<<< HEAD
|
||||||
|
cmd_vel_bridge.launch.py — Nav2 cmd_vel → ESP32 BALANCE autonomous drive bridge.
|
||||||
|
=======
|
||||||
|
cmd_vel_bridge.launch.py — Nav2 cmd_vel → ESP32-S3 autonomous drive bridge.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
Starts cmd_vel_bridge_node, which owns the serial port exclusively and provides:
|
Starts cmd_vel_bridge_node, which owns the serial port exclusively and provides:
|
||||||
- /cmd_vel subscription with velocity limits + smooth ramp
|
- /cmd_vel subscription with velocity limits + smooth ramp
|
||||||
- Deadman switch (zero speed if /cmd_vel silent > cmd_vel_timeout)
|
- Deadman switch (zero speed if /cmd_vel silent > cmd_vel_timeout)
|
||||||
- Mode gate (drives only when STM32 is in AUTONOMOUS mode, md=2)
|
<<<<<<< HEAD
|
||||||
|
- Mode gate (drives only when ESP32 BALANCE is in AUTONOMOUS mode, md=2)
|
||||||
|
=======
|
||||||
|
- Mode gate (drives only when ESP32-S3 is in AUTONOMOUS mode, md=2)
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
- Telemetry RX → /saltybot/imu, /saltybot/balance_state, /diagnostics
|
- Telemetry RX → /saltybot/imu, /saltybot/balance_state, /diagnostics
|
||||||
- /saltybot/cmd publisher (observability)
|
- /saltybot/cmd publisher (observability)
|
||||||
|
|
||||||
@ -72,12 +80,20 @@ def generate_launch_description():
|
|||||||
description="Full path to cmd_vel_bridge_params.yaml (overrides inline args)"),
|
description="Full path to cmd_vel_bridge_params.yaml (overrides inline args)"),
|
||||||
DeclareLaunchArgument(
|
DeclareLaunchArgument(
|
||||||
"serial_port", default_value="/dev/ttyACM0",
|
"serial_port", default_value="/dev/ttyACM0",
|
||||||
description="STM32 USB CDC device node"),
|
<<<<<<< HEAD
|
||||||
|
description="ESP32 USB CDC device node"),
|
||||||
|
=======
|
||||||
|
description="ESP32-S3 USB CDC device node"),
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
DeclareLaunchArgument(
|
DeclareLaunchArgument(
|
||||||
"baud_rate", default_value="921600"),
|
"baud_rate", default_value="921600"),
|
||||||
DeclareLaunchArgument(
|
DeclareLaunchArgument(
|
||||||
"heartbeat_period",default_value="0.2",
|
"heartbeat_period",default_value="0.2",
|
||||||
description="Heartbeat interval (s); must be < STM32 HB timeout (0.5s)"),
|
<<<<<<< HEAD
|
||||||
|
description="Heartbeat interval (s); must be < ESP32 BALANCE HB timeout (0.5s)"),
|
||||||
|
=======
|
||||||
|
description="Heartbeat interval (s); must be < ESP32-S3 HB timeout (0.5s)"),
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
DeclareLaunchArgument(
|
DeclareLaunchArgument(
|
||||||
"max_linear_vel", default_value="0.5",
|
"max_linear_vel", default_value="0.5",
|
||||||
description="Hard speed cap before scaling (m/s)"),
|
description="Hard speed cap before scaling (m/s)"),
|
||||||
|
|||||||
@ -0,0 +1,60 @@
|
|||||||
|
<<<<<<< HEAD:jetson/ros2_ws/src/saltybot_bridge/launch/stm32_cmd.launch.py
|
||||||
|
"""stm32_cmd.launch.py — Launch the ESP32-S3 IO auxiliary bridge node.
|
||||||
|
|
||||||
|
Connects to ESP32-S3 IO board via USB-CDC @ 460800 baud (inter-board protocol).
|
||||||
|
Handles RC monitoring, sensor data, LED/output commands.
|
||||||
|
Primary drive path uses CAN (can_bridge_node / saltybot_can_node), not this node.
|
||||||
|
|
||||||
|
Spec: docs/SAUL-TEE-SYSTEM-REFERENCE.md §5
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
ros2 launch saltybot_bridge stm32_cmd.launch.py
|
||||||
|
ros2 launch saltybot_bridge stm32_cmd.launch.py serial_port:=/dev/ttyACM0
|
||||||
|
=======
|
||||||
|
"""esp32_cmd.launch.py — Launch the binary-framed ESP32-S3 command node (Issue #119).
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
# Default (binary protocol, bidirectional):
|
||||||
|
ros2 launch saltybot_bridge esp32_cmd.launch.py
|
||||||
|
|
||||||
|
# Override serial port:
|
||||||
|
ros2 launch saltybot_bridge esp32_cmd.launch.py serial_port:=/dev/ttyACM1
|
||||||
|
|
||||||
|
# Custom velocity scales:
|
||||||
|
ros2 launch saltybot_bridge esp32_cmd.launch.py speed_scale:=800.0 steer_scale:=-400.0
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only):jetson/ros2_ws/src/saltybot_bridge/launch/esp32_cmd.launch.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from ament_index_python.packages import get_package_share_directory
|
||||||
|
from launch import LaunchDescription
|
||||||
|
from launch.actions import DeclareLaunchArgument
|
||||||
|
from launch.substitutions import LaunchConfiguration
|
||||||
|
from launch_ros.actions import Node
|
||||||
|
|
||||||
|
|
||||||
|
def generate_launch_description() -> LaunchDescription:
|
||||||
|
pkg = get_package_share_directory("saltybot_bridge")
|
||||||
|
params_file = os.path.join(pkg, "config", "esp32_cmd_params.yaml")
|
||||||
|
|
||||||
|
return LaunchDescription([
|
||||||
|
DeclareLaunchArgument("serial_port", default_value="/dev/esp32-io"),
|
||||||
|
DeclareLaunchArgument("baud_rate", default_value="460800"),
|
||||||
|
DeclareLaunchArgument("heartbeat_period", default_value="0.2"),
|
||||||
|
|
||||||
|
Node(
|
||||||
|
package="saltybot_bridge",
|
||||||
|
executable="esp32_cmd_node",
|
||||||
|
name="esp32_cmd_node",
|
||||||
|
output="screen",
|
||||||
|
emulate_tty=True,
|
||||||
|
parameters=[
|
||||||
|
params_file,
|
||||||
|
{
|
||||||
|
"serial_port": LaunchConfiguration("serial_port"),
|
||||||
|
"baud_rate": LaunchConfiguration("baud_rate"),
|
||||||
|
"heartbeat_period": LaunchConfiguration("heartbeat_period"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
),
|
||||||
|
])
|
||||||
@ -1,52 +0,0 @@
|
|||||||
"""stm32_cmd.launch.py — Launch the binary-framed STM32 command node (Issue #119).
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
# Default (binary protocol, bidirectional):
|
|
||||||
ros2 launch saltybot_bridge stm32_cmd.launch.py
|
|
||||||
|
|
||||||
# Override serial port:
|
|
||||||
ros2 launch saltybot_bridge stm32_cmd.launch.py serial_port:=/dev/ttyACM1
|
|
||||||
|
|
||||||
# Custom velocity scales:
|
|
||||||
ros2 launch saltybot_bridge stm32_cmd.launch.py speed_scale:=800.0 steer_scale:=-400.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
from ament_index_python.packages import get_package_share_directory
|
|
||||||
from launch import LaunchDescription
|
|
||||||
from launch.actions import DeclareLaunchArgument
|
|
||||||
from launch.substitutions import LaunchConfiguration
|
|
||||||
from launch_ros.actions import Node
|
|
||||||
|
|
||||||
|
|
||||||
def generate_launch_description() -> LaunchDescription:
|
|
||||||
pkg = get_package_share_directory("saltybot_bridge")
|
|
||||||
params_file = os.path.join(pkg, "config", "stm32_cmd_params.yaml")
|
|
||||||
|
|
||||||
return LaunchDescription([
|
|
||||||
DeclareLaunchArgument("serial_port", default_value="/dev/ttyACM0"),
|
|
||||||
DeclareLaunchArgument("baud_rate", default_value="921600"),
|
|
||||||
DeclareLaunchArgument("speed_scale", default_value="1000.0"),
|
|
||||||
DeclareLaunchArgument("steer_scale", default_value="-500.0"),
|
|
||||||
DeclareLaunchArgument("watchdog_timeout", default_value="0.5"),
|
|
||||||
DeclareLaunchArgument("heartbeat_period", default_value="0.2"),
|
|
||||||
|
|
||||||
Node(
|
|
||||||
package="saltybot_bridge",
|
|
||||||
executable="stm32_cmd_node",
|
|
||||||
name="stm32_cmd_node",
|
|
||||||
output="screen",
|
|
||||||
emulate_tty=True,
|
|
||||||
parameters=[
|
|
||||||
params_file,
|
|
||||||
{
|
|
||||||
"serial_port": LaunchConfiguration("serial_port"),
|
|
||||||
"baud_rate": LaunchConfiguration("baud_rate"),
|
|
||||||
"speed_scale": LaunchConfiguration("speed_scale"),
|
|
||||||
"steer_scale": LaunchConfiguration("steer_scale"),
|
|
||||||
"watchdog_timeout": LaunchConfiguration("watchdog_timeout"),
|
|
||||||
"heartbeat_period": LaunchConfiguration("heartbeat_period"),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
),
|
|
||||||
])
|
|
||||||
@ -2,7 +2,11 @@
|
|||||||
uart_bridge.launch.py — FC↔Orin UART bridge (Issue #362)
|
uart_bridge.launch.py — FC↔Orin UART bridge (Issue #362)
|
||||||
|
|
||||||
Launches serial_bridge_node configured for Jetson Orin UART port.
|
Launches serial_bridge_node configured for Jetson Orin UART port.
|
||||||
Bridges Flight Controller (STM32F722) telemetry from /dev/ttyTHS1 into ROS2.
|
<<<<<<< HEAD
|
||||||
|
Bridges Flight Controller (ESP32) telemetry from /dev/ttyTHS1 into ROS2.
|
||||||
|
=======
|
||||||
|
Bridges Flight Controller (ESP32-S3) telemetry from /dev/ttyTHS1 into ROS2.
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
|
|
||||||
Published topics (same as USB CDC bridge):
|
Published topics (same as USB CDC bridge):
|
||||||
/saltybot/imu sensor_msgs/Imu — pitch/roll/yaw as angular velocity
|
/saltybot/imu sensor_msgs/Imu — pitch/roll/yaw as angular velocity
|
||||||
@ -20,7 +24,11 @@ Usage:
|
|||||||
|
|
||||||
Prerequisites:
|
Prerequisites:
|
||||||
- Flight Controller connected to /dev/ttyTHS1 @ 921600 baud
|
- Flight Controller connected to /dev/ttyTHS1 @ 921600 baud
|
||||||
- STM32 firmware transmitting JSON telemetry frames (50 Hz)
|
<<<<<<< HEAD
|
||||||
|
- ESP32 BALANCE firmware transmitting JSON telemetry frames (50 Hz)
|
||||||
|
=======
|
||||||
|
- ESP32-S3 firmware transmitting JSON telemetry frames (50 Hz)
|
||||||
|
>>>>>>> 291dd68 (feat: remove all STM32/Mamba/BlackPill references — ESP32-S3 only)
|
||||||
- ROS2 environment sourced (source install/setup.bash)
|
- ROS2 environment sourced (source install/setup.bash)
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
|
|||||||
@ -4,9 +4,9 @@
|
|||||||
<name>saltybot_bridge</name>
|
<name>saltybot_bridge</name>
|
||||||
<version>0.1.0</version>
|
<version>0.1.0</version>
|
||||||
<description>
|
<description>
|
||||||
STM32F722 USB CDC serial bridge for saltybot.
|
ESP32-S3 USB CDC serial bridge for saltybot.
|
||||||
serial_bridge_node: JSON telemetry RX → sensor_msgs/Imu + diagnostics.
|
serial_bridge_node: JSON telemetry RX → sensor_msgs/Imu + diagnostics.
|
||||||
stm32_cmd_node (Issue #119): binary-framed protocol — STX/TYPE/LEN/CRC16/ETX,
|
esp32_cmd_node (Issue #119): binary-framed protocol — STX/TYPE/LEN/CRC16/ETX,
|
||||||
commands: HEARTBEAT, SPEED_STEER, ARM, SET_MODE, PID_UPDATE;
|
commands: HEARTBEAT, SPEED_STEER, ARM, SET_MODE, PID_UPDATE;
|
||||||
telemetry: IMU, BATTERY, MOTOR_RPM, ARM_STATE, ERROR; watchdog 500ms.
|
telemetry: IMU, BATTERY, MOTOR_RPM, ARM_STATE, ERROR; watchdog 500ms.
|
||||||
battery_node (Issue #125): SoC tracking, threshold alerts, SQLite history.
|
battery_node (Issue #125): SoC tracking, threshold alerts, SQLite history.
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user