mirror of
https://github.com/legop3/MultiRoombaRover.git
synced 2026-11-16 19:52:17 -05:00
Compare commits
60
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0de727d3e | ||
|
|
9b6bdec116 | ||
|
|
6b57ac1725 | ||
|
|
00cd125fda | ||
|
|
684acdd2b6 | ||
|
|
f138cd7b96 | ||
|
|
6454a9b460 | ||
|
|
1976377235 | ||
|
|
52c171c256 | ||
|
|
42bf67d207 | ||
|
|
d65fd99de4 | ||
|
|
e3d4d9af9b | ||
|
|
ab730ee8a3 | ||
|
|
8fe4f2f98e | ||
|
|
89f3a1cb65 | ||
|
|
79d36cae93 | ||
|
|
1dcd7e5d7d | ||
|
|
b4bc99ab27 | ||
|
|
c94e1a0508 | ||
|
|
abcb0871b2 | ||
|
|
1ffe680895 | ||
|
|
ed26b90384 | ||
|
|
2b48fee00f | ||
|
|
1284125fff | ||
|
|
28d0b1437d | ||
|
|
9d3b8df4bf | ||
|
|
9d42cb5581 | ||
|
|
e670226f8c | ||
|
|
0669f29a4a | ||
|
|
38d3465bf8 | ||
|
|
6bfbb8ad80 | ||
|
|
ba2f66ebc1 | ||
|
|
fde2fca0a0 | ||
|
|
d36ea4f672 | ||
|
|
4be6e6c9a2 | ||
|
|
7bac2fc447 | ||
|
|
e8a407cd49 | ||
|
|
bee1866a70 | ||
|
|
ddfc889a8c | ||
|
|
c71267873a | ||
|
|
1ba4ebe5ff | ||
|
|
607d327e9c | ||
|
|
1bdca60648 | ||
|
|
ea4af2ebb3 | ||
|
|
b2bbaf2085 | ||
|
|
18e7fb8d1b | ||
|
|
ba71106544 | ||
|
|
a395656056 | ||
|
|
50c2c1f5db | ||
|
|
b59389870e | ||
|
|
cd4aee4e74 | ||
|
|
9de0bfb1e7 | ||
|
|
008c90edf1 | ||
|
|
eed88983ca | ||
|
|
923c04736b | ||
|
|
bdc3eb640d | ||
|
|
01354c56e6 | ||
|
|
0ff03a74a5 | ||
|
|
73a78eef20 | ||
|
|
a157ece816 |
@@ -5,6 +5,7 @@
|
||||
.git
|
||||
.gitignore
|
||||
**/node_modules
|
||||
webui/.cache/mediamtx/
|
||||
# Neither the legacy state directory nor the Compose-mounted replacement may
|
||||
# enter an image build. This prevents credentials and backups from becoming
|
||||
# image layers after an operator has started using either deployment layout.
|
||||
|
||||
@@ -58,6 +58,8 @@ jobs:
|
||||
# replaced on each successful push, just as main replaces `latest`.
|
||||
- name: Build and optionally publish
|
||||
uses: docker/build-push-action@v7
|
||||
env:
|
||||
DOCKER_BUILD_RECORD_RETENTION_DAYS: 3
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64
|
||||
|
||||
@@ -5,6 +5,7 @@ create_2_Open_Interface_Spec.txt
|
||||
|
||||
logs
|
||||
node_modules/
|
||||
webui/.cache/mediamtx/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pio
|
||||
@@ -41,3 +42,4 @@ server/data/fleet-reports.sqlite-wal
|
||||
server/data/configuration.sqlite
|
||||
server/data/configuration.sqlite-shm
|
||||
server/data/configuration.sqlite-wal
|
||||
AGENTS.md
|
||||
|
||||
+43
-19
@@ -9,15 +9,21 @@
|
||||
ARG FEDORA_VERSION=43
|
||||
|
||||
FROM fedora:${FEDORA_VERSION} AS architecture-check
|
||||
ARG FEDORA_VERSION
|
||||
ARG TARGETARCH
|
||||
# The central server is currently deployed and verified only on amd64. Failing
|
||||
# here avoids publishing an ARM image whose native workers and hardware paths
|
||||
# have never been exercised on a real ARM server.
|
||||
RUN test "${TARGETARCH}" = "amd64" || (echo "MultiRover server images support only linux/amd64." >&2; exit 1)
|
||||
|
||||
FROM architecture-check AS webui-build
|
||||
RUN dnf install -y --setopt=install_weak_deps=False nodejs npm \
|
||||
&& dnf clean all
|
||||
# Both Node builders reuse the same installed toolchain layer.
|
||||
# Fedora 43 uses DNF5. Cache metadata and RPMs outside image layers, and keep
|
||||
# downloads after installation so invalidated layers can reuse them.
|
||||
FROM architecture-check AS node-build-base
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-node-build-base,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True nodejs npm
|
||||
|
||||
FROM node-build-base AS webui-build
|
||||
WORKDIR /build
|
||||
# Copy dependency manifests first so ordinary source edits retain the expensive
|
||||
# npm cache layer. npm ci makes the checked-in lockfile the exact dependency
|
||||
@@ -25,14 +31,17 @@ WORKDIR /build
|
||||
COPY webui/package.json webui/package-lock.json ./webui/
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
cd webui && npm ci
|
||||
# Keep the pinned browser publisher in a reusable layer across UI source edits.
|
||||
COPY webui/scripts/prepareMediaMtx.js ./webui/scripts/prepareMediaMtx.js
|
||||
RUN cd webui && node scripts/prepareMediaMtx.js
|
||||
COPY webui ./webui
|
||||
# Vite deliberately emits into ../server/public. Create that destination in the
|
||||
# isolated builder and copy only its finished files into the runtime stage.
|
||||
RUN mkdir -p server/public && cd webui && npm run build
|
||||
|
||||
FROM architecture-check AS server-dependencies
|
||||
RUN dnf install -y --setopt=install_weak_deps=False nodejs npm gcc-c++ make python3 \
|
||||
&& dnf clean all
|
||||
FROM node-build-base AS server-dependencies
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-server-dependencies,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True gcc-c++ make python3
|
||||
WORKDIR /build/server
|
||||
COPY server/package.json server/package-lock.json ./
|
||||
# Native Node modules compile here when a matching prebuild is unavailable;
|
||||
@@ -41,7 +50,8 @@ RUN --mount=type=cache,target=/root/.npm \
|
||||
npm ci --omit=dev
|
||||
|
||||
FROM architecture-check AS native-workers
|
||||
RUN dnf install -y --setopt=install_weak_deps=False \
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-native-workers,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True \
|
||||
bluez-libs-devel \
|
||||
gcc-c++ \
|
||||
libcap \
|
||||
@@ -49,8 +59,7 @@ RUN dnf install -y --setopt=install_weak_deps=False \
|
||||
libusb1-devel \
|
||||
make \
|
||||
pkgconf-pkg-config \
|
||||
wiiuse-devel \
|
||||
&& dnf clean all
|
||||
wiiuse-devel
|
||||
WORKDIR /build
|
||||
COPY server/src/services/kinectService/native ./kinect
|
||||
COPY server/src/services/balanceBoardService/native ./balance-board
|
||||
@@ -66,8 +75,8 @@ ARG NEOLINK_VERSION=0.6.2
|
||||
ARG NEOLINK_SHA256=0cb963b44dca7ccc5333154092186e1536c687aef0e1ad119b7f310a7471dbbb
|
||||
ARG GOOGLE_TTS_VERSION=26.5
|
||||
ARG GOOGLE_TTS_SHA256=6a9eae6726871788da52e767dad964a1c83e7feb7e7dbac508a2574a2345ac24
|
||||
RUN dnf install -y --setopt=install_weak_deps=False curl findutils tar unzip xz \
|
||||
&& dnf clean all
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-packaged-tools,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True curl findutils tar unzip xz
|
||||
WORKDIR /build/tools
|
||||
# Each external artifact is pinned and checked before extraction. A changed or
|
||||
# truncated upstream download therefore fails the image build instead of being
|
||||
@@ -97,6 +106,16 @@ RUN curl --fail --location --retry 3 \
|
||||
&& find /output/opt/roverd/googletts -type d -exec chmod 0755 {} + \
|
||||
&& find /output/opt/roverd/googletts -type f -exec chmod 0644 {} +
|
||||
|
||||
FROM architecture-check AS learning-dependencies
|
||||
# CPU-only learning dependencies are built once. Disabled installations never
|
||||
# launch Python or install packages as a side effect of starting Node.
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-learning-dependencies,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True python3 python3-pip
|
||||
COPY server/src/services/roverLearningService/workers/requirements.txt /tmp/learning-requirements.txt
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
python3 -m venv /opt/rover-learning \
|
||||
&& /opt/rover-learning/bin/pip install -r /tmp/learning-requirements.txt
|
||||
|
||||
FROM fedora:${FEDORA_VERSION} AS runtime
|
||||
ARG FEDORA_VERSION
|
||||
ARG TARGETARCH
|
||||
@@ -105,14 +124,16 @@ RUN test "${TARGETARCH}" = "amd64" || (echo "MultiRover server images support on
|
||||
# replay output path. Enable RPM Fusion Free before installing runtime packages
|
||||
# so the image receives the complete FFmpeg build instead of requiring replay
|
||||
# code to work around a deployment-only codec omission.
|
||||
RUN dnf install -y --setopt=install_weak_deps=False \
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-runtime,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True \
|
||||
"https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-${FEDORA_VERSION}.noarch.rpm"
|
||||
# This is the complete runtime package set. Build headers and compilers live in
|
||||
# earlier stages, while media, TTS, USB, and Bluetooth libraries remain here
|
||||
# because enabled services invoke them after startup. Weak dependencies are
|
||||
# deliberately disabled: Fedora otherwise installs desktop portals, graphical
|
||||
# themes, and GPU drivers that a headless server neither starts nor uses.
|
||||
RUN dnf install -y --setopt=install_weak_deps=False \
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-runtime,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True \
|
||||
bluez \
|
||||
bluez-libs \
|
||||
espeak \
|
||||
@@ -134,20 +155,15 @@ RUN dnf install -y --setopt=install_weak_deps=False \
|
||||
tini \
|
||||
wiiuse \
|
||||
--allowerasing \
|
||||
&& dnf clean all \
|
||||
&& useradd --uid 1000 --create-home --home-dir /home/multirover --shell /sbin/nologin multirover \
|
||||
&& install -d -o multirover -g multirover -m 0755 /data /opt/multirover/server
|
||||
|
||||
WORKDIR /opt/multirover/server
|
||||
COPY server/index.js server/package.json server/package-lock.json ./
|
||||
COPY server/src ./src
|
||||
COPY server/assets ./assets
|
||||
COPY server/prompts ./prompts
|
||||
COPY --from=server-dependencies /build/server/node_modules ./node_modules
|
||||
COPY --from=webui-build /build/server/public ./public
|
||||
COPY --from=native-workers /build/kinect/kinect_worker ./src/services/kinectService/native/kinect_worker
|
||||
COPY --from=native-workers /build/balance-board/balance_board_worker ./src/services/balanceBoardService/native/balance_board_worker
|
||||
COPY --from=packaged-tools /output/ /
|
||||
COPY --from=learning-dependencies /opt/rover-learning /opt/rover-learning
|
||||
COPY --chmod=0755 server/bin/chromegtts-wav.py /usr/local/bin/chromegtts-wav
|
||||
COPY --chmod=0755 server/mediamtx/rover-snapshot-writer.sh /usr/local/bin/rover-snapshot-writer.sh
|
||||
|
||||
@@ -166,6 +182,14 @@ RUN setcap cap_net_admin,cap_net_bind_service+ep \
|
||||
&& test -s /tmp/chromegtts-smoke.wav \
|
||||
&& rm /tmp/chromegtts-smoke.wav
|
||||
|
||||
# Frequently edited application files come after dependencies and tool checks,
|
||||
# so server changes do not invalidate the large runtime dependency layers.
|
||||
COPY --from=webui-build /build/server/public ./public
|
||||
COPY server/index.js server/package.json server/package-lock.json ./
|
||||
COPY server/src ./src
|
||||
COPY server/assets ./assets
|
||||
COPY server/prompts ./prompts
|
||||
|
||||
ENV NODE_ENV=production \
|
||||
SERVER_DATA_DIR=/data \
|
||||
ROVER_SNAPSHOT_WRITER_BIN=/usr/local/bin/rover-snapshot-writer.sh
|
||||
|
||||
@@ -64,11 +64,24 @@ To install roverd on your pi:
|
||||
1. Install `Raspberry Pi OS (Legacy) Lite` (exactly what its called in the imager) on your SD card
|
||||
2. Boot the pi up, plug in your good wifi adapter, use `nmtui` to set it up
|
||||
3. Install `git`, clone this repo into your home folder
|
||||
4. Move into the repo folder, run the roverd installer using `sudo pi/install_roverd.sh`
|
||||
4. Move into the repo folder, run the roverd installer using `sudo rover/install_roverd.sh`
|
||||
5. Reboot your raspberry pi
|
||||
6. Roverd, along with the audio and video publishers should now be running. Roverd should have created it's default config file at `/etc/roverd.yaml`
|
||||
6. Roverd, along with the audio and video publishers should now be running. Roverd should have created it's default config file at `/etc/roverd.json`
|
||||
|
||||
Edit the `/etc/roverd.yaml` config file to change settings like your rover's name, color, and set the server IP.
|
||||
Edit the `/etc/roverd.json` config file to change settings like your rover's name, color, and set the server IP.
|
||||
|
||||
Configuration is now a complete JSON object. See [roverd management](docs/roverd-management.md)
|
||||
for schema/default export, local validation, the management API, and deployment checks.
|
||||
|
||||
The roverd rework is in progress; see the [implementation tracker](docs/roverd-rework-plan.md).
|
||||
Native GPIO now lives under `piGpio`, with its parent `enabled` switch disabled by default.
|
||||
Enable that switch only on hosts using the internal Pi GPIO peripheral, and configure its camera servo, headlight, laser, and BRC children there.
|
||||
See [hardware configuration notes](docs/rover-hardware-config.md) for the existing AIY Voice HAT setup and pin constraints.
|
||||
|
||||
Build rover binaries with `make -C rover/roverd all`, or select one architecture with
|
||||
`make -C rover/roverd build ARCH=armv6` (also `armv7`, `arm64`, or `amd64`).
|
||||
Artifacts are `dist/roverd-linux-<architecture>` and remain in the repository.
|
||||
These builds share the same configuration and peripheral support; there is no laptop-specific build.
|
||||
|
||||
|
||||
## Setting up the server
|
||||
|
||||
+5
-1
@@ -23,9 +23,13 @@ services:
|
||||
# Required for Bluetooth hardware such as the Balance Board.
|
||||
- /run/dbus/system_bus_socket:/run/dbus/system_bus_socket:ro
|
||||
|
||||
# Required for Kinect USB access.
|
||||
# Kinect USB access.
|
||||
devices:
|
||||
- /dev/bus/usb:/dev/bus/usb
|
||||
# For a server-local microphone, uncomment this device and group_add below.
|
||||
# - /dev/snd:/dev/snd
|
||||
# group_add:
|
||||
# - "${AUDIO_GID:?Set AUDIO_GID to the host sound device group ID}"
|
||||
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
|
||||
Vendored
+127
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"piGpio": {
|
||||
"enabled": false,
|
||||
"brc": {
|
||||
"enabled": true,
|
||||
"gpioPin": 4,
|
||||
"gpioChip": "gpiochip0",
|
||||
"pulseEvery": "1m0s",
|
||||
"pulseWidth": "1s"
|
||||
},
|
||||
"cameraServo": {
|
||||
"enabled": false,
|
||||
"pin": 12,
|
||||
"freqHz": 50,
|
||||
"cycleLen": 20000,
|
||||
"minPulseUs": 900,
|
||||
"maxPulseUs": 2100,
|
||||
"minAngle": -15,
|
||||
"maxAngle": 30,
|
||||
"homeAngle": 0,
|
||||
"nudgeDegrees": 2,
|
||||
"allowRawPulse": false,
|
||||
"invert": false
|
||||
},
|
||||
"headlight": {
|
||||
"enabled": true,
|
||||
"gpioPin": 22,
|
||||
"gpioChip": "gpiochip0",
|
||||
"initialOn": false,
|
||||
"activeLow": true
|
||||
},
|
||||
"laser": {
|
||||
"enabled": false,
|
||||
"gpioPin": 27,
|
||||
"gpioChip": "gpiochip0",
|
||||
"initialOn": false,
|
||||
"activeLow": false
|
||||
}
|
||||
},
|
||||
"name": "dummy1",
|
||||
"description": "",
|
||||
"color": "",
|
||||
"serverUrl": "ws://127.0.0.1:8080/rover",
|
||||
"serial": {
|
||||
"device": "/dev/ttyS0",
|
||||
"baud": 115200
|
||||
},
|
||||
"battery": {
|
||||
"full": 2068,
|
||||
"warn": 1700,
|
||||
"urgent": 1650
|
||||
},
|
||||
"maxWheelSpeed": 350,
|
||||
"media": {
|
||||
"rtspPort": 8554,
|
||||
"manage": false,
|
||||
"healthUrl": "http://127.0.0.1:9997/v3/paths/list",
|
||||
"healthInterval": "30s",
|
||||
"video": {
|
||||
"enabled": true,
|
||||
"service": "video-publisher.service",
|
||||
"publisher": "pi-libcamera",
|
||||
"device": "",
|
||||
"inputFormat": "",
|
||||
"width": 640,
|
||||
"height": 480,
|
||||
"fps": 30,
|
||||
"bitrate": 2000000,
|
||||
"inverted": true,
|
||||
"sensorMode": "1296:972"
|
||||
},
|
||||
"audioCapture": {
|
||||
"enabled": false,
|
||||
"service": "audio-only-publisher.service",
|
||||
"device": "hw:0,0",
|
||||
"sampleRate": 48000,
|
||||
"channels": 2,
|
||||
"bitrate": 510000
|
||||
},
|
||||
"audioPlayback": {
|
||||
"enabled": true,
|
||||
"service": "audio-forward-listener.service",
|
||||
"device": "forward",
|
||||
"normalize": true,
|
||||
"normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled"
|
||||
}
|
||||
},
|
||||
"audio": {
|
||||
"ttsEnabled": false,
|
||||
"defaultEngine": "flite",
|
||||
"defaultVoice": "rms",
|
||||
"defaultPitch": 50
|
||||
},
|
||||
"horn": {
|
||||
"enabled": false,
|
||||
"volume": 0.25,
|
||||
"sampleRate": 48000,
|
||||
"channels": 1,
|
||||
"device": "",
|
||||
"sineGain": 1,
|
||||
"sawGain": 0.7,
|
||||
"maxDuration": "10s"
|
||||
},
|
||||
"autoSideBrush": {
|
||||
"enabled": true,
|
||||
"speed": 20
|
||||
},
|
||||
"private": {
|
||||
"enabled": false,
|
||||
"safety": {
|
||||
"speedLimitEnabled": false,
|
||||
"speedLimitMaxWheelSpeed": 250,
|
||||
"hardOvercurrentEnabled": false,
|
||||
"overcurrentStopMs": 300,
|
||||
"hardBumpEnabled": false,
|
||||
"bumpBackoffSpeed": 250,
|
||||
"bumpBackoffMs": 350,
|
||||
"cliffEnabled": false,
|
||||
"cliffBackoffSpeed": 250,
|
||||
"cliffBackoffMs": 500,
|
||||
"virtualWallEnabled": true,
|
||||
"virtualWallBackoffSpeed": 250,
|
||||
"virtualWallBackoffMs": 500,
|
||||
"triggerCooldownMs": 800
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
-24
@@ -1,24 +0,0 @@
|
||||
#configuration for roverd
|
||||
name: dummy1
|
||||
serverUrl: ws://127.0.0.1:8080/rover
|
||||
serial:
|
||||
device: /dev/ttyS0
|
||||
baud: 115200
|
||||
brc:
|
||||
gpioPin: 25
|
||||
pulseEvery: 1m
|
||||
pulseWidth: 1s
|
||||
battery:
|
||||
full: 2068
|
||||
warn: 1700
|
||||
urgent: 1650
|
||||
maxWheelSpeed: 350
|
||||
media:
|
||||
manage: false
|
||||
service: mediamtx.service
|
||||
healthUrl: http://127.0.0.1:9997/v3/paths/list
|
||||
healthInterval: 30s
|
||||
headlight:
|
||||
enabled: false
|
||||
laser:
|
||||
enabled: false
|
||||
Vendored
+127
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"piGpio": {
|
||||
"enabled": false,
|
||||
"brc": {
|
||||
"enabled": true,
|
||||
"gpioPin": 4,
|
||||
"gpioChip": "gpiochip0",
|
||||
"pulseEvery": "1m0s",
|
||||
"pulseWidth": "1s"
|
||||
},
|
||||
"cameraServo": {
|
||||
"enabled": false,
|
||||
"pin": 12,
|
||||
"freqHz": 50,
|
||||
"cycleLen": 20000,
|
||||
"minPulseUs": 900,
|
||||
"maxPulseUs": 2100,
|
||||
"minAngle": -15,
|
||||
"maxAngle": 30,
|
||||
"homeAngle": 0,
|
||||
"nudgeDegrees": 2,
|
||||
"allowRawPulse": false,
|
||||
"invert": false
|
||||
},
|
||||
"headlight": {
|
||||
"enabled": true,
|
||||
"gpioPin": 22,
|
||||
"gpioChip": "gpiochip0",
|
||||
"initialOn": false,
|
||||
"activeLow": true
|
||||
},
|
||||
"laser": {
|
||||
"enabled": false,
|
||||
"gpioPin": 27,
|
||||
"gpioChip": "gpiochip0",
|
||||
"initialOn": false,
|
||||
"activeLow": false
|
||||
}
|
||||
},
|
||||
"name": "dummy2",
|
||||
"description": "",
|
||||
"color": "",
|
||||
"serverUrl": "ws://127.0.0.1:8080/rover",
|
||||
"serial": {
|
||||
"device": "/dev/ttyS0",
|
||||
"baud": 115200
|
||||
},
|
||||
"battery": {
|
||||
"full": 2068,
|
||||
"warn": 1700,
|
||||
"urgent": 1650
|
||||
},
|
||||
"maxWheelSpeed": 350,
|
||||
"media": {
|
||||
"rtspPort": 8554,
|
||||
"manage": false,
|
||||
"healthUrl": "http://127.0.0.1:9997/v3/paths/list",
|
||||
"healthInterval": "30s",
|
||||
"video": {
|
||||
"enabled": true,
|
||||
"service": "video-publisher.service",
|
||||
"publisher": "pi-libcamera",
|
||||
"device": "",
|
||||
"inputFormat": "",
|
||||
"width": 640,
|
||||
"height": 480,
|
||||
"fps": 30,
|
||||
"bitrate": 2000000,
|
||||
"inverted": true,
|
||||
"sensorMode": "1296:972"
|
||||
},
|
||||
"audioCapture": {
|
||||
"enabled": false,
|
||||
"service": "audio-only-publisher.service",
|
||||
"device": "hw:0,0",
|
||||
"sampleRate": 48000,
|
||||
"channels": 2,
|
||||
"bitrate": 510000
|
||||
},
|
||||
"audioPlayback": {
|
||||
"enabled": true,
|
||||
"service": "audio-forward-listener.service",
|
||||
"device": "forward",
|
||||
"normalize": true,
|
||||
"normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled"
|
||||
}
|
||||
},
|
||||
"audio": {
|
||||
"ttsEnabled": false,
|
||||
"defaultEngine": "flite",
|
||||
"defaultVoice": "rms",
|
||||
"defaultPitch": 50
|
||||
},
|
||||
"horn": {
|
||||
"enabled": false,
|
||||
"volume": 0.25,
|
||||
"sampleRate": 48000,
|
||||
"channels": 1,
|
||||
"device": "",
|
||||
"sineGain": 1,
|
||||
"sawGain": 0.7,
|
||||
"maxDuration": "10s"
|
||||
},
|
||||
"autoSideBrush": {
|
||||
"enabled": true,
|
||||
"speed": 20
|
||||
},
|
||||
"private": {
|
||||
"enabled": false,
|
||||
"safety": {
|
||||
"speedLimitEnabled": false,
|
||||
"speedLimitMaxWheelSpeed": 250,
|
||||
"hardOvercurrentEnabled": false,
|
||||
"overcurrentStopMs": 300,
|
||||
"hardBumpEnabled": false,
|
||||
"bumpBackoffSpeed": 250,
|
||||
"bumpBackoffMs": 350,
|
||||
"cliffEnabled": false,
|
||||
"cliffBackoffSpeed": 250,
|
||||
"cliffBackoffMs": 500,
|
||||
"virtualWallEnabled": true,
|
||||
"virtualWallBackoffSpeed": 250,
|
||||
"virtualWallBackoffMs": 500,
|
||||
"triggerCooldownMs": 800
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
-24
@@ -1,24 +0,0 @@
|
||||
#configuration for roverd
|
||||
name: dummy2
|
||||
serverUrl: ws://127.0.0.1:8080/rover
|
||||
serial:
|
||||
device: /dev/ttyS0
|
||||
baud: 115200
|
||||
brc:
|
||||
gpioPin: 25
|
||||
pulseEvery: 1m
|
||||
pulseWidth: 1s
|
||||
battery:
|
||||
full: 2068
|
||||
warn: 1700
|
||||
urgent: 1650
|
||||
maxWheelSpeed: 350
|
||||
media:
|
||||
manage: false
|
||||
service: mediamtx.service
|
||||
healthUrl: http://127.0.0.1:9997/v3/paths/list
|
||||
healthInterval: 30s
|
||||
headlight:
|
||||
enabled: false
|
||||
laser:
|
||||
enabled: false
|
||||
Vendored
+127
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"piGpio": {
|
||||
"enabled": false,
|
||||
"brc": {
|
||||
"enabled": true,
|
||||
"gpioPin": 4,
|
||||
"gpioChip": "gpiochip0",
|
||||
"pulseEvery": "1m0s",
|
||||
"pulseWidth": "1s"
|
||||
},
|
||||
"cameraServo": {
|
||||
"enabled": false,
|
||||
"pin": 12,
|
||||
"freqHz": 50,
|
||||
"cycleLen": 20000,
|
||||
"minPulseUs": 900,
|
||||
"maxPulseUs": 2100,
|
||||
"minAngle": -15,
|
||||
"maxAngle": 30,
|
||||
"homeAngle": 0,
|
||||
"nudgeDegrees": 2,
|
||||
"allowRawPulse": false,
|
||||
"invert": false
|
||||
},
|
||||
"headlight": {
|
||||
"enabled": true,
|
||||
"gpioPin": 22,
|
||||
"gpioChip": "gpiochip0",
|
||||
"initialOn": false,
|
||||
"activeLow": true
|
||||
},
|
||||
"laser": {
|
||||
"enabled": false,
|
||||
"gpioPin": 27,
|
||||
"gpioChip": "gpiochip0",
|
||||
"initialOn": false,
|
||||
"activeLow": false
|
||||
}
|
||||
},
|
||||
"name": "dummy3",
|
||||
"description": "",
|
||||
"color": "",
|
||||
"serverUrl": "ws://127.0.0.1:8080/rover",
|
||||
"serial": {
|
||||
"device": "/dev/ttyS0",
|
||||
"baud": 115200
|
||||
},
|
||||
"battery": {
|
||||
"full": 2068,
|
||||
"warn": 1700,
|
||||
"urgent": 1650
|
||||
},
|
||||
"maxWheelSpeed": 350,
|
||||
"media": {
|
||||
"rtspPort": 8554,
|
||||
"manage": false,
|
||||
"healthUrl": "http://127.0.0.1:9997/v3/paths/list",
|
||||
"healthInterval": "30s",
|
||||
"video": {
|
||||
"enabled": true,
|
||||
"service": "video-publisher.service",
|
||||
"publisher": "pi-libcamera",
|
||||
"device": "",
|
||||
"inputFormat": "",
|
||||
"width": 640,
|
||||
"height": 480,
|
||||
"fps": 30,
|
||||
"bitrate": 2000000,
|
||||
"inverted": true,
|
||||
"sensorMode": "1296:972"
|
||||
},
|
||||
"audioCapture": {
|
||||
"enabled": false,
|
||||
"service": "audio-only-publisher.service",
|
||||
"device": "hw:0,0",
|
||||
"sampleRate": 48000,
|
||||
"channels": 2,
|
||||
"bitrate": 510000
|
||||
},
|
||||
"audioPlayback": {
|
||||
"enabled": true,
|
||||
"service": "audio-forward-listener.service",
|
||||
"device": "forward",
|
||||
"normalize": true,
|
||||
"normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled"
|
||||
}
|
||||
},
|
||||
"audio": {
|
||||
"ttsEnabled": false,
|
||||
"defaultEngine": "flite",
|
||||
"defaultVoice": "rms",
|
||||
"defaultPitch": 50
|
||||
},
|
||||
"horn": {
|
||||
"enabled": false,
|
||||
"volume": 0.25,
|
||||
"sampleRate": 48000,
|
||||
"channels": 1,
|
||||
"device": "",
|
||||
"sineGain": 1,
|
||||
"sawGain": 0.7,
|
||||
"maxDuration": "10s"
|
||||
},
|
||||
"autoSideBrush": {
|
||||
"enabled": true,
|
||||
"speed": 20
|
||||
},
|
||||
"private": {
|
||||
"enabled": false,
|
||||
"safety": {
|
||||
"speedLimitEnabled": false,
|
||||
"speedLimitMaxWheelSpeed": 250,
|
||||
"hardOvercurrentEnabled": false,
|
||||
"overcurrentStopMs": 300,
|
||||
"hardBumpEnabled": false,
|
||||
"bumpBackoffSpeed": 250,
|
||||
"bumpBackoffMs": 350,
|
||||
"cliffEnabled": false,
|
||||
"cliffBackoffSpeed": 250,
|
||||
"cliffBackoffMs": 500,
|
||||
"virtualWallEnabled": true,
|
||||
"virtualWallBackoffSpeed": 250,
|
||||
"virtualWallBackoffMs": 500,
|
||||
"triggerCooldownMs": 800
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
-24
@@ -1,24 +0,0 @@
|
||||
#configuration for roverd
|
||||
name: dummy3
|
||||
serverUrl: ws://127.0.0.1:8080/rover
|
||||
serial:
|
||||
device: /dev/ttyS0
|
||||
baud: 115200
|
||||
brc:
|
||||
gpioPin: 25
|
||||
pulseEvery: 1m
|
||||
pulseWidth: 1s
|
||||
battery:
|
||||
full: 2068
|
||||
warn: 1700
|
||||
urgent: 1650
|
||||
maxWheelSpeed: 350
|
||||
media:
|
||||
manage: false
|
||||
service: mediamtx.service
|
||||
healthUrl: http://127.0.0.1:9997/v3/paths/list
|
||||
healthInterval: 30s
|
||||
headlight:
|
||||
enabled: false
|
||||
laser:
|
||||
enabled: false
|
||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
@@ -0,0 +1,51 @@
|
||||
# Rover hardware configuration notes
|
||||
|
||||
This document records hardware-specific requirements while the roverd rework is in progress. The existing installer still contains machine-specific setup; the universal bootstrap and media profiles are not implemented yet. Final profile names and JSON examples will be added when those interfaces exist.
|
||||
|
||||
## Universal configuration requirements
|
||||
|
||||
- Audio capture and playback devices must be selectable on every supported architecture. An ARM machine need not use an AIY HAT, and an AMD64 machine need not use its first sound card.
|
||||
- Keep the Google AIY Voice HAT as an explicit selectable profile, not a default applied to every Pi or every ARM binary.
|
||||
- Prefer stable ALSA card identifiers over card numbers where supported; discover the actual identifier on the rover rather than assuming it from this document.
|
||||
- Preserve concurrent TTS, horn, and forwarded audio playback and their independent volume controls. Device selection must cover these paths as well as the microphone streamer.
|
||||
- Hardware-specific boot overlays, PWM pin allocation, and package setup belong to an explicit hardware choice or documented host setup. They must not be unconditional bootstrap side effects.
|
||||
|
||||
## Agreed audio routing design
|
||||
|
||||
Roverd configuration selects one physical input device and one physical output device. These may be on different sound cards. Roverd generates ALSA routing from those settings on startup, using the ordinary configuration save/restart flow when they change.
|
||||
|
||||
The microphone streamer uses the selected input. TTS, horn, and forwarded audio share the selected output while retaining simultaneous playback and separate volume controls. Profiles use the generated logical devices supplied through their environment; they do not each hardcode or independently select physical audio hardware. Use ALSA conversion where supported instead of requiring all devices to accept the existing HAT playback format.
|
||||
|
||||
AIY setup enables its hardware and uses this same routing system. The bootstrap still asks only for rover name and server address. This design is agreed but not yet implemented.
|
||||
|
||||
## Existing AIY Voice HAT setup
|
||||
|
||||
These facts come from the repository's existing installer/configuration, not a live hardware check:
|
||||
|
||||
- The Pi installer enables `dtoverlay=googlevoicehat-soundcard` and `dtparam=i2s=on`, and disables onboard audio with `dtparam=audio=off`.
|
||||
- The README records that this setup worked on Raspberry Pi OS Bookworm and had problems on Trixie. The rework must not imply that the HAT is verified on every Debian release.
|
||||
- The current ALSA routing uses `hw:0,0` and mixer card `0`. A comment identifies the HAT card as `sndrpigooglevoi`; verify the actual card identifier on the deployed rover before replacing numeric device references.
|
||||
- Logical playback devices are `tts`, `horn`, and `forward`; capture has the `rovermic` alias. They share a playback mixer configured for 16 kHz mono S16_LE and expose `TTSMaster`, `HornMaster`, and `ForwardMaster` volume controls.
|
||||
- The existing source places a kernel-module `options` line in `asound.conf`. During audio-profile implementation, separate module configuration from ALSA PCM configuration instead of copying that assumption into the generic setup.
|
||||
- The installer enables PWM on GPIO12/13 with `dtoverlay=pwm-2chan,pin=12,func=4,pin2=13,func2=4`, explicitly leaving GPIO18/19 free for I2S. The sample servo uses GPIO12, while the checked-in local config has a disabled servo on GPIO19. Do not enable that saved GPIO19 servo setting for the HAT setup without checking wiring and I2S ownership.
|
||||
|
||||
For the new internal GPIO peripheral, enable `piGpio.enabled` on a rover that uses these GPIO features, then configure its children for the actual wiring:
|
||||
|
||||
| Feature | Existing setup to preserve |
|
||||
| --- | --- |
|
||||
| BRC | Enabled, GPIO4 on `gpiochip0`, pulse every 1 minute for 1 second |
|
||||
| Headlight | Enabled, GPIO22 on `gpiochip0`, active-low, initially off |
|
||||
| Laser | Optional, GPIO27 on `gpiochip0`, active-high, initially off |
|
||||
| Camera servo | Optional; sample GPIO12, 50 Hz, cycle length 20000, 900–2100 microseconds, -15 to 30 degrees, home 0, nudge 2 degrees |
|
||||
|
||||
The parent switch now defaults to disabled. Saved child settings do not enable GPIO on their own. External peripherals must not advertise the same enabled role unless the conflicting internal role is disabled.
|
||||
|
||||
## Remaining implementation work
|
||||
|
||||
- [ ] Add AIY capture/playback profiles alongside generic selectable ALSA device profiles.
|
||||
- [ ] Make TTS, horn, forwarded audio, and mixer routing use configured devices consistently.
|
||||
- [ ] Generate ALSA routing from the shared input/output configuration, including distinct input/output cards, logical profile devices, format conversion, and independent playback volume controls.
|
||||
- [ ] Audit fixed card numbers, named PCM assumptions, capture formats, camera orientation/sensor defaults, serial device defaults, and architecture-specific TTS assets.
|
||||
- [ ] Keep required one-time host boot changes visible; distinguish a hardware-overlay reboot from ordinary roverd update/restart behavior.
|
||||
- [ ] Add exact final profile selections and JSON settings for the existing AIY rover.
|
||||
- [ ] Verify on the actual HAT and at least one non-HAT audio device; record results rather than assuming compatibility.
|
||||
+26
-36
@@ -359,43 +359,33 @@ An ESP32 that supplies all three roles describes:
|
||||
}
|
||||
```
|
||||
|
||||
The ESP32 description owns the calibration for hardware attached to that ESP32. Rover YAML does not repeat the ESP32 pin numbers or servo calibration.
|
||||
The ESP32 description owns the calibration for hardware attached to that ESP32. Rover configuration does not repeat the ESP32 pin numbers or servo calibration.
|
||||
|
||||
### Optional backend-selection rule
|
||||
### Peripheral role selection
|
||||
|
||||
`roverd` resolves each built-in role once during startup:
|
||||
Roverd resolves each built-in role once during startup across Firmata peripherals and the optional internal Pi GPIO peripheral. Exactly one provider enables a role; no providers leave it disabled. Multiple providers report a conflict identifying the devices and leave only that role unavailable. Native GPIO has no priority over external peripherals.
|
||||
|
||||
1. If that native Pi GPIO feature is enabled in rover YAML, use the native Pi implementation.
|
||||
2. Otherwise, if exactly one discovered ESP32 declares the role, use its Firmata implementation.
|
||||
3. Otherwise, leave the built-in feature disabled.
|
||||
All native settings live under `piGpio`, whose parent switch defaults to disabled:
|
||||
|
||||
Native configuration deliberately wins. A Pi rover can attach an ESP32 for unrelated generic controls without unexpectedly moving its existing camera servo, headlight, or laser to the ESP32. To deliberately use the ESP32 for one of those features, disable only that native feature in rover YAML.
|
||||
|
||||
Any rover configuration that should use the ESP32 for these roles keeps the corresponding native GPIO features disabled:
|
||||
|
||||
```yaml
|
||||
cameraServo:
|
||||
enabled: false
|
||||
|
||||
headlight:
|
||||
enabled: false
|
||||
|
||||
laser:
|
||||
enabled: false
|
||||
```json
|
||||
{
|
||||
"piGpio": {
|
||||
"enabled": false,
|
||||
"cameraServo": { "enabled": false },
|
||||
"headlight": { "enabled": true, "gpioPin": 22, "activeLow": true },
|
||||
"laser": { "enabled": false },
|
||||
"brc": { "enabled": true, "gpioPin": 4, "pulseEvery": "1m", "pulseWidth": "1s" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
An attached ESP32 can then fill any or all of those roles automatically at the next `roverd` start. This works identically on Raspberry Pi and laptop rover hosts; no USB path or backend name is added to YAML.
|
||||
This is a layout excerpt, not a complete configuration file. Use the JSON sample or `-print-default-config` for all required fields.
|
||||
|
||||
Conflict behavior is fixed and simple:
|
||||
|
||||
- Native feature enabled and ESP32 declares the same role: use native and log that the ESP32 role was ignored.
|
||||
- Native feature disabled and one ESP32 declares the role: use that ESP32.
|
||||
- Native feature disabled and no ESP32 declares the role: disable the feature.
|
||||
- Native feature disabled and multiple ESP32s declare the same role: fail startup with a duplicate-role error rather than choosing by USB enumeration order.
|
||||
While the parent is disabled, saved child settings cause no GPIO probing or initialization. When enabled, the internal peripheral appears as `pi-gpio` / “Pi GPIO” and offers its enabled roles. BRC runs as its automatic background function, not a user control. Pin, chip, servo calibration, and timing settings all remain inside this section. This applies to every architecture build. See the JSON sample config for complete settings; the WebUI configuration editor is a later rework step.
|
||||
|
||||
### Shared controller interfaces
|
||||
|
||||
The current `WSClient` directly owns concrete `*CameraServo` and `*GPIOToggle` values. Supporting either physical backend cleanly requires it to depend on the behavior it uses instead of a platform-specific concrete type.
|
||||
`WSClient` uses controller interfaces shared by the internal GPIO and external Firmata providers.
|
||||
|
||||
The intended interfaces are:
|
||||
|
||||
@@ -433,7 +423,7 @@ ToggleController
|
||||
|
||||
### Effective hello metadata
|
||||
|
||||
The current hello is built from `c.cfg.CameraServo`, `c.cfg.Headlight`, and `c.cfg.Laser`. That cannot remain the source of truth because an ESP32 role may enable a feature whose native YAML entry is disabled.
|
||||
Hello uses the selected controllers’ effective configuration, since external roles are independent of saved native GPIO settings.
|
||||
|
||||
After startup resolution, the selected controller supplies the effective public configuration. `sendHello()` advertises that effective configuration:
|
||||
|
||||
@@ -794,7 +784,7 @@ Use `esp32-s3-devkitc-1` and the matching `/dev/ttyACM*` device for a
|
||||
native-USB ESP32-S3.
|
||||
|
||||
```bash
|
||||
cd pi/roverd
|
||||
cd rover/roverd
|
||||
go run ./cmd/peripheral-probe -port /dev/ttyUSB0
|
||||
```
|
||||
## Connection lifecycle
|
||||
@@ -813,8 +803,8 @@ Peripheral discovery happens exactly once per `roverd` process. The currently im
|
||||
8. Validates every advertised standard-output pin against Firmata capabilities.
|
||||
9. Configures generic digital, PWM, and servo pin modes once.
|
||||
10. Assigns process-local IDs such as `firmata-0` and `firmata-1` in discovery order.
|
||||
11. Resolves `cameraServo`, `headlight`, and `laser` against the native configuration.
|
||||
12. Rejects duplicate ESP32 providers only when the corresponding native role is disabled and Firmata selection would otherwise be ambiguous.
|
||||
11. Registers the internal Pi GPIO peripheral if enabled and resolves camera-servo, headlight, and laser roles across providers.
|
||||
12. Reports duplicate role providers and leaves conflicting roles unavailable.
|
||||
13. Constructs the selected native or Firmata controllers and fixed generic inventory.
|
||||
14. Constructs `WSClient` with those controllers and that inventory.
|
||||
15. Connects to the server and includes the effective built-in configuration and renderable inventory in the normal rover hello.
|
||||
@@ -1144,7 +1134,7 @@ repository reference firmware. The package manifest, README, and examples are
|
||||
self-contained so the same directory can be published directly to the
|
||||
PlatformIO Registry as `legop3/RoverPeripheral`.
|
||||
|
||||
### `pi/roverd`
|
||||
### `rover/roverd`
|
||||
|
||||
`PeripheralManager` is responsible for:
|
||||
|
||||
@@ -1164,9 +1154,9 @@ Only renderable control metadata leaves `roverd`. Firmata pin numbers, output ma
|
||||
|
||||
The manager should remain independent of the existing Roomba Open Interface serial adapter. A peripheral serial connection is not the Roomba base serial connection and must not be routed through `SerialAdapter`.
|
||||
|
||||
The transport foundation is a focused Firmata parser/client in `pi/roverd/firmata.go`. It operates on `io.ReadWriteCloser`, which keeps byte-stream behavior testable without hardware and lets discovery pass either `/dev/ttyUSB*` or `/dev/ttyACM*` ports into the same client. `pi/roverd/cmd/peripheral-probe` remains the direct hardware diagnostic entry point, while `PeripheralManager` now connects the same client to automatic daemon startup discovery.
|
||||
The transport foundation is a focused Firmata parser/client in `rover/roverd/firmata.go`. It operates on `io.ReadWriteCloser`, which keeps byte-stream behavior testable without hardware and lets discovery pass either `/dev/ttyUSB*` or `/dev/ttyACM*` ports into the same client. `rover/roverd/cmd/peripheral-probe` remains the direct hardware diagnostic entry point, while `PeripheralManager` now connects the same client to automatic daemon startup discovery.
|
||||
|
||||
`WSClient` now depends on shared camera-servo and toggle controller interfaces rather than platform-selected concrete types. The startup resolver uses the same native-first rule in the ARM Pi and amd64 laptop binaries. Firmata camera movement retains the established limits, home position, nudging, inversion, pulse calibration, raw-pulse policy, and movement-rate behavior; Firmata toggles retain logical state and polarity conversion.
|
||||
`WSClient` now depends on shared camera-servo and toggle controller interfaces rather than platform-selected concrete types. The startup resolver uses the same unique-provider rule in every architecture binary. Firmata camera movement retains the established limits, home position, nudging, inversion, pulse calibration, raw-pulse policy, and movement-rate behavior; Firmata toggles retain logical state and polarity conversion.
|
||||
|
||||
### Server
|
||||
|
||||
@@ -1247,8 +1237,8 @@ The completed system should be verified with a real ESP32 and rover Linux comput
|
||||
- Confirm camera angle limits, home position, nudge amount, inversion, pulse calibration, and rate limiting match the declared ESP32 configuration.
|
||||
- Confirm headlight and laser toggle state events remain identical to the native Pi path.
|
||||
- Confirm existing laser restrictions still apply with the Firmata backend.
|
||||
- Enable a native role and declare the same ESP32 role; confirm native wins and the ignored role is logged.
|
||||
- Disable native and declare the same role from two ESP32s; confirm startup fails with a clear duplicate-role error.
|
||||
- Enable Pi GPIO and a native role also declared by an ESP32; confirm the conflict lists both providers and leaves that role unavailable.
|
||||
- Declare the same role from two ESP32s; confirm a clear conflict and that unrelated roles remain available.
|
||||
- Confirm a Pi rover can use native built-in controls and generic ESP32 controls simultaneously.
|
||||
- Repeat ESP32 role selection on both the ARM Pi binary and amd64 laptop binary and confirm their commands and advertised configurations match.
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
# Roverd configuration and management
|
||||
|
||||
Roverd now reads `/etc/roverd.json`. YAML settings are no longer accepted. Repository samples and installer paths use JSON; there is no configuration migration or legacy reader.
|
||||
|
||||
The schema is generated from the Go configuration types. Both configuration files and remote submissions must contain the complete object. Derived media URLs are excluded from saved settings and still included in control hello metadata.
|
||||
|
||||
## Local configuration commands
|
||||
|
||||
These commands do not open hardware, start media, or connect to the server:
|
||||
|
||||
```sh
|
||||
./dist/roverd-linux-amd64 -print-default-config
|
||||
./dist/roverd-linux-amd64 -print-config-schema
|
||||
./dist/roverd-linux-amd64 -config rover/roverd/roverd.sample.json -check-config
|
||||
```
|
||||
|
||||
Select the appropriate architecture binary on a rover. The default object supplies initial values; edit the name and server URL before installing it. The initial serial path may need configuration for the actual hardware.
|
||||
|
||||
## Connections and state
|
||||
|
||||
- `/rover`: control commands, acknowledgements, sensors, and complete `roverState` snapshots.
|
||||
- `/rover/management`: configuration hello, management commands/acknowledgements, host statistics, and daemon events.
|
||||
- Derive the management address from the configured `ws://host[:port]/rover` or `wss://host[:port]/rover` control URL; there is no second server address to maintain.
|
||||
- Management starts independently of hardware initialization and remains available after serial/peripheral startup failure.
|
||||
- Control disconnect docking/reboot behavior still depends on control connectivity. A live management connection does not count as a working control connection.
|
||||
- The server maintains management records independently of the control roster, only in memory. Management disconnect removes the record; hello repopulates it.
|
||||
- Profile catalogs in hello are currently empty. YAML media profiles are the next media implementation stage, not installed catalogs hidden elsewhere.
|
||||
|
||||
## Configuration page
|
||||
|
||||
Open `/admin?section=fleet` as an admin or lockdown admin. Select a management-connected rover, edit its schema-driven form, and use “Save to this rover”. For a fleet change, select the field below the form and use “Apply this field to all rovers”; its value comes from the current draft. Review individual results. Offline rovers are not queued.
|
||||
|
||||
## Admin Socket.IO API
|
||||
|
||||
Each request receives a callback containing either `{ success: true, ...result }` or `{ error: "..." }`. Authorization uses the existing admin/lockdown-admin role check.
|
||||
|
||||
| Event | Payload | Result |
|
||||
| --- | --- | --- |
|
||||
| `roverManagement:list` | `{}` | `rovers`, including management-only rovers |
|
||||
| `roverManagement:get` | `{ roverId }` | Current configuration, schema, profiles, host statistics, recent notices |
|
||||
| `roverManagement:save` | `{ roverId, config }` | Request ID after roverd acknowledges the complete object |
|
||||
| `roverManagement:applyField` | `{ path: ["piGpio", "enabled"], value: false }` | Individual `results` containing rover ID, success/error, and successful request ID |
|
||||
| `roverManagement:command` | `{ roverId, type, reboot?, media? }` | Request ID after acknowledgement; types are `reboot`, `update`, `media` |
|
||||
|
||||
Admin notifications are `roverManagement:changed`, `roverManagement:offline`, `roverManagement:hostStats`, and `roverManagement:event`. Requests time out if no acknowledgement arrives. Disconnect before acknowledgement reports an unknown outcome as an error; reconnect and read the actual configuration rather than assuming it was not saved.
|
||||
|
||||
The existing reboot/update UI paths use management delivery and retain `commandAck` notifications. The separate user “reboot my rover” permission/cooldown checks remain in place. Generic media-management commands now require admin privileges.
|
||||
|
||||
## Save lifecycle
|
||||
|
||||
1. Validate the complete JSON object against the schema and existing semantic checks.
|
||||
2. Block new control commands and stop motion when a control runtime exists.
|
||||
3. Write and sync a temporary file, then atomically replace the configuration file with mode `0600`.
|
||||
4. Attempt the acknowledgement, cancel the daemon runtime, and release hardware resources.
|
||||
5. Re-execute roverd, reload the saved file, and send a new management hello.
|
||||
|
||||
Once the file has been replaced, roverd restarts even if the acknowledgement cannot be delivered. The server does not optimistically overwrite its cached configuration. Invalid submissions leave the file untouched.
|
||||
|
||||
## Deployment verification still required
|
||||
|
||||
Do this on the intended server/rover, not the development machine:
|
||||
|
||||
1. Deploy the changed server and the matching rover binary/config together. Capture `journalctl -u roverd -f` and server logs.
|
||||
2. With an authenticated admin Socket.IO session, call `roverManagement:list` and `roverManagement:get`. Expect configuration and schema even when the rover's serial device cannot open.
|
||||
3. Change a harmless setting such as description in the returned full object and call `roverManagement:save`. Expect an acknowledgement, disconnect/reconnect, and a new hello containing that setting. Confirm `/etc/roverd.json` matches and survives a service restart.
|
||||
4. Submit an incomplete object. Expect an error, no file replacement, and no restart.
|
||||
5. Confirm host statistics and autocharge/watchdog/daemon notices still reach their existing UI/alert consumers through management. Headlight/laser state must arrive as a complete `roverState` snapshot on control.
|
||||
6. Verify reboot/update requests use management, the normal user reboot restrictions still apply, and non-admin clients cannot read/save configuration or invoke the admin command endpoint.
|
||||
7. Confirm new movement commands cannot execute while a save/reboot/update is stopping the rover, and that control disconnect safety still works independently of management.
|
||||
|
||||
Record acknowledgement errors, reconnect hello contents, relevant journal/server output, and physical stop behavior in the implementation tracker. Do not treat CLI validation or compilation as evidence of these deployed flows.
|
||||
|
||||
## Pending stages
|
||||
|
||||
Browser/live verification of configuration and operational state, YAML media catalogs/child supervision, universal ALSA routing, standalone bootstrap, and replacement update workflow remain pending. The current updater and systemd media supervisor have moved transport but retain their existing implementations until those stages.
|
||||
|
||||
Apply-field targets the currently management-connected fleet. It clones each rover’s own configuration, replaces an existing field, and sends the complete object for rover-side validation. Inspect individual results for failures. Missing fields and changed connections are reported; offline changes are not queued. Paths traverse object fields, not array elements. Array-valued fields can be replaced as a whole.
|
||||
|
||||
Control state messages have the shape `{ "type": "roverState", "state": { "headlightOn": false, "laserOn": null } }`. Null indicates an unavailable role. Each message replaces the server object; disconnect clears it. The roster exposes `roverState` directly, rather than per-device `state` objects.
|
||||
@@ -0,0 +1,275 @@
|
||||
# Roverd rework plan and implementation tracker
|
||||
|
||||
Status: implementation authorized on 2026-11-16; repository/build, internal GPIO, and JSON/management backend implemented; live management verification and remaining stages pending.
|
||||
|
||||
This is the persistent plan and progress record for the roverd rework. Update it as implementation proceeds, recording completed work, decisions, verification evidence, and remaining work. Keep unfinished work unchecked; distinguish implemented behavior from runtime-verified behavior.
|
||||
|
||||
## Authorization and working rules
|
||||
|
||||
- The user explicitly authorized implementation with `IPI` on 2026-11-16.
|
||||
- No backward compatibility: no migrations, old-path aliases, legacy fallbacks, or dual protocols. Roverd, server, and WebUI move together.
|
||||
- Prefer the simplest effective implementation. The behavior below is the intended outcome; avoid adding frameworks or bookkeeping without a concrete need.
|
||||
- Follow repository verification rules: no new tests unless requested, no automatic full-project checks, and use the smallest useful verification. This development machine is not the deployed server or rover hardware.
|
||||
|
||||
## Agreed design
|
||||
|
||||
### Repository and builds
|
||||
|
||||
- Rename `pi/` to `rover/`; update paths, imports, scripts, build commands, and documentation.
|
||||
- Replace machine-specific builds and the `debian_laptop` distinction with architecture-specific Linux builds: ARMv6, ARMv7, ARM64, and AMD64.
|
||||
- Hardware support depends on configuration and available hardware, not a Pi/laptop classification. Remove the existing laptop-specific hardware stubs as part of resolving this split.
|
||||
- Keep prebuilt binaries committed in `dist/`. No published releases or release bundles are required.
|
||||
- Detect the installed OS architecture during installation, including 32-bit ARM installations; do not select solely from CPU capability.
|
||||
- Debian is the target platform across rover hardware.
|
||||
|
||||
### Internal Pi GPIO peripheral
|
||||
|
||||
- Provide one `piGpio` configuration section, presented as “Pi GPIO peripheral”, with a parent `enabled` switch defaulting to disabled.
|
||||
- Keep all native GPIO settings inside this section, beneath the parent switch in the editor:
|
||||
- Camera servo: enablement, pin, PWM, calibration, limits, and movement settings.
|
||||
- Headlight and laser: individual enablement, pin/chip, polarity, and initial state.
|
||||
- BRC: enablement, pin/chip, pulse interval, and pulse width.
|
||||
- Disabling the parent switch disables the entire internal peripheral without probing, initializing, or accessing GPIO resources. Preserve its saved settings for later re-enablement. No Pi GPIO settings remain scattered elsewhere in configuration.
|
||||
- When enabled, register one internal peripheral named “Pi GPIO”, with a stable ID such as `pi-gpio`, offering only the configured enabled camera-servo/headlight/laser roles.
|
||||
- Separate peripheral identity and role ownership from the Firmata transport. Use a small common provider interface for external Firmata peripherals and the internal GPIO peripheral, reusing the existing camera-servo and toggle controller interfaces.
|
||||
- Call GPIO implementations directly in process; do not simulate serial connections or Firmata messages.
|
||||
- The internal peripheral owns BRC startup and shutdown as an automatic background function, not a fake user-facing control.
|
||||
- Apply one role-conflict rule across providers: if multiple peripherals advertise the same role, report the providers and leave that role unavailable until corrected. Keep management accessible. Remove the current implicit native-GPIO priority; different roles may come from different peripherals.
|
||||
- Operational state uses the same `roverState` object regardless of whether its provider is internal GPIO or an external peripheral.
|
||||
- This runtime switch replaces the machine-specific GPIO build distinction. GPIO being disabled must permit operation on non-Pi hosts without GPIO errors.
|
||||
|
||||
### Configuration ownership and saves
|
||||
|
||||
- Roverd owns one `/etc/roverd.json` object containing all rover settings and supplies its JSON Schema.
|
||||
- Include selected media profiles, enablement, devices, and media settings in configuration. Derive runtime values such as complete streaming URLs in roverd.
|
||||
- Management hello sends current configuration, schema, and available media profiles.
|
||||
- The server holds these only in memory. Reconnection repopulates them; there is no configuration database or offline change queue.
|
||||
- Every save transmits the complete configuration object, even when only one field changed.
|
||||
- Roverd validates the proposed configuration, atomically writes it, acknowledges the save, stops motion and child processes, and restarts. Its next hello reports the configuration actually loaded.
|
||||
- Invalid submissions return an error without replacing the file.
|
||||
- No deltas, configuration versions, or rollback system.
|
||||
- Existing JSON tags omit some settings; do not mistake current hello metadata serialization for a complete configuration representation.
|
||||
|
||||
### Communication channels
|
||||
|
||||
Control channel:
|
||||
|
||||
- Driving and other rover actions, with their acknowledgements.
|
||||
- Roomba sensor telemetry.
|
||||
- Complete `roverState` messages.
|
||||
|
||||
Management channel (a separate WebSocket):
|
||||
|
||||
- Configuration and profile management.
|
||||
- Reboot and software update commands/results.
|
||||
- Media process control, status, and output.
|
||||
- Host statistics.
|
||||
- Daemon status notices, including autocharge timer notices and watchdog diagnostics.
|
||||
|
||||
Classify existing events by purpose rather than moving the entire existing event stream wholesale. Update server handlers and UI consumers along with their producers. Headlight and laser state are operational state, not management.
|
||||
|
||||
Start management before hardware initialization so hardware configuration errors remain remotely diagnosable and fixable. Use the existing admin authorization path for management operations. Preserve motion-stop behavior for reboot, update, and configuration restart. Control-connection safety behavior must remain tied to control availability, not be satisfied by a live management connection.
|
||||
|
||||
### One current rover state
|
||||
|
||||
- Roverd owns one `roverState` JSON object for operational state such as headlight and laser states.
|
||||
- Send the full object on control connection/reconnection and whenever its contents change.
|
||||
- The server replaces its current object for that rover and uses that single copy for all consumers and UI updates.
|
||||
- Remove separate headlight/laser state stores and per-field state events. No patches or deltas.
|
||||
- Clear current state on disconnect so stale values are not presented as live.
|
||||
- Roomba telemetry and management status remain separate from `roverState`.
|
||||
|
||||
### WebUI
|
||||
|
||||
- Reuse the existing React JSON Schema form library for each rover's configuration page.
|
||||
- “Save to this rover” submits the complete configuration.
|
||||
- “Apply this field to all rovers” replaces that field in each connected rover's own configuration, then sends each its complete resulting object. Preserve every rover's other settings.
|
||||
- Show individual results; skip offline rovers without queued changes.
|
||||
- Include profile selection, custom profile editing, media status/output, reboot, and software update controls.
|
||||
|
||||
### Audio devices and ALSA routing
|
||||
|
||||
- One audio configuration selects the physical input device and physical output device on every architecture. Input and output may belong to different sound cards; prefer stable ALSA device names over fixed card numbers.
|
||||
- The microphone streamer uses the selected input. Forwarded audio, TTS, and horn share the selected output, with simultaneous playback and independent volume controls.
|
||||
- Roverd generates ALSA routing from these settings as part of configuration startup. Supported format conversion belongs in the ALSA routing rather than assuming every device accepts the AIY format.
|
||||
- Media profiles consume the resulting logical audio devices through the command environment instead of hardcoding physical devices such as `hw:0,0`.
|
||||
- AIY-specific setup enables the HAT hardware; it uses this same audio configuration and routing system, not a separate set of device settings.
|
||||
- Audio changes use the ordinary whole-object configuration save/restart flow. Device selection remains in the WebUI configuration, not the bootstrap questionnaire.
|
||||
|
||||
### Media profiles
|
||||
|
||||
- Keep three accessible YAML catalogs under `rover/profiles/`: video publishing, microphone publishing, and audio playback.
|
||||
- Each profile has an identifier, name, description, optional `setup` command, and `run` command. Support multiline shell commands and pipelines.
|
||||
- Read bundled profiles directly from the managed repository checkout. No separate profile installation or registration.
|
||||
- Allow exactly one custom YAML profile per category under `/etc/roverd/profiles/`, editable through management. These files remain outside the checkout and survive updates.
|
||||
- JSON configuration selects profiles and supplies settings such as devices, resolution, and bitrate.
|
||||
- Profiles may contain hardware-specific configurations contributed by rover builders; no plugin API or custom code module is needed for each encoder.
|
||||
- Preserve Google AIY Voice HAT support as an explicit option, while supporting configurable audio devices on every architecture. Do not treat Pi/ARM as synonymous with AIY hardware or assume sound card zero.
|
||||
- Audit setup-specific assumptions beyond streamers, including TTS/horn/mixer routing, boot overlays, PWM/I2S pin conflicts, cameras, serial devices, and TTS assets. Generalize where useful and document the exact selections needed for the existing rover in [hardware configuration notes](rover-hardware-config.md).
|
||||
|
||||
### Command variables and setup
|
||||
|
||||
- Launch commands through a shell. Supply string values through environment variables rather than inserting them into shell source or creating a template language.
|
||||
- Supply rover name, server host, audio/video devices, media settings, complete publish/playback URLs, and profile working directory to both setup and run commands.
|
||||
- Example: `ffmpeg -i "$ROVER_VIDEO_DEVICE" … "$ROVER_VIDEO_PUBLISH_URL"`.
|
||||
- Each profile gets a persistent working directory under `/var/lib/roverd/profiles/` for downloads, builds, and other generated files.
|
||||
- At every roverd startup, run each selected enabled profile's setup command before its run command. Commands must be safe to repeat.
|
||||
- No persistent setup-success tracking. Profile changes save configuration and restart roverd, naturally running setup for the newly selected profile.
|
||||
- Routine streamer retries run only the run command.
|
||||
- Setup failure is visible and prevents that streamer from launching, without stopping roverd or the other streamers.
|
||||
|
||||
### Media supervision and output
|
||||
|
||||
- Roverd directly supervises the three media commands as child processes.
|
||||
- Restart exited commands after a short retry delay. Server restarts and Wi-Fi interruptions are routine retry situations.
|
||||
- Streamer failure never stops or restarts roverd. Management connection loss does not stop streamers.
|
||||
- Shutdown stops complete child process groups, including pipelines.
|
||||
- Capture stdout/stderr and continuously forward output through management while connected. Use bounded buffering so noisy commands or disconnections cannot block streamers or consume unlimited memory.
|
||||
- No viewer subscriptions or output-demand tracking.
|
||||
- Remove old streamer systemd services and the code managing them. Systemd supervises only roverd, running as root.
|
||||
|
||||
### Standalone bootstrap
|
||||
|
||||
The bootstrap script works without an existing repository on the rover:
|
||||
|
||||
1. Install basic Debian prerequisites.
|
||||
2. Clone the repository into `/opt/roverd`.
|
||||
3. Invoke the checkout's installation script.
|
||||
4. Automatically select the committed binary matching the installed OS architecture.
|
||||
5. Create initial configuration and working directories.
|
||||
6. Install and start the single root roverd service.
|
||||
|
||||
Ask for only rover name and server address. Everything else starts with defaults and is configured through management; no camera, encoder, audio, or machine-profile questionnaire.
|
||||
|
||||
`/opt/roverd` belongs to roverd and is not a development working directory. Profile setup handles hardware-specific dependencies.
|
||||
|
||||
### Self-update
|
||||
|
||||
- Use a helper that survives roverd restarting.
|
||||
- Update the managed checkout, invoke the same installation script used by bootstrap, install the matching committed binary, and restart roverd.
|
||||
- Bundled profiles update with the checkout. Preserve local JSON configuration, custom profiles, and persistent profile working directories.
|
||||
- Forward progress through management while available and make the update result available after reconnection.
|
||||
- Routine updates restart the service without rebooting the computer.
|
||||
|
||||
## Implementation checklist
|
||||
|
||||
The order below is a working sequence, not a requirement to leave incompatible intermediate states deployed.
|
||||
|
||||
- [x] Receive explicit `IPI` before code implementation (2026-11-16).
|
||||
- [x] Rename `pi/` to `rover/` and update references.
|
||||
- [x] Replace machine-specific build targets/tags with architecture-specific artifacts and resolve hardware support split.
|
||||
- [x] Group every native GPIO setting under the disabled-by-default Pi GPIO peripheral switch in the current configuration and samples.
|
||||
- [x] Expose the grouped Pi GPIO configuration in the new JSON schema/UI.
|
||||
- [x] Register Pi GPIO through the common peripheral provider path, including BRC lifecycle ownership and uniform role-conflict handling.
|
||||
- [x] Connect peripheral operational state to the new shared `roverState` object.
|
||||
- [x] Gate GPIO provider registration, initialization, and BRC startup behind the parent switch; retain saved child settings. Hardware validation remains pending.
|
||||
- [x] Implement complete JSON configuration serialization, schema, validation, atomic saves, and restart flow (live save/reconnect verification pending).
|
||||
- [x] Implement separate management connection and in-memory server management state.
|
||||
- [x] Move reboot, update, media management, host statistics, and daemon status messages to management; update consumers. Preserve the separately authorized user reboot path.
|
||||
- [x] Separate management lifecycle from hardware startup failures (deployment verification pending).
|
||||
- [x] Implement full-object `roverState` and consolidate server/UI operational-state consumers (live verification pending).
|
||||
- [ ] Add bundled YAML catalogs and one custom YAML profile per media category.
|
||||
- [ ] Preserve AIY HAT as an explicit profile and expose ordinary audio-device selection on every architecture, including TTS/horn/mixer paths.
|
||||
- [ ] Generate ALSA routing from shared input/output selections; connect microphone, TTS, horn, forwarded audio, and independent volume controls to the resulting logical devices.
|
||||
- [ ] Document exact configuration for the existing AIY rover and audit other machine-specific assumptions.
|
||||
- [ ] Implement command environments, persistent working directories, and setup on each daemon startup.
|
||||
- [ ] Replace media systemd management with child-process supervision and continuous bounded output forwarding.
|
||||
- [x] Implement per-rover schema editor and complete-object saves (browser/live verification pending).
|
||||
- [x] Implement apply-one-field-to-all-connected-rovers with individual results (browser/live verification pending).
|
||||
- [ ] Add profile editing/selection, media output/status, reboot, and update UI.
|
||||
- [ ] Implement standalone bootstrap with only name/address input and automatic OS architecture selection.
|
||||
- [ ] Implement shared checkout installation and self-update with reconnect-visible results.
|
||||
- [ ] Remove obsolete services, configuration files, scripts, build distinctions, and documentation.
|
||||
- [ ] Update user/contributor documentation, including profile variables, setup expectations, building, installation, and updates.
|
||||
- [ ] Perform focused available verification and record results below.
|
||||
- [ ] Record deployment/hardware checks still required; do not claim those verified locally.
|
||||
|
||||
## Verification record
|
||||
|
||||
2026-11-16, foundation stage:
|
||||
|
||||
- Focused existing peripheral tests passed: `go test . -run 'Test(DisabledNativeRolesResolveToFirmataOnEveryHostBuild|MissingNativeAndFirmataRolesRemainDisabled|ConflictingRolesRemainUnavailableWithoutInitializingGPIO|Peripheral)' -count=1` in `rover/roverd`. Adapted existing expectations for the deliberately changed config/role-conflict behavior; no new test files were created. These exercise Firmata behavior, parent-disabled selection with enabled saved children, and conflicts that must not initialize native hardware.
|
||||
- An initial test invocation from the repository root failed because the Go module is under `rover/roverd`; reran from that module as above.
|
||||
- Architecture builds passed for ARMv6, ARMv7, ARM64, and AMD64. Regenerated all four artifacts after final shutdown/error-handling corrections; all builds passed.
|
||||
- `git diff --check` passed for tracked changes.
|
||||
- `bash -n rover/install/profiles.sh` passed. Actual installation was not run on this development machine.
|
||||
- GPIO electrical behavior, BRC timing, and AIY audio remain unverified on hardware. On the actual rover, check startup inventory/role conflicts and exercise configured light/servo/BRC outputs; capture journal output and observed behavior.
|
||||
|
||||
|
||||
Record each meaningful check with the affected behavior, command or action, result, and limitations. In particular, distinguish local evidence from actual rover/server verification of connection recovery, motion stopping, process cleanup, media streaming, and updates.
|
||||
|
||||
## Progress and decisions
|
||||
|
||||
- 2026-11-15: Consolidated the agreed design and user corrections into this persistent tracker. Implementation is pending `IPI`.
|
||||
- 2026-11-16: Added the internal Pi GPIO peripheral design after inspecting current role ownership and BRC handling. All native GPIO options belong under one parent enable switch; disabled means no GPIO access. Implementation remains pending `IPI`.
|
||||
- 2026-11-16: Received `IPI` and started the repository/build and internal GPIO foundation. The user additionally required universal device options while retaining an explicit AIY HAT setup; recorded existing assumptions in `rover-hardware-config.md`.
|
||||
- Rejected complexity: release publishing, separate profile installation, persistent setup tracking, viewer-dependent output forwarding, and backward compatibility.
|
||||
- Settled state boundary: operational state uses complete `roverState` objects on control; configuration/host/process/daemon management uses the management connection.
|
||||
|
||||
## Remaining implementation details
|
||||
|
||||
Resolve these with the simplest approach during implementation and record the result here; they do not change the agreed behavior:
|
||||
|
||||
- Exact profile YAML shape, environment variable names, and architecture artifact names.
|
||||
- Exact management message shapes and remaining existing event classifications.
|
||||
- Update target selection using the existing repository workflow, without introducing release publishing.
|
||||
- Startup defaults that let a newly installed rover connect for configuration before its hardware is configured.
|
||||
|
||||
### Foundation implementation notes (2026-11-16)
|
||||
|
||||
- Added common role providers and the internal `pi-gpio` peripheral. Conflicts and role initialization failures leave that role unavailable while other roles continue; existing hello/controller behavior remains until the communication rework.
|
||||
- BRC belongs to the internal peripheral and waits for its writer to stop before releasing GPIO. Shutdown interrupts long pulses.
|
||||
- The installer now chooses the architecture artifact independently of its existing media setup profile. Media setup profiles and YAML config are still the old implementation, pending their planned replacement; this is not a parallel compatibility path.
|
||||
- Removed obsolete generic/laptop daemon artifacts and the duplicate daemon binary inside the source tree. New architecture binaries live in `dist/`.
|
||||
- JSON configuration/schema and management backend were subsequently implemented below. Full rework and hardware deployment verification are not complete.
|
||||
|
||||
### JSON and management backend (2026-11-16)
|
||||
|
||||
- Replaced YAML settings with complete JSON configs, including repository samples and dummy configs. No legacy decoder or migration path. The existing media implementation remains until its planned replacement.
|
||||
- Added generated draft-7 JSON Schema using `invopop/jsonschema` and validation using `santhosh-tekuri/jsonschema/v6`; retained semantic validation and excluded derived media URLs from persisted configuration.
|
||||
- Added CLI default/schema export and hardware-free configuration checking. Atomic saves block new control commands, stop motion, acknowledge, unwind hardware, and re-execute roverd.
|
||||
- Added `/rover/management` and admin Socket.IO read/save/command endpoints. Management state is separate from the control roster, so startup failures do not hide a rover from management.
|
||||
- Moved host statistics and daemon events (including autocharge notices) to management. Operational toggle events remain on control until the unified state stage.
|
||||
- Existing admin reboot/update and the user-owned-rover reboot path now use management transport. The existing user authorization/cooldown policy is preserved; generic media management now requires admin access.
|
||||
- Management hello currently has empty profile catalogs: profiles are not implemented yet. Shared audio-device fields will be introduced with functioning ALSA routing, not exposed as inactive settings.
|
||||
- See [protocol and deployment checks](roverd-management.md). No live server or rover services were started on this development machine.
|
||||
|
||||
Verification for this stage:
|
||||
|
||||
- The actual AMD64 daemon's `-check-config` accepted both JSON samples, the checked-in rover config, and the first dummy config. It rejected `{}` with missing-required-property errors before hardware initialization. Schema export also succeeded.
|
||||
- Syntax checks passed for the new management server service, WebSocket routing, command routing, and control connection handler.
|
||||
- Refreshed ARMv6, ARMv7, ARM64, and AMD64 artifacts successfully after the final shutdown changes. Server management syntax and tracked diff whitespace checks passed.
|
||||
- Live acknowledgement/save/restart/reconnect, motion stopping, role authorization, and hardware-failure recovery remain unverified. Follow the deployment checks above and record their results here.
|
||||
|
||||
### Handoff after usage-budget notice (2026-11-16)
|
||||
|
||||
- Stopped after the JSON/management backend stage; no UI or ALSA implementation started in this stage.
|
||||
- Final shutdown handling pauses automatic charging, blocks control commands and watchdog recovery, and cancels disconnect actions before stopping motion. If a management action fails before commitment, control and automatic charging resume. Live motion behavior remains unverified.
|
||||
- Existing media helper scripts, machine-specific installer setup, and Chrome TTS variants are still present intentionally as unfinished rework items, not completed universal audio support.
|
||||
- Next work: the schema-driven WebUI editor and field-to-all save flow against the documented management API, followed by unified rover state and the media/audio stages. Existing IPI authorization remains in effect.
|
||||
- No live server/rover processes were launched or left running. No commits were made. Work remains in the shared working tree, including newly added files and generated architecture binaries.
|
||||
|
||||
### Apply-field backend (2026-11-16)
|
||||
|
||||
- Implemented admin-only `roverManagement:applyField` with object-field paths, independent whole-object submissions, connection-change detection, and individual outcomes. Offline rovers are not queued.
|
||||
- Node syntax check passed. Live fleet saves remain unverified. WebUI editor and apply-field controls are still pending; the combined checklist item remains unchecked.
|
||||
|
||||
### Configuration WebUI (2026-11-16)
|
||||
|
||||
- Added `/admin?section=fleet` for admins and lockdown admins, independent of lockdown-only server configuration.
|
||||
- The page lists management connections, renders the rover-supplied schema, saves complete objects, and lets an administrator select a field from the draft for fleet-wide application with individual results.
|
||||
- Offline drafts remain mounted; server reconnection refreshes the roster. Authoritative changed configuration replaces the draft. Switching the selected rover starts its form from the latest reported configuration.
|
||||
- Focused ESLint passed for the new component and AdminApp, after correcting the initial command working directory to `webui`. No full build or browser/server process was started.
|
||||
- Verify the page against actual server/rover connections: admin access, hardware-failure management visibility, form validation, save/reconnect, and fleet success/error reporting. Production WebUI assets have not been regenerated.
|
||||
- Configuration UI/backend implementation is now present; end-to-end deployment verification remains pending. Profile/status/output controls, unified rover state, audio/media supervision, and bootstrap/update rework are still separate outstanding stages.
|
||||
|
||||
- Placement correction: rover configuration is embedded in the existing fleet management panel alongside the rover roster. Removed the separate administration tab.
|
||||
|
||||
### Unified operational state (2026-11-16)
|
||||
|
||||
- Roverd owns a complete `roverState` object with `headlightOn` and `laserOn`; null indicates an unavailable role. Sends on control connection/reconnection and logical changes. Pending notifications coalesce to the latest complete snapshot.
|
||||
- Server replaces one current object, exposes it in roster snapshots, and clears it on disconnect. Superseded sockets cannot overwrite state or remove a newer connection. Removed per-toggle event handling and separate server state stores.
|
||||
- Desktop/mobile/HUD controls, darkness reward restoration, and learning snapshots read the shared object. Telemetry and daemon management remain separate.
|
||||
- All four architecture binaries rebuilt successfully; focused frontend lint and server syntax checks passed. The two existing roster lifecycle tests passed after updating their state fixture. No new tests added.
|
||||
- Still verify live initial state, toggles through both GPIO/Firmata, reconnect state, disconnect clearing, and darkness restoration. Production UI assets have not been rebuilt.
|
||||
- Next implementation stage: YAML media profiles, command environments and child-process supervision, alongside the planned universal audio routing.
|
||||
@@ -26,6 +26,8 @@ Phase 1 must be complete and verified before Phase 2 begins. Containerization mu
|
||||
|
||||
## Decision log
|
||||
|
||||
- 2026-10-02: The admin container controls accept a tag within the repository supplied by Compose through `MULTIROVER_TARGET_IMAGE`. A successful healthy replacement saves the tag in the lifecycle status volume; failed replacements retain the previous selection. Checks and later updates follow that saved tag. Changing repositories in Compose resets the selection. Manual Compose deployments still use the Compose image and can replace a UI-selected image; the UI displays both references. The lifecycle helper itself is updated through Compose. Image rollback does not revert application data migrations. Deploy this feature to both the application and lifecycle services before using tag selection.
|
||||
|
||||
- 2026-09-14: Publish `ghcr.io/legop3/multiroombarover:latest` only from the repository's main branch. Every other repository branch publishes one moving development image named for that branch, with invalid tag separators normalized; these are development selectors rather than numbered releases. Pull requests only verify that the image builds. There are no release numbers, semantic-version tags, stable/edge channels, or operator-facing version selection. Docker image digests remain an internal mechanism for detecting an available update and retaining the previously running image for rollback.
|
||||
- 2026-09-15: Support only `linux/amd64` for the central server image. Rover computers remain independently ARM-capable, but publishing an untested ARM server image would multiply native-worker, media-binary, TTS-library, and hardware validation without serving the current deployment. ARM server support can be added later when a real ARM server exists to verify it.
|
||||
- 2026-09-15: Mount the application data directory from the Docker-managed `multirover-data` named volume instead of a host bind path. Docker initializes the empty volume with the image's non-root ownership, eliminating host UID matching, directory creation, ownership commands, and root application startup. The admin backup/restore system is the supported portable interface to the complete data tree.
|
||||
|
||||
@@ -64,6 +64,7 @@ socket.on('connect', async () => {
|
||||
// previously stored session with this object instead of merging snapshots.
|
||||
socket.on('session:sync', (session) => {
|
||||
console.log('Session:', session);
|
||||
console.log('Server mode:', session.mode);
|
||||
});
|
||||
|
||||
// chat:init contains the recent chat history available when the bot connects.
|
||||
@@ -105,6 +106,21 @@ Run it with:
|
||||
node bot.js
|
||||
```
|
||||
|
||||
## Reading server mode
|
||||
|
||||
Read `session.mode` from the `session:sync` snapshot to get the current server
|
||||
mode. Its possible values are `open`, `turns`, `admin`, and `lockdown`.
|
||||
|
||||
The server sends a fresh session snapshot whenever the mode changes, so the
|
||||
example's handler receives both the initial mode and subsequent updates. No
|
||||
polling or separate mode listener is needed. If your bot stores session data for
|
||||
its chat-handling logic, replace the stored session on every `session:sync` and
|
||||
read the mode from that latest snapshot.
|
||||
|
||||
`session.mode` is the server-wide mode; `session.role` is this connection's role
|
||||
(such as `spectator`), and `session.operatingMode` is a separate connection field.
|
||||
Use `session.mode` when answering chat questions about the server's current mode.
|
||||
|
||||
## Events used
|
||||
|
||||
- `nickname:set` sets the bot's visible nickname.
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Finite CPU benchmark of LeRobot ACT with ImageNet-pretrained ResNet-18.
|
||||
|
||||
First run: python3 perf/act-benchmark.py --setup
|
||||
Repeat: python3 perf/act-benchmark.py
|
||||
Quick: python3 perf/act-benchmark.py --threads 4 --seconds 2 --iterations 2 --batch-size 2
|
||||
|
||||
Python >=3.12, Linux. Setup uses a private cached environment. Only the visual
|
||||
backbone is pretrained; the action policy is randomly initialized. Synthetic
|
||||
in-memory inputs measure compute, NOT learning quality or driving competence.
|
||||
No rover connections, server changes, training checkpoints, or background jobs.
|
||||
"""
|
||||
import argparse
|
||||
import contextlib
|
||||
import importlib.metadata
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import resource
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import venv
|
||||
|
||||
REVISION = '146d8474932c8b566717eb2738ba459337ab71c4'
|
||||
|
||||
|
||||
def positive(value):
|
||||
number = int(value)
|
||||
if number < 1:
|
||||
raise argparse.ArgumentTypeError('Must be positive')
|
||||
return number
|
||||
|
||||
|
||||
def arguments():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('--setup', action='store_true')
|
||||
parser.add_argument('--cache', type=Path, default=Path.home() / '.cache/rover-act-benchmark')
|
||||
parser.add_argument('--threads', nargs='+', type=positive, default=[4, 8, 16])
|
||||
parser.add_argument('--seconds', type=positive, default=10)
|
||||
parser.add_argument('--iterations', type=positive, default=10)
|
||||
parser.add_argument('--batch-size', type=positive, default=8, help='Training only; inference batch is always one rover')
|
||||
parser.add_argument('--chunk-size', type=positive, default=10, help='Future command steps per prediction, not observed history')
|
||||
parser.add_argument('--width', type=positive, default=160)
|
||||
parser.add_argument('--height', type=positive, default=120)
|
||||
parser.add_argument('--sensors', type=positive, default=30)
|
||||
parser.add_argument('--mode', choices=['both', 'inference', 'training'], default='both')
|
||||
parser.add_argument('--timeout', type=positive, default=900, help='Hard per-case wall time limit in seconds')
|
||||
parser.add_argument('--worker', action='store_true', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--result', type=Path, help=argparse.SUPPRESS)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def setup(args):
|
||||
python = args.cache / 'venv/bin/python'
|
||||
if not python.exists():
|
||||
venv.EnvBuilder(with_pip=True).create(args.cache / 'venv')
|
||||
subprocess.run([str(python), '-m', 'pip', 'install', '--no-compile', 'torch', 'torchvision',
|
||||
'--index-url', 'https://download.pytorch.org/whl/cpu'], check=True)
|
||||
# Install only ACT's import dependencies: the full robotics/dataset stack has
|
||||
# unrelated version constraints and is not exercised by this benchmark.
|
||||
subprocess.run([str(python), '-m', 'pip', 'install', '--no-compile', 'numpy', 'einops>=0.8,<0.9',
|
||||
'draccus>=0.11.6,<0.12', 'huggingface-hub>=1.6,<2', 'safetensors',
|
||||
'packaging', 'termcolor', 'tqdm', 'gymnasium'], check=True)
|
||||
subprocess.run([str(python), '-m', 'pip', 'install', '--no-compile', '--no-deps',
|
||||
f'https://github.com/huggingface/lerobot/archive/{REVISION}.zip'], check=True)
|
||||
(args.cache / 'source-revision').write_text(REVISION)
|
||||
|
||||
|
||||
def worker(args):
|
||||
import torch
|
||||
from lerobot.configs import FeatureType, PolicyFeature
|
||||
from lerobot.policies.act.configuration_act import ACTConfig
|
||||
from lerobot.policies.act.modeling_act import ACTPolicy
|
||||
|
||||
torch.set_num_threads(args.threads[0])
|
||||
torch.set_num_interop_threads(1)
|
||||
torch.manual_seed(7)
|
||||
training = args.mode == 'training'
|
||||
batch_size = args.batch_size if training else 1
|
||||
config = ACTConfig(device='cpu', chunk_size=args.chunk_size, n_action_steps=1,
|
||||
input_features={
|
||||
'observation.images.front': PolicyFeature(type=FeatureType.VISUAL, shape=(3, args.height, args.width)),
|
||||
'observation.state': PolicyFeature(type=FeatureType.STATE, shape=(args.sensors,)),
|
||||
}, output_features={'action': PolicyFeature(type=FeatureType.ACTION, shape=(2,))})
|
||||
policy = ACTPolicy(config).cpu().float()
|
||||
policy.train(training)
|
||||
optimizer_config = config.get_optimizer_preset()
|
||||
optimizer = optimizer_config.build(policy.get_optim_params()) if training else None
|
||||
# Already-normalized tensors stand in for a decoded observation and target
|
||||
# sequence. Avoid video/dataset overhead in this compute-only measurement.
|
||||
images = torch.rand(batch_size, 3, args.height, args.width)
|
||||
mean = torch.tensor([.485, .456, .406]).view(1, 3, 1, 1)
|
||||
std = torch.tensor([.229, .224, .225]).view(1, 3, 1, 1)
|
||||
batch = {'observation.images.front': (images - mean) / std,
|
||||
'observation.state': torch.randn(batch_size, args.sensors)}
|
||||
if training:
|
||||
batch['action'] = torch.rand(batch_size, args.chunk_size, 2) * 2 - 1
|
||||
batch['action_is_pad'] = torch.zeros(batch_size, args.chunk_size, dtype=torch.bool)
|
||||
|
||||
def step():
|
||||
if training:
|
||||
optimizer.zero_grad(set_to_none=True)
|
||||
loss, _ = policy(batch)
|
||||
if not torch.isfinite(loss):
|
||||
raise RuntimeError('Non-finite training loss')
|
||||
loss.backward()
|
||||
norm = torch.nn.utils.clip_grad_norm_(policy.parameters(), optimizer_config.grad_clip_norm,
|
||||
error_if_nonfinite=True)
|
||||
optimizer.step()
|
||||
return {'loss': loss.item(), 'gradientNorm': norm.item()}
|
||||
# select_action can serve cached actions; directly time a full chunk.
|
||||
prediction = policy.predict_action_chunk(batch)
|
||||
if prediction.shape != (1, args.chunk_size, 2) or not torch.isfinite(prediction).all():
|
||||
raise RuntimeError('Invalid action output')
|
||||
return {'outputShape': list(prediction.shape)}
|
||||
|
||||
with (contextlib.nullcontext() if training else torch.inference_mode()):
|
||||
for _ in range(3):
|
||||
step()
|
||||
timings = []
|
||||
started, cpu_started = time.perf_counter(), time.process_time()
|
||||
while len(timings) < args.iterations or time.perf_counter() - started < args.seconds:
|
||||
tick = time.perf_counter()
|
||||
last = step()
|
||||
timings.append((time.perf_counter() - tick) * 1000)
|
||||
elapsed, cpu = time.perf_counter() - started, time.process_time() - cpu_started
|
||||
timings.sort()
|
||||
result = dict(mode=args.mode, threads=args.threads[0], batchSize=batch_size,
|
||||
iterations=len(timings), elapsedSeconds=elapsed, p50Ms=statistics.median(timings),
|
||||
p95Ms=timings[math.ceil(.95*len(timings))-1], maxMs=max(timings),
|
||||
stepsPerSecond=len(timings)/elapsed, examplesPerSecond=len(timings)*batch_size/elapsed,
|
||||
cpuCores=cpu/elapsed, peakMiB=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024,
|
||||
parameters=sum(p.numel() for p in policy.parameters()),
|
||||
trainableParameters=sum(p.numel() for p in policy.parameters() if p.requires_grad),
|
||||
lastStep=last, config={
|
||||
'chunkSize': config.chunk_size, 'dimModel': config.dim_model, 'klWeight': config.kl_weight,
|
||||
'pretrainedBackbone': config.pretrained_backbone_weights, 'useVae': config.use_vae,
|
||||
'encoderLayers': config.n_encoder_layers, 'decoderLayers': config.n_decoder_layers,
|
||||
'feedforwardDimension': config.dim_feedforward, 'observationSteps': config.n_obs_steps,
|
||||
'learningRate': optimizer_config.lr, 'backboneLearningRate': config.optimizer_lr_backbone},
|
||||
versions={key: importlib.metadata.version(key) for key in ['torch','torchvision','lerobot','numpy','einops','draccus']})
|
||||
args.result.write_text(json.dumps(result))
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments()
|
||||
if sys.version_info < (3, 12):
|
||||
raise RuntimeError('Use Python 3.12 or newer')
|
||||
args.cache = args.cache.expanduser().resolve()
|
||||
os.environ['TORCH_HOME'] = str(args.cache / 'torch')
|
||||
if args.worker:
|
||||
worker(args)
|
||||
return
|
||||
if args.setup:
|
||||
setup(args)
|
||||
python = args.cache / 'venv/bin/python'
|
||||
marker = args.cache / 'source-revision'
|
||||
if not python.exists() or not marker.exists() or marker.read_text() != REVISION:
|
||||
raise RuntimeError('Run python3 perf/act-benchmark.py --setup first')
|
||||
print('CPU FP32 ACT: pretrained visual backbone, untrained action policy; synthetic data.', flush=True)
|
||||
print(f'One {args.width}x{args.height} image + {args.sensors} sensors; {args.chunk_size} future left/right command pairs.', flush=True)
|
||||
print('Inference times a fresh full prediction. Training includes backbone gradients and optimizer update.', flush=True)
|
||||
print('mode threads batch p50 ms p95 ms max ms steps/s examples/s CPU cores peak MiB', flush=True)
|
||||
modes = ['inference', 'training'] if args.mode == 'both' else [args.mode]
|
||||
results, failures = [], []
|
||||
initial_load = os.getloadavg()
|
||||
with tempfile.TemporaryDirectory(prefix='act-benchmark-') as directory:
|
||||
for mode in modes:
|
||||
for threads in args.threads:
|
||||
result_path = Path(directory) / 'result.json'
|
||||
command = [str(python), str(Path(__file__).resolve()), '--worker', '--cache', str(args.cache),
|
||||
'--mode', mode, '--threads', str(threads), '--result', str(result_path)]
|
||||
for option in ['seconds','iterations','batch_size','chunk_size','width','height','sensors']:
|
||||
command += ['--'+option.replace('_','-'), str(getattr(args, option))]
|
||||
try:
|
||||
subprocess.run(command, check=True, timeout=args.timeout,
|
||||
env={**os.environ, 'PYTHONDONTWRITEBYTECODE':'1'})
|
||||
r = json.loads(result_path.read_text())
|
||||
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
|
||||
failures.append(dict(mode=mode, threads=threads, error=str(error)))
|
||||
print(f'Case failed: {mode}, {threads} threads: {error}', flush=True)
|
||||
break # Avoid repeating the same setup/import/OOM error.
|
||||
results.append(r)
|
||||
print(f"{mode:10} {threads:7} {r['batchSize']:5} {r['p50Ms']:6.1f} {r['p95Ms']:6.1f} {r['maxMs']:6.1f} {r['stepsPerSecond']:7.2f} {r['examplesPerSecond']:10.2f} {r['cpuCores']:9.2f} {r['peakMiB']:8.0f}", flush=True)
|
||||
if failures:
|
||||
break
|
||||
report = dict(benchmark='act-cpu-v1', sourceRevision=REVISION, platform=platform.platform(),
|
||||
python=sys.version, logicalCpus=os.cpu_count(), initialLoadAverage=initial_load,
|
||||
finalLoadAverage=os.getloadavg(), imageSize=[args.width,args.height], sensors=args.sensors,
|
||||
chunkSize=args.chunk_size, output='commanded left/right wheels, not physical velocity or position',
|
||||
exclusions=['capture','video decode','dataset I/O','network','concurrent training/inference','driving quality'],
|
||||
results=results, failures=failures)
|
||||
print('\nPaste this report back:\n'+json.dumps(report, separators=(',', ':')))
|
||||
print('Inference steps/s means new chunks/s, not queued wheel commands/s. Training loss on random data is not a quality score.')
|
||||
if failures:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (Exception, KeyboardInterrupt) as error:
|
||||
print(f'Benchmark failed: {error}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,208 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CPU benchmark of published NoMaD exploration, without ROS or rover connections.
|
||||
|
||||
Run: python3 perf/nomad-benchmark.py --setup
|
||||
Subsequent runs: python3 perf/nomad-benchmark.py
|
||||
Quick run: python3 perf/nomad-benchmark.py --threads 4 --samples 1 --seconds 2 --iterations 2
|
||||
|
||||
--setup installs CPU dependencies in a private cached venv and downloads pinned
|
||||
upstream source plus the official checkpoint. Nothing touches server packages.
|
||||
Synthetic images measure compute, NOT navigation quality. Excludes capture,
|
||||
video decode, network, physical control, training, and concurrent rover load.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.metadata
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import resource
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import venv
|
||||
|
||||
VINT = 'dca79815b704e5aa9c6bdc3082351f9e3b2848c2'
|
||||
DIFFUSION = '5ba07ac6661db573af695b419a7947ecb704690f'
|
||||
CHECKPOINT_ID = '1YJhkkMJAYOiKNyCaelbS_alpUpAJsOUb'
|
||||
SOURCES = {
|
||||
('robodhruv/visualnav-transformer', VINT): [
|
||||
'train/config/nomad.yaml', 'train/vint_train/data/data_config.yaml',
|
||||
'train/vint_train/models/nomad/nomad.py',
|
||||
'train/vint_train/models/nomad/nomad_vint.py',
|
||||
'train/vint_train/models/vint/self_attention.py',
|
||||
],
|
||||
('real-stanford/diffusion_policy', DIFFUSION): [
|
||||
'diffusion_policy/model/diffusion/conditional_unet1d.py',
|
||||
'diffusion_policy/model/diffusion/conv1d_components.py',
|
||||
'diffusion_policy/model/diffusion/positional_embedding.py',
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def positive(value):
|
||||
result = int(value)
|
||||
if result < 1:
|
||||
raise argparse.ArgumentTypeError('Must be positive')
|
||||
return result
|
||||
|
||||
|
||||
def arguments():
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument('--setup', action='store_true')
|
||||
p.add_argument('--cache', type=Path, default=Path.home() / '.cache/rover-nomad-benchmark')
|
||||
p.add_argument('--threads', type=positive, nargs='+', default=[4, 8, 16])
|
||||
p.add_argument('--samples', type=positive, nargs='+', default=[1, 8], help='Candidate trajectories per decision, not rover count')
|
||||
p.add_argument('--seconds', type=positive, default=10)
|
||||
p.add_argument('--iterations', type=positive, default=10)
|
||||
p.add_argument('--worker', action='store_true', help=argparse.SUPPRESS)
|
||||
p.add_argument('--result', type=Path, help=argparse.SUPPRESS)
|
||||
return p.parse_args()
|
||||
|
||||
|
||||
def download(url, path):
|
||||
if path.exists():
|
||||
return
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(path.suffix + '.part')
|
||||
print('Downloading', path.name, flush=True)
|
||||
with urllib.request.urlopen(url, timeout=120) as response, temporary.open('wb') as output:
|
||||
import shutil
|
||||
shutil.copyfileobj(response, output)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def prepare(args):
|
||||
python = args.cache / 'venv/bin/python'
|
||||
if not python.exists():
|
||||
venv.EnvBuilder(with_pip=True).create(args.cache / 'venv')
|
||||
subprocess.run([str(python), '-m', 'pip', 'install', 'torch', 'torchvision',
|
||||
'--index-url', 'https://download.pytorch.org/whl/cpu'], check=True)
|
||||
subprocess.run([str(python), '-m', 'pip', 'install', 'numpy', 'diffusers',
|
||||
'efficientnet-pytorch', 'einops', 'PyYAML', 'gdown'], check=True)
|
||||
for (repo, revision), paths in SOURCES.items():
|
||||
for path in paths:
|
||||
download(f'https://raw.githubusercontent.com/{repo}/{revision}/{path}', args.cache / 'source' / revision / path)
|
||||
checkpoint = args.cache / 'nomad.pth'
|
||||
if not checkpoint.exists():
|
||||
temporary = checkpoint.with_suffix('.part')
|
||||
subprocess.run([str(python), '-m', 'gdown', CHECKPOINT_ID, '-O', str(temporary)], check=True)
|
||||
temporary.replace(checkpoint)
|
||||
|
||||
|
||||
def worker(args):
|
||||
import numpy as np
|
||||
import torch
|
||||
import yaml
|
||||
from diffusers.schedulers.scheduling_ddpm import DDPMScheduler
|
||||
sys.path[:0] = [str(args.cache / 'source' / VINT / 'train'), str(args.cache / 'source' / DIFFUSION)]
|
||||
from vint_train.models.nomad.nomad import NoMaD, DenseNetwork
|
||||
from vint_train.models.nomad.nomad_vint import NoMaD_ViNT, replace_bn_with_gn
|
||||
from diffusion_policy.model.diffusion.conditional_unet1d import ConditionalUnet1D
|
||||
|
||||
threads, samples = args.threads[0], args.samples[0]
|
||||
torch.set_num_threads(threads)
|
||||
torch.set_num_interop_threads(1)
|
||||
torch.manual_seed(0)
|
||||
c = yaml.safe_load((args.cache / 'source' / VINT / 'train/config/nomad.yaml').read_text())
|
||||
vision = replace_bn_with_gn(NoMaD_ViNT(
|
||||
context_size=c['context_size'], obs_encoding_size=c['encoding_size'],
|
||||
mha_num_attention_heads=c['mha_num_attention_heads'],
|
||||
mha_num_attention_layers=c['mha_num_attention_layers'], mha_ff_dim_factor=c['mha_ff_dim_factor']))
|
||||
model = NoMaD(vision, ConditionalUnet1D(input_dim=2, global_cond_dim=c['encoding_size'],
|
||||
down_dims=c['down_dims'], cond_predict_scale=c['cond_predict_scale']), DenseNetwork(c['encoding_size'])).eval()
|
||||
# Strict loading prevents accidentally benchmarking a partly random model.
|
||||
model.load_state_dict(torch.load(args.cache / 'nomad.pth', map_location='cpu', weights_only=True), strict=True)
|
||||
scheduler = DDPMScheduler(num_train_timesteps=c['num_diffusion_iters'],
|
||||
beta_schedule='squaredcos_cap_v2', clip_sample=True, prediction_type='epsilon')
|
||||
width, height = c['image_size']
|
||||
frames = torch.rand(c['context_size'] + 1, 3, height, width)
|
||||
mean = torch.tensor([.485, .456, .406]).view(1, 3, 1, 1)
|
||||
std = torch.tensor([.229, .224, .225]).view(1, 3, 1, 1)
|
||||
mask = torch.ones(1, dtype=torch.long)
|
||||
stats = yaml.safe_load((args.cache / 'source' / VINT / 'train/vint_train/data/data_config.yaml').read_text())['action_stats']
|
||||
low, high = np.array(stats['min']), np.array(stats['max'])
|
||||
|
||||
def decision():
|
||||
start = time.perf_counter()
|
||||
obs = ((frames - mean) / std).reshape(1, -1, height, width)
|
||||
goal = torch.randn(1, 3, height, width)
|
||||
cond = model('vision_encoder', obs_img=obs, goal_img=goal, input_goal_mask=mask).repeat(samples, 1)
|
||||
encoded = time.perf_counter()
|
||||
action = torch.randn(samples, c['len_traj_pred'], 2)
|
||||
scheduler.set_timesteps(c['num_diffusion_iters'])
|
||||
for step in scheduler.timesteps:
|
||||
noise = model('noise_pred_net', sample=action, timestep=step, global_cond=cond)
|
||||
action = scheduler.step(noise, step, action).prev_sample
|
||||
# Match upstream get_action: unnormalize deltas then accumulate waypoints.
|
||||
waypoints = np.cumsum((action.numpy() + 1) / 2 * (high - low) + low, axis=1)
|
||||
if not np.isfinite(waypoints).all():
|
||||
raise RuntimeError('Non-finite model output')
|
||||
end = time.perf_counter()
|
||||
return (end - start) * 1000, (encoded - start) * 1000, (end - encoded) * 1000
|
||||
|
||||
rows = []
|
||||
with torch.inference_mode():
|
||||
for _ in range(3):
|
||||
decision()
|
||||
start, cpu = time.perf_counter(), time.process_time()
|
||||
while len(rows) < args.iterations or time.perf_counter() - start < args.seconds:
|
||||
rows.append(decision())
|
||||
elapsed, cpu = time.perf_counter() - start, time.process_time() - cpu
|
||||
total = sorted(r[0] for r in rows)
|
||||
result = dict(threads=threads, candidateTrajectories=samples, iterations=len(rows),
|
||||
p50Ms=statistics.median(total), p95Ms=total[math.ceil(.95 * len(total)) - 1], maxMs=max(total),
|
||||
decisionsPerSecond=len(rows)/elapsed, cpuCores=cpu/elapsed,
|
||||
peakMiB=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024,
|
||||
visionMeanMs=statistics.mean(r[1] for r in rows), diffusionAndDecodeMeanMs=statistics.mean(r[2] for r in rows),
|
||||
parameters=sum(p.numel() for p in model.parameters()), diffusionSteps=c['num_diffusion_iters'],
|
||||
imageSize=c['image_size'], frames=c['context_size']+1,
|
||||
versions={name: importlib.metadata.version(name) for name in ['torch','torchvision','diffusers','numpy','efficientnet-pytorch','einops']})
|
||||
args.result.write_text(json.dumps(result))
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments()
|
||||
args.cache = args.cache.expanduser().resolve()
|
||||
if args.worker:
|
||||
worker(args)
|
||||
return
|
||||
if args.setup:
|
||||
prepare(args)
|
||||
python = args.cache / 'venv/bin/python'
|
||||
if not python.exists() or not (args.cache / 'nomad.pth').exists():
|
||||
raise RuntimeError('First run: python3 perf/nomad-benchmark.py --setup')
|
||||
print('CPU FP32 NoMaD exploration; synthetic images; no driving-quality measurement.', flush=True)
|
||||
print('Candidates are trajectories for ONE rover. Includes vision + all 10 diffusion steps.', flush=True)
|
||||
print('threads candidates p50 ms p95 ms max ms decisions/s CPU cores peak MiB', flush=True)
|
||||
results = []
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory(prefix='nomad-bench-') as directory:
|
||||
for threads in args.threads:
|
||||
for samples in args.samples:
|
||||
path = Path(directory) / 'result.json'
|
||||
subprocess.run([str(python), str(Path(__file__).resolve()), '--worker', '--cache', str(args.cache),
|
||||
'--threads', str(threads), '--samples', str(samples), '--seconds', str(args.seconds),
|
||||
'--iterations', str(args.iterations), '--result', str(path)], check=True,
|
||||
timeout=max(600, args.seconds*20), env={**os.environ, 'PYTHONDONTWRITEBYTECODE':'1'})
|
||||
r = json.loads(path.read_text()); results.append(r)
|
||||
print(f"{threads:7} {samples:10} {r['p50Ms']:7.1f} {r['p95Ms']:7.1f} {r['maxMs']:7.1f} {r['decisionsPerSecond']:11.2f} {r['cpuCores']:9.2f} {r['peakMiB']:8.0f}", flush=True)
|
||||
with (args.cache / 'nomad.pth').open('rb') as f:
|
||||
digest = hashlib.file_digest(f, 'sha256').hexdigest()
|
||||
report = dict(benchmark='nomad-cpu-v1', platform=platform.platform(), logicalCpus=os.cpu_count(),
|
||||
loadAverage=os.getloadavg(), sourceRevisions=dict(vint=VINT,diffusion=DIFFUSION), checkpointSha256=digest,
|
||||
exclusions=['capture','video decode','network','physical control','training','concurrent model workloads'], results=results)
|
||||
print('\nPaste this report back:\n' + json.dumps(report, separators=(',', ':')))
|
||||
print('At 10 decisions/s the total budget is 100ms; at 5/s it is 200ms. Leave room for the excluded pipeline.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (Exception, KeyboardInterrupt) as error:
|
||||
print(f'Benchmark failed: {error}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -1,24 +0,0 @@
|
||||
BIN_DIR ?= ../../dist
|
||||
GOOS ?= linux
|
||||
GOARCH ?= arm
|
||||
GOARM ?= 6
|
||||
|
||||
.PHONY: build pi-build debian-laptop dummy verifier-tools clean
|
||||
|
||||
build: pi-build debian-laptop dummy
|
||||
|
||||
verifier-tools:
|
||||
GOOS=$(GOOS) GOARCH=$(GOARCH) GOARM=$(GOARM) go build -trimpath -ldflags="-s -w" -o $(BIN_DIR)/servoverifier ./cmd/servoverifier
|
||||
GOOS=$(GOOS) GOARCH=$(GOARCH) GOARM=$(GOARM) go build -trimpath -ldflags="-s -w" -o $(BIN_DIR)/hornverifier ./cmd/hornverifier
|
||||
|
||||
pi-build: verifier-tools
|
||||
GOOS=$(GOOS) GOARCH=$(GOARCH) GOARM=$(GOARM) go build -trimpath -ldflags="-s -w" -o $(BIN_DIR)/roverd ./cmd/roverd
|
||||
|
||||
debian-laptop:
|
||||
GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -tags debian_laptop -o $(BIN_DIR)/roverd-debian-laptop ./cmd/roverd
|
||||
|
||||
dummy:
|
||||
GOOS=linux GOARCH=amd64 go build -tags dummy -o $(BIN_DIR)/roverd-dummy ./cmd/roverd
|
||||
|
||||
clean:
|
||||
rm -f $(BIN_DIR)/roverd $(BIN_DIR)/roverd-debian-laptop $(BIN_DIR)/roverd-dummy $(BIN_DIR)/servoverifier $(BIN_DIR)/hornverifier
|
||||
@@ -1,25 +0,0 @@
|
||||
//go:build debian_laptop
|
||||
|
||||
package roverd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
)
|
||||
|
||||
type BRCPulser struct{}
|
||||
|
||||
func NewBRCPulser(_ BRCConfig, _ *log.Logger) (*BRCPulser, error) {
|
||||
/*
|
||||
The first Debian laptop profile keeps BRC disabled instead of pretending a
|
||||
USB serial modem-control line has already been selected and tested. The
|
||||
config can set brc.gpioPin: -1 to skip construction entirely; if someone
|
||||
enables it, fail loudly so the rover does not silently miss wake pulses.
|
||||
*/
|
||||
return nil, fmt.Errorf("brc is not supported in the debian-laptop build yet")
|
||||
}
|
||||
|
||||
func (b *BRCPulser) Close() {}
|
||||
|
||||
func (b *BRCPulser) Start(ctx context.Context) {}
|
||||
@@ -1,45 +0,0 @@
|
||||
//go:build debian_laptop
|
||||
|
||||
package roverd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
)
|
||||
|
||||
type CameraServo struct{}
|
||||
|
||||
func NewCameraServo(_ CameraServoConfig, _ *log.Logger) (*CameraServo, error) {
|
||||
/*
|
||||
This constructor represents only native host GPIO. The shared startup
|
||||
resolver selects the normal Firmata implementation when an ESP32 provides
|
||||
the role, so external hardware is not laptop-specific code.
|
||||
*/
|
||||
return nil, fmt.Errorf("camera servo not supported in the debian-laptop build")
|
||||
}
|
||||
|
||||
func (c *CameraServo) Close() {}
|
||||
|
||||
func (c *CameraServo) SetAngle(angle float64) error {
|
||||
return fmt.Errorf("camera servo disabled")
|
||||
}
|
||||
|
||||
func (c *CameraServo) Nudge(delta float64) error {
|
||||
return fmt.Errorf("camera servo disabled")
|
||||
}
|
||||
|
||||
func (c *CameraServo) SetPulseWidth(micros int) error {
|
||||
return fmt.Errorf("camera servo disabled")
|
||||
}
|
||||
|
||||
func (c *CameraServo) CurrentAngle() float64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (c *CameraServo) Configuration() CameraServoConfig {
|
||||
return CameraServoConfig{}
|
||||
}
|
||||
|
||||
func (c *CameraServo) BackendDescription() string {
|
||||
return "native GPIO"
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
module multiroombarover/pi/roverd
|
||||
|
||||
go 1.25.4
|
||||
|
||||
require (
|
||||
github.com/stianeikeland/go-rpio/v4 v4.6.0
|
||||
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07
|
||||
github.com/warthog618/go-gpiocdev v0.9.1
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
nhooyr.io/websocket v1.8.17
|
||||
)
|
||||
|
||||
require golang.org/x/sys v0.38.0 // indirect
|
||||
@@ -1,40 +0,0 @@
|
||||
//go:build debian_laptop
|
||||
|
||||
package roverd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
)
|
||||
|
||||
type GPIOToggle struct {
|
||||
name string
|
||||
}
|
||||
|
||||
func NewGPIOToggle(name string, _ GPIOToggleConfig, _ *log.Logger) (*GPIOToggle, error) {
|
||||
/*
|
||||
A Debian laptop has no native Raspberry Pi GPIO contract. Returning an
|
||||
error here catches an invalid native configuration; the shared resolver
|
||||
selects an ESP32 Firmata toggle before this constructor when native GPIO
|
||||
is disabled.
|
||||
*/
|
||||
return nil, fmt.Errorf("%s not supported in the debian-laptop build", name)
|
||||
}
|
||||
|
||||
func (g *GPIOToggle) Close() {}
|
||||
|
||||
func (g *GPIOToggle) HandleAction(action string) error {
|
||||
return fmt.Errorf("%s not supported in the debian-laptop build", g.name)
|
||||
}
|
||||
|
||||
func (g *GPIOToggle) On() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (g *GPIOToggle) Configuration() GPIOToggleConfig {
|
||||
return GPIOToggleConfig{}
|
||||
}
|
||||
|
||||
func (g *GPIOToggle) BackendDescription() string {
|
||||
return "native GPIO"
|
||||
}
|
||||
Binary file not shown.
@@ -1,105 +0,0 @@
|
||||
# Sample configuration for roverd on a Debian laptop rover.
|
||||
name: laptop-rover
|
||||
description: "Debian laptop rover using USB serial, webcam, mic, and speakers."
|
||||
color: "#4DB6AC"
|
||||
serverUrl: ws://control-server.local:8080/rover
|
||||
|
||||
serial:
|
||||
device: /dev/ttyUSB0
|
||||
baud: 115200
|
||||
|
||||
# BRC is disabled in the first Debian laptop profile because USB serial
|
||||
# RTS/DTR wake-pulse support needs adapter-specific testing before it should be
|
||||
# trusted to keep a Roomba awake.
|
||||
brc:
|
||||
gpioPin: -1
|
||||
|
||||
battery:
|
||||
full: 2068
|
||||
warn: 1700
|
||||
urgent: 1650
|
||||
|
||||
maxWheelSpeed: 350
|
||||
|
||||
media:
|
||||
# Media URLs are derived from serverUrl's hostname, this port, and the rover name.
|
||||
rtspPort: 8554
|
||||
manage: true
|
||||
healthUrl: ""
|
||||
healthInterval: 30s
|
||||
video:
|
||||
enabled: true
|
||||
service: debian-laptop-video-publisher.service
|
||||
publisher: debian-laptop-v4l2
|
||||
device: /dev/video0
|
||||
# Check supported values with:
|
||||
# v4l2-ctl --device=/dev/video0 --list-formats-ext
|
||||
# Common working values are mjpeg and yuyv422.
|
||||
inputFormat: mjpeg
|
||||
width: 640
|
||||
height: 480
|
||||
fps: 30
|
||||
bitrate: 2000000
|
||||
inverted: false
|
||||
audioCapture:
|
||||
enabled: true
|
||||
service: audio-only-publisher.service
|
||||
device: default
|
||||
sampleRate: 48000
|
||||
channels: 2
|
||||
bitrate: 510000
|
||||
audioPlayback:
|
||||
enabled: true
|
||||
service: audio-forward-listener.service
|
||||
# The Debian laptop installer creates a named "forward" ALSA device so
|
||||
# browser-forwarded audio has its own ForwardMaster mixer control instead
|
||||
# of sharing the TTS default output path.
|
||||
device: forward
|
||||
normalize: true
|
||||
|
||||
cameraServo:
|
||||
enabled: false
|
||||
|
||||
audio:
|
||||
# TTS does not need Pi-specific hardware. The laptop ALSA profile maps the
|
||||
# normal default playback device through the TTSMaster softvol control, so
|
||||
# the existing flite/espeak execution path can stay unchanged.
|
||||
ttsEnabled: true
|
||||
defaultEngine: flite
|
||||
|
||||
horn:
|
||||
# Horn audio is generated locally by roverd and plays through the named
|
||||
# "horn" ALSA device by default, which the laptop installer wires to a
|
||||
# separate HornMaster softvol control.
|
||||
enabled: true
|
||||
|
||||
headlight:
|
||||
enabled: false
|
||||
|
||||
laser:
|
||||
enabled: false
|
||||
|
||||
autoSideBrush:
|
||||
enabled: true
|
||||
speed: 20
|
||||
|
||||
private:
|
||||
enabled: false
|
||||
safety:
|
||||
speedLimitEnabled: false
|
||||
speedLimitMaxWheelSpeed: 250
|
||||
hardOvercurrentEnabled: false
|
||||
overcurrentStopMs: 300
|
||||
hardBumpEnabled: false
|
||||
bumpBackoffSpeed: 250
|
||||
bumpBackoffMs: 350
|
||||
cliffEnabled: false
|
||||
cliffBackoffSpeed: 250
|
||||
cliffBackoffMs: 500
|
||||
# Virtual walls are default-on for private rovers because they mark a
|
||||
# deliberate boundary, and the server can escape by reversing the last
|
||||
# commanded wheel directions instead of always backing straight up.
|
||||
virtualWallEnabled: true
|
||||
virtualWallBackoffSpeed: 250
|
||||
virtualWallBackoffMs: 500
|
||||
triggerCooldownMs: 800
|
||||
@@ -1,111 +0,0 @@
|
||||
# Sample configuration for roverd
|
||||
name: roomba-alpha
|
||||
description: "Loves corners, hates cords."
|
||||
color: "#4DB6AC"
|
||||
serverUrl: ws://control-server.local:8080/rover
|
||||
serial:
|
||||
device: /dev/ttyAMA0
|
||||
baud: 115200
|
||||
brc:
|
||||
gpioPin: 4
|
||||
gpioChip: gpiochip0
|
||||
pulseEvery: 1m
|
||||
pulseWidth: 1s
|
||||
battery:
|
||||
full: 2068
|
||||
warn: 1700
|
||||
urgent: 1650
|
||||
maxWheelSpeed: 350
|
||||
media:
|
||||
# Media URLs are derived from serverUrl's hostname, this port, and the rover name.
|
||||
rtspPort: 8554
|
||||
manage: true
|
||||
healthUrl: ""
|
||||
healthInterval: 30s
|
||||
video:
|
||||
enabled: true
|
||||
service: video-publisher.service
|
||||
publisher: pi-libcamera
|
||||
width: 640
|
||||
height: 480
|
||||
fps: 30
|
||||
bitrate: 2000000
|
||||
# Default assumes camera is mounted upside down; set false for upright mounts.
|
||||
inverted: true
|
||||
sensorMode: 1296:972
|
||||
audioCapture:
|
||||
enabled: false
|
||||
service: audio-only-publisher.service
|
||||
device: hw:0,0
|
||||
sampleRate: 48000
|
||||
channels: 2
|
||||
bitrate: 510000
|
||||
audioPlayback:
|
||||
enabled: true
|
||||
service: audio-forward-listener.service
|
||||
device: forward
|
||||
normalize: true
|
||||
cameraServo:
|
||||
enabled: false
|
||||
pin: 12
|
||||
freqHz: 50
|
||||
cycleLen: 20000
|
||||
minPulseUs: 900
|
||||
maxPulseUs: 2100
|
||||
invert: false
|
||||
minAngle: -15
|
||||
maxAngle: 30
|
||||
homeAngle: 0
|
||||
nudgeDegrees: 2
|
||||
allowRawPulse: false
|
||||
audio:
|
||||
captureEnabled: false
|
||||
captureDevice: hw:0,0
|
||||
playbackDevice: forward
|
||||
ttsEnabled: false
|
||||
defaultEngine: flite
|
||||
defaultVoice: rms
|
||||
defaultPitch: 50
|
||||
horn:
|
||||
enabled: false
|
||||
volume: 0.25
|
||||
sampleRate: 48000
|
||||
channels: 1
|
||||
sineGain: 1.0
|
||||
sawGain: 0.7
|
||||
maxDuration: 1.2s
|
||||
headlight:
|
||||
enabled: true
|
||||
gpioPin: 22
|
||||
gpioChip: gpiochip0
|
||||
initialOn: false
|
||||
activeLow: true
|
||||
laser:
|
||||
enabled: false
|
||||
gpioPin: 27
|
||||
gpioChip: gpiochip0
|
||||
initialOn: false
|
||||
activeLow: false
|
||||
autoSideBrush:
|
||||
enabled: true
|
||||
speed: 20
|
||||
private:
|
||||
enabled: false
|
||||
safety:
|
||||
speedLimitEnabled: false
|
||||
speedLimitMaxWheelSpeed: 250
|
||||
hardOvercurrentEnabled: false
|
||||
overcurrentStopMs: 300
|
||||
hardBumpEnabled: false
|
||||
bumpBackoffSpeed: 250
|
||||
bumpBackoffMs: 350
|
||||
cliffEnabled: false
|
||||
cliffBackoffSpeed: 250
|
||||
cliffBackoffMs: 500
|
||||
# Virtual walls are default-on for private rovers because they mark a
|
||||
# deliberate boundary, and the server can escape by reversing the last
|
||||
# commanded wheel directions instead of always backing straight up.
|
||||
virtualWallEnabled: true
|
||||
virtualWallBackoffSpeed: 250
|
||||
virtualWallBackoffMs: 500
|
||||
triggerCooldownMs: 800
|
||||
@@ -1,78 +0,0 @@
|
||||
# Sample configuration for roverd
|
||||
name: roomba-alpha
|
||||
description: "Loves corners, hates cords."
|
||||
serverUrl: ws://control-server.local:8080/rover
|
||||
serial:
|
||||
device: /dev/ttyAMA0
|
||||
baud: 115200
|
||||
brc:
|
||||
gpioPin: 4
|
||||
gpioChip: gpiochip0
|
||||
pulseEvery: 1m
|
||||
pulseWidth: 1s
|
||||
battery:
|
||||
full: 2068
|
||||
warn: 1700
|
||||
urgent: 1650
|
||||
maxWheelSpeed: 350
|
||||
media:
|
||||
manage: false
|
||||
healthUrl: http://127.0.0.1:9997/v3/paths/list
|
||||
healthInterval: 30s
|
||||
video:
|
||||
enabled: true
|
||||
service: video-publisher.service
|
||||
publisher: pi-libcamera
|
||||
audioCapture:
|
||||
enabled: false
|
||||
service: audio-only-publisher.service
|
||||
audioPlayback:
|
||||
enabled: true
|
||||
service: audio-forward-listener.service
|
||||
cameraServo:
|
||||
enabled: false
|
||||
pin: 19
|
||||
freqHz: 50
|
||||
cycleLen: 20000
|
||||
minPulseUs: 900
|
||||
maxPulseUs: 2100
|
||||
minAngle: -15
|
||||
maxAngle: 30
|
||||
homeAngle: 0
|
||||
nudgeDegrees: 2
|
||||
allowRawPulse: false
|
||||
headlight:
|
||||
enabled: true
|
||||
gpioPin: 22
|
||||
gpioChip: gpiochip0
|
||||
initialOn: false
|
||||
activeLow: true
|
||||
laser:
|
||||
enabled: false
|
||||
gpioPin: 27
|
||||
gpioChip: gpiochip0
|
||||
initialOn: false
|
||||
activeLow: false
|
||||
autoSideBrush:
|
||||
enabled: true
|
||||
speed: 20
|
||||
private:
|
||||
enabled: false
|
||||
safety:
|
||||
speedLimitEnabled: false
|
||||
speedLimitMaxWheelSpeed: 250
|
||||
hardOvercurrentEnabled: false
|
||||
overcurrentStopMs: 300
|
||||
hardBumpEnabled: false
|
||||
bumpBackoffSpeed: 250
|
||||
bumpBackoffMs: 350
|
||||
cliffEnabled: false
|
||||
cliffBackoffSpeed: 250
|
||||
cliffBackoffMs: 500
|
||||
# Virtual walls are default-on for private rovers because they mark a
|
||||
# deliberate boundary, and the server can escape by reversing the last
|
||||
# commanded wheel directions instead of always backing straight up.
|
||||
virtualWallEnabled: true
|
||||
virtualWallBackoffSpeed: 250
|
||||
virtualWallBackoffMs: 500
|
||||
triggerCooldownMs: 800
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
# Reference ALSA routing for the Debian laptop rover profile.
|
||||
#
|
||||
# This intentionally mirrors pi/asound.conf as closely as a normal PC can:
|
||||
# This intentionally mirrors rover/asound.conf as closely as a normal PC can:
|
||||
# one fixed hardware card, one dmix playback engine, separate softvol controls
|
||||
# for TTS/horn/forwarded audio, and a raw capture alias for the rover mic.
|
||||
#
|
||||
@@ -136,7 +136,7 @@ run_pipeline() {
|
||||
|
||||
# The capture format comes from roverd's normalized media config. Keeping
|
||||
# arecord and ffmpeg on the same env-backed values prevents the publisher
|
||||
# script from quietly disagreeing with roverd.yaml about sample rate or
|
||||
# script from quietly disagreeing with roverd.json about sample rate or
|
||||
# channel count.
|
||||
#
|
||||
# The buffer and period are byte counts because arecord interprets -B/-F in
|
||||
+1
-1
@@ -80,7 +80,7 @@ if [[ -n "${ROVERD_VIDEO_INPUT_FORMAT}" ]]; then
|
||||
# wrong negotiated format can still produce a decodable stream, but the
|
||||
# picture appears as green/noisy mush because ffmpeg is interpreting the
|
||||
# frame bytes with the wrong pixel format. Passing input_format pins V4L2 to
|
||||
# the camera mode selected in roverd.yaml.
|
||||
# the camera mode selected in roverd.json.
|
||||
INPUT_FORMAT_ARGS=(-input_format "${ROVERD_VIDEO_INPUT_FORMAT}")
|
||||
fi
|
||||
|
||||
@@ -39,7 +39,7 @@ if [[ "${ROVERD_SELF_UPDATE_SYSTEMD:-}" != "1" ]] && command -v systemd-run >/de
|
||||
fi
|
||||
|
||||
if [[ ! -f "$ENV_FILE" ]]; then
|
||||
echo "Missing $ENV_FILE; run pi/install_roverd.sh once to register the repository path" >&2
|
||||
echo "Missing $ENV_FILE; run rover/install_roverd.sh once to register the repository path" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -56,8 +56,8 @@ if [[ ! -d "$ROVERD_REPO_DIR/.git" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -x "$ROVERD_REPO_DIR/pi/install_roverd.sh" ]]; then
|
||||
echo "Installer is missing or not executable: $ROVERD_REPO_DIR/pi/install_roverd.sh" >&2
|
||||
if [[ ! -x "$ROVERD_REPO_DIR/rover/install_roverd.sh" ]]; then
|
||||
echo "Installer is missing or not executable: $ROVERD_REPO_DIR/rover/install_roverd.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -93,6 +93,6 @@ log "Repository fast-forward pull complete"
|
||||
# The installer already owns the full desired rover host state. Reusing it here
|
||||
# prevents this update helper from becoming a second, partial installer that can
|
||||
# drift away from the normal manual install path.
|
||||
"$ROVERD_REPO_DIR/pi/install_roverd.sh"
|
||||
"$ROVERD_REPO_DIR/rover/install_roverd.sh"
|
||||
log "Installer completed successfully"
|
||||
systemctl reboot
|
||||
@@ -77,7 +77,7 @@ if [[ "${ROVERD_VIDEO_ENABLE}" -ne 1 ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# The inversion decision is made in roverd.yaml and written into media.env, so
|
||||
# The inversion decision is made in roverd.json and written into media.env, so
|
||||
# this script only converts the configured logical value into libcamera flags.
|
||||
FLIP_ARGS=()
|
||||
if [[ "${ROVERD_VIDEO_INVERT}" -ne 0 ]]; then
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
CONFIG_DEST="/etc/roverd.yaml"
|
||||
CONFIG_DEST="/etc/roverd.json"
|
||||
|
||||
log() {
|
||||
echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*"
|
||||
@@ -58,7 +58,7 @@ validate_install_inputs() {
|
||||
|
||||
install_roverd_binary() {
|
||||
ensure_user roverd "$ROVERD_GROUPS"
|
||||
install -o roverd -g roverd -m 0755 "$BINARY_SRC" /usr/local/bin/roverd
|
||||
install -o root -g root -m 0755 "$BINARY_SRC" /usr/local/bin/roverd
|
||||
log "Installed roverd binary for profile $PROFILE"
|
||||
}
|
||||
|
||||
@@ -68,12 +68,12 @@ install_roverd_config() {
|
||||
CONFIG_EXISTS=1
|
||||
log "Existing $CONFIG_DEST found; leaving it in place"
|
||||
else
|
||||
install -D -o roverd -g roverd -m 0640 "$CONFIG_SRC" "$CONFIG_DEST"
|
||||
install -D -o root -g root -m 0600 "$CONFIG_SRC" "$CONFIG_DEST"
|
||||
log "Installed sample config to $CONFIG_DEST (edit before starting service)"
|
||||
fi
|
||||
}
|
||||
|
||||
install_roverd_unit() {
|
||||
install -m 0644 pi/systemd/roverd.service /etc/systemd/system/roverd.service
|
||||
install -m 0644 rover/systemd/roverd.service /etc/systemd/system/roverd.service
|
||||
log "Installed roverd systemd unit"
|
||||
}
|
||||
@@ -184,7 +184,7 @@ load_or_create_debian_laptop_alsa_config() {
|
||||
else
|
||||
if ! { true </dev/tty >/dev/tty; } 2>/dev/null; then
|
||||
echo "Missing $DEBIAN_LAPTOP_INSTALLER_CONFIG and no interactive terminal is available for ALSA setup." >&2
|
||||
echo "Run sudo ./pi/install_roverd.sh --debian-laptop once from a terminal, then reuse the generated config for future installs." >&2
|
||||
echo "Run sudo ./rover/install_roverd.sh --debian-laptop once from a terminal, then reuse the generated config for future installs." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -337,7 +337,7 @@ install_debian_laptop_audio_support() {
|
||||
load_or_create_debian_laptop_alsa_config
|
||||
render_debian_laptop_asound_config
|
||||
|
||||
install -D -o root -g root -m 0755 pi/bin/chromegtts-daemon-laptop.py /usr/local/bin/chromegtts-daemon
|
||||
install -D -o root -g root -m 0755 rover/bin/chromegtts-daemon-laptop.py /usr/local/bin/chromegtts-daemon
|
||||
log "Installed laptop chromegtts daemon"
|
||||
|
||||
install_google_tts_assets_laptop
|
||||
@@ -5,7 +5,7 @@ write_media_env_placeholder() {
|
||||
|
||||
case "$PROFILE" in
|
||||
pi)
|
||||
# roverd rewrites media.env after loading /etc/roverd.yaml. These
|
||||
# roverd rewrites media.env after loading /etc/roverd.json. These
|
||||
# values only make the services syntactically usable before the first
|
||||
# successful roverd run, so they mirror the Pi defaults instead of
|
||||
# trying to become a second source of truth.
|
||||
@@ -73,12 +73,12 @@ install_pi_audio_support() {
|
||||
log "googlevoicehat-soundcard overlay already present in $boot_config"
|
||||
fi
|
||||
fi
|
||||
if [[ -f pi/asound.conf ]]; then
|
||||
install -m 0644 pi/asound.conf /etc/asound.conf
|
||||
if [[ -f rover/asound.conf ]]; then
|
||||
install -m 0644 rover/asound.conf /etc/asound.conf
|
||||
log "Installed ALSA config to /etc/asound.conf"
|
||||
alsa_reload_notice=1
|
||||
else
|
||||
log "WARNING: pi/asound.conf missing; skipping ALSA config install"
|
||||
log "WARNING: rover/asound.conf missing; skipping ALSA config install"
|
||||
fi
|
||||
|
||||
if [[ "${alsa_reload_notice:-0}" -eq 1 ]]; then
|
||||
@@ -102,7 +102,7 @@ install_pi_audio_support() {
|
||||
|| apt-get install -y --no-install-recommends flite espeak python3 curl xz-utils unzip alsa-utils libc++1-14 libc++abi1-14
|
||||
fi
|
||||
|
||||
install -D -o root -g root -m 0755 pi/bin/chromegtts-daemon.py /usr/local/bin/chromegtts-daemon
|
||||
install -D -o root -g root -m 0755 rover/bin/chromegtts-daemon.py /usr/local/bin/chromegtts-daemon
|
||||
log "Installed chromegtts daemon"
|
||||
|
||||
install_google_tts_assets
|
||||
@@ -6,19 +6,19 @@ CONFIG_SRC=""
|
||||
|
||||
usage() {
|
||||
cat <<'USAGE'
|
||||
Usage: sudo ./pi/install_roverd.sh [options]
|
||||
Usage: sudo ./rover/install_roverd.sh [options]
|
||||
|
||||
Options:
|
||||
--profile <name> Install profile: pi or debian-laptop (default: pi)
|
||||
--debian-laptop Shortcut for --profile debian-laptop
|
||||
-b, --binary <path> Path to the roverd binary (default depends on profile)
|
||||
-c, --config <path> Source config to install if /etc/roverd.yaml is missing
|
||||
-b, --binary <path> Path to the roverd binary (default: detected OS architecture)
|
||||
-c, --config <path> Source config to install if /etc/roverd.json is missing
|
||||
(default depends on profile)
|
||||
-h, --help Show this help text
|
||||
|
||||
The script must run from the repository root and as root (sudo). It will:
|
||||
* create system users/groups if needed
|
||||
* install /usr/local/bin/roverd and /etc/roverd.yaml
|
||||
* install /usr/local/bin/roverd and /etc/roverd.json
|
||||
* install profile-specific video helpers and shared audio helpers
|
||||
* install profile-specific ALSA/system audio setup
|
||||
* install the fixed-command self-update helper used by admin-triggered updates
|
||||
@@ -59,22 +59,33 @@ parse_args() {
|
||||
}
|
||||
|
||||
select_profile() {
|
||||
# Binary selection follows the installed userland, independent of the
|
||||
# temporary media installer profiles removed later in the rework.
|
||||
case "$(dpkg --print-architecture)" in
|
||||
amd64) binary_arch=amd64 ;;
|
||||
arm64) binary_arch=arm64 ;;
|
||||
armhf)
|
||||
# ARMv6 also runs on ARMv7; use the conservative artifact for
|
||||
# 32-bit Debian derivatives whose armhf baseline differs.
|
||||
binary_arch=armv6 ;;
|
||||
*) echo "Unsupported OS architecture" >&2; exit 1 ;;
|
||||
esac
|
||||
BINARY_SRC="${BINARY_SRC:-dist/roverd-linux-$binary_arch}"
|
||||
|
||||
case "$PROFILE" in
|
||||
pi)
|
||||
BINARY_SRC="${BINARY_SRC:-dist/roverd}"
|
||||
CONFIG_SRC="${CONFIG_SRC:-pi/roverd/roverd.sample.yaml}"
|
||||
VIDEO_HELPER_SRC="pi/bin/video-publisher.sh"
|
||||
CONFIG_SRC="${CONFIG_SRC:-rover/roverd/roverd.sample.json}"
|
||||
VIDEO_HELPER_SRC="rover/bin/video-publisher.sh"
|
||||
VIDEO_HELPER_DEST="/usr/local/bin/video-publisher"
|
||||
VIDEO_SERVICE_SRC="pi/systemd/video-publisher.service"
|
||||
VIDEO_SERVICE_SRC="rover/systemd/video-publisher.service"
|
||||
VIDEO_SERVICE_NAME="video-publisher.service"
|
||||
ROVERD_GROUPS="dialout,gpio,video,render,audio"
|
||||
;;
|
||||
debian-laptop)
|
||||
BINARY_SRC="${BINARY_SRC:-dist/roverd-debian-laptop}"
|
||||
CONFIG_SRC="${CONFIG_SRC:-pi/roverd/roverd.debian-laptop.sample.yaml}"
|
||||
VIDEO_HELPER_SRC="pi/bin/debian-laptop-video-publisher.sh"
|
||||
CONFIG_SRC="${CONFIG_SRC:-rover/roverd/roverd.debian-laptop.sample.json}"
|
||||
VIDEO_HELPER_SRC="rover/bin/debian-laptop-video-publisher.sh"
|
||||
VIDEO_HELPER_DEST="/usr/local/bin/debian-laptop-video-publisher"
|
||||
VIDEO_SERVICE_SRC="pi/systemd/debian-laptop-video-publisher.service"
|
||||
VIDEO_SERVICE_SRC="rover/systemd/debian-laptop-video-publisher.service"
|
||||
VIDEO_SERVICE_NAME="debian-laptop-video-publisher.service"
|
||||
ROVERD_GROUPS="dialout,video,render,audio"
|
||||
;;
|
||||
@@ -12,7 +12,7 @@ install_self_update_support() {
|
||||
printf -v quoted_repo_root '%q' "$REPO_ROOT"
|
||||
install -D -o root -g root -m 0644 /dev/null "$update_env"
|
||||
cat > "$update_env" <<ENV
|
||||
# Managed by pi/install_roverd.sh.
|
||||
# Managed by rover/install_roverd.sh.
|
||||
# This path is intentionally captured from the installer working directory so
|
||||
# admin-triggered rover updates always operate on the same full repository that
|
||||
# was used for the manual install.
|
||||
@@ -23,9 +23,9 @@ ENV
|
||||
# The helper is root-owned and argument-free. sudoers grants the roverd
|
||||
# service user exactly this command and nothing broader, which is important
|
||||
# because update requests arrive over the rover websocket.
|
||||
install -D -o root -g root -m 0755 pi/bin/roverd-self-update.sh /usr/local/sbin/roverd-self-update
|
||||
install -D -o root -g root -m 0755 rover/bin/roverd-self-update.sh /usr/local/sbin/roverd-self-update
|
||||
cat > "$sudoers_file" <<'SUDOERS'
|
||||
# Managed by pi/install_roverd.sh.
|
||||
# Managed by rover/install_roverd.sh.
|
||||
# Allow only the roverd service account to run the fixed self-update helper.
|
||||
roverd ALL=(root) NOPASSWD: /usr/local/sbin/roverd-self-update
|
||||
SUDOERS
|
||||
@@ -10,12 +10,12 @@ install_media_units() {
|
||||
|
||||
# Audio capture publishing and forwarded-audio playback use the same ffmpeg
|
||||
# and ALSA contract on both profiles, so they stay as shared installer work.
|
||||
install -D -o root -g root -m 0755 pi/bin/audio-only-publisher.sh /usr/local/bin/audio-only-publisher
|
||||
install -m 0644 pi/systemd/audio-only-publisher.service /etc/systemd/system/audio-only-publisher.service
|
||||
install -D -o root -g root -m 0755 rover/bin/audio-only-publisher.sh /usr/local/bin/audio-only-publisher
|
||||
install -m 0644 rover/systemd/audio-only-publisher.service /etc/systemd/system/audio-only-publisher.service
|
||||
log "Installed audio-only publisher helper + systemd unit"
|
||||
|
||||
install -D -o root -g root -m 0755 pi/bin/audio-forward-listener.sh /usr/local/bin/audio-forward-listener
|
||||
install -m 0644 pi/systemd/audio-forward-listener.service /etc/systemd/system/audio-forward-listener.service
|
||||
install -D -o root -g root -m 0755 rover/bin/audio-forward-listener.sh /usr/local/bin/audio-forward-listener
|
||||
install -m 0644 rover/systemd/audio-forward-listener.service /etc/systemd/system/audio-forward-listener.service
|
||||
log "Installed audio-forward listener helper + systemd unit"
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
#
|
||||
# Installer entry point for roverd hosts.
|
||||
#
|
||||
# The detailed work lives in pi/install/*.sh so platform-specific setup stays
|
||||
# The detailed work lives in rover/install/*.sh so platform-specific setup stays
|
||||
# local to the profile that needs it. This file should read like the install
|
||||
# order: choose a profile, validate inputs, install shared roverd pieces,
|
||||
# install profile support, then enable the services.
|
||||
@@ -17,13 +17,13 @@ REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
||||
# simple and prevents each function from needing its own path resolver.
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
source pi/install/common.sh
|
||||
source pi/install/profiles.sh
|
||||
source pi/install/self_update.sh
|
||||
source pi/install/pi_profile.sh
|
||||
source pi/install/debian_laptop_profile.sh
|
||||
source pi/install/media_env.sh
|
||||
source pi/install/systemd.sh
|
||||
source rover/install/common.sh
|
||||
source rover/install/profiles.sh
|
||||
source rover/install/self_update.sh
|
||||
source rover/install/pi_profile.sh
|
||||
source rover/install/debian_laptop_profile.sh
|
||||
source rover/install/media_env.sh
|
||||
source rover/install/systemd.sh
|
||||
|
||||
main() {
|
||||
parse_args "$@"
|
||||
@@ -0,0 +1,29 @@
|
||||
BIN_DIR ?= ../../dist
|
||||
ARCH ?= amd64
|
||||
GOARCH := $(ARCH)
|
||||
GOARM :=
|
||||
ifneq ($(filter armv6 armv7,$(ARCH)),)
|
||||
GOARCH := arm
|
||||
GOARM := $(patsubst armv%,%,$(ARCH))
|
||||
endif
|
||||
|
||||
.PHONY: build all armv6 armv7 arm64 amd64 dummy verifier-tools clean
|
||||
|
||||
# Binaries are committed to the repository; no release publishing is needed.
|
||||
build:
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=$(GOARCH) GOARM=$(GOARM) go build -trimpath -ldflags="-s -w" -o $(BIN_DIR)/roverd-linux-$(ARCH) ./cmd/roverd
|
||||
|
||||
all: armv6 armv7 arm64 amd64
|
||||
|
||||
armv6 armv7 arm64 amd64:
|
||||
$(MAKE) build ARCH=$@
|
||||
|
||||
verifier-tools:
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=$(GOARCH) GOARM=$(GOARM) go build -trimpath -ldflags="-s -w" -o $(BIN_DIR)/servoverifier-linux-$(ARCH) ./cmd/servoverifier
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=$(GOARCH) GOARM=$(GOARM) go build -trimpath -ldflags="-s -w" -o $(BIN_DIR)/hornverifier-linux-$(ARCH) ./cmd/hornverifier
|
||||
|
||||
dummy:
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags dummy -o $(BIN_DIR)/roverd-dummy ./cmd/roverd
|
||||
|
||||
clean:
|
||||
rm -f $(BIN_DIR)/roverd-linux-* $(BIN_DIR)/roverd-dummy $(BIN_DIR)/servoverifier-linux-* $(BIN_DIR)/hornverifier-linux-*
|
||||
@@ -3,16 +3,19 @@ package roverd
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
autoChargeTimeout = 1 * time.Second
|
||||
autoChargeTimeout = 10 * time.Second
|
||||
autoChargeCooldown = 0 * time.Minute
|
||||
sourceHomeBase = 1 << 1
|
||||
)
|
||||
|
||||
type AutoChargeController struct {
|
||||
mu sync.Mutex
|
||||
paused bool
|
||||
adapter *SerialAdapter
|
||||
events chan<- RoverEvent
|
||||
logger *log.Logger
|
||||
@@ -42,6 +45,11 @@ func (a *AutoChargeController) Run(ctx context.Context, samples <-chan SensorSam
|
||||
}
|
||||
|
||||
func (a *AutoChargeController) processSample(sample SensorSample) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.paused {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
docked := sample.ChargeSources&sourceHomeBase != 0
|
||||
charging := isCharging(sample.ChargingState)
|
||||
@@ -107,3 +115,12 @@ func (a *AutoChargeController) emitEvent(event string, data map[string]any) {
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// Pausing waits for any current dock attempt to finish before management stops
|
||||
// motion, preventing the automatic timer from issuing a later movement command.
|
||||
func (a *AutoChargeController) SetPaused(paused bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.paused = paused
|
||||
a.timerStart = time.Time{}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build !dummy && !debian_laptop
|
||||
//go:build !dummy
|
||||
|
||||
package roverd
|
||||
|
||||
@@ -14,6 +14,7 @@ type BRCPulser struct {
|
||||
cfg BRCConfig
|
||||
logger *log.Logger
|
||||
line *gpiocdev.Line
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func NewBRCPulser(cfg BRCConfig, logger *log.Logger) (*BRCPulser, error) {
|
||||
@@ -32,10 +33,12 @@ func NewBRCPulser(cfg BRCConfig, logger *log.Logger) (*BRCPulser, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &BRCPulser{cfg: cfg, logger: logger, line: line}, nil
|
||||
return &BRCPulser{cfg: cfg, logger: logger, line: line, done: make(chan struct{})}, nil
|
||||
}
|
||||
|
||||
func (b *BRCPulser) Close() {
|
||||
// The owner cancels the pulse loop before closing its GPIO line.
|
||||
<-b.done
|
||||
if b.line != nil {
|
||||
_ = b.line.SetValue(1)
|
||||
b.line.Close()
|
||||
@@ -44,11 +47,15 @@ func (b *BRCPulser) Close() {
|
||||
|
||||
func (b *BRCPulser) Start(ctx context.Context) {
|
||||
go func() {
|
||||
defer close(b.done)
|
||||
ticker := time.NewTicker(b.cfg.PulseEvery.Duration)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
b.pulseOnce()
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
b.pulseOnce(ctx)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
@@ -58,7 +65,7 @@ func (b *BRCPulser) Start(ctx context.Context) {
|
||||
}()
|
||||
}
|
||||
|
||||
func (b *BRCPulser) pulseOnce() {
|
||||
func (b *BRCPulser) pulseOnce(ctx context.Context) {
|
||||
if b.line == nil {
|
||||
return
|
||||
}
|
||||
@@ -66,7 +73,14 @@ func (b *BRCPulser) pulseOnce() {
|
||||
b.logger.Printf("brc pulse low: %v", err)
|
||||
return
|
||||
}
|
||||
time.Sleep(b.cfg.PulseWidth.Duration)
|
||||
// Cancellation ends a pulse promptly before peripheral shutdown releases
|
||||
// the line, even when a long pulse width was configured.
|
||||
timer := time.NewTimer(b.cfg.PulseWidth.Duration)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-timer.C:
|
||||
}
|
||||
if err := b.line.SetValue(1); err != nil {
|
||||
b.logger.Printf("brc pulse high: %v", err)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build !dummy && !debian_laptop
|
||||
//go:build !dummy
|
||||
|
||||
package roverd
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
roverd "multiroombarover/pi/roverd"
|
||||
roverd "multiroombarover/rover/roverd"
|
||||
|
||||
"github.com/tarm/serial"
|
||||
)
|
||||
@@ -2,39 +2,86 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
roverd "multiroombarover/pi/roverd"
|
||||
roverd "multiroombarover/rover/roverd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var cfgPath string
|
||||
flag.StringVar(&cfgPath, "config", "/etc/roverd.yaml", "path to roverd configuration file")
|
||||
flag.StringVar(&cfgPath, "config", "/etc/roverd.json", "path to roverd JSON configuration")
|
||||
printDefaults := flag.Bool("print-default-config", false, "print a complete initial JSON configuration and exit")
|
||||
printSchema := flag.Bool("print-config-schema", false, "print the configuration JSON Schema and exit")
|
||||
checkConfig := flag.Bool("check-config", false, "validate configuration without opening hardware or connecting")
|
||||
flag.Parse()
|
||||
|
||||
if *printDefaults {
|
||||
data, _ := json.MarshalIndent(roverd.DefaultConfig(), "", " ")
|
||||
fmt.Println(string(data))
|
||||
return
|
||||
}
|
||||
if *printSchema {
|
||||
fmt.Println(string(roverd.ConfigurationSchema()))
|
||||
return
|
||||
}
|
||||
cfg, err := roverd.LoadConfig(cfgPath)
|
||||
if err != nil {
|
||||
log.Fatalf("load config: %v", err)
|
||||
}
|
||||
if err := roverd.UpdatePublisherEnv(cfg.Media); err != nil {
|
||||
log.Fatalf("prepare media env: %v", err)
|
||||
if *checkConfig {
|
||||
fmt.Println("Configuration valid")
|
||||
return
|
||||
}
|
||||
if run(cfg, cfgPath) {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := syscall.Exec(executable, os.Args, os.Environ()); err != nil {
|
||||
log.Fatalf("restart roverd: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func run(cfg *roverd.Config, cfgPath string) bool {
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
|
||||
logger := log.New(os.Stdout, "roverd: ", log.LstdFlags|log.Lmicroseconds|log.LUTC)
|
||||
events := make(chan roverd.RoverEvent, 128)
|
||||
console := roverd.NewConsoleNotifier(logger)
|
||||
console.SetEvents(events)
|
||||
var restarting atomic.Bool
|
||||
management := roverd.NewManagementClient(cfg, cfgPath, events, logger, func() { restarting.Store(true); cancel() })
|
||||
managementDone := make(chan struct{})
|
||||
go func() { defer close(managementDone); management.Run(ctx) }()
|
||||
// Hardware failures leave management connected until a corrected config
|
||||
// requests restart. runHardware unwinds its own resources on failure.
|
||||
media := roverd.NewMediaSupervisor(cfg.Media, logger)
|
||||
management.SetMedia(media)
|
||||
if media != nil {
|
||||
media.Start(ctx)
|
||||
}
|
||||
if err := runHardware(ctx, cfg, events, management, media, logger, console); err != nil {
|
||||
console.Notify(fmt.Sprintf("Hardware unavailable: %v. Management remains connected.", err))
|
||||
}
|
||||
<-ctx.Done()
|
||||
<-managementDone
|
||||
return restarting.Load()
|
||||
}
|
||||
|
||||
func runHardware(ctx context.Context, cfg *roverd.Config, eventStream chan roverd.RoverEvent, management *roverd.ManagementClient, mediaSupervisor *roverd.MediaSupervisor, logger *log.Logger, console *roverd.ConsoleNotifier) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
serialPort, err := roverd.OpenSerial(cfg.Serial)
|
||||
if err != nil {
|
||||
logger.Fatalf("open serial: %v", err)
|
||||
return fmt.Errorf("open serial: %w", err)
|
||||
}
|
||||
defer serialPort.Close()
|
||||
|
||||
@@ -44,45 +91,33 @@ func main() {
|
||||
peripherals, err := roverd.DiscoverPeripheralManager(ctx, cfg.Serial.Device, logger)
|
||||
if err != nil {
|
||||
console.Notify(fmt.Sprintf("Rover peripheral startup failed: %v", err))
|
||||
logger.Fatalf("discover rover peripherals: %v", err)
|
||||
return fmt.Errorf("discover rover peripherals: %w", err)
|
||||
}
|
||||
defer peripherals.Close()
|
||||
for _, message := range peripherals.StartupBroadcasts() {
|
||||
console.Notify(message)
|
||||
}
|
||||
|
||||
var pulser *roverd.BRCPulser
|
||||
if cfg.BRC.Enabled() {
|
||||
pulser, err = roverd.NewBRCPulser(cfg.BRC, logger)
|
||||
if err != nil {
|
||||
logger.Fatalf("init BRC pulser: %v", err)
|
||||
}
|
||||
defer pulser.Close()
|
||||
pulser.Start(ctx)
|
||||
}
|
||||
|
||||
sensorFrames := make(chan []byte, 8)
|
||||
sensorSamples := make(chan roverd.SensorSample, 8)
|
||||
eventStream := make(chan roverd.RoverEvent, 16)
|
||||
|
||||
streamer := roverd.NewSensorStreamer(serialPort, sensorFrames, sensorSamples, logger)
|
||||
go streamer.Run(ctx)
|
||||
|
||||
adapter := roverd.NewSerialAdapter(serialPort, logger)
|
||||
|
||||
mediaSupervisor := roverd.NewMediaSupervisor(cfg.Media, logger)
|
||||
if mediaSupervisor != nil {
|
||||
mediaSupervisor.Start(ctx)
|
||||
}
|
||||
|
||||
// Backend selection is identical on Pi and laptop hosts: enabled native
|
||||
// GPIO wins, otherwise a discovered ESP32 may provide the built-in role.
|
||||
// Resolve roles across external and internal peripherals without transport priority.
|
||||
hardwareControllers, err := roverd.ResolveRoverHardwareControllers(cfg, peripherals, logger)
|
||||
if err != nil {
|
||||
console.Notify(fmt.Sprintf("Rover peripheral startup failed while selecting hardware: %v", err))
|
||||
logger.Fatalf("resolve rover hardware controllers: %v", err)
|
||||
return fmt.Errorf("resolve rover hardware controllers: %w", err)
|
||||
}
|
||||
defer hardwareControllers.Close()
|
||||
if err := peripherals.StartInternal(ctx); err != nil {
|
||||
logger.Printf("internal peripheral: %v", err)
|
||||
console.Notify(fmt.Sprintf("Pi GPIO background function unavailable: %v", err))
|
||||
}
|
||||
for _, message := range peripherals.StartupBroadcasts() {
|
||||
console.Notify(message)
|
||||
}
|
||||
|
||||
for _, message := range hardwareControllers.StartupBroadcasts() {
|
||||
console.Notify(message)
|
||||
}
|
||||
@@ -107,13 +142,17 @@ func main() {
|
||||
}()
|
||||
|
||||
autoCharge := roverd.NewAutoChargeController(adapter, eventStream, logger)
|
||||
go autoCharge.Run(ctx, sensorSamples)
|
||||
|
||||
client := roverd.NewWSClient(cfg, adapter, sensorFrames, eventStream, mediaSupervisor, hardwareControllers.CameraServo, hardwareControllers.Headlight, hardwareControllers.Laser, peripherals, logger, console)
|
||||
client.SetAutoCharge(autoCharge)
|
||||
go autoCharge.Run(ctx, sensorSamples)
|
||||
if !management.SetRuntime(client, mediaSupervisor) {
|
||||
return nil
|
||||
}
|
||||
defer client.PrepareShutdown()
|
||||
|
||||
// Startup is announced only after every configured hardware dependency has
|
||||
// initialized successfully. A message here therefore means the control loop
|
||||
// is genuinely ready, rather than merely that systemd launched the process.
|
||||
// The control loop is ready after startup resolution. Individual unavailable
|
||||
// peripheral roles have already been reported and do not prevent connection.
|
||||
console.Notify("roverd started and hardware initialization completed.")
|
||||
defer console.Notify("roverd stopped.")
|
||||
|
||||
@@ -125,7 +164,7 @@ func main() {
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
return nil
|
||||
case <-time.After(retryDelay):
|
||||
}
|
||||
|
||||
@@ -133,4 +172,6 @@ func main() {
|
||||
retryDelay *= 2
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -9,7 +9,7 @@ type helloMessage struct {
|
||||
Color string `json:"color,omitempty"`
|
||||
Battery BatteryConfig `json:"battery"`
|
||||
MaxWheelSpeed int `json:"maxWheelSpeed"`
|
||||
Media MediaConfig `json:"media"`
|
||||
Media any `json:"media"`
|
||||
CameraServo CameraServoConfig `json:"cameraServo"`
|
||||
Audio AudioConfig `json:"audio"`
|
||||
Horn HornConfig `json:"horn"`
|
||||
@@ -41,7 +41,6 @@ type inboundMessage struct {
|
||||
MotorPWM *motorPWMPayload `json:"motorPwm,omitempty"`
|
||||
Raw string `json:"raw,omitempty"`
|
||||
SensorStream *sensorStreamPayload `json:"sensorStream,omitempty"`
|
||||
Media *mediaCommand `json:"media,omitempty"`
|
||||
Servo *servoPayload `json:"servo,omitempty"`
|
||||
TTS *ttsPayload `json:"tts,omitempty"`
|
||||
Horn *hornPayload `json:"horn,omitempty"`
|
||||
@@ -50,11 +49,6 @@ type inboundMessage struct {
|
||||
Laser *togglePayload `json:"laser,omitempty"`
|
||||
Peripheral *peripheralPayload `json:"peripheral,omitempty"`
|
||||
Song *songPayload `json:"song,omitempty"`
|
||||
Reboot *rebootPayload `json:"reboot,omitempty"`
|
||||
// Update is intentionally just a marker payload. The server can request the
|
||||
// fixed self-update workflow, but it cannot pass paths, commands, branches,
|
||||
// or installer flags through the websocket into the privileged helper.
|
||||
Update *updatePayload `json:"update,omitempty"`
|
||||
}
|
||||
|
||||
type driveDirectPayload struct {
|
||||
@@ -11,21 +11,23 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
)
|
||||
|
||||
type SerialConfig struct {
|
||||
Device string `yaml:"device"`
|
||||
Baud int `yaml:"baud"`
|
||||
Device string `json:"device"`
|
||||
Baud int `json:"baud" jsonschema:"minimum=1"`
|
||||
}
|
||||
|
||||
type Duration struct {
|
||||
time.Duration
|
||||
}
|
||||
|
||||
func (d *Duration) UnmarshalYAML(value *yaml.Node) error {
|
||||
func (d *Duration) UnmarshalJSON(data []byte) error {
|
||||
var raw string
|
||||
if err := value.Decode(&raw); err != nil {
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed, err := time.ParseDuration(raw)
|
||||
@@ -36,93 +38,88 @@ func (d *Duration) UnmarshalYAML(value *yaml.Node) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d Duration) MarshalYAML() (interface{}, error) {
|
||||
return d.Duration.String(), nil
|
||||
}
|
||||
func (d Duration) MarshalJSON() ([]byte, error) { return json.Marshal(d.Duration.String()) }
|
||||
|
||||
type BRCConfig struct {
|
||||
GPIOPin int `yaml:"gpioPin"`
|
||||
GPIOChip string `yaml:"gpioChip"`
|
||||
PulseEvery Duration `yaml:"pulseEvery"`
|
||||
PulseWidth Duration `yaml:"pulseWidth"`
|
||||
}
|
||||
|
||||
func (b BRCConfig) Enabled() bool {
|
||||
return b.GPIOPin >= 0
|
||||
Enabled bool `json:"enabled"`
|
||||
GPIOPin int `json:"gpioPin"`
|
||||
GPIOChip string `json:"gpioChip"`
|
||||
PulseEvery Duration `json:"pulseEvery"`
|
||||
PulseWidth Duration `json:"pulseWidth"`
|
||||
}
|
||||
|
||||
type BatteryConfig struct {
|
||||
Full int `yaml:"full"`
|
||||
Warn int `yaml:"warn"`
|
||||
Urgent int `yaml:"urgent"`
|
||||
Full int `json:"full"`
|
||||
Warn int `json:"warn"`
|
||||
Urgent int `json:"urgent"`
|
||||
}
|
||||
|
||||
type AudioConfig struct {
|
||||
// AudioConfig is only for sounds generated by roverd itself. Live capture
|
||||
// and playback are media-publisher concerns, so those settings live under
|
||||
// MediaConfig where they can be written directly into media.env.
|
||||
TTSEnabled bool `yaml:"ttsEnabled" json:"ttsEnabled"`
|
||||
DefaultEngine string `yaml:"defaultEngine" json:"defaultEngine,omitempty"`
|
||||
DefaultVoice string `yaml:"defaultVoice" json:"defaultVoice,omitempty"`
|
||||
DefaultPitch int `yaml:"defaultPitch" json:"defaultPitch,omitempty"`
|
||||
TTSEnabled bool `json:"ttsEnabled"`
|
||||
DefaultEngine string `json:"defaultEngine"`
|
||||
DefaultVoice string `json:"defaultVoice"`
|
||||
DefaultPitch int `json:"defaultPitch"`
|
||||
}
|
||||
|
||||
type HornConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
Volume float64 `yaml:"volume" json:"-"`
|
||||
SampleRate int `yaml:"sampleRate" json:"-"`
|
||||
Channels int `yaml:"channels" json:"-"`
|
||||
Device string `yaml:"device" json:"-"`
|
||||
SineGain float64 `yaml:"sineGain" json:"-"`
|
||||
SawGain float64 `yaml:"sawGain" json:"-"`
|
||||
MaxDuration Duration `yaml:"maxDuration" json:"-"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Volume float64 `json:"volume"`
|
||||
SampleRate int `json:"sampleRate"`
|
||||
Channels int `json:"channels"`
|
||||
Device string `json:"device"`
|
||||
SineGain float64 `json:"sineGain"`
|
||||
SawGain float64 `json:"sawGain"`
|
||||
MaxDuration Duration `json:"maxDuration"`
|
||||
}
|
||||
|
||||
type MediaConfig struct {
|
||||
// RTSPPort is shared by the derived video, microphone, and forwarded-audio
|
||||
// RTSP URLs. Keeping it at this level prevents each nested block from needing
|
||||
// to repeat the same server port when the common MediaMTX listener is used.
|
||||
RTSPPort int `yaml:"rtspPort" json:"-"`
|
||||
Manage bool `yaml:"manage" json:"manage"`
|
||||
HealthURL string `yaml:"healthUrl" json:"healthUrl,omitempty"`
|
||||
HealthInterval Duration `yaml:"healthInterval" json:"-"`
|
||||
Video VideoMediaConfig `yaml:"video" json:"video"`
|
||||
AudioCapture AudioCaptureConfig `yaml:"audioCapture" json:"audioCapture"`
|
||||
AudioPlayback AudioPlaybackConfig `yaml:"audioPlayback" json:"audioPlayback"`
|
||||
RTSPPort int `json:"rtspPort" jsonschema:"minimum=1,maximum=65535"`
|
||||
Manage bool `json:"manage"`
|
||||
HealthURL string `json:"healthUrl"`
|
||||
HealthInterval Duration `json:"healthInterval"`
|
||||
Video VideoMediaConfig `json:"video"`
|
||||
AudioCapture AudioCaptureConfig `json:"audioCapture"`
|
||||
AudioPlayback AudioPlaybackConfig `json:"audioPlayback"`
|
||||
}
|
||||
|
||||
type VideoMediaConfig struct {
|
||||
// Publisher selects the installed publisher script/pipeline family. The
|
||||
// first pass uses pi-libcamera for current rovers; laptop-v4l2 can be added
|
||||
// without changing the server-facing media shape again.
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
Service string `yaml:"service" json:"service,omitempty"`
|
||||
Publisher string `yaml:"publisher" json:"publisher,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Service string `json:"service"`
|
||||
Publisher string `json:"publisher"`
|
||||
// PublishURL is derived during validation. It remains in rover metadata for server-side
|
||||
// consumers, but is not a second hand-written endpoint in /etc/roverd.yaml.
|
||||
PublishURL string `yaml:"-" json:"publishUrl,omitempty"`
|
||||
Device string `yaml:"device" json:"device,omitempty"`
|
||||
InputFormat string `yaml:"inputFormat" json:"-"`
|
||||
Width int `yaml:"width" json:"-"`
|
||||
Height int `yaml:"height" json:"-"`
|
||||
FPS int `yaml:"fps" json:"-"`
|
||||
Bitrate int `yaml:"bitrate" json:"-"`
|
||||
Inverted bool `yaml:"inverted" json:"-"`
|
||||
SensorMode string `yaml:"sensorMode" json:"-"`
|
||||
// consumers through MediaMetadata, but is never persisted in configuration.
|
||||
PublishURL string `json:"-"`
|
||||
Device string `json:"device"`
|
||||
InputFormat string `json:"inputFormat"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
FPS int `json:"fps"`
|
||||
Bitrate int `json:"bitrate"`
|
||||
Inverted bool `json:"inverted"`
|
||||
SensorMode string `json:"sensorMode"`
|
||||
}
|
||||
|
||||
type AudioCaptureConfig struct {
|
||||
// AudioCapture describes the rover microphone stream that browsers can
|
||||
// subscribe to as "<rover>-audio". A disabled capture block still has
|
||||
// normalized defaults so enabling it only requires flipping enabled: true.
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
Service string `yaml:"service" json:"service,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Service string `json:"service"`
|
||||
// PublishURL follows the same derived-only contract as the video path.
|
||||
PublishURL string `yaml:"-" json:"publishUrl,omitempty"`
|
||||
Device string `yaml:"device" json:"device,omitempty"`
|
||||
SampleRate int `yaml:"sampleRate" json:"-"`
|
||||
Channels int `yaml:"channels" json:"-"`
|
||||
Bitrate int `yaml:"bitrate" json:"-"`
|
||||
PublishURL string `json:"-"`
|
||||
Device string `json:"device"`
|
||||
SampleRate int `json:"sampleRate"`
|
||||
Channels int `json:"channels"`
|
||||
Bitrate int `json:"bitrate"`
|
||||
}
|
||||
|
||||
type AudioPlaybackConfig struct {
|
||||
@@ -130,36 +127,36 @@ type AudioPlaybackConfig struct {
|
||||
// MediaMTX for playback on the rover speaker. The URL is a request/read URL
|
||||
// for the rover listener, while the server converts it to publish mode when
|
||||
// it needs to inject audio.
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
Service string `yaml:"service" json:"service,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Service string `json:"service"`
|
||||
// ForwardURL is derived because the server and rover must agree on the exact -fwd path.
|
||||
ForwardURL string `yaml:"-" json:"forwardUrl,omitempty"`
|
||||
Device string `yaml:"device" json:"device,omitempty"`
|
||||
Normalize bool `yaml:"normalize" json:"-"`
|
||||
NormalizeFilter string `yaml:"normalizeFilter" json:"-"`
|
||||
ForwardURL string `json:"-"`
|
||||
Device string `json:"device"`
|
||||
Normalize bool `json:"normalize"`
|
||||
NormalizeFilter string `json:"normalizeFilter"`
|
||||
}
|
||||
|
||||
type CameraServoConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
Pin int `yaml:"pin" json:"pin"`
|
||||
FreqHz int `yaml:"freqHz" json:"freqHz"`
|
||||
CycleLen int `yaml:"cycleLen" json:"cycleLen"`
|
||||
MinPulseUs int `yaml:"minPulseUs" json:"minPulseUs"`
|
||||
MaxPulseUs int `yaml:"maxPulseUs" json:"maxPulseUs"`
|
||||
MinAngle float64 `yaml:"minAngle" json:"minAngle"`
|
||||
MaxAngle float64 `yaml:"maxAngle" json:"maxAngle"`
|
||||
HomeAngle float64 `yaml:"homeAngle" json:"homeAngle"`
|
||||
NudgeDegrees float64 `yaml:"nudgeDegrees" json:"nudgeDegrees"`
|
||||
AllowRawPulse bool `yaml:"allowRawPulse" json:"allowRawPulse"`
|
||||
Invert bool `yaml:"invert" json:"invert"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Pin int `json:"pin"`
|
||||
FreqHz int `json:"freqHz"`
|
||||
CycleLen int `json:"cycleLen"`
|
||||
MinPulseUs int `json:"minPulseUs"`
|
||||
MaxPulseUs int `json:"maxPulseUs"`
|
||||
MinAngle float64 `json:"minAngle"`
|
||||
MaxAngle float64 `json:"maxAngle"`
|
||||
HomeAngle float64 `json:"homeAngle"`
|
||||
NudgeDegrees float64 `json:"nudgeDegrees"`
|
||||
AllowRawPulse bool `json:"allowRawPulse"`
|
||||
Invert bool `json:"invert"`
|
||||
}
|
||||
|
||||
type GPIOToggleConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
GPIOPin int `yaml:"gpioPin" json:"gpioPin"`
|
||||
GPIOChip string `yaml:"gpioChip" json:"gpioChip"`
|
||||
InitialOn bool `yaml:"initialOn" json:"initialOn"`
|
||||
ActiveLow bool `yaml:"activeLow" json:"activeLow"`
|
||||
Enabled bool `json:"enabled"`
|
||||
GPIOPin int `json:"gpioPin"`
|
||||
GPIOChip string `json:"gpioChip"`
|
||||
InitialOn bool `json:"initialOn"`
|
||||
ActiveLow bool `json:"activeLow"`
|
||||
}
|
||||
|
||||
func (g GPIOToggleConfig) LogicalToGPIO(on bool) int {
|
||||
@@ -173,68 +170,102 @@ func (g GPIOToggleConfig) LogicalToGPIO(on bool) int {
|
||||
}
|
||||
|
||||
type AutoSideBrushConfig struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
Speed int `yaml:"speed"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Speed int `json:"speed"`
|
||||
}
|
||||
|
||||
type PrivateConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
Safety PrivateSafetyConfig `yaml:"safety" json:"safety"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Safety PrivateSafetyConfig `json:"safety"`
|
||||
}
|
||||
|
||||
type PrivateSafetyConfig struct {
|
||||
SpeedLimitEnabled bool `yaml:"speedLimitEnabled" json:"speedLimitEnabled"`
|
||||
SpeedLimitMaxWheelMMs int `yaml:"speedLimitMaxWheelSpeed" json:"speedLimitMaxWheelSpeed"`
|
||||
HardOvercurrentEnabled bool `yaml:"hardOvercurrentEnabled" json:"hardOvercurrentEnabled"`
|
||||
OvercurrentStopMs int `yaml:"overcurrentStopMs" json:"overcurrentStopMs"`
|
||||
HardBumpEnabled bool `yaml:"hardBumpEnabled" json:"hardBumpEnabled"`
|
||||
BumpBackoffSpeed int `yaml:"bumpBackoffSpeed" json:"bumpBackoffSpeed"`
|
||||
BumpBackoffMs int `yaml:"bumpBackoffMs" json:"bumpBackoffMs"`
|
||||
CliffEnabled bool `yaml:"cliffEnabled" json:"cliffEnabled"`
|
||||
CliffBackoffSpeed int `yaml:"cliffBackoffSpeed" json:"cliffBackoffSpeed"`
|
||||
CliffBackoffMs int `yaml:"cliffBackoffMs" json:"cliffBackoffMs"`
|
||||
VirtualWallEnabled bool `yaml:"virtualWallEnabled" json:"virtualWallEnabled"`
|
||||
VirtualWallBackoffSpeed int `yaml:"virtualWallBackoffSpeed" json:"virtualWallBackoffSpeed"`
|
||||
VirtualWallBackoffMs int `yaml:"virtualWallBackoffMs" json:"virtualWallBackoffMs"`
|
||||
TriggerCooldownMs int `yaml:"triggerCooldownMs" json:"triggerCooldownMs"`
|
||||
SpeedLimitEnabled bool `json:"speedLimitEnabled"`
|
||||
SpeedLimitMaxWheelMMs int `json:"speedLimitMaxWheelSpeed"`
|
||||
HardOvercurrentEnabled bool `json:"hardOvercurrentEnabled"`
|
||||
OvercurrentStopMs int `json:"overcurrentStopMs"`
|
||||
HardBumpEnabled bool `json:"hardBumpEnabled"`
|
||||
BumpBackoffSpeed int `json:"bumpBackoffSpeed"`
|
||||
BumpBackoffMs int `json:"bumpBackoffMs"`
|
||||
CliffEnabled bool `json:"cliffEnabled"`
|
||||
CliffBackoffSpeed int `json:"cliffBackoffSpeed"`
|
||||
CliffBackoffMs int `json:"cliffBackoffMs"`
|
||||
VirtualWallEnabled bool `json:"virtualWallEnabled"`
|
||||
VirtualWallBackoffSpeed int `json:"virtualWallBackoffSpeed"`
|
||||
VirtualWallBackoffMs int `json:"virtualWallBackoffMs"`
|
||||
TriggerCooldownMs int `json:"triggerCooldownMs"`
|
||||
}
|
||||
|
||||
type PiGPIOConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
BRC BRCConfig `json:"brc"`
|
||||
CameraServo CameraServoConfig `json:"cameraServo"`
|
||||
Headlight GPIOToggleConfig `json:"headlight"`
|
||||
Laser GPIOToggleConfig `json:"laser"`
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Name string `yaml:"name"`
|
||||
Description string `yaml:"description" json:"description,omitempty"`
|
||||
Color string `yaml:"color" json:"color,omitempty"`
|
||||
ServerURL string `yaml:"serverUrl"`
|
||||
Serial SerialConfig `yaml:"serial"`
|
||||
BRC BRCConfig `yaml:"brc"`
|
||||
Battery BatteryConfig `yaml:"battery"`
|
||||
MaxWheelMMs int `yaml:"maxWheelSpeed"`
|
||||
Media MediaConfig `yaml:"media"`
|
||||
CameraServo CameraServoConfig `yaml:"cameraServo"`
|
||||
Audio AudioConfig `yaml:"audio"`
|
||||
Horn HornConfig `yaml:"horn"`
|
||||
Headlight GPIOToggleConfig `yaml:"headlight" json:"headlight"`
|
||||
Laser GPIOToggleConfig `yaml:"laser" json:"laser"`
|
||||
AutoSideBrush AutoSideBrushConfig `yaml:"autoSideBrush"`
|
||||
Private PrivateConfig `yaml:"private" json:"private"`
|
||||
PiGPIO PiGPIOConfig `json:"piGpio"`
|
||||
Name string `json:"name" jsonschema:"minLength=1"`
|
||||
Description string `json:"description"`
|
||||
Color string `json:"color"`
|
||||
ServerURL string `json:"serverUrl" jsonschema:"minLength=1"`
|
||||
Serial SerialConfig `json:"serial"`
|
||||
Battery BatteryConfig `json:"battery"`
|
||||
MaxWheelMMs int `json:"maxWheelSpeed" jsonschema:"minimum=1,maximum=500"`
|
||||
Media MediaConfig `json:"media"`
|
||||
Audio AudioConfig `json:"audio"`
|
||||
Horn HornConfig `json:"horn"`
|
||||
AutoSideBrush AutoSideBrushConfig `json:"autoSideBrush"`
|
||||
Private PrivateConfig `json:"private"`
|
||||
}
|
||||
|
||||
func LoadConfig(path string) (*Config, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// DefaultConfig supplies initial settings; persisted and remotely submitted
|
||||
// configuration is always a complete object.
|
||||
func DefaultConfig() Config {
|
||||
cfg := Config{
|
||||
MaxWheelMMs: 500,
|
||||
BRC: BRCConfig{
|
||||
GPIOPin: 4,
|
||||
GPIOChip: "gpiochip0",
|
||||
PulseEvery: Duration{
|
||||
Duration: time.Minute,
|
||||
Name: "rover", ServerURL: "ws://localhost:8080/rover",
|
||||
Serial: SerialConfig{Device: "/dev/ttyUSB0", Baud: 115200},
|
||||
Battery: BatteryConfig{Full: 2068, Warn: 1700, Urgent: 1650},
|
||||
PiGPIO: PiGPIOConfig{
|
||||
BRC: BRCConfig{
|
||||
Enabled: true,
|
||||
GPIOPin: 4,
|
||||
GPIOChip: "gpiochip0",
|
||||
PulseEvery: Duration{
|
||||
Duration: time.Minute,
|
||||
},
|
||||
PulseWidth: Duration{
|
||||
Duration: time.Second,
|
||||
},
|
||||
},
|
||||
PulseWidth: Duration{
|
||||
Duration: time.Second,
|
||||
CameraServo: CameraServoConfig{
|
||||
Pin: 12,
|
||||
FreqHz: 50,
|
||||
CycleLen: 20000,
|
||||
MinPulseUs: 900,
|
||||
MaxPulseUs: 2100,
|
||||
MinAngle: -15,
|
||||
MaxAngle: 30,
|
||||
HomeAngle: 0,
|
||||
NudgeDegrees: 2,
|
||||
},
|
||||
Headlight: GPIOToggleConfig{
|
||||
Enabled: true,
|
||||
GPIOPin: 22,
|
||||
GPIOChip: "gpiochip0",
|
||||
InitialOn: false,
|
||||
ActiveLow: true,
|
||||
},
|
||||
Laser: GPIOToggleConfig{
|
||||
Enabled: false,
|
||||
GPIOPin: 27,
|
||||
GPIOChip: "gpiochip0",
|
||||
InitialOn: false,
|
||||
ActiveLow: false,
|
||||
},
|
||||
},
|
||||
MaxWheelMMs: 500,
|
||||
Media: MediaConfig{
|
||||
RTSPPort: 8554,
|
||||
HealthInterval: Duration{Duration: 30 * time.Second},
|
||||
@@ -265,17 +296,6 @@ func LoadConfig(path string) (*Config, error) {
|
||||
NormalizeFilter: "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled",
|
||||
},
|
||||
},
|
||||
CameraServo: CameraServoConfig{
|
||||
Pin: 12,
|
||||
FreqHz: 50,
|
||||
CycleLen: 20000,
|
||||
MinPulseUs: 900,
|
||||
MaxPulseUs: 2100,
|
||||
MinAngle: -15,
|
||||
MaxAngle: 30,
|
||||
HomeAngle: 0,
|
||||
NudgeDegrees: 2,
|
||||
},
|
||||
Audio: AudioConfig{
|
||||
TTSEnabled: false,
|
||||
DefaultEngine: "flite",
|
||||
@@ -291,20 +311,6 @@ func LoadConfig(path string) (*Config, error) {
|
||||
SawGain: 0.7,
|
||||
MaxDuration: Duration{Duration: 10000 * time.Millisecond},
|
||||
},
|
||||
Headlight: GPIOToggleConfig{
|
||||
Enabled: true,
|
||||
GPIOPin: 22,
|
||||
GPIOChip: "gpiochip0",
|
||||
InitialOn: false,
|
||||
ActiveLow: true,
|
||||
},
|
||||
Laser: GPIOToggleConfig{
|
||||
Enabled: false,
|
||||
GPIOPin: 27,
|
||||
GPIOChip: "gpiochip0",
|
||||
InitialOn: false,
|
||||
ActiveLow: false,
|
||||
},
|
||||
AutoSideBrush: AutoSideBrushConfig{
|
||||
Enabled: true,
|
||||
Speed: 20,
|
||||
@@ -329,51 +335,85 @@ func LoadConfig(path string) (*Config, error) {
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.Name == "" {
|
||||
return nil, errors.New("missing name")
|
||||
}
|
||||
normalizedColor, err := normalizeHexColor(cfg.Color)
|
||||
return cfg
|
||||
}
|
||||
|
||||
func LoadConfig(path string) (*Config, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return DecodeConfig(data)
|
||||
}
|
||||
|
||||
func DecodeConfig(data []byte) (*Config, error) {
|
||||
if err := ValidateConfigurationSchema(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var cfg Config
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
return nil, errors.New("expected one JSON object")
|
||||
}
|
||||
if err := validateConfig(&cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func validateConfig(cfg *Config) error {
|
||||
if cfg.Name == "" {
|
||||
return errors.New("missing name")
|
||||
}
|
||||
normalizedColor, err := normalizeHexColor(cfg.Color)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Color = normalizedColor
|
||||
if cfg.ServerURL == "" {
|
||||
return nil, errors.New("missing serverUrl")
|
||||
server, err := url.Parse(cfg.ServerURL)
|
||||
if err != nil || server.Hostname() == "" || (server.Scheme != "ws" && server.Scheme != "wss") || server.Path != "/rover" || server.RawQuery != "" || server.Fragment != "" {
|
||||
return errors.New("serverUrl must be ws://host[:port]/rover or wss://host[:port]/rover")
|
||||
}
|
||||
if cfg.Serial.Device == "" || cfg.Serial.Baud == 0 {
|
||||
return nil, errors.New("serial device/baud required")
|
||||
return errors.New("serial device/baud required")
|
||||
}
|
||||
if cfg.Battery.Full == 0 {
|
||||
return nil, errors.New("battery thresholds required")
|
||||
return errors.New("battery thresholds required")
|
||||
}
|
||||
if cfg.MaxWheelMMs <= 0 || cfg.MaxWheelMMs > 500 {
|
||||
return nil, fmt.Errorf("maxWheelSpeed must be 1-500, got %d", cfg.MaxWheelMMs)
|
||||
return fmt.Errorf("maxWheelSpeed must be 1-500, got %d", cfg.MaxWheelMMs)
|
||||
}
|
||||
if cfg.BRC.GPIOChip == "" {
|
||||
cfg.BRC.GPIOChip = "gpiochip0"
|
||||
if cfg.PiGPIO.BRC.GPIOChip == "" {
|
||||
cfg.PiGPIO.BRC.GPIOChip = "gpiochip0"
|
||||
}
|
||||
if cfg.Media.RTSPPort <= 0 {
|
||||
cfg.Media.RTSPPort = 8554
|
||||
}
|
||||
if err := validateMediaConfig(&cfg.Media, cfg.ServerURL, cfg.Name); err != nil {
|
||||
return nil, fmt.Errorf("media: %w", err)
|
||||
return fmt.Errorf("media: %w", err)
|
||||
}
|
||||
if err := validateServoConfig(&cfg.CameraServo); err != nil {
|
||||
return nil, fmt.Errorf("cameraServo: %w", err)
|
||||
}
|
||||
if err := validateGPIOToggleConfig(&cfg.Headlight); err != nil {
|
||||
return nil, fmt.Errorf("headlight: %w", err)
|
||||
}
|
||||
if err := validateGPIOToggleConfig(&cfg.Laser); err != nil {
|
||||
return nil, fmt.Errorf("laser: %w", err)
|
||||
if cfg.PiGPIO.Enabled {
|
||||
if err := validateServoConfig(&cfg.PiGPIO.CameraServo); err != nil {
|
||||
return fmt.Errorf("cameraServo: %w", err)
|
||||
}
|
||||
if err := validateGPIOToggleConfig(&cfg.PiGPIO.Headlight); err != nil {
|
||||
return fmt.Errorf("headlight: %w", err)
|
||||
}
|
||||
if err := validateGPIOToggleConfig(&cfg.PiGPIO.Laser); err != nil {
|
||||
return fmt.Errorf("laser: %w", err)
|
||||
}
|
||||
if cfg.PiGPIO.BRC.Enabled && (cfg.PiGPIO.BRC.GPIOPin < 0 || cfg.PiGPIO.BRC.PulseEvery.Duration <= 0 || cfg.PiGPIO.BRC.PulseWidth.Duration <= 0) {
|
||||
return errors.New("piGpio.brc: nonnegative pin and positive pulse durations required")
|
||||
}
|
||||
}
|
||||
validateAudioConfig(&cfg.Audio)
|
||||
validateHornConfig(&cfg.Horn)
|
||||
validateAutoSideBrushConfig(&cfg.AutoSideBrush)
|
||||
return &cfg, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateServoConfig(cfg *CameraServoConfig) error {
|
||||
@@ -625,3 +665,14 @@ func normalizeHexColor(raw string) (string, error) {
|
||||
}
|
||||
return strings.ToUpper(trimmed), nil
|
||||
}
|
||||
|
||||
// MediaMetadata adds derived endpoints only to the control hello.
|
||||
func (cfg *Config) MediaMetadata() map[string]any {
|
||||
data, _ := json.Marshal(cfg.Media)
|
||||
var media map[string]any
|
||||
json.Unmarshal(data, &media)
|
||||
media["video"].(map[string]any)["publishUrl"] = cfg.Media.Video.PublishURL
|
||||
media["audioCapture"].(map[string]any)["publishUrl"] = cfg.Media.AudioCapture.PublishURL
|
||||
media["audioPlayback"].(map[string]any)["forwardUrl"] = cfg.Media.AudioPlayback.ForwardURL
|
||||
return media
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package roverd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/invopop/jsonschema"
|
||||
validator "github.com/santhosh-tekuri/jsonschema/v6"
|
||||
)
|
||||
|
||||
func (Duration) JSONSchema() *jsonschema.Schema {
|
||||
return &jsonschema.Schema{Type: "string", Description: "Duration, for example 250ms, 1s, or 1m."}
|
||||
}
|
||||
|
||||
var configurationSchema = sync.OnceValues(func() (json.RawMessage, *validator.Schema) {
|
||||
r := jsonschema.Reflector{Anonymous: true, DoNotReference: true}
|
||||
schema := r.Reflect(&Config{})
|
||||
// The existing React form validator uses draft 7. This schema contains no
|
||||
// references or newer keywords, so both ends use the same simple dialect.
|
||||
schema.Version = "http://json-schema.org/draft-07/schema#"
|
||||
schema.Title = "Rover configuration"
|
||||
data, err := json.Marshal(schema)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
var document any
|
||||
if err := json.Unmarshal(data, &document); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
compiler := validator.NewCompiler()
|
||||
const location = "urn:roverd:configuration"
|
||||
if err := compiler.AddResource(location, document); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
compiled, err := compiler.Compile(location)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return data, compiled
|
||||
})
|
||||
|
||||
func ConfigurationSchema() json.RawMessage {
|
||||
data, _ := configurationSchema()
|
||||
return data
|
||||
}
|
||||
|
||||
func ValidateConfigurationSchema(data []byte) error {
|
||||
var value any
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
_, schema := configurationSchema()
|
||||
return schema.Validate(value)
|
||||
}
|
||||
|
||||
// SaveConfig replaces one complete object, never merging or keeping revisions.
|
||||
// A temporary file on the same filesystem prevents partial JSON after a crash.
|
||||
func SaveConfig(path string, cfg *Config) error {
|
||||
data, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := os.CreateTemp(filepath.Dir(path), ".roverd-config-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(file.Name())
|
||||
defer file.Close()
|
||||
if _, err = file.Write(append(data, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = file.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = file.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = os.Rename(file.Name(), path); err != nil {
|
||||
return fmt.Errorf("replace configuration: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -16,6 +16,7 @@ const roverConsolePath = "/dev/tty1"
|
||||
// it does not reliably reach a virtual console that is only showing a login
|
||||
// prompt.
|
||||
type ConsoleNotifier struct {
|
||||
events chan<- RoverEvent
|
||||
path string
|
||||
logger *log.Logger
|
||||
mu sync.Mutex
|
||||
@@ -44,6 +45,12 @@ func (n *ConsoleNotifier) Notify(message string) {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
|
||||
if n.events != nil {
|
||||
select {
|
||||
case n.events <- RoverEvent{Type: "event", Event: "daemon.notice", Ts: time.Now().UnixMilli(), Data: map[string]any{"message": message}}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
console, err := os.OpenFile(n.path, os.O_WRONLY|os.O_APPEND, 0)
|
||||
if err != nil {
|
||||
n.logFailure("open", err)
|
||||
@@ -65,3 +72,9 @@ func (n *ConsoleNotifier) logFailure(operation string, err error) {
|
||||
n.logger.Printf("console notification %s failed for %s: %v", operation, n.path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (n *ConsoleNotifier) SetEvents(events chan<- RoverEvent) {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
n.events = events
|
||||
}
|
||||
+30
-35
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -33,10 +34,12 @@ func TestDisabledNativeRolesResolveToFirmataOnEveryHostBuild(t *testing.T) {
|
||||
}
|
||||
defer manager.Close()
|
||||
|
||||
// All native entries are disabled, exactly as they can be on either a Pi or
|
||||
// laptop rover. The shared resolver must therefore select every ESP32 role.
|
||||
// The parent switch suppresses every native role even with saved child
|
||||
// settings enabled. No GPIO provider may displace the external peripheral.
|
||||
baseline := len(connection.Bytes())
|
||||
controllers, err := ResolveRoverHardwareControllers(&Config{}, manager, discardLogger())
|
||||
controllers, err := ResolveRoverHardwareControllers(&Config{PiGPIO: PiGPIOConfig{
|
||||
CameraServo: CameraServoConfig{Enabled: true}, Headlight: GPIOToggleConfig{Enabled: true}, Laser: GPIOToggleConfig{Enabled: true},
|
||||
}}, manager, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("resolve: %v", err)
|
||||
}
|
||||
@@ -93,49 +96,41 @@ func TestMissingNativeAndFirmataRolesRemainDisabled(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnabledNativeRolesWinEvenWithSeveralFirmataProviders(t *testing.T) {
|
||||
func TestConflictingRolesRemainUnavailableWithoutInitializingGPIO(t *testing.T) {
|
||||
roleDescription := PeripheralDescription{RoverControls: PeripheralRoverControls{
|
||||
CameraServo: &PeripheralCameraServo{},
|
||||
Headlight: &PeripheralDigitalRole{},
|
||||
Laser: &PeripheralDigitalRole{},
|
||||
CameraServo: &PeripheralCameraServo{}, Headlight: &PeripheralDigitalRole{}, Laser: &PeripheralDigitalRole{},
|
||||
}}
|
||||
manager := &PeripheralManager{
|
||||
byID: make(map[string]*managedPeripheral),
|
||||
peripherals: []*managedPeripheral{
|
||||
{metadata: RoverPeripheralMetadata{ID: "firmata-0"}, description: roleDescription},
|
||||
{metadata: RoverPeripheralMetadata{ID: "firmata-1"}, description: roleDescription},
|
||||
},
|
||||
}
|
||||
cfg := &Config{
|
||||
manager := &PeripheralManager{peripherals: []*managedPeripheral{
|
||||
{metadata: RoverPeripheralMetadata{ID: "firmata-0"}, description: roleDescription},
|
||||
}}
|
||||
cfg := &Config{PiGPIO: PiGPIOConfig{Enabled: true,
|
||||
CameraServo: CameraServoConfig{Enabled: true},
|
||||
Headlight: GPIOToggleConfig{Enabled: true},
|
||||
Laser: GPIOToggleConfig{Enabled: true},
|
||||
}
|
||||
nativeCamera := &testCameraServoController{cfg: cfg.CameraServo}
|
||||
nativeToggles := map[string]*testToggleController{}
|
||||
Headlight: GPIOToggleConfig{Enabled: true}, Laser: GPIOToggleConfig{Enabled: true},
|
||||
}}
|
||||
factories := nativeHardwareControllerFactories{
|
||||
newCameraServo: func(_ CameraServoConfig, _ *log.Logger) (CameraServoController, error) {
|
||||
return nativeCamera, nil
|
||||
newCameraServo: func(CameraServoConfig, *log.Logger) (CameraServoController, error) {
|
||||
t.Fatal("conflicting GPIO servo must not initialize")
|
||||
return nil, nil
|
||||
},
|
||||
newToggle: func(name string, config GPIOToggleConfig, _ *log.Logger) (ToggleController, error) {
|
||||
controller := &testToggleController{cfg: config}
|
||||
nativeToggles[name] = controller
|
||||
return controller, nil
|
||||
newToggle: func(string, GPIOToggleConfig, *log.Logger) (ToggleController, error) {
|
||||
t.Fatal("conflicting GPIO toggle must not initialize")
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
|
||||
// Duplicate Firmata declarations are irrelevant when native hardware wins;
|
||||
// selection must neither fail nor initialize either ESP32 provider.
|
||||
controllers, err := resolveRoverHardwareControllers(cfg, manager, discardLogger(), factories)
|
||||
if err != nil {
|
||||
t.Fatalf("resolve native precedence: %v", err)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if controllers.CameraServo != nativeCamera || controllers.Headlight != nativeToggles["headlight"] || controllers.Laser != nativeToggles["laser"] {
|
||||
t.Fatal("resolver did not retain native controllers")
|
||||
if controllers.CameraServo != nil || controllers.Headlight != nil || controllers.Laser != nil {
|
||||
t.Fatal("conflicting roles must remain unavailable")
|
||||
}
|
||||
messages := controllers.StartupBroadcasts()
|
||||
if len(messages) != 2 || messages[0] != "Ignored ESP32 camera servo, headlight, laser because native GPIO is enabled." || messages[1] != "Rover hardware ready: camera servo via native GPIO, headlight via native GPIO, laser via native GPIO." {
|
||||
t.Fatalf("native precedence broadcasts = %#v", messages)
|
||||
if len(controllers.issues) != 3 {
|
||||
t.Fatalf("expected three role conflicts, got %v", controllers.issues)
|
||||
}
|
||||
for _, issue := range controllers.issues {
|
||||
if !strings.Contains(issue, "firmata-0, pi-gpio") {
|
||||
t.Fatalf("missing provider identities: %s", issue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
module multiroombarover/rover/roverd
|
||||
|
||||
go 1.25.4
|
||||
|
||||
require (
|
||||
github.com/invopop/jsonschema v0.13.0
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2
|
||||
github.com/stianeikeland/go-rpio/v4 v4.6.0
|
||||
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07
|
||||
github.com/warthog618/go-gpiocdev v0.9.1
|
||||
nhooyr.io/websocket v1.8.17
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/buger/jsonparser v1.1.1 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -1,9 +1,22 @@
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
|
||||
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
|
||||
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/invopop/jsonschema v0.13.0 h1:KvpoAJWEjR3uD9Kbm2HWJmqsEaHt8lBUpd0qHcIi21E=
|
||||
github.com/invopop/jsonschema v0.13.0/go.mod h1:ffZ5Km5SWWRAIN6wbDXItl95euhFz2uON45H2qjYt+0=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
|
||||
github.com/stianeikeland/go-rpio/v4 v4.6.0 h1:eAJgtw3jTtvn/CqwbC82ntcS+dtzUTgo5qlZKe677EY=
|
||||
github.com/stianeikeland/go-rpio/v4 v4.6.0/go.mod h1:A3GvHxC1Om5zaId+HqB3HKqx4K/AqeckxB7qRjxMK7o=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
@@ -14,8 +27,12 @@ github.com/warthog618/go-gpiocdev v0.9.1 h1:pwHPaqjJfhCipIQl78V+O3l9OKHivdRDdmgX
|
||||
github.com/warthog618/go-gpiocdev v0.9.1/go.mod h1:dN3e3t/S2aSNC+hgigGE/dBW8jE1ONk9bDSEYfoPyl8=
|
||||
github.com/warthog618/go-gpiosim v0.1.1 h1:MRAEv+T+itmw+3GeIGpQJBfanUVyg0l3JCTwHtwdre4=
|
||||
github.com/warthog618/go-gpiosim v0.1.1/go.mod h1:YXsnB+I9jdCMY4YAlMSRrlts25ltjmuIsrnoUrBLdqU=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build !dummy && !debian_laptop
|
||||
//go:build !dummy
|
||||
|
||||
package roverd
|
||||
|
||||
@@ -3,7 +3,6 @@ package roverd
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -40,26 +39,20 @@ type ToggleController interface {
|
||||
}
|
||||
|
||||
// RoverHardwareControllers is the result of the single startup-time backend
|
||||
// decision. Its effective configurations are derived from whichever backend
|
||||
// won, making the normal rover hello accurate on both Pi and laptop hosts.
|
||||
// decision. Effective configurations describe the selected role providers.
|
||||
type RoverHardwareControllers struct {
|
||||
CameraServo CameraServoController
|
||||
Headlight ToggleController
|
||||
Laser ToggleController
|
||||
ignoredESP32Roles []string
|
||||
CameraServo CameraServoController
|
||||
Headlight ToggleController
|
||||
Laser ToggleController
|
||||
issues []string
|
||||
}
|
||||
|
||||
// StartupBroadcasts returns short operator-facing messages. Detailed pin and
|
||||
// protocol information remains in the journal; tty1 only explains which
|
||||
// physical backend won and whether an advertised ESP32 role was ignored.
|
||||
// protocol information remains in the journal; tty1 reports selected providers
|
||||
// and unavailable roles.
|
||||
func (controllers RoverHardwareControllers) StartupBroadcasts() []string {
|
||||
var messages []string
|
||||
if len(controllers.ignoredESP32Roles) > 0 {
|
||||
messages = append(messages, fmt.Sprintf(
|
||||
"Ignored ESP32 %s because native GPIO is enabled.",
|
||||
strings.Join(controllers.ignoredESP32Roles, ", "),
|
||||
))
|
||||
}
|
||||
messages = append(messages, controllers.issues...)
|
||||
messages = append(messages, fmt.Sprintf(
|
||||
"Rover hardware ready: camera servo via %s, headlight via %s, laser via %s.",
|
||||
controllerBackend(controllers.CameraServo),
|
||||
@@ -81,9 +74,8 @@ type nativeHardwareControllerFactories struct {
|
||||
newToggle func(string, GPIOToggleConfig, *log.Logger) (ToggleController, error)
|
||||
}
|
||||
|
||||
// ResolveRoverHardwareControllers applies one rule on every real rover build:
|
||||
// enabled native GPIO wins, otherwise one discovered ESP32 may fill the role.
|
||||
// The rule is intentionally not selected by GOARCH or the debian_laptop tag.
|
||||
// ResolveRoverHardwareControllers selects one provider per role, independent of
|
||||
// transport. Conflicts disable only the affected role and are reported locally.
|
||||
func ResolveRoverHardwareControllers(cfg *Config, peripherals *PeripheralManager, logger *log.Logger) (RoverHardwareControllers, error) {
|
||||
factories := nativeHardwareControllerFactories{
|
||||
newCameraServo: func(config CameraServoConfig, logger *log.Logger) (CameraServoController, error) {
|
||||
@@ -98,56 +90,37 @@ func ResolveRoverHardwareControllers(cfg *Config, peripherals *PeripheralManager
|
||||
|
||||
func resolveRoverHardwareControllers(cfg *Config, peripherals *PeripheralManager, logger *log.Logger, factories nativeHardwareControllerFactories) (RoverHardwareControllers, error) {
|
||||
var controllers RoverHardwareControllers
|
||||
if cfg.PiGPIO.Enabled {
|
||||
peripherals.piGPIO = &piGPIOPeripheral{cfg: cfg.PiGPIO, factories: factories}
|
||||
}
|
||||
// Resolving each role separately leaves unrelated hardware usable when a
|
||||
// declaration conflicts or an individual device cannot initialize.
|
||||
var err error
|
||||
// Record ignored declarations separately from selecting controllers so the
|
||||
// same native-first decision can be explained on the local rover console.
|
||||
if cfg.CameraServo.Enabled && peripherals.HasRoverRole("cameraServo") {
|
||||
controllers.ignoredESP32Roles = append(controllers.ignoredESP32Roles, "camera servo")
|
||||
report := func(role string, err error) {
|
||||
if err != nil {
|
||||
message := fmt.Sprintf("%s unavailable: %v", role, err)
|
||||
controllers.issues = append(controllers.issues, message)
|
||||
logger.Print(message)
|
||||
}
|
||||
}
|
||||
if cfg.Headlight.Enabled && peripherals.HasRoverRole("headlight") {
|
||||
controllers.ignoredESP32Roles = append(controllers.ignoredESP32Roles, "headlight")
|
||||
}
|
||||
if cfg.Laser.Enabled && peripherals.HasRoverRole("laser") {
|
||||
controllers.ignoredESP32Roles = append(controllers.ignoredESP32Roles, "laser")
|
||||
}
|
||||
|
||||
controllers.CameraServo, err = resolveCameraServoController(cfg.CameraServo, peripherals, logger, factories.newCameraServo)
|
||||
controllers.CameraServo, err = peripherals.NewCameraServo(logger)
|
||||
if err != nil {
|
||||
return RoverHardwareControllers{}, fmt.Errorf("init camera servo: %w", err)
|
||||
controllers.CameraServo = nil
|
||||
}
|
||||
controllers.Headlight, err = resolveToggleController("headlight", cfg.Headlight, peripherals, logger, factories.newToggle)
|
||||
report("camera servo", err)
|
||||
controllers.Headlight, err = peripherals.NewToggle("headlight", logger)
|
||||
if err != nil {
|
||||
controllers.Close()
|
||||
return RoverHardwareControllers{}, fmt.Errorf("init headlight: %w", err)
|
||||
controllers.Headlight = nil
|
||||
}
|
||||
controllers.Laser, err = resolveToggleController("laser", cfg.Laser, peripherals, logger, factories.newToggle)
|
||||
report("headlight", err)
|
||||
controllers.Laser, err = peripherals.NewToggle("laser", logger)
|
||||
if err != nil {
|
||||
controllers.Close()
|
||||
return RoverHardwareControllers{}, fmt.Errorf("init laser: %w", err)
|
||||
controllers.Laser = nil
|
||||
}
|
||||
report("laser", err)
|
||||
return controllers, nil
|
||||
}
|
||||
|
||||
func resolveCameraServoController(nativeConfig CameraServoConfig, peripherals *PeripheralManager, logger *log.Logger, newNative func(CameraServoConfig, *log.Logger) (CameraServoController, error)) (CameraServoController, error) {
|
||||
if nativeConfig.Enabled {
|
||||
if peripherals.HasRoverRole("cameraServo") {
|
||||
logger.Printf("ignoring ESP32 cameraServo because native camera servo is enabled")
|
||||
}
|
||||
return newNative(nativeConfig, logger)
|
||||
}
|
||||
return peripherals.NewFirmataCameraServo(logger)
|
||||
}
|
||||
|
||||
func resolveToggleController(name string, nativeConfig GPIOToggleConfig, peripherals *PeripheralManager, logger *log.Logger, newNative func(string, GPIOToggleConfig, *log.Logger) (ToggleController, error)) (ToggleController, error) {
|
||||
if nativeConfig.Enabled {
|
||||
if peripherals.HasRoverRole(name) {
|
||||
logger.Printf("ignoring ESP32 %s because native %s is enabled", name, name)
|
||||
}
|
||||
return newNative(name, nativeConfig, logger)
|
||||
}
|
||||
return peripherals.NewFirmataToggle(name, logger)
|
||||
}
|
||||
|
||||
// Close releases selected controller resources in reverse dependency order.
|
||||
// Firmata controllers do not close the shared serial connection; that remains
|
||||
// owned by PeripheralManager and is released by its separate shutdown defer.
|
||||
@@ -0,0 +1,273 @@
|
||||
package roverd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"nhooyr.io/websocket"
|
||||
)
|
||||
|
||||
type ManagementClient struct {
|
||||
cfg *Config
|
||||
configPath string
|
||||
events chan RoverEvent
|
||||
log *log.Logger
|
||||
restart func()
|
||||
mu sync.Mutex
|
||||
runtime *WSClient
|
||||
media *MediaSupervisor
|
||||
stopping bool
|
||||
}
|
||||
|
||||
type managementCommand struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id"`
|
||||
Config json.RawMessage `json:"config"`
|
||||
Reboot *rebootPayload `json:"reboot"`
|
||||
Media *mediaCommand `json:"media"`
|
||||
}
|
||||
|
||||
func NewManagementClient(cfg *Config, path string, events chan RoverEvent, logger *log.Logger, restart func()) *ManagementClient {
|
||||
return &ManagementClient{cfg: cfg, configPath: path, events: events, log: logger, restart: restart}
|
||||
}
|
||||
|
||||
// Startup can finish while a management action is being accepted. Do not attach
|
||||
// a new command source once shutdown has begun.
|
||||
func (m *ManagementClient) SetRuntime(client *WSClient, media *MediaSupervisor) bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.stopping {
|
||||
client.PrepareShutdown()
|
||||
return false
|
||||
}
|
||||
m.runtime, m.media = client, media
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *ManagementClient) Run(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
if err := m.connect(ctx); err != nil && ctx.Err() == nil {
|
||||
m.log.Printf("management connection: %v", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ManagementClient) connect(parent context.Context) error {
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
defer cancel()
|
||||
endpoint, _ := url.Parse(m.cfg.ServerURL)
|
||||
endpoint.Path = "/rover/management"
|
||||
dialCtx, dialCancel := context.WithTimeout(ctx, dialTimeout)
|
||||
conn, _, err := websocket.Dial(dialCtx, endpoint.String(), nil)
|
||||
dialCancel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
conn.SetReadLimit(1024 * 1024)
|
||||
if err := writeJSON(ctx, conn, map[string]any{
|
||||
"type": "hello", "name": m.cfg.Name, "config": m.cfg,
|
||||
"schema": ConfigurationSchema(), "profiles": map[string]any{"video": []any{}, "audioCapture": []any{}, "audioPlayback": []any{}},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
errors := make(chan error, 3)
|
||||
go func() { errors <- keepalive(ctx, conn) }()
|
||||
go func() { errors <- m.read(ctx, conn) }()
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case event := <-m.events:
|
||||
if err := writeJSON(ctx, conn, event); err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
go m.forwardHostStats(ctx, conn)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case err := <-errors:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ManagementClient) read(ctx context.Context, conn *websocket.Conn) error {
|
||||
for {
|
||||
_, data, err := conn.Read(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var command managementCommand
|
||||
if err := json.Unmarshal(data, &command); err != nil {
|
||||
return err
|
||||
}
|
||||
if command.ID == "" {
|
||||
continue
|
||||
}
|
||||
after, commandErr := m.execute(ctx, command)
|
||||
ack := ackMessage{Type: "ack", ID: command.ID, Status: "ok"}
|
||||
if commandErr != nil {
|
||||
ack.Status = "error"
|
||||
ack.Error = commandErr.Error()
|
||||
}
|
||||
err = writeJSON(ctx, conn, ack)
|
||||
// Once configuration is committed, restart even if the acknowledgement
|
||||
// cannot reach the server. Reconnection reports the actual saved object.
|
||||
if after != nil {
|
||||
after()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ManagementClient) execute(ctx context.Context, command managementCommand) (func(), error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.stopping {
|
||||
return nil, fmt.Errorf("management action already pending")
|
||||
}
|
||||
if command.Type == "media" {
|
||||
if m.media == nil || command.Media == nil {
|
||||
return nil, fmt.Errorf("media supervisor unavailable")
|
||||
}
|
||||
return nil, m.media.HandleAction(ctx, command.Media.Action)
|
||||
}
|
||||
var config *Config
|
||||
var err error
|
||||
switch command.Type {
|
||||
case "config.set":
|
||||
config, err = DecodeConfig(command.Config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "reboot", "update":
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported management command: %s", command.Type)
|
||||
}
|
||||
if m.runtime != nil {
|
||||
if err := m.runtime.PrepareShutdown(); err != nil {
|
||||
m.runtime.ResumeControl()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
resume := func() {
|
||||
if m.runtime != nil {
|
||||
m.runtime.ResumeControl()
|
||||
}
|
||||
}
|
||||
if command.Type == "config.set" {
|
||||
if err := SaveConfig(m.configPath, config); err != nil {
|
||||
resume()
|
||||
return nil, err
|
||||
}
|
||||
m.stopping = true
|
||||
return m.restart, nil
|
||||
}
|
||||
// The updater remains a fixed-purpose helper; browser input cannot select
|
||||
// executable paths or shell arguments. Its implementation is a later stage.
|
||||
path, args := "systemctl", []string{"reboot"}
|
||||
if command.Type == "update" {
|
||||
path, args = "/usr/local/sbin/roverd-self-update", nil
|
||||
}
|
||||
if _, err := exec.LookPath(path); err != nil {
|
||||
resume()
|
||||
return nil, err
|
||||
}
|
||||
m.stopping = true
|
||||
delay := 300 * time.Millisecond
|
||||
if command.Reboot != nil && command.Reboot.DelayMs > 0 {
|
||||
delay = time.Duration(clampInt(command.Reboot.DelayMs, 50, 5000)) * time.Millisecond
|
||||
}
|
||||
return func() {
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(delay):
|
||||
}
|
||||
m.emit("system."+command.Type+"Starting", nil)
|
||||
cmd := exec.Command(path, args...)
|
||||
if err := cmd.Run(); err != nil {
|
||||
m.log.Printf("management %s failed: %v", command.Type, err)
|
||||
m.emit("system."+command.Type+"Failed", map[string]any{"error": err.Error()})
|
||||
m.mu.Lock()
|
||||
m.stopping = false
|
||||
resume()
|
||||
m.mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}, nil
|
||||
}
|
||||
func (c *ManagementClient) forwardHostStats(ctx context.Context, conn *websocket.Conn) {
|
||||
var previousNetworkSample *networkRateSample
|
||||
|
||||
send := func() bool {
|
||||
// Host stats are collected on demand so each outbound message describes
|
||||
// the current Pi state. Collection failures are encoded into the stats
|
||||
// payload, which keeps this telemetry path from closing the rover socket.
|
||||
stats := CollectHostStats(ctx)
|
||||
// Throughput is derived here because this loop owns the ordered, periodic
|
||||
// samples for one connection. CollectHostStats stays independent, while a
|
||||
// reconnect automatically receives a clean counter baseline.
|
||||
previousNetworkSample = applyNetworkThroughput(stats.WiFi, previousNetworkSample)
|
||||
msg := hostStatsMessage{
|
||||
Type: "hostStats",
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
Stats: stats,
|
||||
}
|
||||
if err := writeJSON(ctx, conn, msg); err != nil {
|
||||
c.log.Printf("host stats send failed: %v", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Send once immediately so a newly connected rover can populate the UI
|
||||
// without waiting for the first ticker interval.
|
||||
if !send() {
|
||||
return
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(hostStatsInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if !send() {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ManagementClient) SetMedia(media *MediaSupervisor) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.media = media
|
||||
}
|
||||
|
||||
func (m *ManagementClient) emit(event string, data map[string]any) {
|
||||
select {
|
||||
case m.events <- RoverEvent{Type: "event", Event: event, Ts: time.Now().UnixMilli(), Data: data}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ func UpdatePublisherEnv(media MediaConfig) error {
|
||||
/*
|
||||
The env file is intentionally verbose: every publisher receives concrete
|
||||
values instead of silently falling back to script-local defaults. That
|
||||
makes roverd.yaml the owner of media behavior while keeping the shell
|
||||
makes roverd.json the owner of media behavior while keeping the shell
|
||||
scripts as small pipeline launchers.
|
||||
*/
|
||||
fmt.Fprintf(&buf, "ROVERD_VIDEO_ENABLE=%d\n", boolToInt(media.Video.Enabled))
|
||||
@@ -57,6 +57,7 @@ type managedPeripheral struct {
|
||||
// connection behind it. The inventory never changes after discovery, even if a
|
||||
// USB device later disappears; a process restart is the only rescan mechanism.
|
||||
type PeripheralManager struct {
|
||||
piGPIO *piGPIOPeripheral
|
||||
mu sync.RWMutex
|
||||
peripherals []*managedPeripheral
|
||||
byID map[string]*managedPeripheral
|
||||
@@ -172,7 +173,7 @@ func discoverPeripheralManager(ctx context.Context, excludedDevice string, logge
|
||||
func (manager *PeripheralManager) StartupBroadcasts() []string {
|
||||
inventory := manager.Inventory()
|
||||
if len(inventory) == 0 {
|
||||
return []string{"No ESP32 rover peripherals detected during startup."}
|
||||
return []string{"No rover peripherals enabled or detected during startup."}
|
||||
}
|
||||
messages := make([]string, 0, len(inventory))
|
||||
for _, peripheral := range inventory {
|
||||
@@ -387,83 +388,87 @@ func (peripheral *managedPeripheral) requirePinMode(owner string, pin int, requi
|
||||
return fmt.Errorf("%s advertises pin %d without required Firmata mode 0x%02x", owner, pin, requiredMode)
|
||||
}
|
||||
|
||||
// HasRoverRole reports whether discovery found an ESP32 implementation of one
|
||||
// established rover control. It is used only for startup selection and logging;
|
||||
// commands continue to target the selected controller interface directly.
|
||||
func (manager *PeripheralManager) HasRoverRole(role string) bool {
|
||||
return len(manager.roverRoleProviders(role)) > 0
|
||||
// Role providers share identity and controller construction, without requiring
|
||||
// internal hardware to pretend it has a Firmata client or serial connection.
|
||||
type roverRoleProvider interface {
|
||||
roleID() string
|
||||
hasRole(string) bool
|
||||
cameraServo(*log.Logger) (CameraServoController, error)
|
||||
toggle(string, *log.Logger) (ToggleController, error)
|
||||
}
|
||||
|
||||
func (manager *PeripheralManager) roverRoleProviders(role string) []*managedPeripheral {
|
||||
func (p *managedPeripheral) roleID() string { return p.metadata.ID }
|
||||
func (p *managedPeripheral) hasRole(role string) bool {
|
||||
switch role {
|
||||
case "cameraServo":
|
||||
return p.description.RoverControls.CameraServo != nil
|
||||
case "headlight":
|
||||
return p.description.RoverControls.Headlight != nil
|
||||
case "laser":
|
||||
return p.description.RoverControls.Laser != nil
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (p *managedPeripheral) cameraServo(logger *log.Logger) (CameraServoController, error) {
|
||||
return newFirmataCameraServo(p, *p.description.RoverControls.CameraServo, logger)
|
||||
}
|
||||
func (p *managedPeripheral) toggle(role string, logger *log.Logger) (ToggleController, error) {
|
||||
declaration := p.description.RoverControls.Headlight
|
||||
if role == "laser" {
|
||||
declaration = p.description.RoverControls.Laser
|
||||
}
|
||||
return newFirmataToggle(role, p, *declaration, logger)
|
||||
}
|
||||
|
||||
func (manager *PeripheralManager) roleProvider(role string) (roverRoleProvider, error) {
|
||||
if manager == nil {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
manager.mu.RLock()
|
||||
defer manager.mu.RUnlock()
|
||||
var providers []*managedPeripheral
|
||||
for _, peripheral := range manager.peripherals {
|
||||
switch role {
|
||||
case "cameraServo":
|
||||
if peripheral.description.RoverControls.CameraServo != nil {
|
||||
providers = append(providers, peripheral)
|
||||
}
|
||||
case "headlight":
|
||||
if peripheral.description.RoverControls.Headlight != nil {
|
||||
providers = append(providers, peripheral)
|
||||
}
|
||||
case "laser":
|
||||
if peripheral.description.RoverControls.Laser != nil {
|
||||
providers = append(providers, peripheral)
|
||||
}
|
||||
var selected roverRoleProvider
|
||||
var ids []string
|
||||
consider := func(provider roverRoleProvider) {
|
||||
if provider.hasRole(role) {
|
||||
selected = provider
|
||||
ids = append(ids, provider.roleID())
|
||||
}
|
||||
}
|
||||
return providers
|
||||
for _, peripheral := range manager.peripherals {
|
||||
consider(peripheral)
|
||||
}
|
||||
if manager.piGPIO != nil {
|
||||
consider(manager.piGPIO)
|
||||
}
|
||||
if len(ids) > 1 {
|
||||
return nil, fmt.Errorf("rover peripheral role %s has multiple providers: %s", role, strings.Join(ids, ", "))
|
||||
}
|
||||
return selected, nil
|
||||
}
|
||||
|
||||
// NewFirmataCameraServo constructs the shared camera controller only when a
|
||||
// discovered peripheral declared that standardized role. Absence is a normal
|
||||
// disabled-feature result rather than an error.
|
||||
func (manager *PeripheralManager) NewFirmataCameraServo(logger *log.Logger) (CameraServoController, error) {
|
||||
providers := manager.roverRoleProviders("cameraServo")
|
||||
if len(providers) == 0 {
|
||||
return nil, nil
|
||||
func (manager *PeripheralManager) NewCameraServo(logger *log.Logger) (CameraServoController, error) {
|
||||
provider, err := manager.roleProvider("cameraServo")
|
||||
if err != nil || provider == nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(providers) > 1 {
|
||||
return nil, duplicateRoverRoleError("cameraServo", providers)
|
||||
}
|
||||
peripheral := providers[0]
|
||||
return newFirmataCameraServo(peripheral, *peripheral.description.RoverControls.CameraServo, logger)
|
||||
return provider.cameraServo(logger)
|
||||
}
|
||||
|
||||
// NewFirmataToggle resolves either standardized digital role without exposing
|
||||
// the peripheral connection or ESP32 pin to WSClient.
|
||||
func (manager *PeripheralManager) NewFirmataToggle(role string, logger *log.Logger) (ToggleController, error) {
|
||||
providers := manager.roverRoleProviders(role)
|
||||
if len(providers) == 0 {
|
||||
return nil, nil
|
||||
func (manager *PeripheralManager) NewToggle(role string, logger *log.Logger) (ToggleController, error) {
|
||||
provider, err := manager.roleProvider(role)
|
||||
if err != nil || provider == nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(providers) > 1 {
|
||||
return nil, duplicateRoverRoleError(role, providers)
|
||||
}
|
||||
peripheral := providers[0]
|
||||
var declaration *PeripheralDigitalRole
|
||||
switch role {
|
||||
case "headlight":
|
||||
declaration = peripheral.description.RoverControls.Headlight
|
||||
case "laser":
|
||||
declaration = peripheral.description.RoverControls.Laser
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown Firmata toggle role %q", role)
|
||||
}
|
||||
return newFirmataToggle(role, peripheral, *declaration, logger)
|
||||
return provider.toggle(role, logger)
|
||||
}
|
||||
|
||||
func duplicateRoverRoleError(role string, providers []*managedPeripheral) error {
|
||||
providerIDs := make([]string, 0, len(providers))
|
||||
for _, provider := range providers {
|
||||
providerIDs = append(providerIDs, provider.metadata.ID)
|
||||
// StartInternal starts automatic functions after role registration. BRC belongs
|
||||
// to the internal peripheral lifecycle rather than the daemon entry point.
|
||||
func (manager *PeripheralManager) StartInternal(ctx context.Context) error {
|
||||
if manager == nil || manager.piGPIO == nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("rover peripheral role %s has multiple providers: %s", role, strings.Join(providerIDs, ", "))
|
||||
return manager.piGPIO.start(ctx, manager.logger)
|
||||
}
|
||||
|
||||
// Inventory returns a defensive copy in startup order. Server reconnects reuse
|
||||
@@ -487,6 +492,9 @@ func (manager *PeripheralManager) Inventory() []RoverPeripheralMetadata {
|
||||
}
|
||||
inventory = append(inventory, metadata)
|
||||
}
|
||||
if manager.piGPIO != nil {
|
||||
inventory = append(inventory, RoverPeripheralMetadata{ID: "pi-gpio", Name: "Pi GPIO", Controls: []RoverPeripheralControl{}})
|
||||
}
|
||||
return inventory
|
||||
}
|
||||
|
||||
@@ -572,7 +580,12 @@ func (manager *PeripheralManager) Close() {
|
||||
return
|
||||
}
|
||||
manager.closeOnce.Do(func() {
|
||||
manager.cancel()
|
||||
if manager.cancel != nil {
|
||||
manager.cancel()
|
||||
}
|
||||
if manager.piGPIO != nil {
|
||||
manager.piGPIO.close()
|
||||
}
|
||||
manager.mu.Lock()
|
||||
defer manager.mu.Unlock()
|
||||
for _, peripheral := range manager.peripherals {
|
||||
@@ -85,7 +85,7 @@ func TestPeripheralManagerDiscoversInventoryAndDispatchesControls(t *testing.T)
|
||||
|
||||
func TestPeripheralManagerBroadcastsNoDevices(t *testing.T) {
|
||||
manager := &PeripheralManager{byID: make(map[string]*managedPeripheral)}
|
||||
want := "No ESP32 rover peripherals detected during startup."
|
||||
want := "No rover peripherals enabled or detected during startup."
|
||||
if messages := manager.StartupBroadcasts(); len(messages) != 1 || messages[0] != want {
|
||||
t.Fatalf("startup broadcasts = %#v, want %q", messages, want)
|
||||
}
|
||||
@@ -246,7 +246,7 @@ func TestPeripheralManagerRejectsDuplicateBuiltInProvidersWhenRoleIsSelected(t *
|
||||
t.Fatalf("discovery should retain providers until native precedence is known: %v", err)
|
||||
}
|
||||
defer manager.Close()
|
||||
if _, err := manager.NewFirmataToggle("headlight", discardLogger()); err == nil || !strings.Contains(err.Error(), "role headlight has multiple providers") {
|
||||
if _, err := manager.NewToggle("headlight", discardLogger()); err == nil || !strings.Contains(err.Error(), "role headlight has multiple providers") {
|
||||
t.Fatalf("expected duplicate provider selection error, got %v", err)
|
||||
}
|
||||
if first.Closed() || second.Closed() {
|
||||
@@ -0,0 +1,64 @@
|
||||
package roverd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
)
|
||||
|
||||
// piGPIOPeripheral is an in-process provider. It exists only when the parent
|
||||
// switch is enabled; merely loading saved GPIO settings never opens hardware.
|
||||
type piGPIOPeripheral struct {
|
||||
cfg PiGPIOConfig
|
||||
factories nativeHardwareControllerFactories
|
||||
pulser *BRCPulser
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (p *piGPIOPeripheral) roleID() string { return "pi-gpio" }
|
||||
|
||||
func (p *piGPIOPeripheral) hasRole(role string) bool {
|
||||
switch role {
|
||||
case "cameraServo":
|
||||
return p.cfg.CameraServo.Enabled
|
||||
case "headlight":
|
||||
return p.cfg.Headlight.Enabled
|
||||
case "laser":
|
||||
return p.cfg.Laser.Enabled
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *piGPIOPeripheral) cameraServo(logger *log.Logger) (CameraServoController, error) {
|
||||
return p.factories.newCameraServo(p.cfg.CameraServo, logger)
|
||||
}
|
||||
|
||||
func (p *piGPIOPeripheral) toggle(role string, logger *log.Logger) (ToggleController, error) {
|
||||
cfg := p.cfg.Headlight
|
||||
if role == "laser" {
|
||||
cfg = p.cfg.Laser
|
||||
}
|
||||
return p.factories.newToggle(role, cfg, logger)
|
||||
}
|
||||
|
||||
func (p *piGPIOPeripheral) start(ctx context.Context, logger *log.Logger) error {
|
||||
if !p.cfg.BRC.Enabled {
|
||||
return nil
|
||||
}
|
||||
pulser, err := NewBRCPulser(p.cfg.BRC, logger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.pulser = pulser
|
||||
ctx, p.cancel = context.WithCancel(ctx)
|
||||
p.pulser.Start(ctx)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *piGPIOPeripheral) close() {
|
||||
if p.cancel != nil {
|
||||
p.cancel()
|
||||
}
|
||||
if p.pulser != nil {
|
||||
p.pulser.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"piGpio": {
|
||||
"enabled": false,
|
||||
"brc": {
|
||||
"enabled": false,
|
||||
"gpioPin": 4,
|
||||
"gpioChip": "gpiochip0",
|
||||
"pulseEvery": "1m0s",
|
||||
"pulseWidth": "1s"
|
||||
},
|
||||
"cameraServo": {
|
||||
"enabled": false,
|
||||
"pin": 12,
|
||||
"freqHz": 50,
|
||||
"cycleLen": 20000,
|
||||
"minPulseUs": 900,
|
||||
"maxPulseUs": 2100,
|
||||
"minAngle": -15,
|
||||
"maxAngle": 30,
|
||||
"homeAngle": 0,
|
||||
"nudgeDegrees": 2,
|
||||
"allowRawPulse": false,
|
||||
"invert": false
|
||||
},
|
||||
"headlight": {
|
||||
"enabled": false,
|
||||
"gpioPin": 22,
|
||||
"gpioChip": "gpiochip0",
|
||||
"initialOn": false,
|
||||
"activeLow": true
|
||||
},
|
||||
"laser": {
|
||||
"enabled": false,
|
||||
"gpioPin": 27,
|
||||
"gpioChip": "gpiochip0",
|
||||
"initialOn": false,
|
||||
"activeLow": false
|
||||
}
|
||||
},
|
||||
"name": "laptop-rover",
|
||||
"description": "Debian laptop rover using USB serial, webcam, mic, and speakers.",
|
||||
"color": "#4DB6AC",
|
||||
"serverUrl": "ws://control-server.local:8080/rover",
|
||||
"serial": {
|
||||
"device": "/dev/ttyUSB0",
|
||||
"baud": 115200
|
||||
},
|
||||
"battery": {
|
||||
"full": 2068,
|
||||
"warn": 1700,
|
||||
"urgent": 1650
|
||||
},
|
||||
"maxWheelSpeed": 350,
|
||||
"media": {
|
||||
"rtspPort": 8554,
|
||||
"manage": true,
|
||||
"healthUrl": "",
|
||||
"healthInterval": "30s",
|
||||
"video": {
|
||||
"enabled": true,
|
||||
"service": "debian-laptop-video-publisher.service",
|
||||
"publisher": "debian-laptop-v4l2",
|
||||
"device": "/dev/video0",
|
||||
"inputFormat": "mjpeg",
|
||||
"width": 640,
|
||||
"height": 480,
|
||||
"fps": 30,
|
||||
"bitrate": 2000000,
|
||||
"inverted": false,
|
||||
"sensorMode": "1296:972"
|
||||
},
|
||||
"audioCapture": {
|
||||
"enabled": true,
|
||||
"service": "audio-only-publisher.service",
|
||||
"device": "default",
|
||||
"sampleRate": 48000,
|
||||
"channels": 2,
|
||||
"bitrate": 510000
|
||||
},
|
||||
"audioPlayback": {
|
||||
"enabled": true,
|
||||
"service": "audio-forward-listener.service",
|
||||
"device": "forward",
|
||||
"normalize": true,
|
||||
"normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled"
|
||||
}
|
||||
},
|
||||
"audio": {
|
||||
"ttsEnabled": true,
|
||||
"defaultEngine": "flite",
|
||||
"defaultVoice": "rms",
|
||||
"defaultPitch": 50
|
||||
},
|
||||
"horn": {
|
||||
"enabled": true,
|
||||
"volume": 0.25,
|
||||
"sampleRate": 48000,
|
||||
"channels": 1,
|
||||
"device": "",
|
||||
"sineGain": 1,
|
||||
"sawGain": 0.7,
|
||||
"maxDuration": "10s"
|
||||
},
|
||||
"autoSideBrush": {
|
||||
"enabled": true,
|
||||
"speed": 20
|
||||
},
|
||||
"private": {
|
||||
"enabled": false,
|
||||
"safety": {
|
||||
"speedLimitEnabled": false,
|
||||
"speedLimitMaxWheelSpeed": 250,
|
||||
"hardOvercurrentEnabled": false,
|
||||
"overcurrentStopMs": 300,
|
||||
"hardBumpEnabled": false,
|
||||
"bumpBackoffSpeed": 250,
|
||||
"bumpBackoffMs": 350,
|
||||
"cliffEnabled": false,
|
||||
"cliffBackoffSpeed": 250,
|
||||
"cliffBackoffMs": 500,
|
||||
"virtualWallEnabled": true,
|
||||
"virtualWallBackoffSpeed": 250,
|
||||
"virtualWallBackoffMs": 500,
|
||||
"triggerCooldownMs": 800
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"piGpio": {
|
||||
"enabled": false,
|
||||
"brc": {
|
||||
"enabled": true,
|
||||
"gpioPin": 4,
|
||||
"gpioChip": "gpiochip0",
|
||||
"pulseEvery": "1m",
|
||||
"pulseWidth": "1s"
|
||||
},
|
||||
"cameraServo": {
|
||||
"enabled": false,
|
||||
"pin": 19,
|
||||
"freqHz": 50,
|
||||
"cycleLen": 20000,
|
||||
"minPulseUs": 900,
|
||||
"maxPulseUs": 2100,
|
||||
"minAngle": -15,
|
||||
"maxAngle": 30,
|
||||
"homeAngle": 0,
|
||||
"nudgeDegrees": 2,
|
||||
"allowRawPulse": false,
|
||||
"invert": false
|
||||
},
|
||||
"headlight": {
|
||||
"enabled": true,
|
||||
"gpioPin": 22,
|
||||
"gpioChip": "gpiochip0",
|
||||
"initialOn": false,
|
||||
"activeLow": true
|
||||
},
|
||||
"laser": {
|
||||
"enabled": false,
|
||||
"gpioPin": 27,
|
||||
"gpioChip": "gpiochip0",
|
||||
"initialOn": false,
|
||||
"activeLow": false
|
||||
}
|
||||
},
|
||||
"name": "roomba-alpha",
|
||||
"description": "Loves corners, hates cords.",
|
||||
"color": "",
|
||||
"serverUrl": "ws://control-server.local:8080/rover",
|
||||
"serial": {
|
||||
"device": "/dev/ttyAMA0",
|
||||
"baud": 115200
|
||||
},
|
||||
"battery": {
|
||||
"full": 2068,
|
||||
"warn": 1700,
|
||||
"urgent": 1650
|
||||
},
|
||||
"maxWheelSpeed": 350,
|
||||
"media": {
|
||||
"rtspPort": 8554,
|
||||
"manage": false,
|
||||
"healthUrl": "http://127.0.0.1:9997/v3/paths/list",
|
||||
"healthInterval": "30s",
|
||||
"video": {
|
||||
"enabled": true,
|
||||
"service": "video-publisher.service",
|
||||
"publisher": "pi-libcamera",
|
||||
"device": "",
|
||||
"inputFormat": "",
|
||||
"width": 640,
|
||||
"height": 480,
|
||||
"fps": 30,
|
||||
"bitrate": 2000000,
|
||||
"inverted": true,
|
||||
"sensorMode": "1296:972"
|
||||
},
|
||||
"audioCapture": {
|
||||
"enabled": false,
|
||||
"service": "audio-only-publisher.service",
|
||||
"device": "hw:0,0",
|
||||
"sampleRate": 48000,
|
||||
"channels": 2,
|
||||
"bitrate": 510000
|
||||
},
|
||||
"audioPlayback": {
|
||||
"enabled": true,
|
||||
"service": "audio-forward-listener.service",
|
||||
"device": "forward",
|
||||
"normalize": true,
|
||||
"normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled"
|
||||
}
|
||||
},
|
||||
"audio": {
|
||||
"ttsEnabled": false,
|
||||
"defaultEngine": "flite",
|
||||
"defaultVoice": "rms",
|
||||
"defaultPitch": 50
|
||||
},
|
||||
"horn": {
|
||||
"enabled": false,
|
||||
"volume": 0.25,
|
||||
"sampleRate": 48000,
|
||||
"channels": 1,
|
||||
"device": "",
|
||||
"sineGain": 1,
|
||||
"sawGain": 0.7,
|
||||
"maxDuration": "10s"
|
||||
},
|
||||
"autoSideBrush": {
|
||||
"enabled": true,
|
||||
"speed": 20
|
||||
},
|
||||
"private": {
|
||||
"enabled": false,
|
||||
"safety": {
|
||||
"speedLimitEnabled": false,
|
||||
"speedLimitMaxWheelSpeed": 250,
|
||||
"hardOvercurrentEnabled": false,
|
||||
"overcurrentStopMs": 300,
|
||||
"hardBumpEnabled": false,
|
||||
"bumpBackoffSpeed": 250,
|
||||
"bumpBackoffMs": 350,
|
||||
"cliffEnabled": false,
|
||||
"cliffBackoffSpeed": 250,
|
||||
"cliffBackoffMs": 500,
|
||||
"virtualWallEnabled": true,
|
||||
"virtualWallBackoffSpeed": 250,
|
||||
"virtualWallBackoffMs": 500,
|
||||
"triggerCooldownMs": 800
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user