Compare commits

...
Author SHA1 Message Date
legop3 5ba231cb1b rover migration
Container image / image (push) Failing after 49s
2026-11-17 13:47:48 -05:00
legop3 f455edb24a fix realtime datas 2026-11-17 13:40:01 -05:00
legop3 f1e7820caf testing rover self update 2026-11-17 13:27:14 -05:00
legop3 9735e3c0c2 use shared schedma editortoritor 2026-11-17 13:15:04 -05:00
legop3 b62d5a5fc6 ui betterment 2026-11-17 13:08:11 -05:00
legop3 7413b134ad cleanups
Container image / image (push) Failing after 50s
2026-11-17 00:48:38 -05:00
legop3 c384a1389a cleanupses 2026-11-17 00:34:27 -05:00
legop3 2d9b6e4a36 cleanups 2026-11-16 23:22:43 -05:00
legop3 9626389dbe installer / updates 2026-11-16 23:08:30 -05:00
legop3 91c9194856 streamer movement 2026-11-16 22:59:38 -05:00
legop3 b0de727d3e roverstate yay yay. future implements for non-roomba rovers...
Container image / image (push) Failing after 54s
2026-11-16 18:17:22 -05:00
legop3 9b6bdec116 move from /pi to /rover because it isnt just pi anymore.
new json config stuff and ui
2026-11-16 17:45:38 -05:00
legop3 6b57ac1725 todoing
Container image / image (push) Failing after 1m1s
2026-11-13 16:59:14 -05:00
legop3 00cd125fda URL filter in TTS 2026-11-13 16:54:02 -05:00
legop3 684acdd2b6 Add new item to to-do list for MRR platform conversion
Container image / image (push) Failing after 1m5s
2026-11-12 14:52:53 -05:00
legop3 f138cd7b96 Update to-do list with new tasks
Container image / image (push) Failing after 1m5s
Added new tasks for user experience and settings rework.
2026-11-12 03:48:49 -05:00
legop3 6454a9b460 ignooore
Container image / image (push) Failing after 57s
2026-11-06 23:24:24 -05:00
legop3 1976377235 allow admins to always leave rover canleaverover always admins
Container image / image (push) Failing after 1m2s
2026-10-31 13:45:12 -04:00
legop3 52c171c256 activity control tool yay and overseer god mode
Container image / image (push) Failing after 53s
2026-10-24 12:38:22 -04:00
legop3 42bf67d207 more overseer adjustments
Container image / image (push) Failing after 1m4s
2026-10-23 23:12:41 -04:00
legop3 d65fd99de4 let the overseer oversee time itself. also prompt adjustment 2026-10-23 21:26:43 -04:00
legop3 e3d4d9af9b move overseer vote panel to botom
Container image / image (push) Failing after 57s
2026-10-23 00:50:12 -04:00
legop3 ab730ee8a3 add show button for hide button for docking hud
Container image / image (push) Failing after 1m5s
2026-10-19 13:15:29 -04:00
legop3 8fe4f2f98e actions 100% full lol, fixing
Container image / image (push) Failing after 49s
2026-10-19 01:38:10 -04:00
legop3 89f3a1cb65 slopping the dockerfile to hopefully make building faster
Container image / image (push) Failing after 56s
2026-10-18 15:30:08 -04:00
legop3 79d36cae93 update donecharging wav sound
Container image / image (push) Failing after 1m4s
2026-10-18 14:52:27 -04:00
legop3 1dcd7e5d7d add beeps for overcurrent, HELP clear, and low battery 2026-10-18 14:32:59 -04:00
legop3 b4bc99ab27 add server access node to battery embed 2026-10-18 14:22:36 -04:00
legop3 c94e1a0508 change request to switch
Container image / image (push) Failing after 59s
2026-10-09 18:44:50 -04:00
legop3 abcb0871b2 allowed to leave is now used in the web UI to show and hide request / open buttons and trigger popup when leaving the page 2026-10-09 18:30:10 -04:00
legop3 1ffe680895 redoing dock your rover popup thingy
Container image / image (push) Failing after 56s
2026-10-09 17:27:55 -04:00
legop3 ed26b90384 Merge pull request #32 from legop3/FEAT-announcer-audio-stream
Feat announcer audio stream
2026-10-09 14:42:52 -04:00
legop3 2b48fee00f do it properly with the mediamtx giant publisher file that no one maintains a package of for some god forsaken reason agh
Container image / image (push) Failing after 57s
2026-10-09 14:25:09 -04:00
legop3 1284125fff turning into redoing all of the webrtc reading and publishing client side lol 2026-10-09 14:19:06 -04:00
legop3 28d0b1437d guh stupid
Container image / image (push) Failing after 58s
2026-10-08 13:21:23 -04:00
legop3 9d3b8df4bf cleanupses 2026-10-08 13:05:41 -04:00
legop3 9d42cb5581 fix replay command oopsie unrelated 2026-10-08 12:53:32 -04:00
legop3 e670226f8c PTT mode for mic page 2026-10-08 12:48:22 -04:00
legop3 0669f29a4a add webrtc port config so i can test it right lol 2026-10-08 00:33:12 -04:00
legop3 38d3465bf8 room audio 2026-10-08 00:11:32 -04:00
legop3 6bfbb8ad80 replay beeps and boops and flashings
Container image / image (push) Failing after 1m3s
2026-10-07 14:31:54 -04:00
legop3 ba2f66ebc1 add react wrapper thingy to find crashings 2026-10-07 13:38:56 -04:00
legop3 fde2fca0a0 add image tag selection to admin ui
Container image / image (push) Failing after 50s
2026-10-04 13:29:46 -04:00
legop3 d36ea4f672 Merge pull request #31 from legop3/REFACTOR-docking-undocking-serverside
Container image / image (push) Failing after 49s
Refactor docking undocking serverside
2026-10-02 23:23:23 -04:00
legop3 4be6e6c9a2 slop 2026-10-02 23:18:41 -04:00
legop3 7bac2fc447 todoing
Container image / image (push) Failing after 50s
2026-10-02 23:07:14 -04:00
legop3 e8a407cd49 revise what counts for idle service 2026-10-02 23:05:39 -04:00
legop3 bee1866a70 fixings 2026-10-01 21:40:36 -04:00
legop3 ddfc889a8c basically moving docking flows to the server instead of being in the web UI 2026-10-01 21:21:39 -04:00
228 changed files with 4896 additions and 5910 deletions
+1
View File
@@ -5,6 +5,7 @@
.git .git
.gitignore .gitignore
**/node_modules **/node_modules
webui/.cache/mediamtx/
# Neither the legacy state directory nor the Compose-mounted replacement may # Neither the legacy state directory nor the Compose-mounted replacement may
# enter an image build. This prevents credentials and backups from becoming # enter an image build. This prevents credentials and backups from becoming
# image layers after an operator has started using either deployment layout. # image layers after an operator has started using either deployment layout.
+2
View File
@@ -58,6 +58,8 @@ jobs:
# replaced on each successful push, just as main replaces `latest`. # replaced on each successful push, just as main replaces `latest`.
- name: Build and optionally publish - name: Build and optionally publish
uses: docker/build-push-action@v7 uses: docker/build-push-action@v7
env:
DOCKER_BUILD_RECORD_RETENTION_DAYS: 3
with: with:
context: . context: .
platforms: linux/amd64 platforms: linux/amd64
+2
View File
@@ -5,6 +5,7 @@ create_2_Open_Interface_Spec.txt
logs logs
node_modules/ node_modules/
webui/.cache/mediamtx/
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
.pio .pio
@@ -41,3 +42,4 @@ server/data/fleet-reports.sqlite-wal
server/data/configuration.sqlite server/data/configuration.sqlite
server/data/configuration.sqlite-shm server/data/configuration.sqlite-shm
server/data/configuration.sqlite-wal server/data/configuration.sqlite-wal
AGENTS.md
+37 -23
View File
@@ -9,15 +9,21 @@
ARG FEDORA_VERSION=43 ARG FEDORA_VERSION=43
FROM fedora:${FEDORA_VERSION} AS architecture-check FROM fedora:${FEDORA_VERSION} AS architecture-check
ARG FEDORA_VERSION
ARG TARGETARCH ARG TARGETARCH
# The central server is currently deployed and verified only on amd64. Failing # The central server is currently deployed and verified only on amd64. Failing
# here avoids publishing an ARM image whose native workers and hardware paths # here avoids publishing an ARM image whose native workers and hardware paths
# have never been exercised on a real ARM server. # have never been exercised on a real ARM server.
RUN test "${TARGETARCH}" = "amd64" || (echo "MultiRover server images support only linux/amd64." >&2; exit 1) RUN test "${TARGETARCH}" = "amd64" || (echo "MultiRover server images support only linux/amd64." >&2; exit 1)
FROM architecture-check AS webui-build # Both Node builders reuse the same installed toolchain layer.
RUN dnf install -y --setopt=install_weak_deps=False nodejs npm \ # Fedora 43 uses DNF5. Cache metadata and RPMs outside image layers, and keep
&& dnf clean all # 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 WORKDIR /build
# Copy dependency manifests first so ordinary source edits retain the expensive # Copy dependency manifests first so ordinary source edits retain the expensive
# npm cache layer. npm ci makes the checked-in lockfile the exact dependency # 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/ COPY webui/package.json webui/package-lock.json ./webui/
RUN --mount=type=cache,target=/root/.npm \ RUN --mount=type=cache,target=/root/.npm \
cd webui && npm ci 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 COPY webui ./webui
# Vite deliberately emits into ../server/public. Create that destination in the # Vite deliberately emits into ../server/public. Create that destination in the
# isolated builder and copy only its finished files into the runtime stage. # isolated builder and copy only its finished files into the runtime stage.
RUN mkdir -p server/public && cd webui && npm run build RUN mkdir -p server/public && cd webui && npm run build
FROM architecture-check AS server-dependencies FROM node-build-base AS server-dependencies
RUN dnf install -y --setopt=install_weak_deps=False nodejs npm gcc-c++ make python3 \ RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-server-dependencies,target=/var/cache/libdnf5,sharing=locked \
&& dnf clean all dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True gcc-c++ make python3
WORKDIR /build/server WORKDIR /build/server
COPY server/package.json server/package-lock.json ./ COPY server/package.json server/package-lock.json ./
# Native Node modules compile here when a matching prebuild is unavailable; # 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 npm ci --omit=dev
FROM architecture-check AS native-workers 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 \ bluez-libs-devel \
gcc-c++ \ gcc-c++ \
libcap \ libcap \
@@ -49,8 +59,7 @@ RUN dnf install -y --setopt=install_weak_deps=False \
libusb1-devel \ libusb1-devel \
make \ make \
pkgconf-pkg-config \ pkgconf-pkg-config \
wiiuse-devel \ wiiuse-devel
&& dnf clean all
WORKDIR /build WORKDIR /build
COPY server/src/services/kinectService/native ./kinect COPY server/src/services/kinectService/native ./kinect
COPY server/src/services/balanceBoardService/native ./balance-board COPY server/src/services/balanceBoardService/native ./balance-board
@@ -66,8 +75,8 @@ ARG NEOLINK_VERSION=0.6.2
ARG NEOLINK_SHA256=0cb963b44dca7ccc5333154092186e1536c687aef0e1ad119b7f310a7471dbbb ARG NEOLINK_SHA256=0cb963b44dca7ccc5333154092186e1536c687aef0e1ad119b7f310a7471dbbb
ARG GOOGLE_TTS_VERSION=26.5 ARG GOOGLE_TTS_VERSION=26.5
ARG GOOGLE_TTS_SHA256=6a9eae6726871788da52e767dad964a1c83e7feb7e7dbac508a2574a2345ac24 ARG GOOGLE_TTS_SHA256=6a9eae6726871788da52e767dad964a1c83e7feb7e7dbac508a2574a2345ac24
RUN dnf install -y --setopt=install_weak_deps=False curl findutils tar unzip xz \ RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-packaged-tools,target=/var/cache/libdnf5,sharing=locked \
&& dnf clean all dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True curl findutils tar unzip xz
WORKDIR /build/tools WORKDIR /build/tools
# Each external artifact is pinned and checked before extraction. A changed or # Each external artifact is pinned and checked before extraction. A changed or
# truncated upstream download therefore fails the image build instead of being # truncated upstream download therefore fails the image build instead of being
@@ -100,11 +109,12 @@ RUN curl --fail --location --retry 3 \
FROM architecture-check AS learning-dependencies FROM architecture-check AS learning-dependencies
# CPU-only learning dependencies are built once. Disabled installations never # CPU-only learning dependencies are built once. Disabled installations never
# launch Python or install packages as a side effect of starting Node. # launch Python or install packages as a side effect of starting Node.
RUN dnf install -y --setopt=install_weak_deps=False python3 python3-pip \ RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-learning-dependencies,target=/var/cache/libdnf5,sharing=locked \
&& dnf clean all 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 COPY server/src/services/roverLearningService/workers/requirements.txt /tmp/learning-requirements.txt
RUN python3 -m venv /opt/rover-learning \ RUN --mount=type=cache,target=/root/.cache/pip \
&& /opt/rover-learning/bin/pip install --no-cache-dir -r /tmp/learning-requirements.txt python3 -m venv /opt/rover-learning \
&& /opt/rover-learning/bin/pip install -r /tmp/learning-requirements.txt
FROM fedora:${FEDORA_VERSION} AS runtime FROM fedora:${FEDORA_VERSION} AS runtime
ARG FEDORA_VERSION ARG FEDORA_VERSION
@@ -114,14 +124,16 @@ RUN test "${TARGETARCH}" = "amd64" || (echo "MultiRover server images support on
# replay output path. Enable RPM Fusion Free before installing runtime packages # replay output path. Enable RPM Fusion Free before installing runtime packages
# so the image receives the complete FFmpeg build instead of requiring replay # so the image receives the complete FFmpeg build instead of requiring replay
# code to work around a deployment-only codec omission. # 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" "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 # This is the complete runtime package set. Build headers and compilers live in
# earlier stages, while media, TTS, USB, and Bluetooth libraries remain here # earlier stages, while media, TTS, USB, and Bluetooth libraries remain here
# because enabled services invoke them after startup. Weak dependencies are # because enabled services invoke them after startup. Weak dependencies are
# deliberately disabled: Fedora otherwise installs desktop portals, graphical # deliberately disabled: Fedora otherwise installs desktop portals, graphical
# themes, and GPU drivers that a headless server neither starts nor uses. # 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 \
bluez-libs \ bluez-libs \
espeak \ espeak \
@@ -143,17 +155,11 @@ RUN dnf install -y --setopt=install_weak_deps=False \
tini \ tini \
wiiuse \ wiiuse \
--allowerasing \ --allowerasing \
&& dnf clean all \
&& useradd --uid 1000 --create-home --home-dir /home/multirover --shell /sbin/nologin multirover \ && 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 && install -d -o multirover -g multirover -m 0755 /data /opt/multirover/server
WORKDIR /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=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/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=native-workers /build/balance-board/balance_board_worker ./src/services/balanceBoardService/native/balance_board_worker
COPY --from=packaged-tools /output/ / COPY --from=packaged-tools /output/ /
@@ -176,6 +182,14 @@ RUN setcap cap_net_admin,cap_net_bind_service+ep \
&& test -s /tmp/chromegtts-smoke.wav \ && test -s /tmp/chromegtts-smoke.wav \
&& rm /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 \ ENV NODE_ENV=production \
SERVER_DATA_DIR=/data \ SERVER_DATA_DIR=/data \
ROVER_SNAPSHOT_WRITER_BIN=/usr/local/bin/rover-snapshot-writer.sh ROVER_SNAPSHOT_WRITER_BIN=/usr/local/bin/rover-snapshot-writer.sh
+5 -1
View File
@@ -23,9 +23,13 @@ services:
# Required for Bluetooth hardware such as the Balance Board. # Required for Bluetooth hardware such as the Balance Board.
- /run/dbus/system_bus_socket:/run/dbus/system_bus_socket:ro - /run/dbus/system_bus_socket:/run/dbus/system_bus_socket:ro
# Required for Kinect USB access. # Kinect USB access.
devices: devices:
- /dev/bus/usb:/dev/bus/usb - /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: cap_add:
- NET_ADMIN - NET_ADMIN
-24
View File
@@ -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
-24
View File
@@ -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
-24
View File
@@ -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
BIN
View File
Binary file not shown.
Vendored
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Vendored Executable
BIN
View File
Binary file not shown.
Vendored Executable
BIN
View File
Binary file not shown.
Vendored Executable
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
-134
View File
@@ -1,134 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
New Drive corner-pod HUD sketch, second design pass
Purpose: Shows true edge-mounted pods, physically attached expansions, and circular controls.
Scope: Static design communication only; production geometry remains an implementation decision.
-->
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="900" viewBox="0 0 1200 900" role="img" aria-labelledby="title description">
<title id="title">Edge-mounted New Drive HUD pods</title>
<desc id="description">Four pods flow directly into the corners of a four by three rover video. Each has one inward rounded corner, and expansions attach directly along video edges.</desc>
<defs>
<linearGradient id="video" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#26343d" />
<stop offset="0.55" stop-color="#111827" />
<stop offset="1" stop-color="#1f2937" />
</linearGradient>
<linearGradient id="battery" x1="0" y1="1" x2="1" y2="0">
<stop offset="0" stop-color="#22c55e" />
<stop offset="0.72" stop-color="#84cc16" />
<stop offset="1" stop-color="#eab308" />
</linearGradient>
<filter id="shadow" x="-30%" y="-30%" width="160%" height="160%">
<feDropShadow dx="0" dy="5" stdDeviation="8" flood-color="#000000" flood-opacity="0.5" />
</filter>
<style>
.pod { fill: #080a0f; fill-opacity: 0.86; stroke: #d1d5db; stroke-opacity: 0.26; stroke-width: 2; }
.expansion { fill: #080a0f; fill-opacity: 0.82; stroke: #d1d5db; stroke-opacity: 0.2; stroke-width: 2; }
.label { fill: #f8fafc; font-family: Inter, system-ui, sans-serif; font-weight: 700; }
.small { fill: #cbd5e1; font-family: Inter, system-ui, sans-serif; font-size: 17px; }
.tiny { fill: #94a3b8; font-family: Inter, system-ui, sans-serif; font-size: 14px; }
.arrow-button { fill: #1f2937; stroke: #e5e7eb; stroke-opacity: 0.55; stroke-width: 1.5; }
.arrow { fill: none; stroke: #f8fafc; stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
.track { fill: none; stroke: #334155; stroke-linecap: round; }
</style>
</defs>
<!-- The entire canvas is the shared 4:3 video/HUD coordinate space. -->
<rect width="1200" height="900" fill="url(#video)" />
<path d="M0 610 C235 510 390 590 600 515 C820 438 1000 520 1200 430 L1200 900 L0 900 Z" fill="#0b1516" opacity="0.76" />
<path d="M0 655 C240 555 425 635 630 560 C840 483 1020 560 1200 475" fill="none" stroke="#334155" stroke-width="5" opacity="0.42" />
<text x="600" y="450" text-anchor="middle" class="small" opacity="0.28">Rover video</text>
<!-- Top-left pod flows into the top and left edges; only its inward bottom-right corner rounds. -->
<g filter="url(#shadow)">
<path class="pod" d="M0 0 H190 V124 Q190 190 124 190 H0 Z" />
<circle class="track" cx="91" cy="91" r="55" stroke-width="14" />
<circle cx="91" cy="91" r="55" fill="none" stroke="#38bdf8" stroke-width="14" stroke-linecap="round" stroke-dasharray="255 346" transform="rotate(-90 91 91)" />
<text x="91" y="84" text-anchor="middle" class="tiny">Turn</text>
<text x="91" y="116" text-anchor="middle" class="label" font-size="30">0:42</text>
<circle class="arrow-button" cx="22" cy="22" r="16" />
<path class="arrow" d="M29 29 L16 16 M16 16 L25 16 M16 16 L16 25" />
<!-- This expansion begins exactly where the pod ends and continues directly into the top edge. -->
<path class="expansion" d="M190 0 H486 V50 Q486 78 458 78 H190 Z" />
<rect x="210" y="20" width="200" height="38" rx="8" fill="#7c3aed" opacity="0.72" />
<text x="310" y="45" text-anchor="middle" class="label" font-size="18">Rover name</text>
<circle class="arrow-button" cx="458" cy="39" r="14" />
<path class="arrow" d="M458 46 L458 32 M458 32 L452 38 M458 32 L464 38" />
</g>
<!-- Top-right pod and both expansions form one continuous edge-mounted cluster. -->
<g filter="url(#shadow)">
<path class="pod" d="M1010 0 H1200 V190 H1076 Q1010 190 1010 124 Z" />
<circle cx="1105" cy="91" r="59" fill="none" stroke="#334155" stroke-width="13" />
<circle cx="1105" cy="91" r="59" fill="none" stroke="url(#battery)" stroke-width="13" stroke-linecap="round" stroke-dasharray="300 371" transform="rotate(-90 1105 91)" />
<circle cx="1105" cy="91" r="42" fill="none" stroke="#334155" stroke-width="7" />
<circle cx="1105" cy="91" r="42" fill="none" stroke="#f59e0b" stroke-width="7" stroke-linecap="round" stroke-dasharray="112 264" transform="rotate(-90 1105 91)" />
<text x="1105" y="101" text-anchor="middle" class="label" font-size="30">81%</text>
<circle class="arrow-button" cx="1178" cy="22" r="16" />
<path class="arrow" d="M1171 29 L1184 16 M1184 16 L1175 16 M1184 16 L1184 25" />
<!-- Left expansion is attached to the pod at x=1010 and touches the top video edge. -->
<path class="expansion" d="M690 0 H1010 V78 H718 Q690 78 690 50 Z" />
<text x="718" y="31" class="label" font-size="18">Dock assist</text>
<text x="718" y="57" class="small">Dock rover</text>
<rect x="912" y="24" width="38" height="30" rx="6" fill="#312e81" stroke="#a5b4fc" />
<text x="931" y="45" text-anchor="middle" class="label" font-size="14">G</text>
<circle class="arrow-button" cx="980" cy="39" r="14" />
<path class="arrow" d="M980 46 L980 32 M980 32 L974 38 M980 32 L986 38" />
<!-- Lower expansion shares the pod's bottom edge and flows directly into the right edge. -->
<path class="expansion" d="M930 190 H1200 V420 H996 Q930 420 930 354 Z" />
<text x="958" y="225" class="label" font-size="18">Advanced power</text>
<text x="958" y="255" class="small">Voltage</text>
<rect x="958" y="266" width="214" height="8" rx="2" fill="#334155" />
<rect x="958" y="266" width="160" height="8" rx="2" fill="#38bdf8" />
<text x="958" y="306" class="small">Current</text>
<rect x="958" y="317" width="214" height="8" rx="2" fill="#334155" />
<rect x="958" y="317" width="90" height="8" rx="2" fill="#f59e0b" />
<text x="958" y="359" class="tiny">Computer 54 C</text>
<text x="958" y="383" class="tiny">Wi-Fi -58 dBm</text>
<circle class="arrow-button" cx="1174" cy="216" r="14" />
<path class="arrow" d="M1167 216 L1181 216 M1181 216 L1175 210 M1181 216 L1175 222" />
</g>
<!-- Bottom-left pod flows into the left and bottom edges with a compact triangular control group. -->
<g filter="url(#shadow)">
<path class="pod" d="M0 680 H220 Q300 680 300 760 V900 H0 Z" />
<circle cx="68" cy="758" r="38" fill="#172554" stroke="#60a5fa" stroke-width="2" />
<text x="68" y="754" text-anchor="middle" class="label" font-size="24">☀</text>
<text x="68" y="779" text-anchor="middle" class="tiny">E</text>
<circle cx="102" cy="850" r="38" fill="#3b2f0b" stroke="#facc15" stroke-width="2" />
<text x="102" y="846" text-anchor="middle" class="label" font-size="24">⌁</text>
<text x="102" y="871" text-anchor="middle" class="tiny">R</text>
<circle cx="208" cy="798" r="57" fill="#3f1d2e" stroke="#fb7185" stroke-width="3" />
<text x="208" y="794" text-anchor="middle" class="label" font-size="25">Horn</text>
<text x="208" y="823" text-anchor="middle" class="tiny">H</text>
<circle class="arrow-button" cx="252" cy="754" r="14" />
<path class="arrow" d="M246 754 L258 754 M258 754 L253 749 M258 754 L253 759" />
<circle class="arrow-button" cx="22" cy="878" r="16" />
<path class="arrow" d="M29 871 L16 884 M16 884 L25 884 M16 884 L16 875" />
</g>
<!-- Bottom-right pod contains a circular tilt slider rather than a horizontal or pill track. -->
<g filter="url(#shadow)">
<path class="pod" d="M840 900 V760 Q840 680 920 680 H1200 V900 Z" />
<text x="1168" y="714" text-anchor="end" class="label" font-size="18">Camera tilt</text>
<circle class="track" cx="1030" cy="800" r="76" stroke-width="13" />
<circle cx="1030" cy="800" r="76" fill="none" stroke="#38bdf8" stroke-width="13" stroke-linecap="round" stroke-dasharray="285 478" transform="rotate(140 1030 800)" />
<circle cx="976" cy="746" r="13" fill="#e0f2fe" stroke="#0284c7" stroke-width="4" />
<text x="1030" y="808" text-anchor="middle" class="label" font-size="25">-12.5°</text>
<text x="1030" y="832" text-anchor="middle" class="tiny">Click for zero</text>
<circle cx="948" cy="838" r="22" fill="#1e3a8a" stroke="#93c5fd" />
<text x="948" y="844" text-anchor="middle" class="label" font-size="14">J</text>
<circle cx="1112" cy="838" r="22" fill="#1e3a8a" stroke="#93c5fd" />
<text x="1112" y="844" text-anchor="middle" class="label" font-size="14">U</text>
<circle class="arrow-button" cx="1178" cy="878" r="16" />
<path class="arrow" d="M1171 871 L1184 884 M1184 884 L1175 884 M1184 884 L1184 875" />
</g>
<!-- Immediate sensor overlays remain separate and are shown only as faint context here. -->
<path d="M360 900 Q600 808 840 900" fill="none" stroke="#ef4444" stroke-width="13" stroke-linecap="round" opacity="0.25" />
<path d="M410 886 Q600 820 790 886" fill="none" stroke="#22c55e" stroke-width="5" stroke-dasharray="12 10" opacity="0.4" />
</svg>

Before

Width:  |  Height:  |  Size: 9.0 KiB

-75
View File
@@ -1,75 +0,0 @@
- start work on new better ui layout, using components that already exist when possible
- centered rover video, full screen height
- rover HUD contains small but expandable rover telemetry UI and vis
- make newgen folder for new HUD elements. reuse old elements where possible
- make all new hud elements small and clean
- every hud element:
- is a nice small translucent thing with text icons or both
- can be expanded to show more relavent information
- is consistent. maybe make a reusable thing for this
- some specific hud elements:
- top bar:
- battery percentage that goes red and flashes and such
- turns hud that shows people in queue
- big in the middle
- left and right sides
- wheel drop indicators that show up when wheel drop is happening
- overcurrent and battery warnings
- bottom section:
- sensor elements that show up only when the sensor is "happening"
- bumpers
- front IR proximity sensors
- two sidebars
- sidebars contain all the stuff that isnt the rover
- left
- idk
- right
- chat, users, rovers list, and replay sources
- everything involving the rover is a video HUD, everything external is in the sidebars
## section 2
There will be corner mounted (one pod in each corner of the video), rounded pods in the HUD, which will contain gauges and controls for the rover
These pods will be collapsible, with a corner mounted arrow. the arrow points towards the corner when the pod is out, and points out of the corner when the pod is hidden.
There can also be "pod expansions" that will be in the corner of the pod and the side of the video. These are also collapsible, but they collapse into the side of the video that they are touching, instead of collapsing into the corner, with the same style arrow button as the pods.
For example, a pod in the top left is open. This pod has an expansion to it's right that is also open. I can collapse the pod into the corner, the expansion stays, it gets moved into the top left corner where the pod was.
- corner pods:
- top left
- pod
- turns timer
- round gauge circle that ticks down with time
- inside it, is the turn countdown
- this pod goes away when theres nothing to count
- right of pod expansion
- rover name with colored background
- expanded by default
- top right
- pod
- round rover battery bar gauge, based off how battery bar looks
- concentric to this bar is an unlabeled current gauge, styled after the current bar that the top down map contains
- inside the circle, is the battery percentage.
- left of pod expansion
- dock assist button and keybind
- expanded by default
- below pod expansion
- combined advanced power view for the roomba with other info from rover host stats
- bottom left
- pod
- has circular buttons for laser, horn, and headlight
- each button is a related icon and the keybind label for the feature
- arranged nicely
- horn button is larger, and contains an arrow to open the horn settings menu
- this pod disappears when none of these things are enabled
- if one of the button's features is not enabled, that button should go away
- bottom right
- pod
- rounded camera tilt slider, with keybind label on each end for up / down
- in the area inside the slider, show the tilt degrees
- clicking the degrees label should set camera tilt to 0
+49
View File
@@ -0,0 +1,49 @@
# Writing rover media profiles
Bundled profiles live in `rover/profiles/video.yaml`, `audioCapture.yaml`, and `audioPlayback.yaml`. Each catalog is a YAML list with these fields:
- `id`: lowercase letters, digits, underscores, or hyphens; `custom` is reserved.
- `name` and `description`: displayed in Fleet Management.
- `setup`: optional Bash command, safe to repeat at every roverd startup.
- `run`: Bash command that stays running to stream media.
Put commands directly in YAML, not in repository shell helpers. Bash arrays and pipelines work. Commands run as root with error and pipeline failure handling, in `/var/lib/roverd/profiles/<category>/<id>`. That directory persists across restarts and updates.
Enabled profiles run setup serially, then stream independently. Setup failure stops only that streamer. Exited run commands retry after two seconds without repeating setup. Shutdown stops the complete process group. Output and status appear in Fleet Management; output buffering is bounded.
## Command variables
Variables are supplied through the environment. Quote expansions normally, for example `"$ROVER_VIDEO_DEVICE"`.
| Variables | Meaning |
| --- | --- |
| `ROVER_NAME`, `ROVER_SERVER_HOST` | Identity and server hostname |
| `ROVER_PROFILE_DIR`, `ROVER_REPO_DIR` | Persistent working directory and checkout |
| `ROVER_VIDEO_DEVICE`, `ROVER_VIDEO_INPUT_FORMAT` | Camera input |
| `ROVER_VIDEO_WIDTH`, `ROVER_VIDEO_HEIGHT`, `ROVER_VIDEO_FPS`, `ROVER_VIDEO_BITRATE` | Camera/encoder settings |
| `ROVER_VIDEO_INVERTED`, `ROVER_VIDEO_SENSOR_MODE` | Orientation and optional rpicam mode |
| `ROVER_VIDEO_PUBLISH_URL`, `ROVER_AUDIO_PUBLISH_URL`, `ROVER_AUDIO_PLAYBACK_URL` | Complete derived RTSP URLs |
| `ROVER_AUDIO_INPUT_DEVICE`, `ROVER_AUDIO_OUTPUT_DEVICE` | Generated logical ALSA microphone and forwarded-audio routes |
| `ROVER_AUDIO_SAMPLE_RATE`, `ROVER_AUDIO_CHANNELS`, `ROVER_AUDIO_BITRATE` | Microphone encoding settings |
| `ROVER_AUDIO_NORMALIZE`, `ROVER_AUDIO_NORMALIZE_FILTER` | Forwarded-audio normalization |
Fleet Management supports one custom profile per category, saved at `/etc/roverd/profiles/<category>.yaml`. Saving a custom profile restarts roverd; choose it in the streamer's configuration to use it.
## Audio constraints
Use the supplied logical audio routes so microphone, TTS, horn, and forwarded audio follow the configured devices. Physical input/output are selected separately through `audio.inputDevice` and `audio.outputDevice`. Find stable identifiers with `arecord -l` and `aplay -l`.
The output must support a hardware dmix slave with the configured sample rate/channels. Client format conversion uses ALSA plug devices. Independent volume controls may appear only after their PCM first opens. ARMv6 hosts use flite/espeak rather than Chrome TTS.
For the existing AIY Voice HAT, verify card ID `sndrpigooglevoi` before using `hw:CARD=sndrpigooglevoi,DEV=0`; the previous output format was 16000 Hz mono. GPIO18/19 are used by I2S. The existing GPIO12 servo requires `dtoverlay=pwm-2chan,pin=12,func=4,pin2=13,func2=4` in an applicable boot-config section. Reboot after overlay changes.
## Verification still required
Implementation has passed local build/syntax checks; live deployment remains unverified:
- Bootstrap, configuration saves, fleet field changes, and update results after reconnection.
- Camera, microphone, simultaneous TTS/horn/forwarded audio, individual gains, and GPIO/serial operation.
- Streamer retries on a brief connection loss and complete child shutdown on config restart. The separate control watchdog reboots after six minutes offline.
Before replacing an old installation, disable its streamer services and remove its roverd-specific host ALSA definitions; system ALSA hooks can still load those definitions.
+26 -36
View File
@@ -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. All native settings live under `piGpio`, whose parent switch defaults to disabled:
2. Otherwise, if exactly one discovered ESP32 declares the role, use its Firmata implementation.
3. Otherwise, leave the built-in feature 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. ```json
{
Any rover configuration that should use the ESP32 for these roles keeps the corresponding native GPIO features disabled: "piGpio": {
"enabled": false,
```yaml "cameraServo": { "enabled": false },
cameraServo: "headlight": { "enabled": true, "gpioPin": 22, "activeLow": true },
enabled: false "laser": { "enabled": false },
"brc": { "enabled": true, "gpioPin": 4, "pulseEvery": "1m", "pulseWidth": "1s" }
headlight: }
enabled: false }
laser:
enabled: false
``` ```
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 Fleet Management to edit the complete configuration, or `-print-default-config` to inspect all initial fields.
Conflict behavior is fixed and simple: 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. Configure these settings in the Fleet Management configuration editor.
- 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.
### Shared controller interfaces ### 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: The intended interfaces are:
@@ -433,7 +423,7 @@ ToggleController
### Effective hello metadata ### 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: 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. native-USB ESP32-S3.
```bash ```bash
cd pi/roverd cd rover/roverd
go run ./cmd/peripheral-probe -port /dev/ttyUSB0 go run ./cmd/peripheral-probe -port /dev/ttyUSB0
``` ```
## Connection lifecycle ## 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. 8. Validates every advertised standard-output pin against Firmata capabilities.
9. Configures generic digital, PWM, and servo pin modes once. 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. 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. 11. Registers the internal Pi GPIO peripheral if enabled and resolves camera-servo, headlight, and laser roles across providers.
12. Rejects duplicate ESP32 providers only when the corresponding native role is disabled and Firmata selection would otherwise be ambiguous. 12. Reports duplicate role providers and leaves conflicting roles unavailable.
13. Constructs the selected native or Firmata controllers and fixed generic inventory. 13. Constructs the selected native or Firmata controllers and fixed generic inventory.
14. Constructs `WSClient` with those controllers and that 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. 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 self-contained so the same directory can be published directly to the
PlatformIO Registry as `legop3/RoverPeripheral`. PlatformIO Registry as `legop3/RoverPeripheral`.
### `pi/roverd` ### `rover/roverd`
`PeripheralManager` is responsible for: `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 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 ### 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 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 headlight and laser toggle state events remain identical to the native Pi path.
- Confirm existing laser restrictions still apply with the Firmata backend. - 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. - Enable Pi GPIO and a native role also declared by an ESP32; confirm the conflict lists both providers and leaves that role unavailable.
- Disable native and declare the same role from two ESP32s; confirm startup fails with a clear duplicate-role error. - 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. - 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. - Repeat ESP32 role selection on both the ARM Pi binary and amd64 laptop binary and confirm their commands and advertised configurations match.
-787
View File
@@ -1,787 +0,0 @@
# Server administration and container migration
## Status
This document is the live implementation tracker for the migration.
- [x] Phase 1, step 1: Establish the single data-directory contract
- [x] Phase 1, steps 2-5: Configuration database, manual setup-file import, setup, and centralized admin UI
- [x] Phase 1, steps 6-8: Restart, backup/restore, and internal video proxy
- [x] Phase 1, step 9: Complete the remaining legacy-deployment integration and hardware verification
- [x] Phase 2, step 10: Build and locally verify the production application image
- [x] Phase 2, steps 11-12: Add the single-container Compose deployment and locally verify its host-access contract
- [x] Phase 2, step 13: Add application and container health checks
- [x] Phase 2, step 14: Add the restricted lifecycle container and connect the System UI
- [x] Phase 2, step 15: Build pull requests and publish the main branch to the single GHCR `latest` channel
- [ ] Phase 2: Containerization, GHCR publishing, and container lifecycle controls
Phase 1 is complete. The current application has run successfully on the production server with the new configuration, administration, persistence, backup/restore, and internal video-proxy contracts.
The work is deliberately split into two phases:
1. Finish the server-side configuration, administration, persistence, backup, restore, and media-routing changes while the server still uses its current systemd deployment.
2. Containerize the already-finished application, publish images through GHCR, and add container-aware update and restart controls.
Phase 1 must be complete and verified before Phase 2 begins. Containerization must not become a second configuration migration or a reason to maintain two persistence layouts.
## Decision log
- 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.
- 2026-09-14: Apply every committed configuration revision immediately. The configuration coordinator atomically replaces the process-wide snapshot, compares top-level service sections, serially reloads only affected service runtimes, and then refreshes all sessions. Long-lived HTTP/socket handlers remain registered once and delegate to the current runtime; integrations may reconnect or replace their own child process, worker, client, timers, and subscriptions without restarting Node.
- 2026-09-14: Render the schema-driven configuration editor as a YAML-like tree inside one `CardFrame`. Every object or array introduces an ordered header and one indentation guide, every scalar occupies one key/value row, and array operations remain beside their item instead of moving to the far edge. Keep all route-specific RJSF styling in `webui/src/admin/styles.css`, outside the shared global stylesheet.
- 2026-09-14: Restart only the application process, never the host. A lockdown administrator with recent password confirmation requests one audited restart, Node acknowledges and announces it, then sends itself SIGTERM. Existing service signal handlers clean up their owned children, while systemd `Restart=always` and the later container restart policy start the application again.
- 2026-09-14: Keep backup and restore together in one server service after application restart exists. Neither operation stops running services or writers, and no command-line interface is maintained. Backup uses online SQLite snapshots and stable copies of non-database files; restore validates and stages an uploaded archive, records a marker, and uses the normal application restart to replace the data directory during earliest startup.
- 2026-09-14: Define this server's canonical `publicUrl` once at the top of configuration beside `timezone`. Discord links, inter-instance identity, page metadata, and MediaMTX's primary public ICE hostname derive from it. Browser WHEP and WHIP signaling always uses the same-origin `/video` path; `media.additionalHosts` remains only for genuinely additional ICE names or addresses.
- 2026-09-14: Treat container deployment as a fresh installation. Neither startup nor the installer searches for, imports, removes, or otherwise manages an old `config.yaml`; the only old-file paths retained are operator-selected YAML uploads on `/setup` and the protected Configuration page. The separate command-line importer and its dry-run mode are removed. Internal SQLite schema migrations remain because they evolve the active database rather than discovering an old installation.
- 2026-09-14: Keep the one-time first-run setup code in `data/setup-code.txt` with owner-only permissions instead of writing the credential into server logs. Reuse it across restarts and delete it permanently when setup completes.
- 2026-09-14: Feature enablement is exactly the service-owned `enabled` boolean. A service-owned configuration definition marks itself with `feature: true` when that switch belongs in the public feature map; the configuration system derives the map for sessions and command availability, including nested service definitions, without a separate feature registry. Missing credentials, hardware, connections, data, or enabled dependencies are runtime health conditions and never silently change that choice.
- 2026-09-14: Keep configuration as one ordered hierarchical document, matching the former YAML layout. The admin application presents one continuous configuration page and saves the complete document as one revision. There are no artificial Hardware, Integrations, Media, or similar configuration categories and no backend or frontend section registries.
- 2026-09-13: Use an internal Node `/video` proxy. The public reverse proxy will send every site path to Node, Node will strip `/video` and stream WHEP signaling to MediaMTX on loopback, and MediaMTX port 8889 will not be exposed publicly. MediaMTX cannot independently add a WHEP base-path prefix; making `video` part of every stream name would still leave two HTTP servers competing for the public HTTPS listener.
- 2026-09-13: Preserve the existing flat `server/data` layout instead of moving established stores into decorative `state`, `cache`, or `generated` parents. Packaged application assets remain with the application.
- 2026-09-13: "The server" in the filesystem rule specifically means the main Node.js application. Every file it intentionally creates or modifies, including disposable scratch work, must be beneath `SERVER_DATA_DIR`. Installers, systemd, Docker, BlueZ, and unavoidable internal behavior of external libraries are outside that application boundary.
## Final goals
- `config.yaml` and `config.example.yaml` no longer exist.
- All operator-controlled server configuration is stored in a validated database and managed through the web UI.
- All mutable runtime state, generated files, caches, snapshots, recordings, and databases live under one server data directory.
- A complete backup can capture that one data directory consistently, and a restore can safely replace it.
- `/setup` may initialize the database from a YAML file explicitly selected by the operator, and the protected Configuration page may explicitly replace configuration from one later; no automatic host migration or persistent YAML source exists.
- A dedicated `/admin` application contains all server administration.
- The public `/video` route is proxied to MediaMTX by the Node server, eliminating the special external MediaMTX proxy rule.
- The completed server is packaged as a replaceable container whose only persistent mount is the data directory.
- The latest successful main-branch image is built automatically and published to GHCR as `ghcr.io/legop3/multiroombarover:latest`.
- The admin UI can restart, update, health-check, and roll back the application container without giving the main application direct Docker access.
- The final host installation contains as little project-specific material as possible: a Compose file, one Docker-managed data volume, and unavoidable hardware preparation.
## Important boundary: application files versus server data
The data-directory rule applies to everything mutable or instance-specific that the server reads, writes, generates, or persists at runtime. It does not mean copying the application itself into the data directory.
Packaged, read-only application material remains with the application and later inside the image:
- Server source and production dependencies
- Built web UI assets
- Static sound and image assets shipped by the repository
- MediaMTX, ffmpeg, ffprobe, neolink, and TTS tools
- Kinect and Balance Board workers
- Helper scripts shipped as part of the application
The single data directory owns:
- Server configuration and secrets
- Administrator accounts
- Identity and permission records
- Fleet reports
- Persistent service state
- Audit history
- Generated MediaMTX configuration
- Snapshots and replay segments
- Finished replays
- PTZ-generated audio
- Barcode/TTS caches
- Disposable audio-forward and replay-build work under `runtime/`
- Backup and restore coordination state
- Any future file deliberately created or modified by the Node application
Application-owned scratch work must use `SERVER_DATA_DIR/runtime`, even when it is safe to lose on restart. Tests may use the operating system temporary directory because they are not the running server application. Packaged programs and host services can manage their own internal temporary state, but any output path explicitly selected by Node must follow the single-root rule.
# Phase 1: complete the application before containerization
Phase 1 is server, web UI, installer, and migration work only. The current systemd deployment remains the runtime while these contracts are changed and verified.
## 1. Establish the single data-directory contract
The normal development and legacy-install location remains `server/data`. The path continues to be overridable through `SERVER_DATA_DIR`, which will later be set to `/data` in the container.
A representative final layout is:
```text
server/data/
├── configuration.sqlite
├── identity.sqlite
├── fleet-reports.sqlite
├── mediamtx.yml
├── existing service JSON stores
├── barcode-tts-cache/
├── rover-snapshots/
├── replay-segments/
├── replays/
├── ptz-camera-audio/
├── runtime/
│ ├── audio-forward/
│ ├── replay-builds/
│ └── room-camera-replay-builds/
└── system/
├── backup-staging/
└── restore/
```
The exact number of databases is not important. A centralized admin UI does not require unrelated services to share one SQLite connection. Keeping identity and high-volume fleet reporting in their existing databases may remain simpler, provided every database is under the same data directory.
Required work:
- Audit every server filesystem read and write.
- Make every persistent path resolve from the shared data-path helper.
- Move rover and PTZ snapshots out of `/var/lib/rover-snapshots` and into the data directory.
- Remove separate persistent replay path configuration and keep replay segments and completed replays under the data directory.
- Keep generated MediaMTX configuration at its established `data/mediamtx.yml` path.
- Keep barcode speech, PTZ speech, and similar caches under the data directory.
- Check native workers and child-process scripts for hidden working-directory assumptions.
- Update health reporting to inspect the new paths.
- Update the legacy installer so the service receives one `SERVER_DATA_DIR` rather than several unrelated persistent paths.
- Add a focused test that runs services against a temporary data directory and proves that no test artifact escapes it.
- Document which files are durable and which cache directories may be discarded.
The audit must search direct filesystem calls as well as environment-variable defaults. Existing calls that default to `/var/lib`, the repository directory, or an implicit current working directory must be corrected.
## 2. Replace YAML with a configuration database
Implementation architecture:
- Each configurable service owns a side-effect-free fragment containing its key, safe default, and strict schema. One short composition list assembles those fragments into the ordered hierarchical document.
- The database validates and commits that complete document as one coherent immutable revision.
- The admin UI presents one continuous configuration page in the same top-to-bottom order as the former YAML file.
- Nested cards make object relationships readable, but do not create separate categories, navigation destinations, persistence boundaries, or registries.
- Shared editor infrastructure owns loading, dirty state, validation errors, revision conflicts, secret operations, and live-application status for the whole document.
- The browser receives this same schema from the protected admin endpoint and renders it with a maintained JSON Schema form library.
- Standard JSON Schema types drive ordinary fields, nested objects, enums, and arrays. One field-agnostic widget handles every `writeOnly` secret; there are no feature-specific configuration components in React.
Create a synchronous configuration service backed by `better-sqlite3`. Synchronous reads preserve the server's current startup model, in which many services load their configuration while modules are required.
The configuration database should own at least:
- The current complete configuration document
- A monotonically increasing configuration revision
- Previous configuration revisions
- The administrator account catalog and password hashes
- Persistent administrative audit events
- Database/schema migration state
The configuration schema must explicitly describe every supported field. A validation library should be used rather than assembling an ad hoc validator by hand.
Current configuration areas to migrate include:
- Server timezone and public instance identity
- Administrator accounts and Discord identities
- Inter-instance directories and profile
- LLM commentary and Overseer Control
- Barcode games
- Media and WebRTC ICE candidates
- Bandwidth-saving policy
- Audio forwarding and global audio levels
- Home Assistant, Neato, lift, entities, and button mappings
- Room cameras and PTZ camera
- Kinect and Balance Board
- Button box and barcode scanner
- Command names
- Discord bot, channels, and roles
- Social links and driver content
- Fleet-report collection, retention, privacy, and delivery
Required behavior:
- A missing value receives a documented safe default.
- Optional integrations default to disabled.
- Unknown fields are rejected rather than silently ignored.
- Invalid configuration never becomes the active revision.
- A complete revision is written atomically.
- Updates include the acting administrator and timestamp.
- Concurrent editors use revision checking so an older browser cannot overwrite a newer change silently.
- Secrets are never included in ordinary configuration responses, logs, diffs, or audit metadata.
- Secret inputs support replace and clear operations without returning the current value to the browser.
- At least one lockdown administrator must always remain.
- An administrator cannot accidentally remove the only account capable of repairing administration.
Configuration changes use one intentionally simple application rule:
1. Validate the complete proposed document.
2. Commit it as a new database revision.
3. Atomically replace the process-wide configuration snapshot.
4. Compare the old and new top-level sections.
5. Reload every service that owns a changed section, replacing its complete internal runtime when necessary.
6. Report per-service application failures without preventing unrelated services from applying the revision.
7. Refresh sessions only after all affected service reloads finish.
HTTP routes, Socket.IO connection handlers, and process signal handlers are registered once. They consult live state or delegate to the current service runtime, preventing duplicate listeners after repeated saves. Service reloads may reconnect an integration or restart an application-owned child such as MediaMTX, ffmpeg, Kinect, or the Balance Board worker, but never restart the Node application.
Operational actions such as changing server mode, locking a rover, or issuing a rover command remain direct live actions rather than configuration edits.
After migration is complete:
- Remove the YAML configuration loader.
- Remove `SERVER_CONFIG`.
- Remove `config.yaml` and `config.example.yaml` from the repository and installation process.
- Remove `js-yaml` if MediaMTX generation is changed to avoid it or if it is otherwise no longer needed. Generated MediaMTX YAML is an internal artifact, not operator configuration, so retaining `js-yaml` solely for that generator is acceptable.
## 3. Add explicit configuration-file upload to setup and administration
Container deployment starts with a new data directory and never discovers an old installation automatically. As a convenience, the first-run setup page may initialize the empty database from a YAML configuration file deliberately selected by the operator. The protected Configuration page may later replace only the configuration from another explicitly selected legacy file. Neither path is a startup loader, installer migration, command-line workflow, or permanent second source of truth.
Every upload must:
- Accept only an explicitly selected YAML file from `/setup` or the protected Configuration page.
- Parse the complete document.
- Map every recognized field into the new configuration schema.
- Preserve secrets without printing them.
- Apply current defaults for absent fields.
- Ignore fields that do not exist in the current schema, while reporting invalid values supplied for current fields.
- Validate the entire result before writing anything.
- Record the uploaded filename without storing secret values in the audit event.
The setup upload additionally must:
- Require the one-time setup code before processing it.
- Preserve existing bcrypt administrator password hashes, lockdown roles, and Discord IDs.
- Refuse to replace an already-configured database.
- Write the configuration, administrators, and audit event atomically.
The initialized-server upload additionally must:
- Require a lockdown administrator with recent password confirmation.
- Use optimistic revision checking so it cannot overwrite an intervening edit.
- Ignore the entire legacy `admins` collection and leave all current accounts unchanged.
- Preserve stored secrets omitted from the file, replace supplied secrets, and clear explicitly empty secrets.
- Commit through the normal revision path and immediately reload affected services.
The browser uploads the selected contents directly. The server never scans the host for a file, and it does not retain, watch, remove, or reuse the uploaded YAML after the database transaction completes.
## 4. Add first-run setup
The server must boot safely with an empty data directory and without any YAML file.
Required flow:
1. Initialize the databases and safe default configuration.
2. Keep all optional external integrations disabled.
3. Generate a one-time setup code in `data/setup-code.txt` with owner-only permissions. Logs report the file location but never the credential.
4. Serve a restricted `/setup` application.
5. Require the setup code before creating the first lockdown administrator.
6. Offer manual YAML configuration-file upload as an alternative to creating the first administrator from scratch.
7. Otherwise collect only the minimum information needed to establish the instance.
8. Permanently disable setup after the first lockdown administrator exists.
A recovery command must be available for resetting or creating a lockdown administrator from the server console. Environment variables must not act as a recurring authentication bypass on every boot.
## 5. Build the centralized admin application
Create a dedicated `/admin` route instead of continuing to expand the existing driver-page admin panel.
The application should provide these top-level destinations:
- Overview and service health
- Fleet and rover operations
- Users, administrators, verification, and permissions
- Configuration, presented as one hierarchical page
Overview may include application logs, persistent audit history, configuration revisions, backup and restore, and system restart or later container-update state. These operational views do not divide the configuration document into categories.
Existing components and server operations should be moved or reused rather than duplicated. The identity database page and other isolated administrative pages should become destinations within this centralized application where doing so preserves their existing behavior.
Authorization rules:
- Normal administrators may perform routine fleet operations.
- Lockdown administrators manage accounts, secrets, server configuration, backup restoration, and other destructive operations.
- Sensitive changes require recent password confirmation.
- Server-side authorization remains authoritative for every operation; hiding a control in React is not an access check.
Configuration uses one schema-generated typed form rather than a raw YAML or JSON text editor. Repeatable values such as cameras, entities, links, and buttons receive the form library's generic add, remove, and reorder workflow.
## 6. Standardize application restart
Replace the current host reboot operation with one deployment-neutral **Restart application** operation.
The restart operation must:
1. Require a lockdown administrator and recent password confirmation.
2. Reject a second request while one is already pending.
3. Persist an audit event, acknowledge the requester, and notify connected browsers.
4. Stop accepting new HTTP connections and send SIGTERM to the Node process after a short acknowledgement delay.
5. Reuse the cleanup hooks already owned by MediaMTX, ffmpeg, Kinect, Balance Board, and other child-process services.
6. Exit normally and rely on the process supervisor to start the application again.
During Phase 1, systemd uses `Restart=always`. During Phase 2, the container uses a restart policy such as `unless-stopped`. An explicit operator `systemctl stop` or container stop remains stopped; only a process exit is restarted. The browser shows the announced reconnect state and reloads the active administration snapshot after Socket.IO reconnects.
Host rebooting is a separate privilege and is not part of this application contract. The server never invokes `systemctl reboot`.
## 7. Implement complete backup and restore
Everything durable living under one data directory makes the backup boundary simple. Backup and restore remain together under one `backupRestoreService`; there is no generic maintenance framework and no command-line workflow.
### Full backup
The primary admin action is **Download full backup**. A full backup includes the entire durable data payload:
- Configuration and secrets
- Administrator accounts
- Identity and permissions
- Fleet history
- Persistent service state
- Snapshots and replay media
- Generated and cached files that are part of the current server state
- A manifest describing the application and schema versions
The backup operation must:
1. Require a lockdown administrator and recent password confirmation.
2. Leave every service and writer running.
3. Create consistent SQLite snapshots using SQLite's online backup support rather than copying active WAL files.
4. Copy non-database durable files and verify their size and modification time before and after each copy, retrying a file that changed during the copy.
5. Exclude `runtime/`, backup/restore staging, SQLite WAL/SHM files, and incomplete files that never become stable during bounded retries.
6. Produce a manifest containing creation time, application version, schema versions, included paths, sizes, and checksums.
7. Stream the completed archive to the authorized browser and remove temporary staging afterward.
The downloaded archive contains credentials and integration secrets. The UI must say so clearly. It must not be exposed through a permanent public URL or retained indefinitely inside the data directory.
`runtime/` is inside the filesystem boundary but is not durable backup content. Audio FIFOs, incomplete uploads, and in-progress replay builds have no restore value and are excluded without stopping their owners. The initial implementation provides only the authoritative full backup.
### Restore
Restore cannot safely overwrite databases underneath running services. It must be a staged, restart-bound operation.
The restore operation must:
1. Require a lockdown administrator and recent password confirmation.
2. Upload the archive into bounded staging controlled by the data directory.
3. Enforce an upload-size limit that is appropriate for full media-inclusive backups.
4. Reject absolute paths, `..` traversal, symlinks, device files, and unexpected archive structures.
5. Validate the manifest and every checksum before altering active data.
6. Check that the backup version has a supported forward migration path.
7. Display exactly what will be replaced.
8. Require a final explicit confirmation.
9. Record a pending-restore marker.
10. Request the normal application restart.
11. Apply the restore before ordinary services open their databases on the next start.
12. Run database migrations against the restored data when necessary.
13. Start the application and verify its health.
The startup restore path must preserve a local rollback snapshot until the restored server passes validation. If extraction, migration, or startup validation fails, it must put the prior data back and report the failure. Restore coordination files may live under `data/system/restore`, but they must be excluded from the restored payload where necessary to avoid recursively restoring an in-progress operation.
Restoring configuration also restores administrator accounts and secrets. The initiating browser may therefore lose authentication after restart; the reconnect UI must explain this and return to login normally. Backup and restore exist only in the protected admin application.
## 8. Internalize MediaMTX WHEP signaling
The current external proxy maps public `/video/<path>` requests to MediaMTX after stripping `/video`. Node should own that mapping directly.
The final request path is:
```text
Browser: /video/<stream>/whep
Node: strips /video and streams the request internally
MediaMTX: /<stream>/whep on 127.0.0.1:8889
```
Required work:
- Add a maintained HTTP proxy library rather than manually reproducing proxy semantics.
- Register the media proxy early enough that request bodies remain unmodified.
- Stream request and response bodies without buffering.
- Forward `POST`, `PATCH`, `DELETE`, authorization, content type, forwarded protocol, and relevant WHEP response headers.
- Apply bounded but media-appropriate proxy timeouts.
- Bind MediaMTX's WHEP listener to loopback.
- Generate browser WHEP URLs relative to the current site origin.
- Remove `media.whepBaseUrl` from configuration.
- Keep public and LAN ICE candidate hostnames as validated admin configuration.
- Test the exact `/video` prefix removal.
- Confirm that MediaMTX's internal HTTP authorization callback still reaches Node.
The actual WebRTC media does not pass through this HTTP proxy. MediaMTX's ICE TCP/UDP port must remain reachable by browsers.
Afterward, the public TLS proxy sends all paths for the site to Node and no longer needs a separate MediaMTX `/video` upstream.
## 9. Phase 1 verification and completion gate
Phase 1 is complete only when all of the following are true:
- The current systemd installation runs without `config.yaml`.
- A completely empty data directory can be initialized through `/setup`.
- An explicitly selected YAML file can initialize the empty database exactly once.
- The setup upload ignores nonexistent fields and reports invalid values supplied for current fields.
- Startup and installation do not search for or modify an old `config.yaml`.
- All mutable server state is contained by the configured data directory.
- A complete backup can be downloaded and validated.
- A restore replaces the server state only after validation and survives restart.
- Failed restore validation leaves the current server unchanged.
- Configuration, administrator accounts, and secrets survive restart.
- The final lockdown administrator cannot be removed accidentally.
- All administrative surfaces are available through `/admin` with server-side authorization.
- Configuration changes create auditable revisions and apply to the running services without an application restart.
- `/video` works through Node without a special public proxy rule for MediaMTX.
- Rover sockets, RTSP publishing, WHEP playback, snapshots, replays, PTZ, Discord, Home Assistant, Kinect, Balance Board, and reporting retain their intended behavior when enabled.
### Filesystem boundary implementation notes
Implemented on 2026-09-13:
- Removed the obsolete `server/src/data` fallback so there is one default data root.
- Added a shared rover-snapshot directory resolver beneath `SERVER_DATA_DIR`.
- Converted rover snapshot polling, PTZ snapshot reads, and health reporting to that resolver.
- Made the MediaMTX supervisor pass its resolved `SERVER_DATA_DIR` to runOnReady hooks.
- Converted the snapshot writer to require that data root and write to `rover-snapshots` beneath it.
- Removed the separate snapshot and replay-segment locations from the systemd unit generated by the installer.
- Made the installer create and own the canonical data and snapshot directories.
- Preserved the existing flat data layout; established SQLite, JSON, replay, cache, and generated MediaMTX paths were already within the boundary.
- Moved audio-forward FIFOs/uploads and both replay-rendering workspaces from the host temporary directory to `data/runtime`.
- Removed the configurable audio-forward runtime path so configuration cannot direct application writes outside `SERVER_DATA_DIR`.
- Kept prompts, public assets, helper binaries, native workers, and TTS assets with the packaged application because they are read-only application material.
- Left any old `/var/lib/rover-snapshots` and `/var/lib/replay-segments` directories untouched but reported during installation. Nothing reads or writes them after the upgraded service starts, and the operator can remove them after verifying the new paths on the actual server.
Local verification completed:
- Data-path helper tests passed for the default root and an overridden temporary root.
- MediaMTX supervisor testing confirmed that the resolved root reaches child hooks.
- The snapshot writer created `rover-snapshots` beneath a temporary data root and failed closed when no data root was supplied.
- All 91 server tests passed, including the new data-path and MediaMTX supervisor coverage.
- Installer and snapshot-writer shell syntax checks passed.
- Source inventory found no remaining application runtime use of the operating system temporary directory, the old snapshot/replay environment variables, or `/var/lib` paths; only tests use OS temporary directories and the installer retains a deliberate legacy-directory notice.
- Real snapshot generation and legacy-directory cleanup still require verification on the actual server during deployment.
### Configuration and administration implementation notes
Implemented on 2026-09-14:
- Added one ordered, strictly validated hierarchical configuration assembled from side-effect-free definitions owned by the services that consume each value.
- Added immutable SQLite configuration revisions, active-revision tracking, administrator accounts, schema migrations, and persistent administrative audit events under the shared data directory.
- Added full-document saves with optimistic revision checking. A stale browser cannot overwrite a newer revision, and invalid or unknown fields cannot become active.
- Redacted secrets from browser responses and audit data. The one complete save operation preserves stored secrets unless the administrator explicitly replaces or clears them.
- Converted every runtime configuration consumer to the synchronous database-backed configuration service and removed the YAML loader, `SERVER_CONFIG`, and the tracked example YAML.
- Added an explicit one-time YAML upload to `/setup`. Existing bcrypt hashes, lockdown roles, Discord identities, configuration, and secrets can be imported only when the operator selects the file; the installer and startup perform no automatic discovery or migration, and there is no command-line importer.
- Added the same explicit legacy YAML picker to the protected Configuration page for replacing an initialized server's configuration. It requires recent lockdown-password confirmation, ignores every YAML administrator entry, filters nonexistent settings, validates current fields, preserves omitted secrets, applies explicitly supplied or empty secrets, uses optimistic revision checking, records the selected filename in audit history, and reloads affected services immediately.
- The one-time setup upload now passes its committed configuration through the same live-application coordinator, so a fresh installation does not need an immediate restart after importing YAML.
- Made setup-file import recursively retain only fields present in the current schema. Stale keys from the permissive YAML era are ignored without aliases or historical translations, while invalid values for real current settings still fail validation; stream-only and snapshot-only room-camera entries remain accepted as they were by the runtime.
- Added safe empty-data startup, a file-backed one-time setup code, the restricted `/setup` route, and a console administrator-recovery command. The credential persists at `data/setup-code.txt` across restarts with `0600` permissions, never appears in logs, and is deleted when setup completes.
- Added the centralized `/admin` route with Overview, Fleet operations, Users and administrators, and one schema-generated hierarchical Configuration page in legacy YAML order.
- Replaced every feature-specific configuration form with `@rjsf/core`; the protected admin snapshot supplies the server's assembled schema, and one generic widget handles all schema-declared secrets.
- Replaced RJSF's unthemed Bootstrap markup with a generic MultiRover tree renderer. The complete document now follows schema order as indented object, array, item, and key/value rows; array controls remain readable text beside each item, and the route-specific styling lives outside the global stylesheet.
- Replaced the editor's custom section borders, header backgrounds, and indentation guides with the application's shared `CardFrame` at every object, array, and array-item layer. Scalar settings remain compact key/value rows, descriptions use the wider value column, and collection actions stay beside their content instead of moving to the far edge.
- Disabled RJSF's internal checkbox label and description generically, leaving the shared field row as the single owner of each boolean setting's name, required marker, and description.
- Restored the former example YAML's installation-specific values as both schema-owned input examples and the actual initial values for non-secret settings and collection shapes. The only intentionally empty defaults are the three credentials and active driver HTML; their placeholders still explain the expected input without falsely marking credentials as configured or publishing sample content.
- Strengthened top-level hierarchy with a 1.5-rem sibling gap while retaining compact spacing within each configuration section.
- Extended `CardFrame` with an optional explicit accent while preserving its assigned-rover default, then gave every configuration nesting level its own complete header-and-border accent. Nested CardFrames themselves now carry the YAML-like indentation, scalar contents remain aligned with their owning card, and descriptions use a larger, higher-contrast treatment.
- Added an opt-in sticky-header behavior to the shared `CardFrame`. Top-level configuration titles use it beneath the independently sticky action toolbar while nested titles remain in normal flow to prevent overlap, and scalar key labels are now visually stronger than their descriptions.
- Traced all 156 schema nodes to their runtime consumers and added operator-facing descriptions for every root, section, collection, array item, and scalar option. A recursive configuration test now rejects any future schema node without a description; currently reserved settings explicitly state that they have no runtime effect.
- Converged feature control into service-owned configuration: each public feature opts in beside its own schema, and the configuration system derives those exact `enabled` switches for sessions and command discovery. The former server feature registry was removed; configuration completeness and hardware availability remain visible as runtime status instead of becoming hidden enablement rules.
- Lazy-loaded setup and administration so the schema-form dependency is not included in ordinary driver-page downloads.
- Reused the existing fleet and identity administration surfaces, added password reconfirmation for sensitive operations, and prevented removal or demotion of the final lockdown administrator.
- Added configuration revision history, rollback, audit history, and immediate application reporting.
- Added a serialized live-configuration coordinator and converted configurable service runtimes to apply changed sections without restarting Node. Passive policies read the current immutable snapshot; network, hardware, timer, and child-process services replace or retune their owned runtime while stable HTTP/socket handlers continue delegating to it. The admin editor reports any service-specific reload failure after the revision is safely committed.
- Replaced the privileged host-reboot action with one lockdown-only, recently confirmed, audited application restart on the admin Overview. Node announces the restart, stops accepting new HTTP connections, and signals itself after acknowledging the browser; the existing service signal hooks clean up owned child processes, and systemd now restarts clean application exits without making `systemctl stop` ineffective.
- Added one protected backup-and-restore service and admin page. Backups keep the application online, use SQLite's online snapshot API for all three databases, make verified stable copies of the remaining durable files, and produce a checksummed archive through a short-lived one-use download. Restore uploads are size-limited, reject unsafe archive entries, verify the complete manifest, checksums, SQLite integrity, and supported schema versions, then remain staged until explicit recent-password confirmation.
- Restore now uses the normal application restart rather than stopping services itself. The earliest server startup swaps the validated replacement into the data directory, retains one rollback copy, and removes that copy only after the restored application reaches a stabilization point; an interrupted or failed first startup automatically puts the previous data back on the following start. Backup/restore control files and all staging remain inside `data/backup-restore`.
- Fixed production WAL-mode snapshots creating unmanifested SQLite `-wal` and `-shm` files during schema inspection. Backup and restore validation now remove only those temporary staged sidecars before archiving or applying data, and the regression fixture uses WAL mode to match the real databases.
- Added the early streaming `/video` middleware with `http-proxy-middleware`. Express removes the public prefix before forwarding WHEP/WHIP requests to `127.0.0.1:8889`, while root-relative MediaMTX session locations receive the prefix again so subsequent browser `PATCH` and `DELETE` requests follow the same path. MediaMTX signaling now binds to loopback; its ICE UDP/TCP listener remains directly reachable on port 8189.
- Replaced Discord's `siteUrl`, the inter-instance profile's `publicUrl`, and media `whepBaseUrl` with one top-level `publicUrl`. A numbered internal database migration transforms every saved configuration revision before current validation, and the media section now contains only optional additional ICE hosts. WHEP and microphone WHIP URLs are fixed relative paths, so they work through the current origin without knowing its hostname.
- Discord command authorization and lockdown moderation recipients now read the live administrator registry, so setup imports and later Discord-ID or role edits take effect without restarting the server.
- Full-data restore now leaves `runtime/` untouched, matching its existing exclusion from backup archives and preventing the non-root application from trying to remove lifecycle-controller state owned by the root controller container.
- The Users and administrators tab now requests at most 100 lightweight identity summaries through one bounded SQLite query. Search and moderation filters run on the server, while complete signals, permissions, and feature state load only after selecting a user, preventing large identity databases from blocking Socket.IO heartbeats or freezing the browser.
- Removed the remaining server-local SRT hops after Fedora's newer libSRT rejected the zero-payload ACKACK packets emitted by MediaMTX's GoSRT implementation on every acknowledgement cycle. PTZ publishing, replay capture, and snapshot capture now share the existing RTSP/TCP listener, SRT is disabled, and browser-session authorization is bypassed only for loopback readers and rover `-fwd` speaker feeds.
- Fixed inter-instance public payload generation to read feature flags and social links from the same live configuration revision. Social links enabled through the new configuration system no longer trigger an undefined legacy-config reference and an HTTP 500 response.
Local verification completed:
- All 119 server tests passed, including populated legacy-style default coverage, complete schema-description and input-example coverage, file-backed setup-code lifecycle and symlink rejection, service-definition-derived feature projection, schema-derived secret paths, configuration defaults and strict validation, full-document revision conflicts, secret preservation, administrator invariants, setup and initialized-server YAML import safety, recursive removal of nonexistent fields, inter-instance payload generation with social links enabled, and the earlier filesystem coverage.
- All 27 server test files passed after live application, backup/restore, the internal media proxy, and the inter-instance regression coverage were added. The media tests stream exact SDP and trickle-ICE bodies through `POST`, `PATCH`, and `DELETE`, preserve headers, verify prefix and session-location rewriting, confirm loopback-only signaling, and derive the public ICE hostname from the canonical URL. The database migration and production-style WAL backup/restore paths are also covered. Application restart was not signaled on the development machine.
- Focused admin, route, and identity UI lint passed.
- All 20 existing focused web UI tests passed.
- The production web UI build completed successfully and regenerated the checked-in server assets.
- Installer syntax and repository whitespace checks passed.
- A local startup smoke test reached listener initialization. MediaMTX then exited because `/usr/local/bin/mediamtx` is intentionally absent on this development machine; actual enabled integrations and media remain deployment checks for the real server.
- A second empty-data startup smoke test loaded every reloadable service and reached the HTTP listener without listener-limit warnings. A deliberately substituted failing MediaMTX executable then ended the process as expected; enabled hardware and external integrations still require verification on the actual server.
Testing-server verification completed:
- A full backup created from the running application successfully validated and restored through the admin UI after the WAL-sidecar fix.
- WHEP video playback works when the testing server is published through an ordinary whole-application reverse proxy. No special `/video` upstream, prefix rewrite, buffering rule, or direct public MediaMTX signaling route is present, confirming that Node now owns the complete public signaling path.
# Phase 2: containerization and image delivery
Phase 2 packages the completed Phase 1 application. It must not introduce a second configuration source or a second persistent-data layout.
## 10. Build the production application image
Use a Fedora-based multi-stage build to remain close to the dependencies already installed by the server installer and to avoid Alpine/musl compatibility problems with native modules and the ChromeOS TTS library.
### Web UI build stage
- Install locked web UI dependencies with `npm ci`.
- Run the production Vite build.
- Copy only the built assets into the final server tree.
### Server dependency stage
- Install locked server dependencies with `npm ci --omit=dev`.
- Supply compiler tooling only in the build stage for native Node modules.
- Copy production dependencies into the final image.
### Native worker stage
- Build the Kinect worker against libfreenect/libusb.
- Build the Balance Board worker against wiiuse/BlueZ.
- Build for `linux/amd64` rather than copying checked-in workstation binaries.
### Packaged runtime tools
At image-build time:
- Download pinned MediaMTX and neolink releases.
- Verify checksums.
- Install ffmpeg, ffprobe, TTS engines, required GStreamer libraries, and runtime native libraries.
- Install the ChromeOS TTS library and voice data.
- Install the TTS and snapshot helper scripts.
- Run reasonable build-time smoke checks.
The actual server must never download or compile these dependencies during container startup.
### Final image
The final image should:
- Contain no compiler toolchain, Git checkout, development dependencies, or build cache.
- Run Node as a dedicated non-root user.
- Use a minimal init process to reap child processes.
- Treat `/data` as its only persistent writable location.
- Use `/tmp` only for disposable work.
- Include ordinary OCI source metadata linking the image to this repository, without introducing an application version number.
- Handle `SIGTERM` through the Phase 1 graceful shutdown coordinator.
### Production image implementation notes
Implemented and locally verified on 2026-09-15:
- Added one root multi-stage `Dockerfile` that builds the Vite application, locked production Node dependencies, Kinect worker, and Balance Board worker, then copies only their runtime outputs into a Fedora 43 image.
- Downloaded pinned amd64 MediaMTX 1.15.3, Neolink 0.6.2, and ChromeOS Google TTS 26.5 artifacts during the build and rejected downloads that did not match their recorded SHA-256 checksums.
- Installed the media, TTS, USB, Bluetooth, and native-worker runtime libraries without Fedora weak dependencies. This avoids pulling unrelated desktop recommendations into the headless image while retaining the libraries explicitly required by the current server installer.
- Added a root `.dockerignore` so local dependencies, mutable server data, generated public assets, compiled host workers, logs, and Git metadata cannot leak into the image build context.
- Configured `/data` as `SERVER_DATA_DIR`, ran Node as the dedicated uid 1000 `multirover` user, retained only the Balance Board worker's required capabilities, and used `tini` as the container init process.
- Successfully built and loaded `multiroombarover:local` for `linux/amd64`. Its registry-style compressed content size is approximately 828 MB; Docker reports approximately 2.87 GB of local unpacked disk usage because the complete GStreamer, ffmpeg, Kinect, Node, and offline TTS runtime is intentionally included.
- Confirmed at build time that Chrome TTS loads its packaged voice model and produces a nonempty WAV file.
- Replaced Fedora's restricted `ffmpeg-free` package with RPM Fusion Free's complete `ffmpeg` package after development-container testing exposed that `ffmpeg-free` omits the `libx264` encoder required by rover replay capture, room-camera replay rendering, replay sidebars, and final replay assembly.
- Started the image with host networking and a temporary SELinux-relabeled `/data` bind mount. The application reached its HTTP listener, generated first-run state only inside the mount, and started the packaged MediaMTX with its generated configuration under `/data`.
- Confirmed `/`, `/setup`, and `/admin` return the production UI; `/video/` reaches the loopback MediaMTX proxy; MediaMTX and Neolink execute; both native workers link against the runtime image; and the Balance Board worker retains only `cap_net_admin` and `cap_net_bind_service`.
- Restarted the same container and confirmed the setup credential and configuration database were byte-for-byte unchanged, then confirmed `/admin` returned successfully again.
- Stopped and removed the smoke-test container and deleted its temporary data. No test server process was left running on the development machine.
## 11. Compose deployment
The host-visible project installation should be only:
```text
multirover/
└── compose.yaml
```
Docker owns the separately persisted `multirover-data` volume. Operators move
or inspect its complete contents through the administration backup/restore UI
rather than coordinating host filesystem ownership with the container user.
The Compose project contains:
- The main Multirover application container
- A small lifecycle container used for application update and restart
The application mounts:
```text
data:/data
```
Host networking is the initial preferred design because it most closely preserves current rover RTSP, WebRTC ICE, UDP media, camera, and LAN integration behavior. The exact listeners must be audited before finalizing the Compose file.
Expected externally relevant listeners are:
- Node HTTP, Socket.IO, and proxied WHEP signaling on TCP 8080
- Rover RTSP publishing on TCP 8554
- WebRTC media on TCP and UDP 8189
MediaMTX WHEP on 8889 and API/metrics listeners should stay on loopback unless an identified remote consumer requires otherwise. Publishers and server-local replay/snapshot readers use the single RTSP/TCP listener on 8554; SRT is disabled.
### Compose implementation notes
Implemented and locally verified on 2026-09-15:
- Added one root `compose.yaml` containing only the main application. It uses `ghcr.io/legop3/multiroombarover:latest`, host networking, `restart: unless-stopped`, and the single `data:/data` persistent named-volume mount. The lifecycle service remains a later, separate step rather than a placeholder in the initial deployment.
- Added both possible local data directories to `.dockerignore`, alongside the legacy `server/data`, so credentials, databases, recordings, backups, and generated state cannot enter later image builds even during development or manual inspection.
- Started the exact Compose definition from an empty Docker-managed volume using the locally built image tagged with the final GHCR name. The application created its configuration database, setup credential, and generated MediaMTX configuration only under that volume.
- Confirmed the production UI responds on `/`, `/setup`, and `/admin`. A request to `/video/` reached the internal MediaMTX proxy and received MediaMTX's expected not-found response because the empty configuration had no requested stream.
- Restarted through Compose and confirmed the setup credential and configuration database remained byte-for-byte unchanged. A separate marker created through `/data` also remained present after restart.
## 12. Hardware access with minimal host setup
The host must still provide the kernel and system services that containers cannot safely configure for themselves.
Kinect requirements:
- One host udev rule granting the intended device access
- The necessary USB device mount, likely `/dev/bus/usb` because Kinect device numbering can change
- libfreenect and the worker inside the image
Balance Board requirements:
- Host Bluetooth daemon configuration required by the existing raw HID design
- Access to the host BlueZ D-Bus socket
- Only the network capabilities required by the native worker
- No fully privileged main application container
The exact capabilities and device permissions must be proven on the real server hardware. This development machine is not the actual server and cannot complete that validation.
### Hardware-access implementation notes
Implemented and locally verified as far as this development host permits on 2026-09-15:
- Added the BlueZ command-line package to the runtime image because the Balance Board service commissions devices through `bluetoothctl`; the rebuilt image reports BlueZ 5.87.
- Exposed `/dev/bus/usb` so reconnecting Kinect devices do not depend on a temporary bus/device number, and granted only `NET_ADMIN` for the Balance Board worker rather than using privileged mode.
- Mounted only the host system D-Bus socket for BlueZ access. Docker's per-container SELinux label is disabled because Fedora blocks access to the shared host socket and USB device nodes otherwise, while relabeling the system socket would affect the host; the process remains non-root and Docker's namespace, capability, and seccomp isolation remain active.
- Confirmed the container can open the mounted system D-Bus socket and that its native Balance Board worker retains only its existing file capabilities. The development host's Bluetooth daemon is inactive and no production Kinect or Balance Board is attached, so real discovery, reconnect, and streaming remain part of the actual-server validation.
The host should not need Node, npm, MediaMTX, ffmpeg, neolink, application source, or a Multirover systemd unit after cutover.
## 13. Health checks
Add an internal health endpoint that verifies:
- Node is accepting requests.
- Configuration initialization and migrations succeeded.
- The data directory is readable and writable.
- Required SQLite databases are usable.
- MediaMTX is running and its internal endpoint responds.
Optional remote integrations should report degraded status to administrators without forcing a container restart loop. Home Assistant, Discord, a camera, or an LLM server being offline does not mean the application process itself is unhealthy.
Compose should use the health endpoint and a restart policy suitable for unattended operation.
### Health-check implementation notes
Implemented on 2026-09-15:
- Added an unauthenticated `GET /health` readiness endpoint that exposes only two non-sensitive booleans: whether the application user can read and write the configured data directory and whether MediaMTX answers through its loopback-only metrics listener.
- Treated successful route execution as proof that Node is accepting HTTP and that configuration initialization completed. This avoids repeatedly querying every SQLite database or turning optional integrations and currently offline media sources into container restart conditions.
- Added the image-level Docker health check using Node's built-in `fetch`, so Compose receives the readiness state without installing another command-line probe utility.
## 14. Restricted lifecycle container
The main web application must not mount the Docker socket. Docker socket access is effectively host-root access.
A small lifecycle container should be the only component with Docker control. It should:
- Have no public network port.
- Accept requests only through a shared Unix socket under `data/system` or another private Compose-only channel.
- Operate only on the fixed Multirover application service.
- Reject arbitrary command lines, service names, image names, and Compose arguments.
- Persist update job state so it survives replacement of the application container.
- Compare the running image's internal digest with the current `latest` digest.
- Pull the fixed `ghcr.io/legop3/multiroombarover:latest` image.
- Restart or recreate the application container.
- Wait for the application health check.
- Retain and restore the previous image when the replacement fails.
The `/admin` System section should expose:
- Whether the running application is current or an update is available
- Check for update
- Update and restart
- Restart application
- Update progress and recent output
- Last update result
- Rollback result
These operations require a lockdown administrator and recent password confirmation. The browser must expect its socket to disappear, show a reconnect state, and retrieve the persistent job result after the new application becomes healthy.
The Compose contract should remain stable so ordinary main-branch image updates replace only the application image. Updating the lifecycle component or changing host mounts/capabilities is a separate, rarer deployment-format update and must not be disguised as an ordinary application update.
### Lifecycle-controller implementation notes
Implemented on 2026-09-15:
- Reused the single published application image for the lifecycle service with a controller-only command. This avoids a second Dockerfile, image name, GHCR workflow, and release lifecycle while the two containers still run separate processes with separate privileges.
- Mounted `/var/run/docker.sock` only in the network-disabled lifecycle container. The application communicates through a dedicated Unix-socket volume and cannot submit an image name, container name, command, or Docker option; the controller operates only on the fixed `multirover` container and the deployment-selected MultiRover image.
- Added fixed status, update-check, restart, and update operations. Update checks pull the configured moving image and compare Docker image IDs. Updates retain the previous image ID, recreate the application with its existing Compose host contract, wait for the image health check, and restore the previous image when replacement health fails.
- Persisted the current operation and result in the private lifecycle Unix-socket volume. This survives ordinary application replacement and browser reconnection without mounting the root lifecycle controller into the application's `/data` volume, leaving all application runtime paths owned by the non-root server.
- Connected the existing lockdown-administrator password confirmation and audit history to the lifecycle operations. The Administration overview polls persisted progress, reports update and rollback results, and keeps the legacy process-level restart only when no controller socket exists.
- Accepted self-updates, administrator restarts, and backup-restore restarts share a helper that sets the persistent admin reason to "server is restarting" and removes every current rover driver with the same notice. This does not change server mode or automatically clear the reason after startup.
- Defined the deployment image once through a Compose YAML anchor. Both services and the controller target reuse that exact value, so production stays on `ghcr.io/legop3/multiroombarover:latest` and development requires changing only the single visible selector line to a branch tag.
## 15. GHCR publishing automation
Add repository automation that:
- On pull requests, runs all required verification and proves that the production image builds without publishing it.
- On each repository branch push, builds the production image from a clean checkout.
- Uses the production Dockerfile as the single verification path. Its locked dependency installs, web UI production build, native worker builds, external-artifact checksum checks, and TTS smoke test must all pass before publication.
- Builds the supported `linux/amd64` image without QEMU or a multi-architecture manifest.
- Publishes `ghcr.io/legop3/multiroombarover:latest` from main and one sanitized branch-name tag from every other repository branch; there are no numbered, commit, stable, edge, or release tags.
- Leaves the previously published image for that branch untouched when any required verification or build step fails.
- Uses registry-generated digests only inside the lifecycle implementation for update comparison and rollback.
The deployed server pulls the prebuilt `latest` image. It does not run `git pull`, `npm install`, native compilation, or web UI compilation.
### GHCR automation implementation notes
Implemented on 2026-09-15:
- Added one `Container image` GitHub Actions workflow. Pull requests build the complete production Dockerfile without logging in or publishing. Main-branch pushes publish `ghcr.io/legop3/multiroombarover:latest`, while every other repository branch publishes one moving image using its sanitized branch name.
- Used GitHub's repository-scoped token with only contents-read and packages-write permissions. No separate registry secret, release process, version calculation, QEMU setup, or custom tag-generation code is required.
- Kept one Buildx job for all event types so pull-request verification, development branches, and main-branch publication cannot drift into different image recipes. Docker's maintained metadata action owns branch-name sanitization, and GitHub Actions layer caching avoids repeatedly downloading and rebuilding the image's large pinned media and TTS dependencies.
- Removed the legacy package-lock ignore rules and added the server lockfile required by `npm ci` to the migration change set. Local Docker builds and clean GitHub checkouts now receive the same locked server and web UI dependency inputs instead of allowing an ignored workstation file to mask a missing build input.
- The workflow file was parsed locally and its event, permission, architecture, tag-selection, and conditional-publish contract were checked. The first actual GHCR publication necessarily remains a GitHub-hosted verification after these changes are pushed.
## 16. Container cutover
The actual deployment migration should:
1. Download and validate a full Phase 1 backup.
2. Stop and disable the legacy Multirover systemd service.
3. Ensure no legacy MediaMTX service remains active.
4. Place the Compose file on the host; Docker creates the named data volume on first start.
5. Start the application and lifecycle containers.
6. Confirm that database migrations complete.
7. Confirm the active configuration revision and administrator access.
8. Verify rover connectivity, media publishing, WHEP playback, replay, cameras, and enabled hardware/integrations.
9. Exercise application restart through `/admin`.
10. Exercise an image update and health-check result.
11. Retain the Phase 1 backup until the container deployment has been accepted.
The old systemd application and the Compose application must never run concurrently because they would compete for HTTP and media ports.
## 17. Phase 2 completion gate
Containerization is complete when:
- A new host can start from one Compose file and an automatically created empty data volume.
- Existing state can be restored from a Phase 1 full backup.
- `data:/data` is the only persistent application mount.
- Replacing the application container preserves all state.
- The special external `/video` MediaMTX route is unnecessary.
- The main container has no Docker socket access and is not fully privileged.
- Admin-triggered restart works.
- Admin-triggered update works and persists progress across reconnection.
- A failed image health check rolls back to the prior image.
- The GHCR `latest` image is reproducibly built from the newest successful main-branch commit.
- Kinect and Balance Board behavior has been verified on the actual host.
- Node, npm, application source, and media binaries are no longer installed directly on the host.
# Recommended implementation order
Within the two hard phase boundaries, the safest order is:
- [x] Complete the filesystem audit and single data-directory migration.
- [x] Add the configuration schema/database and administrator storage.
- [x] Add first-run setup and explicit YAML configuration-file upload.
- [x] Convert every configuration consumer and remove YAML runtime loading.
- [x] Converge optional feature control into service-owned `enabled` switches and derive the public feature map from those definitions.
- [x] Build the centralized admin configuration UI.
- [x] Add persistent audit history.
- [x] Apply every configuration revision to running services without restarting the application.
- [x] Standardize graceful application restart.
- [x] Implement online backup and restart-bound staged restore in one service.
- [x] Add the internal `/video` proxy and make the special external route unnecessary.
- [x] Run the full Phase 1 completion gate on the legacy deployment.
- [x] Build and verify the production application image.
- [x] Add Compose, data mounting, networking, and hardware access.
- [x] Add GHCR build and publication automation.
- [x] Add the restricted lifecycle container and connect the System UI.
- [ ] Test update, rollback, backup restore, and hardware on the actual server.
- [ ] Perform the final systemd-to-Compose cutover.
This order gives each invasive change one clear source of failures and leaves the container phase responsible for packaging and supervision rather than unfinished application architecture.
+16
View File
@@ -64,6 +64,7 @@ socket.on('connect', async () => {
// previously stored session with this object instead of merging snapshots. // previously stored session with this object instead of merging snapshots.
socket.on('session:sync', (session) => { socket.on('session:sync', (session) => {
console.log('Session:', session); console.log('Session:', session);
console.log('Server mode:', session.mode);
}); });
// chat:init contains the recent chat history available when the bot connects. // chat:init contains the recent chat history available when the bot connects.
@@ -105,6 +106,21 @@ Run it with:
node bot.js 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 ## Events used
- `nickname:set` sets the bot's visible nickname. - `nickname:set` sets the bot's visible nickname.
+209
View File
@@ -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)
-88
View File
@@ -1,88 +0,0 @@
# Use the Google Voice HAT soundcard as the primary device by name (card id is "sndrpigooglevoi")
options snd_rpi_googlevoicehat_soundcard index=0
# Mix multiple playback clients in software with a fixed low-cost format.
pcm.dmixer {
type dmix
ipc_key 1024
ipc_perm 0666
slave {
pcm "hw:0,0"
format S16_LE
rate 16000
channels 1
period_time 0
period_size 1024
buffer_size 4096
}
}
# TTS volume control (used by default playback path).
pcm.tts_softvol {
type softvol
slave.pcm "dmixer"
control {
name "TTSMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Horn volume control.
pcm.horn_softvol {
type softvol
slave.pcm "dmixer"
control {
name "HornMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Forwarded audio volume control.
pcm.forward_softvol {
type softvol
slave.pcm "dmixer"
control {
name "ForwardMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Per-source playback PCMs.
pcm.tts {
type plug
slave.pcm "tts_softvol"
}
pcm.horn {
type plug
slave.pcm "horn_softvol"
}
pcm.forward {
type plug
slave.pcm "forward_softvol"
}
# Capture alias used by rover config defaults.
pcm.rovermic {
type plug
slave.pcm "hw:0,0"
}
# Defaults: TTS direct playback + raw capture on the HAT.
pcm.!default {
type asym
playback.pcm "tts"
capture.pcm "rovermic"
}
ctl.!default {
type hw
card 0
}
-102
View File
@@ -1,102 +0,0 @@
# Reference ALSA routing for the Debian laptop rover profile.
#
# This intentionally mirrors pi/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.
#
# The Debian laptop installer no longer copies this file directly. It renders
# /etc/asound.conf from /etc/roverd-installer.env so laptops with HDMI as card 0
# can point these same logical mixer devices at their real speaker card.
#
# This is NOT meant to preserve normal desktop audio behavior. The laptop rover
# installer disables PipeWire/PulseAudio so roverd owns the audio hardware like
# the Raspberry Pi rover does. If the laptop's real speaker/mic card is not ALSA
# card 0, rerun the Debian laptop installer and answer the ALSA prompts using:
# aplay -l
# arecord -l
# Mix multiple playback clients in software with a fixed low-cost format.
pcm.dmixer {
type dmix
ipc_key 1024
ipc_perm 0666
slave {
pcm "hw:0,0"
format S16_LE
rate 16000
channels 1
period_time 0
period_size 1024
buffer_size 4096
}
}
# TTS volume control (used by default playback path).
pcm.tts_softvol {
type softvol
slave.pcm "dmixer"
control {
name "TTSMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Horn volume control.
pcm.horn_softvol {
type softvol
slave.pcm "dmixer"
control {
name "HornMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Forwarded audio volume control.
pcm.forward_softvol {
type softvol
slave.pcm "dmixer"
control {
name "ForwardMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Per-source playback PCMs.
pcm.tts {
type plug
slave.pcm "tts_softvol"
}
pcm.horn {
type plug
slave.pcm "horn_softvol"
}
pcm.forward {
type plug
slave.pcm "forward_softvol"
}
# Capture alias used by laptop rover config defaults.
pcm.rovermic {
type plug
slave.pcm "hw:0,0"
}
# Defaults: TTS direct playback + raw capture on the dedicated laptop sound card.
pcm.!default {
type asym
playback.pcm "tts"
capture.pcm "rovermic"
}
ctl.!default {
type hw
card 0
}
-139
View File
@@ -1,139 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
set +H
ENV_FILE="${ROVERD_MEDIA_ENV_FILE:-/var/lib/roverd/media.env}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Environment file ${ENV_FILE} missing; cannot start audio forward listener" >&2
exit 1
fi
# Load KEY=VALUE pairs from media.env without evaluating shell syntax. The forward URL is
# data produced by roverd and must never be interpreted as executable shell code.
load_env_file() {
local content=""
if [[ -r "$ENV_FILE" ]]; then
content="$(cat "$ENV_FILE")"
elif command -v sudo >/dev/null 2>&1; then
content="$(sudo -n cat "$ENV_FILE" 2>/dev/null || true)"
fi
if [[ -z "$content" ]]; then
echo "Cannot read ${ENV_FILE} (permission denied). Run as a user that can read it, or allow sudo -n for cat." >&2
exit 1
fi
local line key val
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
if [[ "$line" =~ ^[[:space:]]*export[[:space:]]+([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
elif [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
else
continue
fi
val="${val#${val%%[![:space:]]*}}"
val="${val%${val##*[![:space:]]}}"
if [[ "$val" =~ ^\".*\"$ ]]; then
val="${val:1:${#val}-2}"
elif [[ "$val" =~ ^\'.*\'$ ]]; then
val="${val:1:${#val}-2}"
fi
printf -v "$key" '%s' "$val"
export "$key"
done <<< "$content"
}
load_env_file
: "${ROVERD_AUDIO_PLAYBACK_ENABLE:?ROVERD_AUDIO_PLAYBACK_ENABLE not set in ${ENV_FILE}}"
if [[ "${ROVERD_AUDIO_PLAYBACK_ENABLE}" -ne 1 ]]; then
echo "Audio playback disabled by roverd media config; skipping audio forward listener" >&2
exit 0
fi
: "${ROVERD_AUDIO_PLAYBACK_FORWARD_URL:?ROVERD_AUDIO_PLAYBACK_FORWARD_URL not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_PLAYBACK_DEVICE:?ROVERD_AUDIO_PLAYBACK_DEVICE not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_PLAYBACK_NORMALIZE:?ROVERD_AUDIO_PLAYBACK_NORMALIZE not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER:?ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER not set in ${ENV_FILE}}"
PLAYBACK_DEVICE="${ROVERD_AUDIO_PLAYBACK_DEVICE}"
if [[ -n "${FFMPEG_BIN:-}" ]]; then
FFMPEG_BIN_PATH="$FFMPEG_BIN"
elif command -v ffmpeg >/dev/null 2>&1; then
FFMPEG_BIN_PATH="$(command -v ffmpeg)"
else
echo "ffmpeg not found; install it via apt install ffmpeg." >&2
exit 1
fi
if command -v aplay >/dev/null 2>&1; then
APLAY_BIN_PATH="$(command -v aplay)"
else
echo "aplay not found; install it via apt install alsa-utils." >&2
exit 1
fi
LAST_FFMPEG_STATUS="unknown"
LAST_APLAY_STATUS="unknown"
run_pipeline() {
set +e
local -a ffmpeg_args=(
-hide_banner
-loglevel warning
-fflags nobuffer
-flags low_delay
-analyzeduration 200k
-probesize 32k
# The forwarded-audio URL is RTSP. Pinning TCP avoids ffmpeg negotiating the
# separate unreliable RTP/UDP transport that the server intentionally disables.
-rtsp_transport tcp
-i "${ROVERD_AUDIO_PLAYBACK_FORWARD_URL}"
-vn
)
if [[ "${ROVERD_AUDIO_PLAYBACK_NORMALIZE}" -ne 0 ]]; then
ffmpeg_args+=(-af "${ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER}")
fi
ffmpeg_args+=(
-ac 1
-ar 16000
-f s16le
pipe:1
)
"${FFMPEG_BIN_PATH}" "${ffmpeg_args[@]}" \
| "${APLAY_BIN_PATH}" \
-q \
-D "${PLAYBACK_DEVICE}" \
-t raw \
-f S16_LE \
-r 16000 \
-c 1
local rc=$?
local -a statuses=("${PIPESTATUS[@]}")
LAST_FFMPEG_STATUS="${statuses[0]:-unknown}"
LAST_APLAY_STATUS="${statuses[1]:-unknown}"
set -e
return "${rc}"
}
trap 'kill 0 2>/dev/null' EXIT INT TERM
while true; do
if run_pipeline; then
exit 0
fi
echo "Audio forward listener exited ffmpeg=${LAST_FFMPEG_STATUS:-unknown} aplay=${LAST_APLAY_STATUS:-unknown}, restarting in 2s..." >&2
sleep 2
done
-171
View File
@@ -1,171 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
set +H
ENV_FILE="${ROVERD_MEDIA_ENV_FILE:-/var/lib/roverd/media.env}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Environment file ${ENV_FILE} missing; cannot publish audio" >&2
exit 1
fi
# Load KEY=VALUE pairs from media.env without evaluating shell syntax. URLs are data;
# sourcing this file would unnecessarily treat server-provided values as shell code.
load_env_file() {
local content=""
if [[ -r "$ENV_FILE" ]]; then
content="$(cat "$ENV_FILE")"
elif command -v sudo >/dev/null 2>&1; then
content="$(sudo -n cat "$ENV_FILE" 2>/dev/null || true)"
fi
if [[ -z "$content" ]]; then
echo "Cannot read ${ENV_FILE} (permission denied). Run as a user that can read it, or allow sudo -n for cat." >&2
exit 1
fi
local line key val
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
if [[ "$line" =~ ^[[:space:]]*export[[:space:]]+([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
elif [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
else
continue
fi
val="${val#${val%%[![:space:]]*}}"
val="${val%${val##*[![:space:]]}}"
if [[ "$val" =~ ^\".*\"$ ]]; then
val="${val:1:${#val}-2}"
elif [[ "$val" =~ ^\'.*\'$ ]]; then
val="${val:1:${#val}-2}"
fi
printf -v "$key" '%s' "$val"
export "$key"
done <<< "$content"
}
load_env_file
: "${ROVERD_AUDIO_CAPTURE_ENABLE:?ROVERD_AUDIO_CAPTURE_ENABLE not set in ${ENV_FILE}}"
if [[ "${ROVERD_AUDIO_CAPTURE_ENABLE}" -ne 1 ]]; then
echo "Audio capture disabled; skipping audio-only publisher" >&2
exit 0
fi
: "${ROVERD_AUDIO_CAPTURE_PUBLISH_URL:?ROVERD_AUDIO_CAPTURE_PUBLISH_URL not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_CAPTURE_DEVICE:?ROVERD_AUDIO_CAPTURE_DEVICE not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_CAPTURE_SAMPLE_RATE:?ROVERD_AUDIO_CAPTURE_SAMPLE_RATE not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_CAPTURE_CHANNELS:?ROVERD_AUDIO_CAPTURE_CHANNELS not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_CAPTURE_BITRATE:?ROVERD_AUDIO_CAPTURE_BITRATE not set in ${ENV_FILE}}"
CAPTURE_DEVICE="${ROVERD_AUDIO_CAPTURE_DEVICE}"
# At the default 48 kHz stereo S32_LE capture format, the old 65,536-byte ALSA
# buffer represented about 171 ms before ffmpeg could publish microphone audio:
# 65,536 / (48,000 samples * 2 channels * 4 bytes) = 0.1707 seconds
# Keep the defaults much smaller because this publisher feeds an interactive
# rover stream, where late-but-smooth audio is less useful than fresher audio.
# These remain environment-overridable so a noisy Pi or sound card can be tuned
# in the field without changing the installed script.
AUDIO_ALSA_BUFFER_BYTES="${AUDIO_ALSA_BUFFER_BYTES:-16384}"
AUDIO_ALSA_PERIOD_BYTES="${AUDIO_ALSA_PERIOD_BYTES:-1024}"
if [[ -n "${FFMPEG_BIN:-}" ]]; then
FFMPEG_BIN_PATH="$FFMPEG_BIN"
elif command -v ffmpeg >/dev/null 2>&1; then
FFMPEG_BIN_PATH="$(command -v ffmpeg)"
else
echo "ffmpeg not found; install it via apt install ffmpeg." >&2
exit 1
fi
run_pipeline() {
local -a pipeline_statuses=()
local ffmpeg_args=(
-hide_banner
-loglevel warning
-fflags nobuffer
-rtbufsize 0
-thread_queue_size 4096
# Match the raw ALSA stream exactly so ffmpeg does not guess the pipe
# format and so the published audio stays full-band stereo before the
# Opus encoder sees it.
-f s32le
-ar "${ROVERD_AUDIO_CAPTURE_SAMPLE_RATE}"
-ac "${ROVERD_AUDIO_CAPTURE_CHANNELS}"
-i pipe:0
# Keep the known-required microphone boost, but remove the old
# resample/downmix filter. That old filter threw away stereo and
# limited the stream to narrow 16 kHz mono before encoding.
-af "volume=20dB"
# Opus supports up to 510 kbps. Using that ceiling keeps the stream at
# the highest practical quality browsers and MediaMTX can carry without
# trying to push raw PCM through the live path.
-c:a libopus
-b:a "${ROVERD_AUDIO_CAPTURE_BITRATE}"
-ar:a "${ROVERD_AUDIO_CAPTURE_SAMPLE_RATE}"
-ac:a "${ROVERD_AUDIO_CAPTURE_CHANNELS}"
# Use the audio profile for quality. Latency is still controlled by the
# 20 ms Opus frame size and the low-buffering capture/publish options
# around the encoder.
-application audio
-frame_duration 20
-compression_level 0
# RTSP carries the existing Opus stream directly, avoiding MediaMTX's costly
# MPEG-TS demux without changing microphone capture or encoding quality. TCP is
# required for the same reliable local-network behavior as the video publisher.
-flush_packets 1
-muxdelay 0
-muxpreload 0
-f rtsp
-rtsp_transport tcp
"${ROVERD_AUDIO_CAPTURE_PUBLISH_URL}"
)
# 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
# channel count.
#
# The buffer and period are byte counts because arecord interprets -B/-F in
# microseconds only when the value has an explicit time suffix. Keeping them
# as byte-sized chunks gives direct control over the capture queue. The new
# defaults are roughly 43 ms total buffer and 2.7 ms wakeup periods at
# 48 kHz stereo S32_LE, which removes about 128 ms of avoidable capture
# latency compared with the old 65,536-byte buffer.
arecord -D "${CAPTURE_DEVICE}" -f S32_LE -c "${ROVERD_AUDIO_CAPTURE_CHANNELS}" -r "${ROVERD_AUDIO_CAPTURE_SAMPLE_RATE}" -B "${AUDIO_ALSA_BUFFER_BYTES}" -F "${AUDIO_ALSA_PERIOD_BYTES}" -q -t raw \
| "${FFMPEG_BIN_PATH}" "${ffmpeg_args[@]}"
pipeline_statuses=("${PIPESTATUS[@]}")
# PIPESTATUS belongs to the pipeline that just finished and is replaced by the next shell
# command. Capture it immediately, then return the publisher failure first because that is
# normally the reason arecord receives a secondary broken pipe.
LAST_ARECORD_STATUS="${pipeline_statuses[0]:-unknown}"
LAST_FFMPEG_STATUS="${pipeline_statuses[1]:-unknown}"
if [[ "${LAST_FFMPEG_STATUS}" != "0" ]]; then
return "${LAST_FFMPEG_STATUS}"
fi
return "${LAST_ARECORD_STATUS}"
}
trap 'kill 0 2>/dev/null' EXIT INT TERM
while true; do
if run_pipeline; then
exit 0
fi
echo "Audio-only publisher exited arecord=${LAST_ARECORD_STATUS:-unknown} ffmpeg=${LAST_FFMPEG_STATUS:-unknown}, restarting in 2s..." >&2
sleep 2
done
-202
View File
@@ -1,202 +0,0 @@
#!/usr/bin/env python3
import ctypes
import ctypes.util
import json
import os
import struct
import subprocess
import sys
ASSET_ROOT = "/opt/roverd/googletts"
LIB_PATH = os.path.join(ASSET_ROOT, "libchrometts.so")
VOICE_DIR = os.path.join(ASSET_ROOT, "en-us-x-multi-r30")
PIPELINE = "pipeline.pb"
PLAYBACK_DEVICE = "tts"
SAMPLE_RATE = "24000"
MAX_TEXT_CHARS = 512
VOICES = {
"sfg": "female",
"iob": "female",
"iog": "female",
"iol": "male",
"iom": "male",
"tpc": "female",
"tpd": "male",
"tpf": "female",
}
DEFAULT_VOICE = "tpf"
DEFAULT_PITCH = 1.0
DEFAULT_SPEED = 1.0
MIN_PITCH = 0.5
MAX_PITCH = 2.0
MIN_SPEED = 0.5
MAX_SPEED = 2.0
_runtime_handles = []
def load_shared_library(path):
mode = ctypes.RTLD_GLOBAL | getattr(os, "RTLD_NOW", 0)
return ctypes.CDLL(path, mode=mode)
def preload_runtime_libraries():
# Laptop-only workaround: some ChromeOS libchrometts builds reference
# compiler helper symbols such as __udivmodti4 without declaring the runtime
# library as an ELF dependency. Loading common compiler runtimes globally
# first makes those symbols visible before ctypes loads libchrometts.so.
for name in ("gcc_s", "atomic", "stdc++", "c++", "c++abi"):
lib = ctypes.util.find_library(name)
if not lib:
continue
try:
_runtime_handles.append(load_shared_library(lib))
except OSError:
pass
preload_runtime_libraries()
def varint(value):
out = bytearray()
while value >= 0x80:
out.append((value & 0x7F) | 0x80)
value >>= 7
out.append(value)
return bytes(out)
def field_bytes(number, payload):
return varint((number << 3) | 2) + varint(len(payload)) + payload
def field_float(number, value):
return varint((number << 3) | 5) + struct.pack("<f", float(value))
def build_utterance(text, pitch=1.0, speed=1.0):
params = field_float(2, pitch) + field_float(3, speed)
msg_b = field_bytes(1, text.encode("utf-8")) + field_bytes(20, params)
msg_a = field_bytes(1, msg_b)
return field_bytes(1, msg_a)
def build_speaker(name, gender):
return field_bytes(1, name.encode("utf-8")) + field_bytes(2, gender.encode("utf-8"))
class ChromeTTS:
def __init__(self):
self.lib = load_shared_library(LIB_PATH)
self.lib.GoogleTtsInit.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
self.lib.GoogleTtsInit.restype = ctypes.c_bool
self.lib.GoogleTtsInitBuffered.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int]
self.lib.GoogleTtsInitBuffered.restype = ctypes.c_bool
self.lib.GoogleTtsGetFramesInAudioBuffer.argtypes = []
self.lib.GoogleTtsGetFramesInAudioBuffer.restype = ctypes.c_size_t
self.lib.GoogleTtsReadBuffered.argtypes = [
ctypes.POINTER(ctypes.c_float),
ctypes.POINTER(ctypes.c_size_t),
]
self.lib.GoogleTtsReadBuffered.restype = ctypes.c_int
self.lib.GoogleTtsShutdown.argtypes = []
self.lib.GoogleTtsShutdown.restype = None
voice_dir = os.path.abspath(VOICE_DIR) + os.sep
pipeline = os.path.join(voice_dir, PIPELINE)
if not self.lib.GoogleTtsInit(pipeline.encode("utf-8"), voice_dir.encode("utf-8")):
raise RuntimeError("GoogleTtsInit failed")
self.frames = int(self.lib.GoogleTtsGetFramesInAudioBuffer())
if self.frames <= 0:
raise RuntimeError("invalid Google TTS audio buffer size")
self.buffer = (ctypes.c_float * self.frames)()
def speak_to_aplay(self, text, voice, pitch=DEFAULT_PITCH, speed=DEFAULT_SPEED):
voice = voice if voice in VOICES else DEFAULT_VOICE
pitch = clamp_float(pitch, MIN_PITCH, MAX_PITCH, DEFAULT_PITCH)
speed = clamp_float(speed, MIN_SPEED, MAX_SPEED, DEFAULT_SPEED)
text = text.strip()
if not text:
raise ValueError("text required")
text = text[:MAX_TEXT_CHARS]
utterance = build_utterance(text, pitch=pitch, speed=speed)
speaker = build_speaker(voice, VOICES[voice])
if not self.lib.GoogleTtsInitBuffered(utterance, speaker, len(utterance), len(speaker)):
raise RuntimeError("GoogleTtsInitBuffered failed")
player = subprocess.Popen(
["aplay", "-q", "-D", PLAYBACK_DEVICE, "-r", SAMPLE_RATE, "-f", "FLOAT_LE", "-c", "1"],
stdin=subprocess.PIPE,
)
try:
frames_written = ctypes.c_size_t(0)
while self.lib.GoogleTtsReadBuffered(self.buffer, ctypes.byref(frames_written)) > 0:
frames = int(frames_written.value)
if frames > 0:
player.stdin.write(ctypes.string_at(self.buffer, frames * ctypes.sizeof(ctypes.c_float)))
player.stdin.close()
rc = player.wait()
if rc != 0:
raise RuntimeError(f"aplay exited with {rc}")
finally:
if player.poll() is None:
player.kill()
player.wait()
def shutdown(self):
self.lib.GoogleTtsShutdown()
def respond(payload):
sys.stdout.write(json.dumps(payload, separators=(",", ":")) + "\n")
sys.stdout.flush()
def clamp_float(value, minimum, maximum, fallback):
try:
value = float(value)
except (TypeError, ValueError):
return fallback
if value <= 0:
return fallback
if value < minimum:
return minimum
if value > maximum:
return maximum
return value
def main():
try:
tts = ChromeTTS()
except Exception as exc:
respond({"ok": False, "error": str(exc)})
return 1
respond({"ok": True, "ready": True})
try:
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
request = json.loads(line)
tts.speak_to_aplay(
str(request.get("text") or ""),
str(request.get("voice") or DEFAULT_VOICE),
request.get("pitch", DEFAULT_PITCH),
request.get("speed", DEFAULT_SPEED),
)
respond({"ok": True})
except Exception as exc:
respond({"ok": False, "error": str(exc)})
finally:
tts.shutdown()
return 0
if __name__ == "__main__":
raise SystemExit(main())
-145
View File
@@ -1,145 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
set +H
ENV_FILE="${ROVERD_MEDIA_ENV_FILE:-/var/lib/roverd/media.env}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Environment file ${ENV_FILE} missing; cannot publish laptop video" >&2
exit 1
fi
# Load roverd's generated media.env as data instead of sourcing it as shell. URLs are
# configuration data, so evaluating the file would be both fragile and unnecessary.
load_env_file() {
local content=""
if [[ -r "$ENV_FILE" ]]; then
content="$(cat "$ENV_FILE")"
elif command -v sudo >/dev/null 2>&1; then
content="$(sudo -n cat "$ENV_FILE" 2>/dev/null || true)"
fi
if [[ -z "$content" ]]; then
echo "Cannot read ${ENV_FILE} (permission denied). Run as a user that can read it, or allow sudo -n for cat." >&2
exit 1
fi
local line key val
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
if [[ "$line" =~ ^[[:space:]]*export[[:space:]]+([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
elif [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
else
continue
fi
val="${val#${val%%[![:space:]]*}}"
val="${val%${val##*[![:space:]]}}"
if [[ "$val" =~ ^\".*\"$ ]]; then
val="${val:1:${#val}-2}"
elif [[ "$val" =~ ^\'.*\'$ ]]; then
val="${val:1:${#val}-2}"
fi
printf -v "$key" '%s' "$val"
export "$key"
done <<< "$content"
}
load_env_file
: "${ROVERD_VIDEO_ENABLE:?ROVERD_VIDEO_ENABLE not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_PUBLISH_URL:?ROVERD_VIDEO_PUBLISH_URL not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_DEVICE:?ROVERD_VIDEO_DEVICE not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_INPUT_FORMAT:?ROVERD_VIDEO_INPUT_FORMAT not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_WIDTH:?ROVERD_VIDEO_WIDTH not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_HEIGHT:?ROVERD_VIDEO_HEIGHT not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_FPS:?ROVERD_VIDEO_FPS not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_BITRATE:?ROVERD_VIDEO_BITRATE not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_INVERT:?ROVERD_VIDEO_INVERT not set in ${ENV_FILE}}"
if [[ "${ROVERD_VIDEO_ENABLE}" -ne 1 ]]; then
echo "Laptop video publisher disabled by roverd media config; skipping" >&2
exit 0
fi
if [[ -z "${ROVERD_VIDEO_DEVICE}" ]]; then
echo "ROVERD_VIDEO_DEVICE is required for the debian-laptop V4L2 publisher" >&2
exit 1
fi
INPUT_FORMAT_ARGS=()
if [[ -n "${ROVERD_VIDEO_INPUT_FORMAT}" ]]; then
# Many laptop webcams expose both compressed MJPEG and raw YUYV modes. The
# 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.
INPUT_FORMAT_ARGS=(-input_format "${ROVERD_VIDEO_INPUT_FORMAT}")
fi
if [[ -n "${FFMPEG_BIN:-}" ]]; then
FFMPEG_BIN_PATH="$FFMPEG_BIN"
elif command -v ffmpeg >/dev/null 2>&1; then
FFMPEG_BIN_PATH="$(command -v ffmpeg)"
else
echo "ffmpeg not found; install it via apt install ffmpeg." >&2
exit 1
fi
VIDEO_FILTER_ARGS=()
if [[ "${ROVERD_VIDEO_INVERT}" -ne 0 ]]; then
# The Pi publisher uses libcamera rotation. With a generic webcam, ffmpeg's
# transpose pair gives the same 180-degree correction without assuming a
# camera-specific driver feature.
VIDEO_FILTER_ARGS=(-vf "transpose=2,transpose=2")
fi
run_pipeline() {
# Keep laptop rovers on the same transport contract as Pi camera rovers. This changes
# only the encoded stream's carrier; V4L2 capture and H264 encoding remain untouched.
"${FFMPEG_BIN_PATH}" \
-hide_banner \
-loglevel warning \
-fflags nobuffer \
-flags low_delay \
-thread_queue_size 4096 \
-f v4l2 \
"${INPUT_FORMAT_ARGS[@]}" \
-framerate "${ROVERD_VIDEO_FPS}" \
-video_size "${ROVERD_VIDEO_WIDTH}x${ROVERD_VIDEO_HEIGHT}" \
-i "${ROVERD_VIDEO_DEVICE}" \
"${VIDEO_FILTER_ARGS[@]}" \
-an \
-c:v libx264 \
-preset veryfast \
-tune zerolatency \
-profile:v baseline \
-pix_fmt yuv420p \
-b:v "${ROVERD_VIDEO_BITRATE}" \
-maxrate "${ROVERD_VIDEO_BITRATE}" \
-bufsize "$((ROVERD_VIDEO_BITRATE / 2))" \
-g "${ROVERD_VIDEO_FPS}" \
-keyint_min "${ROVERD_VIDEO_FPS}" \
-sc_threshold 0 \
-flush_packets 1 \
-muxdelay 0 \
-muxpreload 0 \
-f rtsp \
-rtsp_transport tcp \
"${ROVERD_VIDEO_PUBLISH_URL}"
}
while true; do
if run_pipeline; then
exit 0
fi
echo "Debian laptop video publisher exited, restarting in 2s..." >&2
sleep 2
done
-37
View File
@@ -1,37 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# These publishers contain hardware-facing infinite retry loops, so executing them in a unit
# test would require unsafe process-group traps and fake camera/ALSA devices. Pin the small
# transport boundary directly instead: every publisher must request RTSP/TCP and none may
# reintroduce the high-latency MPEG-TS muxer.
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
assert_rtsp_tcp() {
local file="$1"
if ! grep -q -- '-f rtsp' "$file"; then
echo "Missing RTSP muxer in $file" >&2
exit 1
fi
if ! grep -q -- '-rtsp_transport tcp' "$file"; then
echo "Missing RTSP/TCP pin in $file" >&2
exit 1
fi
if grep -q -- '-f mpegts' "$file"; then
echo "Unexpected MPEG-TS muxer in $file" >&2
exit 1
fi
}
assert_rtsp_tcp "$SCRIPT_DIR/video-publisher.sh"
assert_rtsp_tcp "$SCRIPT_DIR/debian-laptop-video-publisher.sh"
assert_rtsp_tcp "$SCRIPT_DIR/audio-only-publisher.sh"
# The speaker path reads rather than publishes, so it has no output muxer. It must still pin
# RTSP/TCP before its input URL to match the server's TCP-only listener.
if ! grep -q -- '-rtsp_transport tcp' "$SCRIPT_DIR/audio-forward-listener.sh"; then
echo "Missing RTSP/TCP input pin in audio-forward-listener.sh" >&2
exit 1
fi
echo "Media publisher transport checks passed"
-98
View File
@@ -1,98 +0,0 @@
#!/usr/bin/env bash
#
# Fixed-purpose self-update helper for Raspberry Pi rover hosts.
#
# roverd itself runs as the unprivileged "roverd" service user, but updating the
# installed agent requires root because the installer writes to /usr/local/bin,
# /etc, /opt, /var/lib/roverd, and systemd unit locations. This helper is the
# narrow privilege boundary: sudoers allows roverd to run this exact file with no
# arguments, and this file decides the complete update sequence internally.
set -euo pipefail
ENV_FILE="/etc/roverd-update.env"
LOCK_FILE="/var/lock/roverd-self-update.lock"
LOG_FILE="/var/log/roverd-self-update.log"
log() {
# Log to stdout so systemd/journal captures the message when launched by
# roverd, and also append to a stable file so an admin can inspect the last
# update attempt after the roverd service restarts.
local message
message="[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*"
echo "$message"
echo "$message" >> "$LOG_FILE"
}
if [[ "${EUID}" -ne 0 ]]; then
echo "roverd-self-update must run as root" >&2
exit 1
fi
if [[ "${ROVERD_SELF_UPDATE_SYSTEMD:-}" != "1" ]] && command -v systemd-run >/dev/null 2>&1; then
exec systemd-run \
--unit=roverd-self-update \
--collect \
--property=Type=exec \
--setenv=ROVERD_SELF_UPDATE_SYSTEMD=1 \
"$0"
fi
if [[ ! -f "$ENV_FILE" ]]; then
echo "Missing $ENV_FILE; run pi/install_roverd.sh once to register the repository path" >&2
exit 1
fi
# shellcheck disable=SC1090
source "$ENV_FILE"
if [[ -z "${ROVERD_REPO_DIR:-}" ]]; then
echo "ROVERD_REPO_DIR is not set in $ENV_FILE" >&2
exit 1
fi
if [[ ! -d "$ROVERD_REPO_DIR/.git" ]]; then
echo "ROVERD_REPO_DIR does not point at a git checkout: $ROVERD_REPO_DIR" >&2
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
exit 1
fi
mkdir -p "$(dirname "$LOCK_FILE")" "$(dirname "$LOG_FILE")"
touch "$LOG_FILE"
chmod 0644 "$LOG_FILE"
exec 9>"$LOCK_FILE"
if ! flock -n 9; then
log "Another roverd self-update is already running; refusing to start a second one"
exit 1
fi
cd "$ROVERD_REPO_DIR"
log "Starting roverd self-update in $ROVERD_REPO_DIR"
repo_uid="$(stat -c '%u' "$ROVERD_REPO_DIR")"
# Fetch through the normal git remote instead of downloading just one artifact.
# That keeps the binary, installer, scripts, systemd units, and any other rover
# files from this repository on the same commit.
if [[ "$repo_uid" -eq 0 ]]; then
git pull --ff-only
else
# The helper runs as root only for installation privileges. The git checkout
# usually belongs to the human deploy user, so running the pull as that owner
# avoids Git's dubious-ownership protection and preserves whatever SSH/HTTPS
# credentials that user normally uses for this repository.
sudo -H -u "#${repo_uid}" git -C "$ROVERD_REPO_DIR" pull --ff-only
fi
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"
log "Installer completed successfully"
systemctl reboot
-160
View File
@@ -1,160 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# Keep history expansion off so values containing "!" are safe.
set +H
ENV_FILE="${ROVERD_MEDIA_ENV_FILE:-/var/lib/roverd/media.env}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Environment file ${ENV_FILE} missing; cannot publish" >&2
exit 1
fi
# Load KEY=VALUE pairs from ENV_FILE WITHOUT evaluating shell metacharacters.
# This makes URLs containing characters like '&' and '#!' safe without requiring quoting.
load_env_file() {
local content=""
if [[ -r "$ENV_FILE" ]]; then
content="$(cat "$ENV_FILE")"
elif command -v sudo >/dev/null 2>&1; then
# Try to read via sudo without prompting (useful when the service runs as an unprivileged user)
content="$(sudo -n cat "$ENV_FILE" 2>/dev/null || true)"
fi
if [[ -z "$content" ]]; then
echo "Cannot read ${ENV_FILE} (permission denied). Run as a user that can read it, or allow sudo -n for cat." >&2
exit 1
fi
local line key val
while IFS= read -r line || [[ -n "$line" ]]; do
# Skip blank lines and full-line comments.
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
# Support optional leading 'export '
if [[ "$line" =~ ^[[:space:]]*export[[:space:]]+([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
elif [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
else
# Ignore anything that isn't a simple assignment.
continue
fi
# Trim leading/trailing whitespace in value.
val="${val#${val%%[![:space:]]*}}"
val="${val%${val##*[![:space:]]}}"
# If value is wrapped in matching single or double quotes, unwrap.
if [[ "$val" =~ ^\".*\"$ ]]; then
val="${val:1:${#val}-2}"
elif [[ "$val" =~ ^\'.*\'$ ]]; then
val="${val:1:${#val}-2}"
fi
# Assign without evaluation.
printf -v "$key" '%s' "$val"
export "$key"
done <<< "$content"
}
load_env_file
: "${ROVERD_VIDEO_ENABLE:?ROVERD_VIDEO_ENABLE not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_PUBLISH_URL:?ROVERD_VIDEO_PUBLISH_URL not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_WIDTH:?ROVERD_VIDEO_WIDTH not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_HEIGHT:?ROVERD_VIDEO_HEIGHT not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_FPS:?ROVERD_VIDEO_FPS not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_BITRATE:?ROVERD_VIDEO_BITRATE not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_INVERT:?ROVERD_VIDEO_INVERT not set in ${ENV_FILE}}"
if [[ "${ROVERD_VIDEO_ENABLE}" -ne 1 ]]; then
echo "Video publisher disabled by roverd media config; skipping" >&2
exit 0
fi
# The inversion decision is made in roverd.yaml 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
FLIP_ARGS=(--rotation 180)
fi
MODE_ARGS=()
if [[ -n "${ROVERD_VIDEO_SENSOR_MODE:-}" ]]; then
MODE_ARGS=(--mode "${ROVERD_VIDEO_SENSOR_MODE}")
fi
if [[ -n "${LIBCAMERA_BIN:-}" ]]; then
LIBCAMERA_BIN_PATH="$LIBCAMERA_BIN"
elif command -v rpicam-vid >/dev/null 2>&1; then
LIBCAMERA_BIN_PATH="$(command -v rpicam-vid)"
elif command -v libcamera-vid >/dev/null 2>&1; then
LIBCAMERA_BIN_PATH="$(command -v libcamera-vid)"
else
echo "Neither rpicam-vid nor libcamera-vid found; install libcamera-apps." >&2
exit 1
fi
if [[ -n "${FFMPEG_BIN:-}" ]]; then
FFMPEG_BIN_PATH="$FFMPEG_BIN"
elif command -v ffmpeg >/dev/null 2>&1; then
FFMPEG_BIN_PATH="$(command -v ffmpeg)"
else
echo "ffmpeg not found; install it via apt install ffmpeg." >&2
exit 1
fi
run_pipeline() {
# MPEG-TS added most of the former rover-to-browser latency inside MediaMTX's
# demuxer. RTSP carries the same encoded H264 without changing the camera or codec.
# TCP is explicit because plain RTSP/RTP over UDP has no retransmission and proved
# unreliable even though MediaMTX still reported the incomplete stream as ready.
"${LIBCAMERA_BIN_PATH}" \
--inline \
--timeout 0 \
"${MODE_ARGS[@]}" \
--width "${ROVERD_VIDEO_WIDTH}" \
--height "${ROVERD_VIDEO_HEIGHT}" \
"${FLIP_ARGS[@]}" \
--framerate "${ROVERD_VIDEO_FPS}" \
--bitrate "${ROVERD_VIDEO_BITRATE}" \
--codec h264 \
--intra 120 \
--profile baseline \
--denoise auto \
--nopreview \
--metering centre \
--ev 0.1 \
--awb auto \
--saturation 0.6 \
--brightness 0 \
--output - \
| "${FFMPEG_BIN_PATH}" \
-hide_banner \
-loglevel warning \
-fflags nobuffer \
-use_wallclock_as_timestamps 1 \
-f h264 \
-i pipe:0 \
-c:v copy \
-an \
-flush_packets 1 \
-muxdelay 0 \
-muxpreload 0 \
-f rtsp \
-rtsp_transport tcp \
"${ROVERD_VIDEO_PUBLISH_URL}"
}
while true; do
if run_pipeline; then
exit 0
fi
echo "Video publisher exited, restarting in 2s..." >&2
sleep 2
done
-79
View File
@@ -1,79 +0,0 @@
#!/usr/bin/env bash
CONFIG_DEST="/etc/roverd.yaml"
log() {
echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*"
}
ensure_user() {
local user="$1"
local groups="${2:-}"
local existing_groups=""
local group
if [[ -n "$groups" ]]; then
IFS=',' read -ra group_list <<< "$groups"
for group in "${group_list[@]}"; do
if getent group "$group" >/dev/null 2>&1; then
existing_groups="${existing_groups:+$existing_groups,}$group"
else
# Different Debian-family installs expose slightly different
# hardware groups. Skipping missing optional groups lets one
# profile script cover ordinary laptops and Raspberry Pi OS.
log "Skipping missing system group '$group' for $user"
fi
done
fi
if ! id -u "$user" >/dev/null 2>&1; then
if [[ -n "$existing_groups" ]]; then
useradd -r -s /usr/sbin/nologin -G "$existing_groups" "$user"
else
useradd -r -s /usr/sbin/nologin "$user"
fi
elif [[ -n "$existing_groups" ]]; then
usermod -a -G "$existing_groups" "$user"
fi
}
require_root() {
if [[ "${EUID}" -ne 0 ]]; then
echo "Please run as root (sudo)" >&2
exit 1
fi
}
validate_install_inputs() {
if [[ ! -f "$BINARY_SRC" ]]; then
echo "Binary not found at $BINARY_SRC" >&2
exit 1
fi
if [[ ! -f "$CONFIG_SRC" ]]; then
echo "Config source not found at $CONFIG_SRC" >&2
exit 1
fi
}
install_roverd_binary() {
ensure_user roverd "$ROVERD_GROUPS"
install -o roverd -g roverd -m 0755 "$BINARY_SRC" /usr/local/bin/roverd
log "Installed roverd binary for profile $PROFILE"
}
install_roverd_config() {
CONFIG_EXISTS=0
if [[ -f "$CONFIG_DEST" ]]; then
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"
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
log "Installed roverd systemd unit"
}
-425
View File
@@ -1,425 +0,0 @@
#!/usr/bin/env bash
install_debian_laptop_deps() {
# The laptop rover is a dedicated appliance, not a normal desktop/laptop audio
# install. Keep this package set intentionally close to the Pi profile so the
# same roverd TTS/playback/capture code paths are available on both targets.
if command -v ffmpeg >/dev/null 2>&1 \
&& command -v arecord >/dev/null 2>&1 \
&& command -v aplay >/dev/null 2>&1 \
&& command -v amixer >/dev/null 2>&1 \
&& command -v v4l2-ctl >/dev/null 2>&1 \
&& command -v flite >/dev/null 2>&1 \
&& command -v espeak >/dev/null 2>&1 \
&& command -v python3 >/dev/null 2>&1 \
&& command -v curl >/dev/null 2>&1 \
&& command -v xz >/dev/null 2>&1 \
&& command -v unzip >/dev/null 2>&1 \
&& ldconfig -p 2>/dev/null | grep -q 'libgcc_s\.so\.1' \
&& ldconfig -p 2>/dev/null | grep -q 'libstdc\+\+\.so\.6' \
&& ldconfig -p 2>/dev/null | grep -q 'libc++\.so\.1' \
&& ldconfig -p 2>/dev/null | grep -q 'libc++abi\.so\.1'; then
log "Debian laptop media/audio/TTS dependencies already installed; skipping apt install"
return
fi
log "Installing Debian laptop rover dependencies (ffmpeg, ALSA tools, V4L2 tools, flite/espeak, Chrome TTS runtime deps)..."
apt-get update
apt-get install -y --no-install-recommends \
ffmpeg alsa-utils v4l-utils ca-certificates flite espeak python3 curl xz-utils unzip libasound2-plugins libgcc-s1 libstdc++6 libc++1 libc++abi1 \
|| apt-get install -y --no-install-recommends \
ffmpeg alsa-utils v4l-utils ca-certificates flite espeak python3 curl xz-utils unzip libasound2-plugins libgcc-s1 libstdc++6 libc++1-14 libc++abi1-14
}
DEBIAN_LAPTOP_INSTALLER_CONFIG="/etc/roverd-installer.env"
disable_debian_laptop_desktop_audio_stack() {
# This profile is for a dedicated rover laptop. PipeWire/PulseAudio are good
# desktop defaults, but they can grab the hardware device and make the rover's
# root/systemd ALSA services fail or route through a moving per-user graph.
# Mask them globally and kill already-running instances so ALSA owns the box,
# which is the closest behavior to the Pi rover appliance setup.
log "Disabling desktop audio daemons for dedicated laptop rover audio"
local -a user_units=(
pipewire.service
pipewire.socket
pipewire-pulse.service
pipewire-pulse.socket
wireplumber.service
pulseaudio.service
pulseaudio.socket
)
if command -v systemctl >/dev/null 2>&1; then
systemctl --global disable "${user_units[@]}" >/dev/null 2>&1 || true
systemctl --global mask "${user_units[@]}" >/dev/null 2>&1 || true
fi
pkill -x pipewire >/dev/null 2>&1 || true
pkill -x pipewire-pulse >/dev/null 2>&1 || true
pkill -x wireplumber >/dev/null 2>&1 || true
pkill -x pulseaudio >/dev/null 2>&1 || true
}
derive_debian_laptop_alsa_card_from_device() {
local device="$1"
# The common ALSA hardware device shape is hw:CARD,DEVICE. Pulling the card
# number from that string gives the installer a useful default while still
# allowing the prompt to handle named cards or uncommon PCM strings.
if [[ "$device" =~ ^hw:([0-9]+),[0-9]+$ ]]; then
printf '%s\n' "${BASH_REMATCH[1]}"
return
fi
printf '0\n'
}
read_debian_laptop_installer_value() {
local prompt="$1"
local default_value="$2"
local value=""
# Prompting through /dev/tty keeps this usable even when the installer is
# launched through sudo with stdin redirected. The caller already checks for
# an interactive terminal before reaching this function, so failure here is
# genuinely unexpected and should stop the install instead of guessing.
read -r -p "${prompt} [${default_value}]: " value </dev/tty
if [[ -z "$value" ]]; then
value="$default_value"
fi
printf '%s\n' "$value"
}
validate_debian_laptop_alsa_config() {
# The PCM fields are written inside quoted ALSA strings, so keep them to the
# device spellings ALSA normally uses for hardware/plugin PCMs. Rejecting
# whitespace and shell/config punctuation prevents a bad installer config
# from generating an asound.conf that changes structure instead of values.
if [[ ! "$ROVERD_ALSA_PLAYBACK_DEVICE" =~ ^[A-Za-z0-9_.,:+/-]+$ ]]; then
echo "Invalid ROVERD_ALSA_PLAYBACK_DEVICE: $ROVERD_ALSA_PLAYBACK_DEVICE" >&2
exit 1
fi
if [[ ! "$ROVERD_ALSA_CAPTURE_DEVICE" =~ ^[A-Za-z0-9_.,:+/-]+$ ]]; then
echo "Invalid ROVERD_ALSA_CAPTURE_DEVICE: $ROVERD_ALSA_CAPTURE_DEVICE" >&2
exit 1
fi
# Softvol controls and ctl.!default need the playback card, because
# TTSMaster, HornMaster, and ForwardMaster are all playback mixer controls.
# Keep this numeric to match the prompt and avoid needing quoted ALSA card
# ids in the generated config.
if [[ ! "$ROVERD_ALSA_PLAYBACK_CARD" =~ ^[0-9]+$ ]]; then
echo "Invalid ROVERD_ALSA_PLAYBACK_CARD: $ROVERD_ALSA_PLAYBACK_CARD" >&2
exit 1
fi
}
load_debian_laptop_installer_config_file() {
local config_path="$1"
local line key val
# Read only the small allowlist this installer owns. Avoid sourcing the file
# because it lives in /etc and is meant to be installer data, not shell code.
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
if [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
else
continue
fi
val="${val#${val%%[![:space:]]*}}"
val="${val%${val##*[![:space:]]}}"
if [[ "$val" =~ ^\".*\"$ ]]; then
val="${val:1:${#val}-2}"
elif [[ "$val" =~ ^\'.*\'$ ]]; then
val="${val:1:${#val}-2}"
fi
case "$key" in
ROVERD_ALSA_PLAYBACK_DEVICE|ROVERD_ALSA_PLAYBACK_CARD|ROVERD_ALSA_CAPTURE_DEVICE)
printf -v "$key" '%s' "$val"
export "$key"
;;
esac
done < "$config_path"
}
write_debian_laptop_installer_config_file() {
local config_path="$1"
local tmp_path
tmp_path="$(mktemp)"
# This file is intentionally plain KEY=VALUE shell-style data so future
# installs can reuse the same laptop-specific card choices without asking
# again. It is still parsed by an allowlist reader instead of sourced.
cat > "$tmp_path" <<EOF
# Created by install_roverd.sh for the Debian laptop rover profile.
# These values choose the physical ALSA hardware behind the rover's logical
# mixer devices: tts, horn, forward, default playback, and rovermic capture.
ROVERD_ALSA_PLAYBACK_DEVICE="${ROVERD_ALSA_PLAYBACK_DEVICE}"
ROVERD_ALSA_PLAYBACK_CARD="${ROVERD_ALSA_PLAYBACK_CARD}"
ROVERD_ALSA_CAPTURE_DEVICE="${ROVERD_ALSA_CAPTURE_DEVICE}"
EOF
install -o root -g root -m 0644 "$tmp_path" "$config_path"
rm -f "$tmp_path"
}
load_or_create_debian_laptop_alsa_config() {
if [[ -f "$DEBIAN_LAPTOP_INSTALLER_CONFIG" ]]; then
load_debian_laptop_installer_config_file "$DEBIAN_LAPTOP_INSTALLER_CONFIG"
log "Using Debian laptop ALSA installer config from $DEBIAN_LAPTOP_INSTALLER_CONFIG"
elif [[ -n "${ROVERD_ALSA_PLAYBACK_DEVICE:-}" && -n "${ROVERD_ALSA_PLAYBACK_CARD:-}" && -n "${ROVERD_ALSA_CAPTURE_DEVICE:-}" ]]; then
# This keeps unattended installs possible without adding a pile of CLI
# flags. The generated /etc file still becomes the durable source for
# future installs on the same laptop.
validate_debian_laptop_alsa_config
write_debian_laptop_installer_config_file "$DEBIAN_LAPTOP_INSTALLER_CONFIG"
log "Wrote Debian laptop ALSA installer config to $DEBIAN_LAPTOP_INSTALLER_CONFIG from environment"
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
exit 1
fi
log "No $DEBIAN_LAPTOP_INSTALLER_CONFIG found; creating Debian laptop ALSA installer config"
if command -v aplay >/dev/null 2>&1; then
echo "Playback devices from aplay -l:" >/dev/tty
aplay -l >/dev/tty 2>/dev/tty || true
fi
if command -v arecord >/dev/null 2>&1; then
echo "Capture devices from arecord -l:" >/dev/tty
arecord -l >/dev/tty 2>/dev/tty || true
fi
ROVERD_ALSA_PLAYBACK_DEVICE="$(read_debian_laptop_installer_value "ALSA playback device for rover speaker output" "${ROVERD_ALSA_PLAYBACK_DEVICE:-hw:0,0}")"
ROVERD_ALSA_PLAYBACK_CARD="$(read_debian_laptop_installer_value "ALSA playback card number for mixer controls" "${ROVERD_ALSA_PLAYBACK_CARD:-$(derive_debian_laptop_alsa_card_from_device "$ROVERD_ALSA_PLAYBACK_DEVICE")}")"
ROVERD_ALSA_CAPTURE_DEVICE="$(read_debian_laptop_installer_value "ALSA capture device for rover microphone input" "${ROVERD_ALSA_CAPTURE_DEVICE:-$ROVERD_ALSA_PLAYBACK_DEVICE}")"
validate_debian_laptop_alsa_config
write_debian_laptop_installer_config_file "$DEBIAN_LAPTOP_INSTALLER_CONFIG"
log "Wrote Debian laptop ALSA installer config to $DEBIAN_LAPTOP_INSTALLER_CONFIG"
fi
ROVERD_ALSA_PLAYBACK_DEVICE="${ROVERD_ALSA_PLAYBACK_DEVICE:-hw:0,0}"
ROVERD_ALSA_PLAYBACK_CARD="${ROVERD_ALSA_PLAYBACK_CARD:-$(derive_debian_laptop_alsa_card_from_device "$ROVERD_ALSA_PLAYBACK_DEVICE")}"
ROVERD_ALSA_CAPTURE_DEVICE="${ROVERD_ALSA_CAPTURE_DEVICE:-$ROVERD_ALSA_PLAYBACK_DEVICE}"
validate_debian_laptop_alsa_config
}
render_debian_laptop_asound_config() {
local tmp_path
tmp_path="$(mktemp)"
# The rover-facing ALSA names stay stable even when the laptop's physical
# sound card changes. dmixer owns the one real playback PCM, while tts,
# horn, and forward each wrap that mixer with a separate softvol control.
cat > "$tmp_path" <<EOF
# Dedicated ALSA routing for the Debian laptop rover profile.
#
# Generated by install_roverd.sh from $DEBIAN_LAPTOP_INSTALLER_CONFIG.
# Change the physical devices there, then rerun the Debian laptop installer.
#
# Logical playback devices:
# tts - default text-to-speech output with TTSMaster softvol
# horn - horn synth output with HornMaster softvol
# forward - browser-forwarded audio with ForwardMaster softvol
# default - TTS playback plus rovermic capture
#
# Physical routing selected for this laptop:
# playback PCM: ${ROVERD_ALSA_PLAYBACK_DEVICE}
# playback card: ${ROVERD_ALSA_PLAYBACK_CARD}
# capture PCM: ${ROVERD_ALSA_CAPTURE_DEVICE}
# Mix multiple playback clients in software with a fixed low-cost format.
pcm.dmixer {
type dmix
ipc_key 1024
ipc_perm 0666
slave {
pcm "${ROVERD_ALSA_PLAYBACK_DEVICE}"
format S16_LE
rate 16000
channels 1
period_time 0
period_size 1024
buffer_size 4096
}
}
# TTS volume control. TTS uses the default playback route, so this control lets
# generated speech move independently from horns and forwarded browser audio.
pcm.tts_softvol {
type softvol
slave.pcm "dmixer"
control {
name "TTSMaster"
card ${ROVERD_ALSA_PLAYBACK_CARD}
}
min_dB -60.0
max_dB 12.0
}
# Horn volume control. The horn synth opens the logical "horn" device, which
# keeps horn loudness adjustable without changing the shared hardware PCM.
pcm.horn_softvol {
type softvol
slave.pcm "dmixer"
control {
name "HornMaster"
card ${ROVERD_ALSA_PLAYBACK_CARD}
}
min_dB -60.0
max_dB 12.0
}
# Forwarded audio volume control. The browser-audio listener opens "forward",
# so remote audio can be mixed with local rover sounds without bypassing dmix.
pcm.forward_softvol {
type softvol
slave.pcm "dmixer"
control {
name "ForwardMaster"
card ${ROVERD_ALSA_PLAYBACK_CARD}
}
min_dB -60.0
max_dB 12.0
}
# Per-source playback PCMs.
pcm.tts {
type plug
slave.pcm "tts_softvol"
}
pcm.horn {
type plug
slave.pcm "horn_softvol"
}
pcm.forward {
type plug
slave.pcm "forward_softvol"
}
# Capture alias used by laptop rover config defaults. Capture is deliberately
# separate from playback because laptop speakers and microphones often appear
# on different ALSA cards.
pcm.rovermic {
type plug
slave.pcm "${ROVERD_ALSA_CAPTURE_DEVICE}"
}
# Defaults: TTS direct playback + raw capture on the selected laptop devices.
pcm.!default {
type asym
playback.pcm "tts"
capture.pcm "rovermic"
}
ctl.!default {
type hw
card ${ROVERD_ALSA_PLAYBACK_CARD}
}
EOF
install -o root -g root -m 0644 "$tmp_path" /etc/asound.conf
rm -f "$tmp_path"
log "Installed dedicated Debian laptop ALSA config to /etc/asound.conf using playback ${ROVERD_ALSA_PLAYBACK_DEVICE}"
}
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
log "Installed laptop chromegtts daemon"
install_google_tts_assets_laptop
log "ALSA config updated; reboot recommended before testing laptop rover audio"
}
install_google_tts_assets_laptop() {
local asset_dir="/opt/roverd/googletts"
local voice_dir="${asset_dir}/en-us-x-multi-r30"
local dist_url="https://storage.googleapis.com/chromeos-localmirror/distfiles/googletts-26.5.tar.xz"
local tmp_dir
local lib_member=""
local member
if [[ -f "${asset_dir}/libchrometts.so" && -f "${voice_dir}/pipeline.pb" ]]; then
log "Google Chrome TTS assets already installed; skipping download"
return
fi
tmp_dir="$(mktemp -d)"
log "Downloading Google Chrome TTS assets for Debian laptop profile..."
if ! curl -L -o "${tmp_dir}/googletts-26.5.tar.xz" "$dist_url"; then
rm -rf "$tmp_dir"
log "WARNING: failed to download Google Chrome TTS assets; chromegtts will be unavailable"
return
fi
local -a candidate_libs=()
case "$(uname -m)" in
aarch64|arm64)
candidate_libs=(libchrometts_arm64.so)
;;
armv7l|armhf)
candidate_libs=(libchrometts_armv7.so)
;;
x86_64|amd64)
candidate_libs=(libchrometts_x86_64.so libchrometts_amd64.so libchrometts_x64.so libchrometts.so)
;;
i386|i686)
candidate_libs=(libchrometts_x86.so libchrometts_i386.so libchrometts.so)
;;
*)
log "WARNING: unsupported Chrome TTS architecture $(uname -m); skipping Google TTS assets"
rm -rf "$tmp_dir"
return
;;
esac
for member in "${candidate_libs[@]}"; do
if tar -tf "${tmp_dir}/googletts-26.5.tar.xz" "$member" >/dev/null 2>&1; then
lib_member="$member"
break
fi
done
if [[ -z "$lib_member" ]]; then
log "WARNING: no libchrometts library matching $(uname -m) found in Google TTS archive; chromegtts will be unavailable"
rm -rf "$tmp_dir"
return
fi
if ! tar -xf "${tmp_dir}/googletts-26.5.tar.xz" -C "$tmp_dir" en-us-x-multi.zvoice "$lib_member"; then
rm -rf "$tmp_dir"
log "WARNING: failed to unpack Google Chrome TTS assets; chromegtts will be unavailable"
return
fi
install -d -o root -g root -m 0755 "$asset_dir"
install -o root -g root -m 0644 "${tmp_dir}/${lib_member}" "${asset_dir}/libchrometts.so"
rm -rf "$voice_dir"
install -d -o root -g root -m 0755 "$voice_dir"
unzip -q "${tmp_dir}/en-us-x-multi.zvoice" -d "$voice_dir"
chown -R root:root "$asset_dir"
find "$asset_dir" -type d -exec chmod 0755 {} +
find "$asset_dir" -type f -exec chmod 0644 {} +
rm -rf "$tmp_dir"
log "Installed Google Chrome TTS assets to $asset_dir using $lib_member"
}
install_debian_laptop_profile() {
install_debian_laptop_deps
disable_debian_laptop_desktop_audio_stack
install_debian_laptop_audio_support
}
-89
View File
@@ -1,89 +0,0 @@
#!/usr/bin/env bash
write_media_env_placeholder() {
install -d -o roverd -g roverd /var/lib/roverd
case "$PROFILE" in
pi)
# roverd rewrites media.env after loading /etc/roverd.yaml. 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.
cat > /var/lib/roverd/media.env <<'ENV'
# Managed by roverd; placeholder values will be overwritten at runtime.
ROVERD_VIDEO_ENABLE=1
ROVERD_VIDEO_PUBLISHER=pi-libcamera
ROVERD_VIDEO_PUBLISH_URL=rtsp://control-server.local:8554/CHANGE_ME
ROVERD_VIDEO_DEVICE=
ROVERD_VIDEO_INPUT_FORMAT=
ROVERD_VIDEO_WIDTH=640
ROVERD_VIDEO_HEIGHT=480
ROVERD_VIDEO_FPS=30
ROVERD_VIDEO_BITRATE=2000000
ROVERD_VIDEO_INVERT=1
ROVERD_VIDEO_SENSOR_MODE=1296:972
ROVERD_AUDIO_CAPTURE_ENABLE=0
ROVERD_AUDIO_CAPTURE_PUBLISH_URL=rtsp://control-server.local:8554/CHANGE_ME-audio
ROVERD_AUDIO_CAPTURE_DEVICE=hw:0,0
ROVERD_AUDIO_CAPTURE_SAMPLE_RATE=48000
ROVERD_AUDIO_CAPTURE_CHANNELS=2
ROVERD_AUDIO_CAPTURE_BITRATE=510000
ROVERD_AUDIO_PLAYBACK_ENABLE=1
ROVERD_AUDIO_PLAYBACK_FORWARD_URL=rtsp://control-server.local:8554/CHANGE_ME-fwd
ROVERD_AUDIO_PLAYBACK_DEVICE=forward
ROVERD_AUDIO_PLAYBACK_NORMALIZE=1
ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER=dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled
ENV
;;
debian-laptop)
# The laptop placeholder uses the same logical ALSA names as the
# installed laptop asound.conf. That keeps forwarded audio under the
# ForwardMaster mixer control while TTS and horn keep their own paths.
cat > /var/lib/roverd/media.env <<'ENV'
# Managed by roverd; placeholder values will be overwritten at runtime.
ROVERD_VIDEO_ENABLE=1
ROVERD_VIDEO_PUBLISHER=debian-laptop-v4l2
ROVERD_VIDEO_PUBLISH_URL=rtsp://control-server.local:8554/CHANGE_ME
ROVERD_VIDEO_DEVICE=/dev/video0
ROVERD_VIDEO_INPUT_FORMAT=mjpeg
ROVERD_VIDEO_WIDTH=640
ROVERD_VIDEO_HEIGHT=480
ROVERD_VIDEO_FPS=30
ROVERD_VIDEO_BITRATE=2000000
ROVERD_VIDEO_INVERT=0
ROVERD_VIDEO_SENSOR_MODE=
ROVERD_AUDIO_CAPTURE_ENABLE=1
ROVERD_AUDIO_CAPTURE_PUBLISH_URL=rtsp://control-server.local:8554/CHANGE_ME-audio
ROVERD_AUDIO_CAPTURE_DEVICE=default
ROVERD_AUDIO_CAPTURE_SAMPLE_RATE=48000
ROVERD_AUDIO_CAPTURE_CHANNELS=2
ROVERD_AUDIO_CAPTURE_BITRATE=510000
ROVERD_AUDIO_PLAYBACK_ENABLE=1
ROVERD_AUDIO_PLAYBACK_FORWARD_URL=rtsp://control-server.local:8554/CHANGE_ME-fwd
ROVERD_AUDIO_PLAYBACK_DEVICE=forward
ROVERD_AUDIO_PLAYBACK_NORMALIZE=1
ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER=dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled
ENV
;;
esac
chown roverd:roverd /var/lib/roverd/media.env
chmod 0640 /var/lib/roverd/media.env
}
install_audio_fifo() {
local fifo_path="/var/lib/roverd/audio.pcm"
# The capture service and publisher service meet at this FIFO. Recreating
# it only when it is missing or the path is not a FIFO preserves a working
# service pipe while still fixing accidental regular-file leftovers.
if [[ -p "$fifo_path" ]]; then
chown roverd:audio "$fifo_path"
chmod 0660 "$fifo_path"
else
rm -f "$fifo_path"
mkfifo "$fifo_path"
chown roverd:audio "$fifo_path"
chmod 0660 "$fifo_path"
fi
}
-160
View File
@@ -1,160 +0,0 @@
#!/usr/bin/env bash
install_pi_video_deps() {
if command -v ffmpeg >/dev/null 2>&1 && (command -v rpicam-vid >/dev/null 2>&1 || command -v libcamera-vid >/dev/null 2>&1); then
log "Video dependencies already installed; skipping apt install"
return
fi
log "Installing video dependencies (libcamera-apps, ffmpeg)..."
apt-get update
apt-get install -y --no-install-recommends libcamera-apps ffmpeg
}
find_boot_config() {
if [[ -f /boot/firmware/config.txt ]]; then
printf "/boot/firmware/config.txt"
return 0
fi
if [[ -f /boot/config.txt ]]; then
printf "/boot/config.txt"
return 0
fi
return 1
}
ensure_pwm_overlay() {
local boot_config
if ! boot_config="$(find_boot_config)"; then
log "WARNING: unable to locate /boot config.txt; please ensure dtoverlay=pwm-2chan is added manually for servo support"
return
fi
if grep -Eq '^\s*dtoverlay=pwm(-2chan)?' "$boot_config"; then
log "PWM overlay already present in $boot_config"
return
fi
local backup="${boot_config}.roverd.$(date +%Y%m%d%H%M%S).bak"
cp "$boot_config" "$backup"
{
echo ""
echo "# Added by roverd installer to expose PWM hardware for camera servo control on GPIO12/13 (leaves GPIO18/19 free for I2S)"
echo "dtoverlay=pwm-2chan,pin=12,func=4,pin2=13,func2=4"
} >> "$boot_config"
log "Enabled dtoverlay=pwm-2chan on GPIO12/13 in $boot_config (backup at $backup). Reboot required for changes to apply."
}
install_pi_audio_support() {
local boot_config
if ! boot_config="$(find_boot_config)"; then
log "WARNING: unable to locate /boot config.txt; please enable googlevoicehat-soundcard overlay manually"
else
# Ensure onboard audio is disabled (prevents card index flapping)
if grep -Eq '^\s*dtparam=audio=on\b' "$boot_config"; then
log "Disabling onboard audio (dtparam=audio=on -> off) in $boot_config"
sed -i 's/^\s*dtparam=audio=on\b/# roverd disabled onboard audio\ndtparam=audio=off/' "$boot_config"
fi
if ! grep -Eq '^\s*dtparam=audio=off\b' "$boot_config"; then
log "Adding dtparam=audio=off to $boot_config"
echo "dtparam=audio=off" >> "$boot_config"
fi
if ! grep -Eq '^\s*dtparam=i2s=on\b' "$boot_config"; then
log "Adding dtparam=i2s=on to $boot_config"
echo "dtparam=i2s=on" >> "$boot_config"
fi
if ! grep -Eq '^\s*dtoverlay=googlevoicehat-soundcard\b' "$boot_config"; then
local backup="${boot_config}.roverd.$(date +%Y%m%d%H%M%S).bak"
cp "$boot_config" "$backup"
{
echo ""
echo "# Added by roverd installer to enable Google AIY v1 sound card"
echo "dtoverlay=googlevoicehat-soundcard"
} >> "$boot_config"
log "Enabled googlevoicehat-soundcard overlay in $boot_config (backup at $backup). Reboot required."
else
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
log "Installed ALSA config to /etc/asound.conf"
alsa_reload_notice=1
else
log "WARNING: pi/asound.conf missing; skipping ALSA config install"
fi
if [[ "${alsa_reload_notice:-0}" -eq 1 ]]; then
log "ALSA config updated; reboot recommended for overlay + audio changes"
fi
log "Installing TTS/audio packages (flite, espeak, Chrome TTS runtime deps)..."
if command -v flite >/dev/null 2>&1 \
&& command -v espeak >/dev/null 2>&1 \
&& command -v python3 >/dev/null 2>&1 \
&& command -v curl >/dev/null 2>&1 \
&& command -v xz >/dev/null 2>&1 \
&& command -v unzip >/dev/null 2>&1 \
&& command -v aplay >/dev/null 2>&1 \
&& ldconfig -p 2>/dev/null | grep -q 'libc++\.so\.1' \
&& ldconfig -p 2>/dev/null | grep -q 'libc++abi\.so\.1'; then
log "Core TTS packages already installed; skipping apt install"
else
apt-get update
apt-get install -y --no-install-recommends flite espeak python3 curl xz-utils unzip alsa-utils libc++1 libc++abi1 \
|| 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
log "Installed chromegtts daemon"
install_google_tts_assets
}
install_google_tts_assets() {
local asset_dir="/opt/roverd/googletts"
local voice_dir="${asset_dir}/en-us-x-multi-r30"
local dist_url="https://storage.googleapis.com/chromeos-localmirror/distfiles/googletts-26.5.tar.xz"
local tmp_dir
local lib_member
case "$(uname -m)" in
aarch64|arm64)
lib_member="libchrometts_arm64.so"
;;
armv7l|armhf)
lib_member="libchrometts_armv7.so"
;;
*)
log "WARNING: unsupported Chrome TTS architecture $(uname -m); skipping Google TTS assets"
return
;;
esac
if [[ -f "${asset_dir}/libchrometts.so" && -f "${voice_dir}/pipeline.pb" ]]; then
log "Google Chrome TTS assets already installed; skipping download"
return
fi
tmp_dir="$(mktemp -d)"
log "Downloading Google Chrome TTS assets..."
curl -L -o "${tmp_dir}/googletts-26.5.tar.xz" "$dist_url"
tar -xf "${tmp_dir}/googletts-26.5.tar.xz" -C "$tmp_dir" en-us-x-multi.zvoice "$lib_member"
install -d -o root -g root -m 0755 "$asset_dir"
install -o root -g root -m 0644 "${tmp_dir}/${lib_member}" "${asset_dir}/libchrometts.so"
rm -rf "$voice_dir"
install -d -o root -g root -m 0755 "$voice_dir"
unzip -q "${tmp_dir}/en-us-x-multi.zvoice" -d "$voice_dir"
chown -R root:root "$asset_dir"
find "$asset_dir" -type d -exec chmod 0755 {} +
find "$asset_dir" -type f -exec chmod 0644 {} +
rm -rf "$tmp_dir"
log "Installed Google Chrome TTS assets to $asset_dir"
}
install_pi_profile() {
if ! command -v rpicam-vid >/dev/null 2>&1 && ! command -v libcamera-vid >/dev/null 2>&1; then
log "WARNING: neither rpicam-vid nor libcamera-vid found in PATH; install libcamera-apps."
fi
install_pi_video_deps
ensure_pwm_overlay
install_pi_audio_support
}
-105
View File
@@ -1,105 +0,0 @@
#!/usr/bin/env bash
PROFILE="pi"
BINARY_SRC=""
CONFIG_SRC=""
usage() {
cat <<'USAGE'
Usage: sudo ./pi/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
(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 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
* enable roverd.service and media publisher/listener services
USAGE
}
parse_args() {
while [[ $# -gt 0 ]]; do
case "$1" in
--profile)
PROFILE="${2:-}"
shift 2
;;
--debian-laptop)
PROFILE="debian-laptop"
shift
;;
-b|--binary)
BINARY_SRC="${2:-}"
shift 2
;;
-c|--config)
CONFIG_SRC="${2:-}"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown option: $1" >&2
usage
exit 1
;;
esac
done
}
select_profile() {
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"
VIDEO_HELPER_DEST="/usr/local/bin/video-publisher"
VIDEO_SERVICE_SRC="pi/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"
VIDEO_HELPER_DEST="/usr/local/bin/debian-laptop-video-publisher"
VIDEO_SERVICE_SRC="pi/systemd/debian-laptop-video-publisher.service"
VIDEO_SERVICE_NAME="debian-laptop-video-publisher.service"
ROVERD_GROUPS="dialout,video,render,audio"
;;
*)
echo "Unknown profile: $PROFILE" >&2
usage
exit 1
;;
esac
}
install_selected_profile() {
case "$PROFILE" in
pi)
# The Pi profile owns the board-specific camera, PWM, and AIY audio
# setup. Keeping that hardware work behind this dispatcher prevents
# the laptop profile from accidentally inheriting Pi overlays or
# card-index assumptions.
install_pi_profile
;;
debian-laptop)
# The Debian laptop profile only installs ordinary Debian packages
# and a laptop ALSA routing file. Anything that depends on Pi GPIO,
# overlays, or the Google Voice HAT stays out of this path.
install_debian_laptop_profile
;;
esac
}
-38
View File
@@ -1,38 +0,0 @@
#!/usr/bin/env bash
install_self_update_support() {
local sudoers_file="/etc/sudoers.d/roverd-self-update"
local update_env="/etc/roverd-update.env"
local quoted_repo_root
# The self-update helper must know which checkout should receive the git
# pull. Recording the repository root during the normal installer run keeps
# the runtime websocket command simple and prevents the rover from accepting
# a caller-controlled path.
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.
# 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.
ROVERD_REPO_DIR=$quoted_repo_root
ENV
log "Registered roverd update repository at $REPO_ROOT"
# 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
cat > "$sudoers_file" <<'SUDOERS'
# Managed by pi/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
chown root:root "$sudoers_file"
chmod 0440 "$sudoers_file"
if command -v visudo >/dev/null 2>&1; then
visudo -cf "$sudoers_file" >/dev/null
fi
log "Installed roverd self-update helper and sudoers rule"
}
-43
View File
@@ -1,43 +0,0 @@
#!/usr/bin/env bash
install_media_units() {
# Video publishing is the only profile-specific media service right now:
# Pi uses libcamera/rpicam, while Debian laptops publish from a V4L2 webcam.
install -D -o root -g root -m 0755 "$VIDEO_HELPER_SRC" "$VIDEO_HELPER_DEST"
log "Installed $PROFILE video publisher helper"
install -m 0644 "$VIDEO_SERVICE_SRC" "/etc/systemd/system/$VIDEO_SERVICE_NAME"
log "Installed $PROFILE video publisher systemd unit"
# 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
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
log "Installed audio-forward listener helper + systemd unit"
}
enable_and_restart_units() {
systemctl daemon-reload
systemctl enable roverd.service
systemctl enable "$VIDEO_SERVICE_NAME"
systemctl enable audio-only-publisher.service
systemctl enable audio-forward-listener.service
if [[ $CONFIG_EXISTS -eq 1 ]]; then
# An existing config means this host was already configured, so restart
# immediately to pick up the new binary, helpers, units, and media env.
systemctl restart roverd.service
systemctl restart "$VIDEO_SERVICE_NAME"
systemctl restart audio-only-publisher.service
systemctl restart audio-forward-listener.service
log "Restarted roverd + media publishers/listener"
else
# A freshly installed sample config usually still has placeholder names
# and URLs. Enabling without starting avoids connecting a half-configured
# rover to the control server by accident.
log "Skipped auto-start because config is the sample; edit $CONFIG_DEST then run: sudo systemctl restart roverd ${VIDEO_SERVICE_NAME%.service} audio-only-publisher audio-forward-listener"
fi
}
-48
View File
@@ -1,48 +0,0 @@
#!/usr/bin/env bash
#
# Installer entry point for roverd hosts.
#
# The detailed work lives in pi/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.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
# The helper scripts use repository-relative paths because those same paths are
# shown in docs and logs. Moving to the repository root once keeps every module
# 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
main() {
parse_args "$@"
select_profile
require_root
validate_install_inputs
install_roverd_binary
install_self_update_support
install_roverd_config
install_roverd_unit
install_selected_profile
install_media_units
write_media_env_placeholder
install_audio_fifo
enable_and_restart_units
log "Install complete for profile $PROFILE"
}
main "$@"
-24
View File
@@ -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
-25
View File
@@ -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) {}
-45
View File
@@ -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"
}
-136
View File
@@ -1,136 +0,0 @@
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
roverd "multiroombarover/pi/roverd"
)
func main() {
var cfgPath string
flag.StringVar(&cfgPath, "config", "/etc/roverd.yaml", "path to roverd configuration file")
flag.Parse()
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)
}
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
logger := log.New(os.Stdout, "roverd: ", log.LstdFlags|log.Lmicroseconds|log.LUTC)
console := roverd.NewConsoleNotifier(logger)
serialPort, err := roverd.OpenSerial(cfg.Serial)
if err != nil {
logger.Fatalf("open serial: %v", err)
}
defer serialPort.Close()
// Peripheral discovery is intentionally a boot-time operation. The manager
// keeps successful USB ports open across server WebSocket reconnects and is
// rebuilt only when the roverd process itself restarts.
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)
}
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.
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)
}
defer hardwareControllers.Close()
for _, message := range hardwareControllers.StartupBroadcasts() {
console.Notify(message)
}
// A peripheral is never hot-reconnected. Report the first terminal serial
// failure for each discovered board and tell the local operator exactly what
// recovery action the fixed boot-time lifecycle requires.
go func() {
for {
select {
case failure := <-peripherals.Failures():
console.Notify(fmt.Sprintf(
"Rover peripheral %q (%s) disconnected: %v. Reconnect it and restart roverd.",
failure.Name,
failure.ID,
failure.Err,
))
case <-ctx.Done():
return
}
}
}()
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)
// 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.
console.Notify("roverd started and hardware initialization completed.")
defer console.Notify("roverd stopped.")
retryDelay := time.Second
for ctx.Err() == nil {
if err := client.Run(ctx); err != nil {
logger.Printf("websocket loop ended: %v", err)
}
select {
case <-ctx.Done():
return
case <-time.After(retryDelay):
}
if retryDelay < 30*time.Second {
retryDelay *= 2
}
}
}
-13
View File
@@ -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
-40
View File
@@ -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"
}
-68
View File
@@ -1,68 +0,0 @@
package roverd
import (
"bytes"
"fmt"
"os"
"path/filepath"
)
const publisherEnvPath = "/var/lib/roverd/media.env"
func UpdatePublisherEnv(media MediaConfig) error {
if media.Video.Enabled && media.Video.PublishURL == "" {
return fmt.Errorf("media video publishUrl missing")
}
if media.AudioCapture.Enabled && media.AudioCapture.PublishURL == "" {
return fmt.Errorf("media audioCapture publishUrl missing")
}
if media.AudioPlayback.Enabled && media.AudioPlayback.ForwardURL == "" {
return fmt.Errorf("media audioPlayback forwardUrl missing")
}
if media.Video.Width <= 0 || media.Video.Height <= 0 || media.Video.FPS <= 0 || media.Video.Bitrate <= 0 {
return fmt.Errorf("invalid media video dimensions/bitrate")
}
if err := os.MkdirAll(filepath.Dir(publisherEnvPath), 0o755); err != nil {
return err
}
var buf bytes.Buffer
/*
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
scripts as small pipeline launchers.
*/
fmt.Fprintf(&buf, "ROVERD_VIDEO_ENABLE=%d\n", boolToInt(media.Video.Enabled))
fmt.Fprintf(&buf, "ROVERD_VIDEO_PUBLISHER=%s\n", media.Video.Publisher)
fmt.Fprintf(&buf, "ROVERD_VIDEO_PUBLISH_URL=%s\n", media.Video.PublishURL)
fmt.Fprintf(&buf, "ROVERD_VIDEO_DEVICE=%s\n", media.Video.Device)
fmt.Fprintf(&buf, "ROVERD_VIDEO_INPUT_FORMAT=%s\n", media.Video.InputFormat)
fmt.Fprintf(&buf, "ROVERD_VIDEO_WIDTH=%d\n", media.Video.Width)
fmt.Fprintf(&buf, "ROVERD_VIDEO_HEIGHT=%d\n", media.Video.Height)
fmt.Fprintf(&buf, "ROVERD_VIDEO_FPS=%d\n", media.Video.FPS)
fmt.Fprintf(&buf, "ROVERD_VIDEO_BITRATE=%d\n", media.Video.Bitrate)
fmt.Fprintf(&buf, "ROVERD_VIDEO_INVERT=%d\n", boolToInt(media.Video.Inverted))
fmt.Fprintf(&buf, "ROVERD_VIDEO_SENSOR_MODE=%s\n", media.Video.SensorMode)
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_ENABLE=%d\n", boolToInt(media.AudioCapture.Enabled))
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_PUBLISH_URL=%s\n", media.AudioCapture.PublishURL)
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_DEVICE=%s\n", media.AudioCapture.Device)
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_SAMPLE_RATE=%d\n", media.AudioCapture.SampleRate)
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_CHANNELS=%d\n", media.AudioCapture.Channels)
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_BITRATE=%d\n", media.AudioCapture.Bitrate)
fmt.Fprintf(&buf, "ROVERD_AUDIO_PLAYBACK_ENABLE=%d\n", boolToInt(media.AudioPlayback.Enabled))
fmt.Fprintf(&buf, "ROVERD_AUDIO_PLAYBACK_FORWARD_URL=%s\n", media.AudioPlayback.ForwardURL)
fmt.Fprintf(&buf, "ROVERD_AUDIO_PLAYBACK_DEVICE=%s\n", media.AudioPlayback.Device)
fmt.Fprintf(&buf, "ROVERD_AUDIO_PLAYBACK_NORMALIZE=%d\n", boolToInt(media.AudioPlayback.Normalize))
fmt.Fprintf(&buf, "ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER=%s\n", media.AudioPlayback.NormalizeFilter)
if err := os.WriteFile(publisherEnvPath, buf.Bytes(), 0o640); err != nil {
return err
}
return nil
}
func boolToInt(v bool) int {
if v {
return 1
}
return 0
}
-163
View File
@@ -1,163 +0,0 @@
package roverd
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os/exec"
"time"
)
type MediaSupervisor struct {
cfg MediaConfig
logger *log.Logger
client *http.Client
checkInterval time.Duration
}
func NewMediaSupervisor(cfg MediaConfig, logger *log.Logger) *MediaSupervisor {
if err := UpdatePublisherEnv(cfg); err != nil {
logger.Printf("media supervisor: update env failed: %v", err)
}
if !cfg.Manage {
return nil
}
interval := cfg.HealthInterval.Duration
if interval <= 0 {
interval = 30 * time.Second
}
var client *http.Client
if cfg.HealthURL != "" {
client = &http.Client{Timeout: 5 * time.Second}
}
return &MediaSupervisor{
cfg: cfg,
logger: logger,
client: client,
checkInterval: interval,
}
}
func (m *MediaSupervisor) Start(ctx context.Context) {
if m == nil {
return
}
if err := UpdatePublisherEnv(m.cfg); err != nil {
m.logger.Printf("media supervisor: update env failed: %v", err)
}
if m.cfg.HealthURL == "" || m.client == nil {
return
}
go func() {
ticker := time.NewTicker(m.checkInterval)
defer ticker.Stop()
if err := m.checkAndRepair(); err != nil {
m.logger.Printf("media supervisor: %v", err)
}
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if err := m.checkAndRepair(); err != nil {
m.logger.Printf("media supervisor: %v", err)
}
}
}
}()
}
func (m *MediaSupervisor) HandleAction(ctx context.Context, action string) error {
if m == nil {
return errors.New("media supervisor disabled")
}
if err := UpdatePublisherEnv(m.cfg); err != nil {
return err
}
switch action {
case "start", "stop", "restart", "reload", "status":
return m.runSystemctl(ctx, action)
default:
return fmt.Errorf("unknown media action: %s", action)
}
}
func (m *MediaSupervisor) checkAndRepair() error {
ctx, cancel := context.WithTimeout(context.Background(), 7*time.Second)
defer cancel()
if m.checkHealth(ctx) {
return nil
}
m.logger.Printf("media supervisor: health check failed, restarting configured media services")
if err := m.runSystemctl(ctx, "restart"); err != nil {
return fmt.Errorf("restart media services: %w", err)
}
return nil
}
func (m *MediaSupervisor) checkHealth(ctx context.Context) bool {
if m.client == nil || m.cfg.HealthURL == "" {
return true
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.cfg.HealthURL, nil)
if err != nil {
m.logger.Printf("media supervisor: health request: %v", err)
return false
}
resp, err := m.client.Do(req)
if err != nil {
m.logger.Printf("media supervisor: health request failed: %v", err)
return false
}
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, resp.Body)
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return true
}
m.logger.Printf("media supervisor: unexpected health status %d", resp.StatusCode)
return false
}
func (m *MediaSupervisor) runSystemctl(ctx context.Context, action string) error {
services := m.managedServices()
if len(services) == 0 {
return errors.New("no media services configured")
}
runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
for _, service := range services {
cmd := exec.CommandContext(runCtx, "systemctl", action, service)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("systemctl %s %s: %w (%s)", action, service, err, string(output))
}
}
return nil
}
func (m *MediaSupervisor) managedServices() []string {
/*
Only enabled streams are service-managed. This matters for audio capture:
the service may be installed everywhere, but a rover with capture disabled
should not have remote media commands starting a publisher that the config
says should stay off.
*/
services := []string{}
if m.cfg.Video.Enabled && m.cfg.Video.Service != "" {
services = append(services, m.cfg.Video.Service)
}
if m.cfg.AudioCapture.Enabled && m.cfg.AudioCapture.Service != "" {
services = append(services, m.cfg.AudioCapture.Service)
}
if m.cfg.AudioPlayback.Enabled && m.cfg.AudioPlayback.Service != "" {
services = append(services, m.cfg.AudioPlayback.Service)
}
return services
}
-105
View File
@@ -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
-111
View File
@@ -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
-78
View File
@@ -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
-18
View File
@@ -1,18 +0,0 @@
[Unit]
Description=Rover Audio Forward Listener (RTSP/TCP -> ALSA)
After=network-online.target roverd.service
Wants=network-online.target
[Service]
Type=simple
User=roverd
Group=roverd
EnvironmentFile=/var/lib/roverd/media.env
ExecStart=/usr/local/bin/audio-forward-listener
KillMode=control-group
TimeoutStopSec=5
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
-18
View File
@@ -1,18 +0,0 @@
[Unit]
Description=Rover Audio Publisher (ALSA -> RTSP/TCP)
After=network-online.target roverd.service
Wants=network-online.target
[Service]
Type=simple
User=roverd
Group=roverd
EnvironmentFile=/var/lib/roverd/media.env
ExecStart=/usr/local/bin/audio-only-publisher
KillMode=control-group
TimeoutStopSec=5
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
@@ -1,17 +0,0 @@
[Unit]
Description=Rover Debian Laptop Video Publisher (V4L2 -> RTSP/TCP)
After=network-online.target roverd.service
Wants=network-online.target
[Service]
Type=simple
User=roverd
Group=roverd
WorkingDirectory=/var/lib/roverd
EnvironmentFile=/var/lib/roverd/media.env
ExecStart=/usr/local/bin/debian-laptop-video-publisher
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
-17
View File
@@ -1,17 +0,0 @@
[Unit]
Description=Rover Video Publisher (libcamera -> RTSP/TCP)
After=network-online.target roverd.service
Wants=network-online.target
[Service]
Type=simple
User=roverd
Group=roverd
WorkingDirectory=/var/lib/roverd
EnvironmentFile=/var/lib/roverd/media.env
ExecStart=/usr/local/bin/video-publisher
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
@@ -7,11 +7,11 @@ import subprocess
import sys import sys
ASSET_ROOT = "/opt/roverd/googletts" ASSET_ROOT = "/var/lib/roverd/googletts"
LIB_PATH = os.path.join(ASSET_ROOT, "libchrometts.so") LIB_PATH = os.path.join(ASSET_ROOT, "libchrometts.so")
VOICE_DIR = os.path.join(ASSET_ROOT, "en-us-x-multi-r30") VOICE_DIR = os.path.join(ASSET_ROOT, "en-us-x-multi-r30")
PIPELINE = "pipeline.pb" PIPELINE = "pipeline.pb"
PLAYBACK_DEVICE = "tts" PLAYBACK_DEVICE = "rover_tts"
SAMPLE_RATE = "24000" SAMPLE_RATE = "24000"
MAX_TEXT_CHARS = 512 MAX_TEXT_CHARS = 512
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
# A separate systemd job survives replacement/restart of the roverd service.
set -euo pipefail
[[ $EUID == 0 ]] || { echo 'Run as root' >&2; exit 1; }
if [[ ${ROVERD_UPDATE_JOB:-} != 1 ]]; then
exec systemd-run --unit=roverd-self-update --collect --wait \
--property=Type=exec --setenv=ROVERD_UPDATE_JOB=1 "$0"
fi
exec 9>/var/lock/roverd-self-update.lock
flock -n 9 || exit 1
install -d /var/lib/roverd
status() {
echo "$2"
python3 - "$1" "$2" <<'PY'
import json, os, sys, time
path = '/var/lib/roverd/update-status.json'
with open(path + '.tmp', 'w') as f:
json.dump(dict(state=sys.argv[1], message=sys.argv[2], timestamp=int(time.time()*1000)), f)
os.replace(path + '.tmp', path)
PY
}
trap 'result=$?; if (( result != 0 )); then status failed "Update failed (exit $result). See journalctl -u roverd-self-update."; fi' EXIT
source /etc/roverd-update.env
cd "$ROVERD_REPO_DIR"
status running 'Updating repository'
# This is a dedicated root-owned checkout; local configuration lives outside it.
git pull --ff-only
status running 'Installing rover software'
bash rover/install_roverd.sh
status running 'Restarting roverd'
systemctl restart roverd
status succeeded 'Update installed and roverd service restarted'
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env bash
set -euo pipefail
log() { echo "$*"; }
# Package dependencies are installed by install_roverd.sh before this helper runs.
install_google_tts_assets() {
local asset_dir="/var/lib/roverd/googletts"
local voice_dir="${asset_dir}/en-us-x-multi-r30"
local dist_url="https://storage.googleapis.com/chromeos-localmirror/distfiles/googletts-26.5.tar.xz"
local tmp_dir
local lib_member=""
local member
if [[ -f "${asset_dir}/libchrometts.so" && -f "${voice_dir}/pipeline.pb" ]]; then
log "Google Chrome TTS assets already installed; skipping download"
return
fi
tmp_dir="$(mktemp -d)"
log "Downloading Google Chrome TTS assets for this architecture..."
if ! curl -L -o "${tmp_dir}/googletts-26.5.tar.xz" "$dist_url"; then
rm -rf "$tmp_dir"
log "WARNING: failed to download Google Chrome TTS assets; chromegtts will be unavailable"
return
fi
local -a candidate_libs=()
case "$(dpkg --print-architecture)" in
arm64)
candidate_libs=(libchrometts_arm64.so)
;;
armhf)
if [[ "$(uname -m)" == armv6l ]]; then
log "Chrome TTS has no ARMv6 library; use flite or espeak on this host"
rm -rf "$tmp_dir"
return
fi
candidate_libs=(libchrometts_armv7.so)
;;
amd64)
candidate_libs=(libchrometts_x86_64.so libchrometts_amd64.so libchrometts_x64.so libchrometts.so)
;;
i386)
candidate_libs=(libchrometts_x86.so libchrometts_i386.so libchrometts.so)
;;
*)
log "WARNING: unsupported Chrome TTS architecture $(uname -m); skipping Google TTS assets"
rm -rf "$tmp_dir"
return
;;
esac
for member in "${candidate_libs[@]}"; do
if tar -tf "${tmp_dir}/googletts-26.5.tar.xz" "$member" >/dev/null 2>&1; then
lib_member="$member"
break
fi
done
if [[ -z "$lib_member" ]]; then
log "WARNING: no libchrometts library matching $(uname -m) found in Google TTS archive; chromegtts will be unavailable"
rm -rf "$tmp_dir"
return
fi
if ! tar -xf "${tmp_dir}/googletts-26.5.tar.xz" -C "$tmp_dir" en-us-x-multi.zvoice "$lib_member"; then
rm -rf "$tmp_dir"
log "WARNING: failed to unpack Google Chrome TTS assets; chromegtts will be unavailable"
return
fi
install -d -o root -g root -m 0755 "$asset_dir"
install -o root -g root -m 0644 "${tmp_dir}/${lib_member}" "${asset_dir}/libchrometts.so"
rm -rf "$voice_dir"
install -d -o root -g root -m 0755 "$voice_dir"
unzip -q "${tmp_dir}/en-us-x-multi.zvoice" -d "$voice_dir"
chown -R root:root "$asset_dir"
find "$asset_dir" -type d -exec chmod 0755 {} +
find "$asset_dir" -type f -exec chmod 0644 {} +
rm -rf "$tmp_dir"
log "Installed Google Chrome TTS assets to $asset_dir using $lib_member"
}
install_google_tts_assets
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Download this file and run it with sudo; no existing checkout is needed.
set -euo pipefail
[[ $EUID == 0 ]] || { echo 'Run with sudo bash bootstrap.sh' >&2; exit 1; }
# Existing installations keep their identity; only fresh hosts need prompts.
if [[ ! -f /etc/roverd.json && ! -f /etc/roverd.yaml ]]; then
read -r -p 'Rover name: ' rover_name </dev/tty
read -r -p 'Server address (ws://host:port/rover or wss://host/rover): ' server_address </dev/tty
[[ -n "$rover_name" && -n "$server_address" ]] || { echo 'Name and address are required' >&2; exit 1; }
export ROVERD_INITIAL_NAME="$rover_name" ROVERD_INITIAL_SERVER="$server_address"
fi
apt-get update
apt-get install -y git ca-certificates python3 python3-yaml
# The old installer used /opt/roverd for speech assets, not a checkout.
if [[ -d /opt/roverd && ! -e /opt/roverd/.git ]]; then
install -d -m 0700 /var/backups/roverd
previous=$(mktemp -d /var/backups/roverd/old-directory.XXXXXXXX)
mv /opt/roverd "$previous/roverd"
echo "Previous /opt/roverd saved in $previous/roverd"
fi
if [[ ! -e /opt/roverd ]]; then
git clone https://github.com/legop3/MultiRoombaRover.git /opt/roverd
fi
[[ -d /opt/roverd/.git ]] || { echo '/opt/roverd must be a repository checkout' >&2; exit 1; }
git -C /opt/roverd pull --ff-only
export ROVERD_MIGRATE=1
bash /opt/roverd/rover/install_roverd.sh
systemctl restart roverd
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""One-time installed-host conversion. Never imported by roverd."""
import argparse
import copy
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
from urllib.parse import urlparse
def run(*args):
return subprocess.run(args, check=True, text=True, capture_output=True).stdout
def merge_known(target, source):
# New defaults supply fields absent from old configs; explicit false survives.
for key in target.keys() & source.keys():
if isinstance(target[key], dict) and isinstance(source[key], dict):
merge_known(target[key], source[key])
else:
target[key] = copy.deepcopy(source[key])
def convert(old, defaults, alsa, laptop, is_pi):
result = copy.deepcopy(defaults)
merge_known(result, old)
if 'piGpio' not in old:
gpio = result['piGpio']
for key in ('brc', 'cameraServo', 'headlight', 'laser'):
merge_known(gpio[key], old.get(key, {}))
if gpio['brc']['gpioPin'] < 0:
gpio['brc']['enabled'] = False
gpio['enabled'] = is_pi and any(gpio[k]['enabled'] for k in ('brc', 'cameraServo', 'headlight', 'laser'))
media = old.get('media', {})
video = media.get('video', {})
publisher = video.get('publisher')
if publisher and publisher not in ('pi-libcamera', 'debian-laptop-v4l2'):
raise ValueError(f'Custom publisher {publisher!r}: create a YAML profile before migrating')
if 'profile' not in video:
result['media']['video']['profile'] = {'pi-libcamera': 'rpicam', 'debian-laptop-v4l2': 'v4l2'}.get(publisher, 'rpicam' if is_pi and not laptop else 'v4l2')
for category, known in [('video', ('video-publisher.service', 'debian-laptop-video-publisher.service')), ('audioCapture', ('audio-only-publisher.service',)), ('audioPlayback', ('audio-forward-listener.service',))]:
service = media.get(category, {}).get('service')
if service and service not in known:
raise ValueError(f'Custom service {service!r}: convert its command to a profile first')
aiy = 'googlevoicehat' in alsa
for category in ('audioCapture', 'audioPlayback'):
if 'profile' not in media.get(category, {}):
result['media'][category]['profile'] = 'aiy' if aiy else 'alsa'
# Old URLs were overridden by the old daemon too; endpoints now derive from
# name/serverUrl. Preserve a nonstandard RTSP port when it is unambiguous.
ports = set()
for category, field in [('video', 'publishUrl'), ('audioCapture', 'publishUrl'), ('audioPlayback', 'forwardUrl')]:
parsed = urlparse(media.get(category, {}).get(field, ''))
if parsed.scheme == 'rtsp':
suffix = {'video': '', 'audioCapture': '-audio', 'audioPlayback': '-fwd'}[category]
expected_host = urlparse(result['serverUrl']).hostname
if parsed.hostname != expected_host or parsed.path != '/' + result['name'] + suffix or parsed.query or parsed.username:
raise ValueError(f'Custom {category} RTSP URL requires a custom profile')
ports.add(parsed.port or 554)
elif parsed.scheme == 'srt':
print(f'{category}: replacing legacy SRT endpoint with server-derived RTSP')
elif parsed.scheme:
raise ValueError(f'Unsupported legacy stream transport: {parsed.scheme}')
if 'rtspPort' not in media and ports:
if len(ports) != 1:
raise ValueError('Different legacy RTSP ports require a custom profile')
result['media']['rtspPort'] = ports.pop()
audio = result['audio']
previous_audio = old.get('audio', {})
if 'outputDevice' not in previous_audio:
# The old installer wrote a dmixer hardware slave and a rovermic alias.
mix = re.search(r'pcm\.dmixer\s*\{.*?slave\s*\{(.*?)\}', alsa, re.S)
capture = re.search(r'pcm\.rovermic\s*\{.*?slave\.pcm\s+"([^"]+)"', alsa, re.S)
card = re.search(r'name\s+"TTSMaster"\s+card\s+([^\s}]+)', alsa)
if mix:
device = re.search(r'pcm\s+"([^"]+)"', mix[1])
rate = re.search(r'rate\s+(\d+)', mix[1])
channels = re.search(r'channels\s+(\d+)', mix[1])
fmt = re.search(r'format\s+(\S+)', mix[1])
if not all((device, rate, channels, card)) or (fmt and fmt[1] != 'S16_LE'):
raise ValueError('Unsupported host ALSA mixer; set explicit physical audio settings first')
audio.update(outputDevice=device[1], mixerCard=card[1].strip('"'), outputSampleRate=int(rate[1]), outputChannels=int(channels[1]))
elif alsa.strip():
raise ValueError('Unrecognized /etc/asound.conf; cannot safely replace custom audio routing')
elif laptop:
audio.update(outputDevice=laptop['ROVERD_ALSA_PLAYBACK_DEVICE'], mixerCard=laptop['ROVERD_ALSA_PLAYBACK_CARD'], outputSampleRate=16000, outputChannels=1)
else:
raise ValueError('Cannot determine old physical playback device: /etc/asound.conf is missing')
source = media.get('audioCapture', {}).get('device', previous_audio.get('captureDevice', 'rovermic'))
if source in ('default', 'rovermic'):
source = capture[1] if capture else laptop.get('ROVERD_ALSA_CAPTURE_DEVICE')
if not source:
raise ValueError('Cannot determine old microphone hardware device')
audio['inputDevice'] = source
# All playback now shares one hardware route. Do not silently discard
# a deliberately different horn or forwarded-audio device.
for device in (old.get('horn', {}).get('device'), media.get('audioPlayback', {}).get('device')):
if device and device not in ('default', 'horn', 'forward', 'tts', audio['outputDevice']):
raise ValueError(f'Separate playback device {device!r} needs an explicit routing choice')
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--binary', required=True, help='new architecture binary')
parser.add_argument('--alsa-config', type=Path, default=Path('/etc/asound.conf'), help='legacy ALSA definitions for conversion')
parser.add_argument('--source', type=Path, help='override legacy config path')
parser.add_argument('--output', type=Path, help='write validated conversion only; do not alter host services')
args = parser.parse_args()
binary = str(Path(args.binary).resolve())
if args.alsa_config != Path('/etc/asound.conf') and not args.output:
raise ValueError('--alsa-config overrides require --output (preview only)')
source = args.source or next((p for p in (Path('/etc/roverd.json'), Path('/etc/roverd.yaml')) if p.exists()), None)
if source is None:
print('No existing rover configuration to migrate')
return
current = subprocess.run([binary, '-config', str(source), '-check-config'], capture_output=True).returncode == 0
defaults = json.loads(run(binary, '-print-default-config'))
alsa_path = args.alsa_config
alsa = alsa_path.read_text() if alsa_path.exists() else ''
laptop = {}
settings = Path('/etc/roverd-installer.env')
if settings.exists():
for line in settings.read_text().splitlines():
if line.startswith('ROVERD_ALSA_') and '=' in line:
key, value = line.split('=', 1)
laptop[key] = value.strip().strip('\"\'')
if current:
converted = json.loads(source.read_text())
else:
import yaml
# BaseLoader keeps sensor modes such as 1296:972 as strings. SafeLoader
# provides normal booleans/numbers for all other schema fields.
text = source.read_text()
old = yaml.safe_load(text)
if not isinstance(old, dict):
raise ValueError('Legacy configuration must be an object')
raw = yaml.load(text, Loader=yaml.BaseLoader)
if 'sensorMode' in old.get('media', {}).get('video', {}):
old['media']['video']['sensorMode'] = raw['media']['video']['sensorMode']
model = Path('/proc/device-tree/model')
is_pi = model.exists() and 'Raspberry Pi' in model.read_text()
converted = convert(old, defaults, alsa, laptop, is_pi)
units = ['video-publisher', 'debian-laptop-video-publisher', 'audio-only-publisher', 'audio-forward-listener']
legacy = [Path('/etc/roverd.yaml'), settings, Path('/etc/sudoers.d/roverd-self-update'), Path('/var/lib/roverd/media.env'), Path('/var/lib/roverd/audio.pcm')]
for unit in units:
legacy += [Path(f'/etc/systemd/system/{unit}.service'), Path(f'/etc/systemd/system/{unit}.service.d'), Path(f'/usr/local/bin/{unit}')]
# Recognize only installer-owned ALSA files, never delete arbitrary host routing.
if alsa.startswith(('# Use the Google Voice HAT soundcard', '# Dedicated ALSA routing for the Debian laptop rover profile.', '# Reference ALSA routing for the Debian laptop rover profile.')):
legacy.append(alsa_path)
elif alsa.strip() and not current:
raise ValueError('Custom ALSA file needs manual review before migration')
if current and not args.output and not any(p.exists() for p in legacy):
print('Current configuration already installed; migration not needed')
return
# Validate before stopping services or replacing any installed configuration.
with tempfile.TemporaryDirectory(prefix='roverd-migrate-') as staging:
candidate = Path(staging) / 'roverd.json'
candidate.write_text(json.dumps(converted, indent=2) + '\n')
os.chmod(candidate, 0o600)
run(binary, '-config', str(candidate), '-check-config')
if args.output:
shutil.copyfile(candidate, args.output)
os.chmod(args.output, 0o600)
print(f'Validated configuration written to {args.output}')
return
if os.geteuid() != 0:
raise ValueError('Host migration requires root')
root = Path('/var/backups/roverd')
root.mkdir(mode=0o700, parents=True, exist_ok=True)
backup = Path(tempfile.mkdtemp(prefix='migration-', dir=root))
paths = [source, Path('/usr/local/bin/roverd'), Path('/usr/local/bin/chromegtts-daemon'), Path('/etc/systemd/system/roverd.service'), Path('/etc/systemd/system/roverd.service.d'), Path('/etc/roverd-update.env'), Path('/usr/local/sbin/roverd-self-update'), *legacy]
for path in dict.fromkeys(paths):
if not path.exists() and not path.is_symlink():
continue
target = backup / str(path).lstrip('/')
target.parent.mkdir(parents=True, exist_ok=True)
if path.is_dir():
shutil.copytree(path, target, symlinks=True)
else:
shutil.copy2(path, target, follow_symlinks=False)
print(f'Previous installation saved in {backup}', flush=True)
for unit in ['roverd', *units]:
if run('systemctl', 'show', '-p', 'LoadState', '--value', unit + '.service').strip() != 'not-found':
run('systemctl', 'stop', unit + '.service')
if unit != 'roverd':
run('systemctl', 'disable', unit + '.service')
for path in legacy + [Path('/etc/systemd/system/roverd.service.d')]:
if path.is_dir() and not path.is_symlink():
shutil.rmtree(path)
else:
path.unlink(missing_ok=True)
target = Path('/etc/roverd.json')
temporary = target.with_suffix('.json.migrating')
shutil.copyfile(candidate, temporary)
os.chmod(temporary, 0o600)
os.replace(temporary, target)
run('systemctl', 'daemon-reload')
print('Migration complete; shared installer will install and start the new service')
if __name__ == '__main__':
try:
main()
except (ValueError, OSError, subprocess.CalledProcessError) as error:
detail = getattr(error, 'stderr', '') or ''
raise SystemExit(f'Migration stopped: {error}\n{detail}')
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
# Shared installation path for bootstrap and self-update.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
cd "$REPO_ROOT"
[[ $EUID == 0 ]] || { echo 'Run as root' >&2; exit 1; }
case "$(dpkg --print-architecture)" in
amd64) arch=amd64 ;; arm64) arch=arm64 ;;
armhf) case "$(uname -m)" in armv6*) arch=armv6 ;; *) arch=armv7 ;; esac ;;
*) echo 'Unsupported OS architecture' >&2; exit 1 ;;
esac
if [[ ${ROVERD_MIGRATE:-} == 1 ]]; then
python3 rover/install/migrate.py --binary "dist/roverd-linux-$arch"
fi
# Rename avoids overwriting an executable that the running service has mapped.
install -m 0755 "dist/roverd-linux-$arch" /usr/local/bin/roverd.new
mv -f /usr/local/bin/roverd.new /usr/local/bin/roverd
apt-get update
apt-get install -y git ca-certificates python3 util-linux flite espeak curl xz-utils unzip alsa-utils libc++1 libc++abi1
install -d /etc/roverd/profiles /var/lib/roverd
if [[ ! -f /etc/roverd.json ]]; then
/usr/local/bin/roverd -print-default-config > /etc/roverd.json.new
chmod 600 /etc/roverd.json.new
python3 - <<'PYCONFIG'
import json, os
path = '/etc/roverd.json.new'
with open(path) as f:
config = json.load(f)
config['name'] = os.environ.get('ROVERD_INITIAL_NAME', config['name'])
config['serverUrl'] = os.environ.get('ROVERD_INITIAL_SERVER', config['serverUrl'])
with open(path, 'w') as f:
json.dump(config, f, indent=2)
PYCONFIG
/usr/local/bin/roverd -config /etc/roverd.json.new -check-config
mv /etc/roverd.json.new /etc/roverd.json
echo 'Initial configuration created. Configure devices and enabled profiles through Fleet Management.'
fi
install -m 0644 rover/systemd/roverd.service /etc/systemd/system/roverd.service
# Use this checkout directly for catalogs and command resources.
install -d /etc/systemd/system/roverd.service.d
printf '[Service]\nExecStart=\nExecStart=/usr/local/bin/roverd -config /etc/roverd.json -repo "%s"\n' "$REPO_ROOT" > /etc/systemd/system/roverd.service.d/repository.conf
install -m 0755 rover/bin/chromegtts-daemon.py /usr/local/bin/chromegtts-daemon
bash rover/bin/setup-tts.sh
printf -v quoted_repo_root '%q' "$REPO_ROOT"
printf 'ROVERD_REPO_DIR=%s\n' "$quoted_repo_root" > /etc/roverd-update.env
chmod 0600 /etc/roverd-update.env
install -D -o root -g root -m 0755 rover/bin/roverd-self-update.sh /usr/local/sbin/roverd-self-update.new
# Keep the running updater on its original inode until it exits.
mv -f /usr/local/sbin/roverd-self-update.new /usr/local/sbin/roverd-self-update
echo "Registered update checkout at $REPO_ROOT"
# Refuse to report a successful installation with an unusable saved config.
/usr/local/bin/roverd -config /etc/roverd.json -check-config
systemctl daemon-reload
systemctl enable roverd.service
echo 'Installation complete; caller can now restart roverd.'
+37
View File
@@ -0,0 +1,37 @@
- id: alsa
name: ALSA microphone
description: Uses the configured audio input device through roverd's ALSA conversion route.
setup: |
if ! command -v ffmpeg >/dev/null || ! command -v arecord >/dev/null; then
apt-get update && apt-get install -y ffmpeg alsa-utils
fi
run: |
exec ffmpeg -nostdin -f alsa -ar "$ROVER_AUDIO_SAMPLE_RATE" -ac "$ROVER_AUDIO_CHANNELS" -i "$ROVER_AUDIO_INPUT_DEVICE" -c:a libopus -b:a "$ROVER_AUDIO_BITRATE" -f rtsp -rtsp_transport tcp "$ROVER_AUDIO_PUBLISH_URL"
- id: aiy
name: Google AIY Voice HAT microphone
description: Same configurable ALSA route; setup enables the HAT overlay. Reboot once after first enabling its hardware.
setup: |
set -euo pipefail
# Capture/playback setup may run concurrently; serialize edits to boot config.
exec 9>/var/lock/roverd-aiy.lock
flock 9
boot=/boot/firmware/config.txt
[[ -f "$boot" ]] || boot=/boot/config.txt
[[ -f "$boot" ]] || { echo 'AIY setup needs a Raspberry Pi boot config.txt' >&2; exit 1; }
changed=0
for setting in dtparam=i2s=on dtoverlay=googlevoicehat-soundcard; do
if ! grep -Fxq "$setting" "$boot"; then
# Leave any model-specific section before adding shared HAT settings.
if [[ "$changed" == 0 ]]; then printf '\n[all]\n' >> "$boot"; fi
printf '%s\n' "$setting" >> "$boot"
changed=1
fi
done
if [[ "$changed" == 1 ]]; then
echo 'AIY hardware enabled. Reboot the host once before using this sound card.'
fi
if ! command -v ffmpeg >/dev/null || ! command -v aplay >/dev/null; then
apt-get update && apt-get install -y ffmpeg alsa-utils
fi
run: |
exec ffmpeg -nostdin -f alsa -ar "$ROVER_AUDIO_SAMPLE_RATE" -ac "$ROVER_AUDIO_CHANNELS" -i "$ROVER_AUDIO_INPUT_DEVICE" -c:a libopus -b:a "$ROVER_AUDIO_BITRATE" -f rtsp -rtsp_transport tcp "$ROVER_AUDIO_PUBLISH_URL"
+41
View File
@@ -0,0 +1,41 @@
- id: alsa
name: ALSA speaker
description: Uses the configured output alongside TTS and horn with independent volume controls.
setup: |
if ! command -v ffmpeg >/dev/null || ! command -v aplay >/dev/null; then
apt-get update && apt-get install -y ffmpeg alsa-utils
fi
run: |
filters=()
if [ "$ROVER_AUDIO_NORMALIZE" = true ]; then filters=(-af "$ROVER_AUDIO_NORMALIZE_FILTER"); fi
exec ffmpeg -nostdin -rtsp_transport tcp -i "$ROVER_AUDIO_PLAYBACK_URL" -vn "${filters[@]}" -f alsa "$ROVER_AUDIO_OUTPUT_DEVICE"
- id: aiy
name: Google AIY Voice HAT speaker
description: Enables the HAT hardware; uses the same configured ALSA routing as other devices. Reboot once after initial setup.
setup: |
set -euo pipefail
# Capture/playback setup may run concurrently; serialize edits to boot config.
exec 9>/var/lock/roverd-aiy.lock
flock 9
boot=/boot/firmware/config.txt
[[ -f "$boot" ]] || boot=/boot/config.txt
[[ -f "$boot" ]] || { echo 'AIY setup needs a Raspberry Pi boot config.txt' >&2; exit 1; }
changed=0
for setting in dtparam=i2s=on dtoverlay=googlevoicehat-soundcard; do
if ! grep -Fxq "$setting" "$boot"; then
# Leave any model-specific section before adding shared HAT settings.
if [[ "$changed" == 0 ]]; then printf '\n[all]\n' >> "$boot"; fi
printf '%s\n' "$setting" >> "$boot"
changed=1
fi
done
if [[ "$changed" == 1 ]]; then
echo 'AIY hardware enabled. Reboot the host once before using this sound card.'
fi
if ! command -v ffmpeg >/dev/null || ! command -v aplay >/dev/null; then
apt-get update && apt-get install -y ffmpeg alsa-utils
fi
run: |
filters=()
if [ "$ROVER_AUDIO_NORMALIZE" = true ]; then filters=(-af "$ROVER_AUDIO_NORMALIZE_FILTER"); fi
exec ffmpeg -nostdin -rtsp_transport tcp -i "$ROVER_AUDIO_PLAYBACK_URL" -vn "${filters[@]}" -f alsa "$ROVER_AUDIO_OUTPUT_DEVICE"
+25
View File
@@ -0,0 +1,25 @@
- id: v4l2
name: V4L2 camera
description: USB or other Linux V4L2 camera, encoded with software H.264.
setup: |
command -v ffmpeg >/dev/null || { apt-get update && apt-get install -y ffmpeg; }
run: |
filters=()
if [ "$ROVER_VIDEO_INVERTED" = true ]; then filters=(-vf hflip,vflip); fi
exec ffmpeg -nostdin -f v4l2 -input_format "$ROVER_VIDEO_INPUT_FORMAT" -video_size "${ROVER_VIDEO_WIDTH}x${ROVER_VIDEO_HEIGHT}" -framerate "$ROVER_VIDEO_FPS" -i "$ROVER_VIDEO_DEVICE" "${filters[@]}" -an -c:v libx264 -preset ultrafast -tune zerolatency -pix_fmt yuv420p -b:v "$ROVER_VIDEO_BITRATE" -f rtsp -rtsp_transport tcp "$ROVER_VIDEO_PUBLISH_URL"
- id: rpicam
name: Raspberry Pi CSI camera
description: rpicam/libcamera H.264 output, republished through ffmpeg.
setup: |
command -v ffmpeg >/dev/null || { apt-get update && apt-get install -y ffmpeg; }
if ! command -v rpicam-vid >/dev/null && ! command -v libcamera-vid >/dev/null; then
apt-get update
apt-get install -y rpicam-apps
fi
run: |
camera=$(command -v rpicam-vid || command -v libcamera-vid)
options=()
if [ "$ROVER_VIDEO_INVERTED" = true ]; then options+=(--hflip --vflip); fi
if [ -n "$ROVER_VIDEO_SENSOR_MODE" ]; then options+=(--mode "$ROVER_VIDEO_SENSOR_MODE"); fi
"$camera" --timeout 0 --nopreview --inline --codec h264 --width "$ROVER_VIDEO_WIDTH" --height "$ROVER_VIDEO_HEIGHT" --framerate "$ROVER_VIDEO_FPS" --bitrate "$ROVER_VIDEO_BITRATE" "${options[@]}" -o - |
ffmpeg -nostdin -fflags +genpts -f h264 -i pipe:0 -c:v copy -an -f rtsp -rtsp_transport tcp "$ROVER_VIDEO_PUBLISH_URL"
+29
View File
@@ -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-*
@@ -76,7 +76,7 @@ func (c *WSClient) applyMixerGain(control string, gain float64) {
return return
} }
// Convert linear gain to dB, matching softvol max_dB=12.0 in /etc/asound.conf. // Convert linear gain to dB, matching softvol max_dB=12.0 in the generated ALSA routing.
db := 20.0 * math.Log10(normalized) db := 20.0 * math.Log10(normalized)
if db > 12.0 { if db > 12.0 {
db = 12.0 db = 12.0
@@ -100,18 +100,9 @@ func (c *WSClient) applyMixerGain(control string, gain float64) {
} }
func (c *WSClient) trySetMixerControl(control, value string) error { func (c *WSClient) trySetMixerControl(control, value string) error {
// Prefer the active ALSA default route; fall back to card index for compatibility. out, err := exec.Command("amixer", "-q", "-c", c.cfg.Audio.MixerCard, "sset", control, value).CombinedOutput()
candidates := [][]string{ if err != nil {
{"-q", "-D", "default", "sset", control, value}, return fmt.Errorf("%w (%s)", err, string(out))
{"-q", "-c", "0", "sset", control, value},
} }
var lastErr error
for _, args := range candidates {
out, err := exec.Command("amixer", args...).CombinedOutput()
if err == nil {
return nil return nil
} }
lastErr = fmt.Errorf("%w (%s)", err, string(out))
}
return lastErr
}
+60
View File
@@ -0,0 +1,60 @@
package roverd
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
const audioConfigPath = "/var/lib/roverd/asound.conf"
func validateAudioRouting(cfg AudioConfig) error {
for name, value := range map[string]string{"inputDevice": cfg.InputDevice, "outputDevice": cfg.OutputDevice, "mixerCard": cfg.MixerCard} {
if value == "" || strings.ContainsAny(value, "\x00\r\n") {
return fmt.Errorf("audio.%s must be a nonempty single-line ALSA identifier", name)
}
}
return nil
}
// Generate a private ALSA configuration inherited by all roverd children. Do
// not overwrite the host's /etc/asound.conf or impose the AIY card on other hosts.
func AudioConfiguration(cfg AudioConfig) string {
text := "</usr/share/alsa/alsa.conf>\n"
text += fmt.Sprintf(`pcm.rover_capture { type plug slave.pcm %s }
pcm.rover_mix {
type dmix
ipc_key 70601
ipc_key_add_uid true
slave { pcm %s format S16_LE rate %d channels %d }
}
`, strconv.Quote(cfg.InputDevice), strconv.Quote(cfg.OutputDevice), cfg.OutputSampleRate, cfg.OutputChannels)
for _, pair := range [][2]string{{"tts", "TTSMaster"}, {"horn", "HornMaster"}, {"forward", "ForwardMaster"}} {
text += fmt.Sprintf(`pcm.rover_%s_volume {
type softvol
slave.pcm "rover_mix"
control { name %s card %s }
min_dB -60.0
max_dB 12.0
}
pcm.rover_%s { type plug slave.pcm "rover_%s_volume" }
`, pair[0], strconv.Quote(pair[1]), strconv.Quote(cfg.MixerCard), pair[0], pair[0])
}
text += fmt.Sprintf(`pcm.!default { type asym playback.pcm "rover_tts" capture.pcm "rover_capture" }
ctl.!default { type hw card %s }
`, strconv.Quote(cfg.MixerCard))
return text
}
func ConfigureAudio(cfg AudioConfig) error {
text := AudioConfiguration(cfg)
if err := os.MkdirAll(filepath.Dir(audioConfigPath), 0755); err != nil {
return err
}
if err := os.WriteFile(audioConfigPath, []byte(text), 0600); err != nil {
return err
}
return os.Setenv("ALSA_CONFIG_PATH", audioConfigPath)
}
@@ -3,16 +3,19 @@ package roverd
import ( import (
"context" "context"
"log" "log"
"sync"
"time" "time"
) )
const ( const (
autoChargeTimeout = 1 * time.Second autoChargeTimeout = 10 * time.Second
autoChargeCooldown = 0 * time.Minute autoChargeCooldown = 0 * time.Minute
sourceHomeBase = 1 << 1 sourceHomeBase = 1 << 1
) )
type AutoChargeController struct { type AutoChargeController struct {
mu sync.Mutex
paused bool
adapter *SerialAdapter adapter *SerialAdapter
events chan<- RoverEvent events chan<- RoverEvent
logger *log.Logger logger *log.Logger
@@ -42,6 +45,11 @@ func (a *AutoChargeController) Run(ctx context.Context, samples <-chan SensorSam
} }
func (a *AutoChargeController) processSample(sample SensorSample) { func (a *AutoChargeController) processSample(sample SensorSample) {
a.mu.Lock()
defer a.mu.Unlock()
if a.paused {
return
}
now := time.Now() now := time.Now()
docked := sample.ChargeSources&sourceHomeBase != 0 docked := sample.ChargeSources&sourceHomeBase != 0
charging := isCharging(sample.ChargingState) charging := isCharging(sample.ChargingState)
@@ -107,3 +115,12 @@ func (a *AutoChargeController) emitEvent(event string, data map[string]any) {
default: 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{}
}
+19 -5
View File
@@ -1,4 +1,4 @@
//go:build !dummy && !debian_laptop //go:build !dummy
package roverd package roverd
@@ -14,6 +14,7 @@ type BRCPulser struct {
cfg BRCConfig cfg BRCConfig
logger *log.Logger logger *log.Logger
line *gpiocdev.Line line *gpiocdev.Line
done chan struct{}
} }
func NewBRCPulser(cfg BRCConfig, logger *log.Logger) (*BRCPulser, error) { 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 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() { func (b *BRCPulser) Close() {
// The owner cancels the pulse loop before closing its GPIO line.
<-b.done
if b.line != nil { if b.line != nil {
_ = b.line.SetValue(1) _ = b.line.SetValue(1)
b.line.Close() b.line.Close()
@@ -44,11 +47,15 @@ func (b *BRCPulser) Close() {
func (b *BRCPulser) Start(ctx context.Context) { func (b *BRCPulser) Start(ctx context.Context) {
go func() { go func() {
defer close(b.done)
ticker := time.NewTicker(b.cfg.PulseEvery.Duration) ticker := time.NewTicker(b.cfg.PulseEvery.Duration)
defer ticker.Stop() defer ticker.Stop()
for { for {
b.pulseOnce() if ctx.Err() != nil {
return
}
b.pulseOnce(ctx)
select { select {
case <-ctx.Done(): case <-ctx.Done():
return 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 { if b.line == nil {
return return
} }
@@ -66,7 +73,14 @@ func (b *BRCPulser) pulseOnce() {
b.logger.Printf("brc pulse low: %v", err) b.logger.Printf("brc pulse low: %v", err)
return 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 { if err := b.line.SetValue(1); err != nil {
b.logger.Printf("brc pulse high: %v", err) b.logger.Printf("brc pulse high: %v", err)
} }
@@ -1,4 +1,4 @@
//go:build !dummy && !debian_laptop //go:build !dummy
package roverd package roverd
@@ -10,7 +10,7 @@ import (
"os" "os"
"time" "time"
roverd "multiroombarover/pi/roverd" roverd "multiroombarover/rover/roverd"
"github.com/tarm/serial" "github.com/tarm/serial"
) )
+200
View File
@@ -0,0 +1,200 @@
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
roverd "multiroombarover/rover/roverd"
)
func main() {
var cfgPath string
var repoPath string
flag.StringVar(&repoPath, "repo", "/opt/roverd", "managed repository checkout")
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")
printProfiles := flag.Bool("print-media-profiles", false, "read and print media profiles without running commands")
printAudio := flag.Bool("print-audio-config", false, "print generated ALSA configuration without installing it")
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 *printProfiles {
profiles, err := roverd.LoadMediaProfiles(repoPath)
if err != nil {
log.Fatal(err)
}
data, _ := json.MarshalIndent(profiles, "", " ")
fmt.Println(string(data))
return
}
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 *printAudio {
fmt.Print(roverd.AudioConfiguration(cfg.Audio))
return
}
if *checkConfig {
fmt.Println("Configuration valid")
return
}
if run(cfg, cfgPath, repoPath) {
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, repoPath 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() })
if err := roverd.ConfigureAudio(cfg.Audio); err != nil {
console.Notify(fmt.Sprintf("Audio routing unavailable: %v", err))
}
media, err := roverd.NewMediaSupervisor(cfg, repoPath, events, logger)
if err != nil {
console.Notify(fmt.Sprintf("Media profiles unavailable: %v", err))
}
management.SetMedia(media)
management.SetRepository(repoPath)
managementDone := make(chan struct{})
go func() { defer close(managementDone); management.Run(ctx) }()
if media != nil {
media.Start(ctx)
defer media.Stop()
}
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 {
return fmt.Errorf("open serial: %w", err)
}
defer serialPort.Close()
// Peripheral discovery is intentionally a boot-time operation. The manager
// keeps successful USB ports open across server WebSocket reconnects and is
// rebuilt only when the roverd process itself restarts.
peripherals, err := roverd.DiscoverPeripheralManager(ctx, cfg.Serial.Device, logger)
if err != nil {
console.Notify(fmt.Sprintf("Rover peripheral startup failed: %v", err))
return fmt.Errorf("discover rover peripherals: %w", err)
}
defer peripherals.Close()
sensorFrames := make(chan []byte, 8)
sensorSamples := make(chan roverd.SensorSample, 8)
streamer := roverd.NewSensorStreamer(serialPort, sensorFrames, sensorSamples, logger)
go streamer.Run(ctx)
adapter := roverd.NewSerialAdapter(serialPort, logger)
// 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))
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)
}
// A peripheral is never hot-reconnected. Report the first terminal serial
// failure for each discovered board and tell the local operator exactly what
// recovery action the fixed boot-time lifecycle requires.
go func() {
for {
select {
case failure := <-peripherals.Failures():
console.Notify(fmt.Sprintf(
"Rover peripheral %q (%s) disconnected: %v. Reconnect it and restart roverd.",
failure.Name,
failure.ID,
failure.Err,
))
case <-ctx.Done():
return
}
}
}()
autoCharge := roverd.NewAutoChargeController(adapter, eventStream, logger)
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()
// 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.")
retryDelay := time.Second
for ctx.Err() == nil {
if err := client.Run(ctx); err != nil {
logger.Printf("websocket loop ended: %v", err)
}
select {
case <-ctx.Done():
return nil
case <-time.After(retryDelay):
}
if retryDelay < 30*time.Second {
retryDelay *= 2
}
}
return nil
}
@@ -9,7 +9,7 @@ type helloMessage struct {
Color string `json:"color,omitempty"` Color string `json:"color,omitempty"`
Battery BatteryConfig `json:"battery"` Battery BatteryConfig `json:"battery"`
MaxWheelSpeed int `json:"maxWheelSpeed"` MaxWheelSpeed int `json:"maxWheelSpeed"`
Media MediaConfig `json:"media"` Media any `json:"media"`
CameraServo CameraServoConfig `json:"cameraServo"` CameraServo CameraServoConfig `json:"cameraServo"`
Audio AudioConfig `json:"audio"` Audio AudioConfig `json:"audio"`
Horn HornConfig `json:"horn"` Horn HornConfig `json:"horn"`
@@ -27,7 +27,7 @@ type sensorMessage struct {
// hostStatsMessage is intentionally separate from sensorMessage because sensor // hostStatsMessage is intentionally separate from sensorMessage because sensor
// frames are raw Roomba Open Interface data, while these values describe the // frames are raw Roomba Open Interface data, while these values describe the
// Raspberry Pi host that is running roverd. // Linux host that is running roverd.
type hostStatsMessage struct { type hostStatsMessage struct {
Type string `json:"type"` Type string `json:"type"`
Timestamp int64 `json:"ts"` Timestamp int64 `json:"ts"`
@@ -41,7 +41,6 @@ type inboundMessage struct {
MotorPWM *motorPWMPayload `json:"motorPwm,omitempty"` MotorPWM *motorPWMPayload `json:"motorPwm,omitempty"`
Raw string `json:"raw,omitempty"` Raw string `json:"raw,omitempty"`
SensorStream *sensorStreamPayload `json:"sensorStream,omitempty"` SensorStream *sensorStreamPayload `json:"sensorStream,omitempty"`
Media *mediaCommand `json:"media,omitempty"`
Servo *servoPayload `json:"servo,omitempty"` Servo *servoPayload `json:"servo,omitempty"`
TTS *ttsPayload `json:"tts,omitempty"` TTS *ttsPayload `json:"tts,omitempty"`
Horn *hornPayload `json:"horn,omitempty"` Horn *hornPayload `json:"horn,omitempty"`
@@ -50,11 +49,6 @@ type inboundMessage struct {
Laser *togglePayload `json:"laser,omitempty"` Laser *togglePayload `json:"laser,omitempty"`
Peripheral *peripheralPayload `json:"peripheral,omitempty"` Peripheral *peripheralPayload `json:"peripheral,omitempty"`
Song *songPayload `json:"song,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 { type driveDirectPayload struct {
@@ -72,10 +66,6 @@ type sensorStreamPayload struct {
Enable bool `json:"enable"` Enable bool `json:"enable"`
} }
type mediaCommand struct {
Action string `json:"action"`
}
type servoPayload struct { type servoPayload struct {
Angle *float64 `json:"angle,omitempty"` Angle *float64 `json:"angle,omitempty"`
Nudge *float64 `json:"nudge,omitempty"` Nudge *float64 `json:"nudge,omitempty"`
@@ -128,8 +118,6 @@ type rebootPayload struct {
DelayMs int `json:"delayMs,omitempty"` DelayMs int `json:"delayMs,omitempty"`
} }
type updatePayload struct{}
type ackMessage struct { type ackMessage struct {
Type string `json:"type"` Type string `json:"type"`
ID string `json:"id"` ID string `json:"id"`
+245 -224
View File
@@ -11,21 +11,23 @@ import (
"strings" "strings"
"time" "time"
"gopkg.in/yaml.v3" "bytes"
"encoding/json"
"io"
) )
type SerialConfig struct { type SerialConfig struct {
Device string `yaml:"device"` Device string `json:"device"`
Baud int `yaml:"baud"` Baud int `json:"baud" jsonschema:"minimum=1"`
} }
type Duration struct { type Duration struct {
time.Duration time.Duration
} }
func (d *Duration) UnmarshalYAML(value *yaml.Node) error { func (d *Duration) UnmarshalJSON(data []byte) error {
var raw string var raw string
if err := value.Decode(&raw); err != nil { if err := json.Unmarshal(data, &raw); err != nil {
return err return err
} }
parsed, err := time.ParseDuration(raw) parsed, err := time.ParseDuration(raw)
@@ -36,130 +38,119 @@ func (d *Duration) UnmarshalYAML(value *yaml.Node) error {
return nil return nil
} }
func (d Duration) MarshalYAML() (interface{}, error) { func (d Duration) MarshalJSON() ([]byte, error) { return json.Marshal(d.Duration.String()) }
return d.Duration.String(), nil
}
type BRCConfig struct { type BRCConfig struct {
GPIOPin int `yaml:"gpioPin"` Enabled bool `json:"enabled"`
GPIOChip string `yaml:"gpioChip"` GPIOPin int `json:"gpioPin"`
PulseEvery Duration `yaml:"pulseEvery"` GPIOChip string `json:"gpioChip"`
PulseWidth Duration `yaml:"pulseWidth"` PulseEvery Duration `json:"pulseEvery"`
} PulseWidth Duration `json:"pulseWidth"`
func (b BRCConfig) Enabled() bool {
return b.GPIOPin >= 0
} }
type BatteryConfig struct { type BatteryConfig struct {
Full int `yaml:"full"` Full int `json:"full"`
Warn int `yaml:"warn"` Warn int `json:"warn"`
Urgent int `yaml:"urgent"` Urgent int `json:"urgent"`
} }
type AudioConfig struct { type AudioConfig struct {
// AudioConfig is only for sounds generated by roverd itself. Live capture InputDevice string `json:"inputDevice" jsonschema:"minLength=1"`
// and playback are media-publisher concerns, so those settings live under OutputDevice string `json:"outputDevice" jsonschema:"minLength=1"`
// MediaConfig where they can be written directly into media.env. MixerCard string `json:"mixerCard" jsonschema:"minLength=1"`
TTSEnabled bool `yaml:"ttsEnabled" json:"ttsEnabled"` OutputSampleRate int `json:"outputSampleRate" jsonschema:"minimum=8000,maximum=192000"`
DefaultEngine string `yaml:"defaultEngine" json:"defaultEngine,omitempty"` OutputChannels int `json:"outputChannels" jsonschema:"minimum=1,maximum=8"`
DefaultVoice string `yaml:"defaultVoice" json:"defaultVoice,omitempty"` TTSEnabled bool `json:"ttsEnabled"`
DefaultPitch int `yaml:"defaultPitch" json:"defaultPitch,omitempty"` DefaultEngine string `json:"defaultEngine"`
DefaultVoice string `json:"defaultVoice"`
DefaultPitch int `json:"defaultPitch"`
} }
type HornConfig struct { type HornConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"` Enabled bool `json:"enabled"`
Volume float64 `yaml:"volume" json:"-"` Volume float64 `json:"volume"`
SampleRate int `yaml:"sampleRate" json:"-"` SampleRate int `json:"sampleRate"`
Channels int `yaml:"channels" json:"-"` Channels int `json:"channels"`
Device string `yaml:"device" json:"-"` SineGain float64 `json:"sineGain"`
SineGain float64 `yaml:"sineGain" json:"-"` SawGain float64 `json:"sawGain"`
SawGain float64 `yaml:"sawGain" json:"-"` MaxDuration Duration `json:"maxDuration"`
MaxDuration Duration `yaml:"maxDuration" json:"-"`
} }
type MediaConfig struct { type MediaConfig struct {
// RTSPPort is shared by the derived video, microphone, and forwarded-audio // RTSPPort is shared by the derived video, microphone, and forwarded-audio
// RTSP URLs. Keeping it at this level prevents each nested block from needing // 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. // to repeat the same server port when the common MediaMTX listener is used.
RTSPPort int `yaml:"rtspPort" json:"-"` RTSPPort int `json:"rtspPort" jsonschema:"minimum=1,maximum=65535"`
Manage bool `yaml:"manage" json:"manage"` Video VideoMediaConfig `json:"video"`
HealthURL string `yaml:"healthUrl" json:"healthUrl,omitempty"` AudioCapture AudioCaptureConfig `json:"audioCapture"`
HealthInterval Duration `yaml:"healthInterval" json:"-"` AudioPlayback AudioPlaybackConfig `json:"audioPlayback"`
Video VideoMediaConfig `yaml:"video" json:"video"`
AudioCapture AudioCaptureConfig `yaml:"audioCapture" json:"audioCapture"`
AudioPlayback AudioPlaybackConfig `yaml:"audioPlayback" json:"audioPlayback"`
} }
type VideoMediaConfig struct { type VideoMediaConfig struct {
// Publisher selects the installed publisher script/pipeline family. The Profile string `json:"profile" jsonschema:"minLength=1"`
// first pass uses pi-libcamera for current rovers; laptop-v4l2 can be added Enabled bool `json:"enabled"`
// 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"`
// PublishURL is derived during validation. It remains in rover metadata for server-side // 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. // consumers through MediaMetadata, but is never persisted in configuration.
PublishURL string `yaml:"-" json:"publishUrl,omitempty"` PublishURL string `json:"-"`
Device string `yaml:"device" json:"device,omitempty"` Device string `json:"device"`
InputFormat string `yaml:"inputFormat" json:"-"` InputFormat string `json:"inputFormat"`
Width int `yaml:"width" json:"-"` Width int `json:"width"`
Height int `yaml:"height" json:"-"` Height int `json:"height"`
FPS int `yaml:"fps" json:"-"` FPS int `json:"fps"`
Bitrate int `yaml:"bitrate" json:"-"` Bitrate int `json:"bitrate"`
Inverted bool `yaml:"inverted" json:"-"` Inverted bool `json:"inverted"`
SensorMode string `yaml:"sensorMode" json:"-"` SensorMode string `json:"sensorMode"`
} }
type AudioCaptureConfig struct { type AudioCaptureConfig struct {
Profile string `json:"profile" jsonschema:"minLength=1"`
// AudioCapture describes the rover microphone stream that browsers can // AudioCapture describes the rover microphone stream that browsers can
// subscribe to as "<rover>-audio". A disabled capture block still has // subscribe to as "<rover>-audio". A disabled capture block still has
// normalized defaults so enabling it only requires flipping enabled: true. // normalized defaults so enabling it only requires flipping enabled: true.
Enabled bool `yaml:"enabled" json:"enabled"` Enabled bool `json:"enabled"`
Service string `yaml:"service" json:"service,omitempty"`
// PublishURL follows the same derived-only contract as the video path. // PublishURL follows the same derived-only contract as the video path.
PublishURL string `yaml:"-" json:"publishUrl,omitempty"` PublishURL string `json:"-"`
Device string `yaml:"device" json:"device,omitempty"`
SampleRate int `yaml:"sampleRate" json:"-"` SampleRate int `json:"sampleRate"`
Channels int `yaml:"channels" json:"-"` Channels int `json:"channels"`
Bitrate int `yaml:"bitrate" json:"-"` Bitrate int `json:"bitrate"`
} }
type AudioPlaybackConfig struct { type AudioPlaybackConfig struct {
Profile string `json:"profile" jsonschema:"minLength=1"`
// AudioPlayback describes the reverse stream that VIP users publish into // AudioPlayback describes the reverse stream that VIP users publish into
// MediaMTX for playback on the rover speaker. The URL is a request/read URL // 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 // for the rover listener, while the server converts it to publish mode when
// it needs to inject audio. // it needs to inject audio.
Enabled bool `yaml:"enabled" json:"enabled"` Enabled bool `json:"enabled"`
Service string `yaml:"service" json:"service,omitempty"`
// ForwardURL is derived because the server and rover must agree on the exact -fwd path. // ForwardURL is derived because the server and rover must agree on the exact -fwd path.
ForwardURL string `yaml:"-" json:"forwardUrl,omitempty"` ForwardURL string `json:"-"`
Device string `yaml:"device" json:"device,omitempty"`
Normalize bool `yaml:"normalize" json:"-"` Normalize bool `json:"normalize"`
NormalizeFilter string `yaml:"normalizeFilter" json:"-"` NormalizeFilter string `json:"normalizeFilter"`
} }
type CameraServoConfig struct { type CameraServoConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"` Enabled bool `json:"enabled"`
Pin int `yaml:"pin" json:"pin"` Pin int `json:"pin"`
FreqHz int `yaml:"freqHz" json:"freqHz"` FreqHz int `json:"freqHz"`
CycleLen int `yaml:"cycleLen" json:"cycleLen"` CycleLen int `json:"cycleLen"`
MinPulseUs int `yaml:"minPulseUs" json:"minPulseUs"` MinPulseUs int `json:"minPulseUs"`
MaxPulseUs int `yaml:"maxPulseUs" json:"maxPulseUs"` MaxPulseUs int `json:"maxPulseUs"`
MinAngle float64 `yaml:"minAngle" json:"minAngle"` MinAngle float64 `json:"minAngle"`
MaxAngle float64 `yaml:"maxAngle" json:"maxAngle"` MaxAngle float64 `json:"maxAngle"`
HomeAngle float64 `yaml:"homeAngle" json:"homeAngle"` HomeAngle float64 `json:"homeAngle"`
NudgeDegrees float64 `yaml:"nudgeDegrees" json:"nudgeDegrees"` NudgeDegrees float64 `json:"nudgeDegrees"`
AllowRawPulse bool `yaml:"allowRawPulse" json:"allowRawPulse"` AllowRawPulse bool `json:"allowRawPulse"`
Invert bool `yaml:"invert" json:"invert"` Invert bool `json:"invert"`
} }
type GPIOToggleConfig struct { type GPIOToggleConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"` Enabled bool `json:"enabled"`
GPIOPin int `yaml:"gpioPin" json:"gpioPin"` GPIOPin int `json:"gpioPin"`
GPIOChip string `yaml:"gpioChip" json:"gpioChip"` GPIOChip string `json:"gpioChip"`
InitialOn bool `yaml:"initialOn" json:"initialOn"` InitialOn bool `json:"initialOn"`
ActiveLow bool `yaml:"activeLow" json:"activeLow"` ActiveLow bool `json:"activeLow"`
} }
func (g GPIOToggleConfig) LogicalToGPIO(on bool) int { func (g GPIOToggleConfig) LogicalToGPIO(on bool) int {
@@ -173,59 +164,66 @@ func (g GPIOToggleConfig) LogicalToGPIO(on bool) int {
} }
type AutoSideBrushConfig struct { type AutoSideBrushConfig struct {
Enabled bool `yaml:"enabled"` Enabled bool `json:"enabled"`
Speed int `yaml:"speed"` Speed int `json:"speed"`
} }
type PrivateConfig struct { type PrivateConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"` Enabled bool `json:"enabled"`
Safety PrivateSafetyConfig `yaml:"safety" json:"safety"` Safety PrivateSafetyConfig `json:"safety"`
} }
type PrivateSafetyConfig struct { type PrivateSafetyConfig struct {
SpeedLimitEnabled bool `yaml:"speedLimitEnabled" json:"speedLimitEnabled"` SpeedLimitEnabled bool `json:"speedLimitEnabled"`
SpeedLimitMaxWheelMMs int `yaml:"speedLimitMaxWheelSpeed" json:"speedLimitMaxWheelSpeed"` SpeedLimitMaxWheelMMs int `json:"speedLimitMaxWheelSpeed"`
HardOvercurrentEnabled bool `yaml:"hardOvercurrentEnabled" json:"hardOvercurrentEnabled"` HardOvercurrentEnabled bool `json:"hardOvercurrentEnabled"`
OvercurrentStopMs int `yaml:"overcurrentStopMs" json:"overcurrentStopMs"` OvercurrentStopMs int `json:"overcurrentStopMs"`
HardBumpEnabled bool `yaml:"hardBumpEnabled" json:"hardBumpEnabled"` HardBumpEnabled bool `json:"hardBumpEnabled"`
BumpBackoffSpeed int `yaml:"bumpBackoffSpeed" json:"bumpBackoffSpeed"` BumpBackoffSpeed int `json:"bumpBackoffSpeed"`
BumpBackoffMs int `yaml:"bumpBackoffMs" json:"bumpBackoffMs"` BumpBackoffMs int `json:"bumpBackoffMs"`
CliffEnabled bool `yaml:"cliffEnabled" json:"cliffEnabled"` CliffEnabled bool `json:"cliffEnabled"`
CliffBackoffSpeed int `yaml:"cliffBackoffSpeed" json:"cliffBackoffSpeed"` CliffBackoffSpeed int `json:"cliffBackoffSpeed"`
CliffBackoffMs int `yaml:"cliffBackoffMs" json:"cliffBackoffMs"` CliffBackoffMs int `json:"cliffBackoffMs"`
VirtualWallEnabled bool `yaml:"virtualWallEnabled" json:"virtualWallEnabled"` VirtualWallEnabled bool `json:"virtualWallEnabled"`
VirtualWallBackoffSpeed int `yaml:"virtualWallBackoffSpeed" json:"virtualWallBackoffSpeed"` VirtualWallBackoffSpeed int `json:"virtualWallBackoffSpeed"`
VirtualWallBackoffMs int `yaml:"virtualWallBackoffMs" json:"virtualWallBackoffMs"` VirtualWallBackoffMs int `json:"virtualWallBackoffMs"`
TriggerCooldownMs int `yaml:"triggerCooldownMs" json:"triggerCooldownMs"` 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 { type Config struct {
Name string `yaml:"name"` PiGPIO PiGPIOConfig `json:"piGpio"`
Description string `yaml:"description" json:"description,omitempty"` Name string `json:"name" jsonschema:"minLength=1"`
Color string `yaml:"color" json:"color,omitempty"` Description string `json:"description"`
ServerURL string `yaml:"serverUrl"` Color string `json:"color"`
Serial SerialConfig `yaml:"serial"` ServerURL string `json:"serverUrl" jsonschema:"minLength=1"`
BRC BRCConfig `yaml:"brc"` Serial SerialConfig `json:"serial"`
Battery BatteryConfig `yaml:"battery"` Battery BatteryConfig `json:"battery"`
MaxWheelMMs int `yaml:"maxWheelSpeed"` MaxWheelMMs int `json:"maxWheelSpeed" jsonschema:"minimum=1,maximum=500"`
Media MediaConfig `yaml:"media"` Media MediaConfig `json:"media"`
CameraServo CameraServoConfig `yaml:"cameraServo"` Audio AudioConfig `json:"audio"`
Audio AudioConfig `yaml:"audio"` Horn HornConfig `json:"horn"`
Horn HornConfig `yaml:"horn"` AutoSideBrush AutoSideBrushConfig `json:"autoSideBrush"`
Headlight GPIOToggleConfig `yaml:"headlight" json:"headlight"` Private PrivateConfig `json:"private"`
Laser GPIOToggleConfig `yaml:"laser" json:"laser"`
AutoSideBrush AutoSideBrushConfig `yaml:"autoSideBrush"`
Private PrivateConfig `yaml:"private" json:"private"`
} }
func LoadConfig(path string) (*Config, error) { // DefaultConfig supplies initial settings; persisted and remotely submitted
data, err := os.ReadFile(path) // configuration is always a complete object.
if err != nil { func DefaultConfig() Config {
return nil, err
}
cfg := Config{ cfg := Config{
MaxWheelMMs: 500, 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{ BRC: BRCConfig{
Enabled: true,
GPIOPin: 4, GPIOPin: 4,
GPIOChip: "gpiochip0", GPIOChip: "gpiochip0",
PulseEvery: Duration{ PulseEvery: Duration{
@@ -235,36 +233,6 @@ func LoadConfig(path string) (*Config, error) {
Duration: time.Second, Duration: time.Second,
}, },
}, },
Media: MediaConfig{
RTSPPort: 8554,
HealthInterval: Duration{Duration: 30 * time.Second},
Video: VideoMediaConfig{
Enabled: true,
Service: "video-publisher.service",
Publisher: "pi-libcamera",
Width: 640,
Height: 480,
FPS: 30,
Bitrate: 2000000,
Inverted: true,
SensorMode: "1296:972",
},
AudioCapture: AudioCaptureConfig{
Enabled: false,
Service: "audio-only-publisher.service",
Device: "hw:0,0",
SampleRate: 48000,
Channels: 2,
Bitrate: 510000,
},
AudioPlayback: AudioPlaybackConfig{
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",
},
},
CameraServo: CameraServoConfig{ CameraServo: CameraServoConfig{
Pin: 12, Pin: 12,
FreqHz: 50, FreqHz: 50,
@@ -276,21 +244,6 @@ func LoadConfig(path string) (*Config, error) {
HomeAngle: 0, HomeAngle: 0,
NudgeDegrees: 2, NudgeDegrees: 2,
}, },
Audio: AudioConfig{
TTSEnabled: false,
DefaultEngine: "flite",
DefaultVoice: "rms",
DefaultPitch: 50,
},
Horn: HornConfig{
Enabled: false,
Volume: 0.25,
SampleRate: 48000,
Channels: 1,
SineGain: 1.0,
SawGain: 0.7,
MaxDuration: Duration{Duration: 10000 * time.Millisecond},
},
Headlight: GPIOToggleConfig{ Headlight: GPIOToggleConfig{
Enabled: true, Enabled: true,
GPIOPin: 22, GPIOPin: 22,
@@ -305,6 +258,55 @@ func LoadConfig(path string) (*Config, error) {
InitialOn: false, InitialOn: false,
ActiveLow: false, ActiveLow: false,
}, },
},
MaxWheelMMs: 500,
Media: MediaConfig{
RTSPPort: 8554,
Video: VideoMediaConfig{
Profile: "v4l2",
Enabled: true,
Device: "/dev/video0", InputFormat: "mjpeg",
Width: 640,
Height: 480,
FPS: 30,
Bitrate: 2000000,
Inverted: false,
SensorMode: "",
},
AudioCapture: AudioCaptureConfig{
Profile: "alsa",
Enabled: true,
SampleRate: 48000,
Channels: 2,
Bitrate: 510000,
},
AudioPlayback: AudioPlaybackConfig{
Profile: "alsa",
Enabled: true,
Normalize: true,
NormalizeFilter: "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled",
},
},
Audio: AudioConfig{
InputDevice: "hw:0,0", OutputDevice: "hw:0,0", MixerCard: "0", OutputSampleRate: 48000, OutputChannels: 2,
TTSEnabled: true,
DefaultEngine: "google",
DefaultVoice: "rms",
DefaultPitch: 50,
},
Horn: HornConfig{
Enabled: true,
Volume: 0.25,
SampleRate: 48000,
Channels: 1,
SineGain: 1.0,
SawGain: 0.7,
MaxDuration: Duration{Duration: 10000 * time.Millisecond},
},
AutoSideBrush: AutoSideBrushConfig{ AutoSideBrush: AutoSideBrushConfig{
Enabled: true, Enabled: true,
Speed: 20, Speed: 20,
@@ -329,51 +331,88 @@ func LoadConfig(path string) (*Config, error) {
}, },
}, },
} }
if err := yaml.Unmarshal(data, &cfg); err != nil { return cfg
return nil, err
} }
if cfg.Name == "" {
return nil, errors.New("missing name") func LoadConfig(path string) (*Config, error) {
} data, err := os.ReadFile(path)
normalizedColor, err := normalizeHexColor(cfg.Color)
if err != nil { if err != nil {
return nil, err 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 cfg.Color = normalizedColor
if cfg.ServerURL == "" { server, err := url.Parse(cfg.ServerURL)
return nil, errors.New("missing 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 { 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 { 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 { 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 == "" { if cfg.PiGPIO.BRC.GPIOChip == "" {
cfg.BRC.GPIOChip = "gpiochip0" cfg.PiGPIO.BRC.GPIOChip = "gpiochip0"
} }
if cfg.Media.RTSPPort <= 0 { if cfg.Media.RTSPPort <= 0 {
cfg.Media.RTSPPort = 8554 cfg.Media.RTSPPort = 8554
} }
if err := validateMediaConfig(&cfg.Media, cfg.ServerURL, cfg.Name); err != nil { 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 { if cfg.PiGPIO.Enabled {
return nil, fmt.Errorf("cameraServo: %w", err) if err := validateServoConfig(&cfg.PiGPIO.CameraServo); err != nil {
return fmt.Errorf("cameraServo: %w", err)
} }
if err := validateGPIOToggleConfig(&cfg.Headlight); err != nil { if err := validateGPIOToggleConfig(&cfg.PiGPIO.Headlight); err != nil {
return nil, fmt.Errorf("headlight: %w", err) return fmt.Errorf("headlight: %w", err)
} }
if err := validateGPIOToggleConfig(&cfg.Laser); err != nil { if err := validateGPIOToggleConfig(&cfg.PiGPIO.Laser); err != nil {
return nil, fmt.Errorf("laser: %w", err) 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")
}
}
if err := validateAudioRouting(cfg.Audio); err != nil {
return err
} }
validateAudioConfig(&cfg.Audio) validateAudioConfig(&cfg.Audio)
validateHornConfig(&cfg.Horn) validateHornConfig(&cfg.Horn)
validateAutoSideBrushConfig(&cfg.AutoSideBrush) validateAutoSideBrushConfig(&cfg.AutoSideBrush)
return &cfg, nil return nil
} }
func validateServoConfig(cfg *CameraServoConfig) error { func validateServoConfig(cfg *CameraServoConfig) error {
@@ -421,7 +460,7 @@ func clampFloat(value, min, max float64) float64 {
func validateAudioConfig(cfg *AudioConfig) { func validateAudioConfig(cfg *AudioConfig) {
if cfg.DefaultEngine == "" { if cfg.DefaultEngine == "" {
cfg.DefaultEngine = "flite" cfg.DefaultEngine = "google"
} }
if cfg.DefaultVoice == "" { if cfg.DefaultVoice == "" {
cfg.DefaultVoice = "rms" cfg.DefaultVoice = "rms"
@@ -432,18 +471,10 @@ func validateAudioConfig(cfg *AudioConfig) {
} }
func validateMediaConfig(cfg *MediaConfig, serverURL string, roverName string) error { func validateMediaConfig(cfg *MediaConfig, serverURL string, roverName string) error {
/* // Normalize shared settings before they become profile command variables.
The nested media config is the source of truth for the publisher scripts,
so defaults that used to live in shell are normalized here before any env
file is written. This keeps the Pi behavior stable while making laptop
and future publisher variants explicit configuration choices.
*/
if cfg.RTSPPort <= 0 { if cfg.RTSPPort <= 0 {
cfg.RTSPPort = 8554 cfg.RTSPPort = 8554
} }
if cfg.HealthInterval.Duration <= 0 {
cfg.HealthInterval = Duration{Duration: 30 * time.Second}
}
if err := validateVideoMediaConfig(&cfg.Video, serverURL, roverName, cfg.RTSPPort); err != nil { if err := validateVideoMediaConfig(&cfg.Video, serverURL, roverName, cfg.RTSPPort); err != nil {
return fmt.Errorf("video: %w", err) return fmt.Errorf("video: %w", err)
} }
@@ -457,12 +488,6 @@ func validateMediaConfig(cfg *MediaConfig, serverURL string, roverName string) e
} }
func validateVideoMediaConfig(cfg *VideoMediaConfig, serverURL string, roverName string, rtspPort int) error { func validateVideoMediaConfig(cfg *VideoMediaConfig, serverURL string, roverName string, rtspPort int) error {
if cfg.Service == "" {
cfg.Service = "video-publisher.service"
}
if cfg.Publisher == "" {
cfg.Publisher = "pi-libcamera"
}
// V4L2 input formats are consumed by ffmpeg as lowercase names such as // V4L2 input formats are consumed by ffmpeg as lowercase names such as
// mjpeg or yuyv422. Normalizing here keeps the publisher script simple and // mjpeg or yuyv422. Normalizing here keeps the publisher script simple and
// makes hand-edited Debian laptop configs less sensitive to capitalization. // makes hand-edited Debian laptop configs less sensitive to capitalization.
@@ -479,9 +504,6 @@ func validateVideoMediaConfig(cfg *VideoMediaConfig, serverURL string, roverName
if cfg.Bitrate <= 0 { if cfg.Bitrate <= 0 {
cfg.Bitrate = 2000000 cfg.Bitrate = 2000000
} }
if cfg.SensorMode == "" && cfg.Publisher == "pi-libcamera" {
cfg.SensorMode = "1296:972"
}
/* /*
Always derive this endpoint. Older rover configs can contain an explicit SRT publishUrl; Always derive this endpoint. Older rover configs can contain an explicit SRT publishUrl;
honoring it after a binary update would silently leave that rover on the old transport. honoring it after a binary update would silently leave that rover on the old transport.
@@ -495,12 +517,6 @@ func validateVideoMediaConfig(cfg *VideoMediaConfig, serverURL string, roverName
} }
func validateAudioCaptureConfig(cfg *AudioCaptureConfig, serverURL string, roverName string, rtspPort int) error { func validateAudioCaptureConfig(cfg *AudioCaptureConfig, serverURL string, roverName string, rtspPort int) error {
if cfg.Service == "" {
cfg.Service = "audio-only-publisher.service"
}
if cfg.Device == "" {
cfg.Device = "hw:0,0"
}
if cfg.SampleRate <= 0 { if cfg.SampleRate <= 0 {
cfg.SampleRate = 48000 cfg.SampleRate = 48000
} }
@@ -519,12 +535,6 @@ func validateAudioCaptureConfig(cfg *AudioCaptureConfig, serverURL string, rover
} }
func validateAudioPlaybackConfig(cfg *AudioPlaybackConfig, serverURL string, roverName string, rtspPort int) error { func validateAudioPlaybackConfig(cfg *AudioPlaybackConfig, serverURL string, roverName string, rtspPort int) error {
if cfg.Service == "" {
cfg.Service = "audio-forward-listener.service"
}
if cfg.Device == "" {
cfg.Device = "forward"
}
if cfg.NormalizeFilter == "" { if cfg.NormalizeFilter == "" {
cfg.NormalizeFilter = "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled" cfg.NormalizeFilter = "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled"
} }
@@ -625,3 +635,14 @@ func normalizeHexColor(raw string) (string, error) {
} }
return strings.ToUpper(trimmed), nil 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
}
+85
View File
@@ -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 // it does not reliably reach a virtual console that is only showing a login
// prompt. // prompt.
type ConsoleNotifier struct { type ConsoleNotifier struct {
events chan<- RoverEvent
path string path string
logger *log.Logger logger *log.Logger
mu sync.Mutex mu sync.Mutex
@@ -44,6 +45,12 @@ func (n *ConsoleNotifier) Notify(message string) {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() 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) console, err := os.OpenFile(n.path, os.O_WRONLY|os.O_APPEND, 0)
if err != nil { if err != nil {
n.logFailure("open", err) 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) 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
}
@@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"log" "log"
"strings"
"testing" "testing"
) )
@@ -33,10 +34,12 @@ func TestDisabledNativeRolesResolveToFirmataOnEveryHostBuild(t *testing.T) {
} }
defer manager.Close() defer manager.Close()
// All native entries are disabled, exactly as they can be on either a Pi or // The parent switch suppresses every native role even with saved child
// laptop rover. The shared resolver must therefore select every ESP32 role. // settings enabled. No GPIO provider may displace the external peripheral.
baseline := len(connection.Bytes()) 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 { if err != nil {
t.Fatalf("resolve: %v", err) 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{ roleDescription := PeripheralDescription{RoverControls: PeripheralRoverControls{
CameraServo: &PeripheralCameraServo{}, CameraServo: &PeripheralCameraServo{}, Headlight: &PeripheralDigitalRole{}, Laser: &PeripheralDigitalRole{},
Headlight: &PeripheralDigitalRole{},
Laser: &PeripheralDigitalRole{},
}} }}
manager := &PeripheralManager{ manager := &PeripheralManager{peripherals: []*managedPeripheral{
byID: make(map[string]*managedPeripheral),
peripherals: []*managedPeripheral{
{metadata: RoverPeripheralMetadata{ID: "firmata-0"}, description: roleDescription}, {metadata: RoverPeripheralMetadata{ID: "firmata-0"}, description: roleDescription},
{metadata: RoverPeripheralMetadata{ID: "firmata-1"}, description: roleDescription}, }}
}, cfg := &Config{PiGPIO: PiGPIOConfig{Enabled: true,
}
cfg := &Config{
CameraServo: CameraServoConfig{Enabled: true}, CameraServo: CameraServoConfig{Enabled: true},
Headlight: GPIOToggleConfig{Enabled: true}, Headlight: GPIOToggleConfig{Enabled: true}, Laser: GPIOToggleConfig{Enabled: true},
Laser: GPIOToggleConfig{Enabled: true}, }}
}
nativeCamera := &testCameraServoController{cfg: cfg.CameraServo}
nativeToggles := map[string]*testToggleController{}
factories := nativeHardwareControllerFactories{ factories := nativeHardwareControllerFactories{
newCameraServo: func(_ CameraServoConfig, _ *log.Logger) (CameraServoController, error) { newCameraServo: func(CameraServoConfig, *log.Logger) (CameraServoController, error) {
return nativeCamera, nil t.Fatal("conflicting GPIO servo must not initialize")
return nil, nil
}, },
newToggle: func(name string, config GPIOToggleConfig, _ *log.Logger) (ToggleController, error) { newToggle: func(string, GPIOToggleConfig, *log.Logger) (ToggleController, error) {
controller := &testToggleController{cfg: config} t.Fatal("conflicting GPIO toggle must not initialize")
nativeToggles[name] = controller return nil, nil
return controller, 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) controllers, err := resolveRoverHardwareControllers(cfg, manager, discardLogger(), factories)
if err != nil { 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"] { if controllers.CameraServo != nil || controllers.Headlight != nil || controllers.Laser != nil {
t.Fatal("resolver did not retain native controllers") t.Fatal("conflicting roles must remain unavailable")
}
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)
} }
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)
} }
} }
+22
View File
@@ -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
gopkg.in/yaml.v3 v3.0.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
)
+17
View File
@@ -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 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 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 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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 h1:eAJgtw3jTtvn/CqwbC82ntcS+dtzUTgo5qlZKe677EY=
github.com/stianeikeland/go-rpio/v4 v4.6.0/go.mod h1:A3GvHxC1Om5zaId+HqB3HKqx4K/AqeckxB7qRjxMK7o= 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= 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-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 h1:MRAEv+T+itmw+3GeIGpQJBfanUVyg0l3JCTwHtwdre4=
github.com/warthog618/go-gpiosim v0.1.1/go.mod h1:YXsnB+I9jdCMY4YAlMSRrlts25ltjmuIsrnoUrBLdqU= 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 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= 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 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
@@ -1,4 +1,4 @@
//go:build !dummy && !debian_laptop //go:build !dummy
package roverd package roverd
@@ -3,7 +3,6 @@ package roverd
import ( import (
"fmt" "fmt"
"log" "log"
"strings"
"time" "time"
) )
@@ -40,26 +39,20 @@ type ToggleController interface {
} }
// RoverHardwareControllers is the result of the single startup-time backend // RoverHardwareControllers is the result of the single startup-time backend
// decision. Its effective configurations are derived from whichever backend // decision. Effective configurations describe the selected role providers.
// won, making the normal rover hello accurate on both Pi and laptop hosts.
type RoverHardwareControllers struct { type RoverHardwareControllers struct {
CameraServo CameraServoController CameraServo CameraServoController
Headlight ToggleController Headlight ToggleController
Laser ToggleController Laser ToggleController
ignoredESP32Roles []string issues []string
} }
// StartupBroadcasts returns short operator-facing messages. Detailed pin and // StartupBroadcasts returns short operator-facing messages. Detailed pin and
// protocol information remains in the journal; tty1 only explains which // protocol information remains in the journal; tty1 reports selected providers
// physical backend won and whether an advertised ESP32 role was ignored. // and unavailable roles.
func (controllers RoverHardwareControllers) StartupBroadcasts() []string { func (controllers RoverHardwareControllers) StartupBroadcasts() []string {
var messages []string var messages []string
if len(controllers.ignoredESP32Roles) > 0 { messages = append(messages, controllers.issues...)
messages = append(messages, fmt.Sprintf(
"Ignored ESP32 %s because native GPIO is enabled.",
strings.Join(controllers.ignoredESP32Roles, ", "),
))
}
messages = append(messages, fmt.Sprintf( messages = append(messages, fmt.Sprintf(
"Rover hardware ready: camera servo via %s, headlight via %s, laser via %s.", "Rover hardware ready: camera servo via %s, headlight via %s, laser via %s.",
controllerBackend(controllers.CameraServo), controllerBackend(controllers.CameraServo),
@@ -81,9 +74,8 @@ type nativeHardwareControllerFactories struct {
newToggle func(string, GPIOToggleConfig, *log.Logger) (ToggleController, error) newToggle func(string, GPIOToggleConfig, *log.Logger) (ToggleController, error)
} }
// ResolveRoverHardwareControllers applies one rule on every real rover build: // ResolveRoverHardwareControllers selects one provider per role, independent of
// enabled native GPIO wins, otherwise one discovered ESP32 may fill the role. // transport. Conflicts disable only the affected role and are reported locally.
// The rule is intentionally not selected by GOARCH or the debian_laptop tag.
func ResolveRoverHardwareControllers(cfg *Config, peripherals *PeripheralManager, logger *log.Logger) (RoverHardwareControllers, error) { func ResolveRoverHardwareControllers(cfg *Config, peripherals *PeripheralManager, logger *log.Logger) (RoverHardwareControllers, error) {
factories := nativeHardwareControllerFactories{ factories := nativeHardwareControllerFactories{
newCameraServo: func(config CameraServoConfig, logger *log.Logger) (CameraServoController, error) { 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) { func resolveRoverHardwareControllers(cfg *Config, peripherals *PeripheralManager, logger *log.Logger, factories nativeHardwareControllerFactories) (RoverHardwareControllers, error) {
var controllers RoverHardwareControllers 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 var err error
// Record ignored declarations separately from selecting controllers so the report := func(role string, err error) {
// 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")
}
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)
if err != nil { if err != nil {
return RoverHardwareControllers{}, fmt.Errorf("init camera servo: %w", err) message := fmt.Sprintf("%s unavailable: %v", role, err)
controllers.issues = append(controllers.issues, message)
logger.Print(message)
} }
controllers.Headlight, err = resolveToggleController("headlight", cfg.Headlight, peripherals, logger, factories.newToggle) }
controllers.CameraServo, err = peripherals.NewCameraServo(logger)
if err != nil { if err != nil {
controllers.Close() controllers.CameraServo = nil
return RoverHardwareControllers{}, fmt.Errorf("init headlight: %w", err)
} }
controllers.Laser, err = resolveToggleController("laser", cfg.Laser, peripherals, logger, factories.newToggle) report("camera servo", err)
controllers.Headlight, err = peripherals.NewToggle("headlight", logger)
if err != nil { if err != nil {
controllers.Close() controllers.Headlight = nil
return RoverHardwareControllers{}, fmt.Errorf("init laser: %w", err)
} }
report("headlight", err)
controllers.Laser, err = peripherals.NewToggle("laser", logger)
if err != nil {
controllers.Laser = nil
}
report("laser", err)
return controllers, nil 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. // Close releases selected controller resources in reverse dependency order.
// Firmata controllers do not close the shared serial connection; that remains // Firmata controllers do not close the shared serial connection; that remains
// owned by PeripheralManager and is released by its separate shutdown defer. // owned by PeripheralManager and is released by its separate shutdown defer.
+1 -4
View File
@@ -124,10 +124,7 @@ func (h *HornSynth) run(waveform string, freqs []float64, stop <-chan struct{})
h.mu.Unlock() h.mu.Unlock()
volume *= gain volume *= gain
device := strings.TrimSpace(h.cfg.Device) device := "rover_horn"
if device == "" {
device = "horn"
}
args := []string{"-q", "-D", device, "-f", "S16_LE", "-c", fmt.Sprintf("%d", channels), "-r", fmt.Sprintf("%d", rate), "-t", "raw"} args := []string{"-q", "-D", device, "-f", "S16_LE", "-c", fmt.Sprintf("%d", channels), "-r", fmt.Sprintf("%d", rate), "-t", "raw"}
cmd := exec.Command("aplay", args...) cmd := exec.Command("aplay", args...)
stdin, err := cmd.StdinPipe() stdin, err := cmd.StdinPipe()
@@ -20,7 +20,7 @@ const (
) )
// HostStats is the wire format sent from roverd to the server. It avoids // HostStats is the wire format sent from roverd to the server. It avoids
// Roomba-specific sensor naming so the browser can treat these values as Pi // Roomba-specific sensor naming so the browser can treat these values as Linux
// host health, not robot telemetry. // host health, not robot telemetry.
type HostStats struct { type HostStats struct {
UptimeSec *float64 `json:"uptimeSec,omitempty"` UptimeSec *float64 `json:"uptimeSec,omitempty"`
@@ -136,6 +136,8 @@ func CollectHostStats(ctx context.Context) HostStats {
} }
} }
// Firmware voltage/throttle telemetry is optional on non-Pi hosts.
if _, err := exec.LookPath("vcgencmd"); err == nil {
if coreV, err := readCoreVoltage(ctx); err != nil { if coreV, err := readCoreVoltage(ctx); err != nil {
stats.addError("coreVoltage", err) stats.addError("coreVoltage", err)
} else { } else {
@@ -149,6 +151,8 @@ func CollectHostStats(ctx context.Context) HostStats {
stats.applyThrottleFlags(flags) stats.applyThrottleFlags(flags)
} }
}
if wifi, err := collectWiFiStats(ctx); err != nil { if wifi, err := collectWiFiStats(ctx); err != nil {
stats.addError("wifi", err) stats.addError("wifi", err)
if wifi != nil { if wifi != nil {
+332
View File
@@ -0,0 +1,332 @@
package roverd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"os/exec"
"sync"
"time"
"nhooyr.io/websocket"
)
type ManagementClient struct {
cfg *Config
repo string
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"`
Category string `json:"category"`
Profile *MediaProfile `json:"profile"`
}
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": m.profileCatalog(), "mediaStatus": m.mediaStatus(), "updateStatus": readUpdateStatus(),
}); 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)
go m.forwardUpdateStatus(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 == "profile.set" {
if command.Profile == nil {
return nil, fmt.Errorf("profile required")
}
if err := SaveCustomProfile(command.Category, *command.Profile); err != nil {
return nil, err
}
m.stopping = true
if m.runtime != nil {
_ = m.runtime.PrepareShutdown()
}
return m.restart, nil
}
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. The separate systemd job survives restart.
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 host 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:
}
}
func (m *ManagementClient) SetRepository(repo string) { m.repo = repo }
func (m *ManagementClient) profileCatalog() map[string][]MediaProfile {
profiles, err := LoadMediaProfiles(m.repo)
if err != nil {
m.log.Printf("profile catalog: %v", err)
return map[string][]MediaProfile{}
}
return profiles
}
func (m *ManagementClient) mediaStatus() map[string]string {
if m.media == nil {
return nil
}
return m.media.Status()
}
// Persist only the latest update result, so reconnects do not depend on an
// in-memory event surviving the service restart.
func readUpdateStatus() json.RawMessage {
data, err := os.ReadFile("/var/lib/roverd/update-status.json")
if err != nil || !json.Valid(data) {
return nil
}
return data
}
func (m *ManagementClient) forwardUpdateStatus(ctx context.Context, conn *websocket.Conn) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var previous json.RawMessage
for {
current := readUpdateStatus()
if current != nil && !bytes.Equal(current, previous) {
if err := writeJSON(ctx, conn, map[string]any{"type": "updateStatus", "status": current}); err != nil {
return
}
previous = current
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
+114
View File
@@ -0,0 +1,114 @@
package roverd
import (
"bytes"
"fmt"
"gopkg.in/yaml.v3"
"os"
"path/filepath"
"regexp"
)
var mediaCategories = []string{"video", "audioCapture", "audioPlayback"}
var profileID = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]*$`)
type MediaProfile struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name" json:"name"`
Description string `yaml:"description" json:"description"`
Setup string `yaml:"setup" json:"setup"`
Run string `yaml:"run" json:"run"`
}
func validateProfile(p MediaProfile) error {
if !profileID.MatchString(p.ID) || p.Name == "" || p.Run == "" {
return fmt.Errorf("profile requires a lowercase identifier, name, and run command")
}
return nil
}
func LoadMediaProfiles(repo string) (map[string][]MediaProfile, error) {
catalogs := make(map[string][]MediaProfile)
for _, category := range mediaCategories {
data, err := os.ReadFile(filepath.Join(repo, "rover", "profiles", category+".yaml"))
if err != nil {
return nil, err
}
decoder := yaml.NewDecoder(bytes.NewReader(data))
decoder.KnownFields(true)
var profiles []MediaProfile
if err := decoder.Decode(&profiles); err != nil {
return nil, fmt.Errorf("%s: %w", category, err)
}
seen := map[string]bool{}
for _, p := range profiles {
if err := validateProfile(p); err != nil {
return nil, err
}
if p.ID == "custom" || seen[p.ID] {
return nil, fmt.Errorf("duplicate/reserved profile %s", p.ID)
}
seen[p.ID] = true
}
data, err = os.ReadFile(filepath.Join("/etc/roverd/profiles", category+".yaml"))
if err == nil {
var custom MediaProfile
decoder = yaml.NewDecoder(bytes.NewReader(data))
decoder.KnownFields(true)
if err = decoder.Decode(&custom); err != nil {
return nil, err
}
if err = validateProfile(custom); err != nil {
return nil, err
}
if custom.ID != "custom" {
return nil, fmt.Errorf("custom profile ID must be custom")
}
profiles = append(profiles, custom)
} else if !os.IsNotExist(err) {
return nil, err
}
catalogs[category] = profiles
}
return catalogs, nil
}
func SaveCustomProfile(category string, profile MediaProfile) error {
valid := false
for _, name := range mediaCategories {
if category == name {
valid = true
}
}
if !valid {
return fmt.Errorf("unknown media category")
}
profile.ID = "custom"
if err := validateProfile(profile); err != nil {
return err
}
data, err := yaml.Marshal(profile)
if err != nil {
return err
}
dir := "/etc/roverd/profiles"
if err = os.MkdirAll(dir, 0755); err != nil {
return err
}
file, err := os.CreateTemp(dir, ".profile-*")
if err != nil {
return err
}
defer os.Remove(file.Name())
defer file.Close()
if _, err = file.Write(data); err != nil {
return err
}
if err = file.Sync(); err != nil {
return err
}
if err = file.Close(); err != nil {
return err
}
return os.Rename(file.Name(), filepath.Join(dir, category+".yaml"))
}
+204
View File
@@ -0,0 +1,204 @@
package roverd
import (
"context"
"fmt"
"log"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"sync"
"syscall"
"time"
)
type MediaSupervisor struct {
statusMu sync.Mutex
statuses map[string]string
cfg *Config
repo string
profiles map[string][]MediaProfile
events chan RoverEvent
logger *log.Logger
mu sync.Mutex
setupMu sync.Mutex
cancel context.CancelFunc
done chan struct{}
}
func NewMediaSupervisor(cfg *Config, repo string, events chan RoverEvent, logger *log.Logger) (*MediaSupervisor, error) {
profiles, err := LoadMediaProfiles(repo)
if err != nil {
return nil, err
}
return &MediaSupervisor{cfg: cfg, repo: repo, profiles: profiles, events: events, logger: logger, statuses: make(map[string]string)}, nil
}
func (m *MediaSupervisor) Profiles() map[string][]MediaProfile { return m.profiles }
func (m *MediaSupervisor) emit(kind, category, message string) {
if kind == "media.status" {
m.statusMu.Lock()
m.statuses[category] = message
m.statusMu.Unlock()
}
event := RoverEvent{Type: "event", Event: kind, Ts: time.Now().UnixMilli(), Data: map[string]any{"category": category, "message": message}}
select {
case m.events <- event:
default:
} // Never block a child on a slow/disconnected server.
}
func (m *MediaSupervisor) Start(ctx context.Context) {
m.mu.Lock()
defer m.mu.Unlock()
if m.cancel != nil {
return
}
ctx, m.cancel = context.WithCancel(ctx)
m.done = make(chan struct{})
go func() {
defer close(m.done)
var workers sync.WaitGroup
for _, category := range mediaCategories {
enabled, id := m.selection(category)
if !enabled {
m.emit("media.status", category, "disabled")
continue
}
workers.Add(1)
go func(category, id string) { defer workers.Done(); m.supervise(ctx, category, id) }(category, id)
}
workers.Wait()
}()
}
func (m *MediaSupervisor) Stop() {
m.mu.Lock()
defer m.mu.Unlock()
if m.cancel == nil {
return
}
m.cancel()
<-m.done
m.cancel = nil
}
func (m *MediaSupervisor) selection(category string) (bool, string) {
switch category {
case "video":
return m.cfg.Media.Video.Enabled, m.cfg.Media.Video.Profile
case "audioCapture":
return m.cfg.Media.AudioCapture.Enabled, m.cfg.Media.AudioCapture.Profile
default:
return m.cfg.Media.AudioPlayback.Enabled, m.cfg.Media.AudioPlayback.Profile
}
}
func (m *MediaSupervisor) supervise(ctx context.Context, category, id string) {
var profile *MediaProfile
for _, p := range m.profiles[category] {
if p.ID == id {
copy := p
profile = &copy
break
}
}
if profile == nil {
m.emit("media.status", category, "unknown profile: "+id)
return
}
dir := filepath.Join("/var/lib/roverd/profiles", category, id)
if err := os.MkdirAll(dir, 0755); err != nil {
m.emit("media.status", category, err.Error())
return
}
env := m.environment(dir)
if profile.Setup != "" {
m.emit("media.status", category, "setup")
m.setupMu.Lock()
err := m.command(ctx, category, dir, env, profile.Setup)
m.setupMu.Unlock()
if err != nil {
m.emit("media.status", category, "setup failed: "+err.Error())
return
}
}
for ctx.Err() == nil {
m.emit("media.status", category, "running")
err := m.command(ctx, category, dir, env, profile.Run)
if ctx.Err() != nil {
break
}
m.emit("media.status", category, fmt.Sprintf("exited (%v); retrying in 2s", err))
select {
case <-ctx.Done():
case <-time.After(2 * time.Second):
}
}
m.emit("media.status", category, "stopped")
}
type mediaOutput struct {
supervisor *MediaSupervisor
category string
}
func (w mediaOutput) Write(data []byte) (int, error) {
// Split even output without newlines into bounded messages.
count := len(data)
for len(data) > 0 {
n := len(data)
if n > 4096 {
n = 4096
}
w.supervisor.emit("media.output", w.category, string(data[:n]))
data = data[n:]
}
return count, nil
}
func (m *MediaSupervisor) command(ctx context.Context, category, dir string, env []string, command string) error {
cmd := exec.CommandContext(ctx, "/bin/bash", "-e", "-o", "pipefail", "-c", command)
cmd.Dir = dir
cmd.Env = env
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Stdout = mediaOutput{m, category}
cmd.Stderr = mediaOutput{m, category}
// Kill the entire group: shell pipelines must not survive cancellation or
// retain stdout pipes after their parent shell exits.
cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) }
cmd.WaitDelay = 2 * time.Second
if err := cmd.Start(); err != nil {
return err
}
err := cmd.Wait()
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
return err
}
func (m *MediaSupervisor) environment(dir string) []string {
cfg := m.cfg
host, _ := url.Parse(cfg.ServerURL)
values := map[string]string{
"ROVER_NAME": cfg.Name, "ROVER_SERVER_HOST": host.Hostname(), "ROVER_PROFILE_DIR": dir, "ROVER_REPO_DIR": m.repo,
"ROVER_VIDEO_DEVICE": cfg.Media.Video.Device, "ROVER_VIDEO_INPUT_FORMAT": cfg.Media.Video.InputFormat,
"ROVER_VIDEO_WIDTH": strconv.Itoa(cfg.Media.Video.Width), "ROVER_VIDEO_HEIGHT": strconv.Itoa(cfg.Media.Video.Height),
"ROVER_VIDEO_FPS": strconv.Itoa(cfg.Media.Video.FPS), "ROVER_VIDEO_BITRATE": strconv.Itoa(cfg.Media.Video.Bitrate),
"ROVER_VIDEO_INVERTED": strconv.FormatBool(cfg.Media.Video.Inverted), "ROVER_VIDEO_SENSOR_MODE": cfg.Media.Video.SensorMode,
"ROVER_VIDEO_PUBLISH_URL": cfg.Media.Video.PublishURL, "ROVER_AUDIO_PUBLISH_URL": cfg.Media.AudioCapture.PublishURL,
"ROVER_AUDIO_PLAYBACK_URL": cfg.Media.AudioPlayback.ForwardURL, "ROVER_AUDIO_INPUT_DEVICE": "rover_capture", "ROVER_AUDIO_OUTPUT_DEVICE": "rover_forward",
"ROVER_AUDIO_SAMPLE_RATE": strconv.Itoa(cfg.Media.AudioCapture.SampleRate), "ROVER_AUDIO_CHANNELS": strconv.Itoa(cfg.Media.AudioCapture.Channels),
"ROVER_AUDIO_BITRATE": strconv.Itoa(cfg.Media.AudioCapture.Bitrate), "ROVER_AUDIO_NORMALIZE": strconv.FormatBool(cfg.Media.AudioPlayback.Normalize),
"ROVER_AUDIO_NORMALIZE_FILTER": cfg.Media.AudioPlayback.NormalizeFilter,
}
env := os.Environ()
for key, value := range values {
env = append(env, key+"="+value)
}
return env
}
func (m *MediaSupervisor) Status() map[string]string {
m.statusMu.Lock()
defer m.statusMu.Unlock()
result := make(map[string]string)
for key, value := range m.statuses {
result[key] = value
}
return result
}

Some files were not shown because too many files have changed in this diff Show More