Compare commits

...
Author SHA1 Message Date
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
legop3 c71267873a micrationslop
Container image / image (push) Failing after 56s
2026-10-01 02:33:56 -04:00
legop3 1ba4ebe5ff add more better options for HA activities and automatically changing them (for google home switch lol) 2026-10-01 02:11:07 -04:00
legop3 607d327e9c slop 2026-09-30 22:17:08 -04:00
legop3 1bdca60648 slop 2026-09-30 21:03:06 -04:00
244 changed files with 5449 additions and 5108 deletions
+1
View File
@@ -5,6 +5,7 @@
.git
.gitignore
**/node_modules
webui/.cache/mediamtx/
# Neither the legacy state directory nor the Compose-mounted replacement may
# enter an image build. This prevents credentials and backups from becoming
# image layers after an operator has started using either deployment layout.
+2
View File
@@ -58,6 +58,8 @@ jobs:
# replaced on each successful push, just as main replaces `latest`.
- name: Build and optionally publish
uses: docker/build-push-action@v7
env:
DOCKER_BUILD_RECORD_RETENTION_DAYS: 3
with:
context: .
platforms: linux/amd64
+2
View File
@@ -5,6 +5,7 @@ create_2_Open_Interface_Spec.txt
logs
node_modules/
webui/.cache/mediamtx/
__pycache__/
*.py[cod]
.pio
@@ -41,3 +42,4 @@ server/data/fleet-reports.sqlite-wal
server/data/configuration.sqlite
server/data/configuration.sqlite-shm
server/data/configuration.sqlite-wal
AGENTS.md
+37 -23
View File
@@ -9,15 +9,21 @@
ARG FEDORA_VERSION=43
FROM fedora:${FEDORA_VERSION} AS architecture-check
ARG FEDORA_VERSION
ARG TARGETARCH
# The central server is currently deployed and verified only on amd64. Failing
# here avoids publishing an ARM image whose native workers and hardware paths
# have never been exercised on a real ARM server.
RUN test "${TARGETARCH}" = "amd64" || (echo "MultiRover server images support only linux/amd64." >&2; exit 1)
FROM architecture-check AS webui-build
RUN dnf install -y --setopt=install_weak_deps=False nodejs npm \
&& dnf clean all
# Both Node builders reuse the same installed toolchain layer.
# Fedora 43 uses DNF5. Cache metadata and RPMs outside image layers, and keep
# downloads after installation so invalidated layers can reuse them.
FROM architecture-check AS node-build-base
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-node-build-base,target=/var/cache/libdnf5,sharing=locked \
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True nodejs npm
FROM node-build-base AS webui-build
WORKDIR /build
# Copy dependency manifests first so ordinary source edits retain the expensive
# npm cache layer. npm ci makes the checked-in lockfile the exact dependency
@@ -25,14 +31,17 @@ WORKDIR /build
COPY webui/package.json webui/package-lock.json ./webui/
RUN --mount=type=cache,target=/root/.npm \
cd webui && npm ci
# Keep the pinned browser publisher in a reusable layer across UI source edits.
COPY webui/scripts/prepareMediaMtx.js ./webui/scripts/prepareMediaMtx.js
RUN cd webui && node scripts/prepareMediaMtx.js
COPY webui ./webui
# Vite deliberately emits into ../server/public. Create that destination in the
# isolated builder and copy only its finished files into the runtime stage.
RUN mkdir -p server/public && cd webui && npm run build
FROM architecture-check AS server-dependencies
RUN dnf install -y --setopt=install_weak_deps=False nodejs npm gcc-c++ make python3 \
&& dnf clean all
FROM node-build-base AS server-dependencies
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-server-dependencies,target=/var/cache/libdnf5,sharing=locked \
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True gcc-c++ make python3
WORKDIR /build/server
COPY server/package.json server/package-lock.json ./
# Native Node modules compile here when a matching prebuild is unavailable;
@@ -41,7 +50,8 @@ RUN --mount=type=cache,target=/root/.npm \
npm ci --omit=dev
FROM architecture-check AS native-workers
RUN dnf install -y --setopt=install_weak_deps=False \
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-native-workers,target=/var/cache/libdnf5,sharing=locked \
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True \
bluez-libs-devel \
gcc-c++ \
libcap \
@@ -49,8 +59,7 @@ RUN dnf install -y --setopt=install_weak_deps=False \
libusb1-devel \
make \
pkgconf-pkg-config \
wiiuse-devel \
&& dnf clean all
wiiuse-devel
WORKDIR /build
COPY server/src/services/kinectService/native ./kinect
COPY server/src/services/balanceBoardService/native ./balance-board
@@ -66,8 +75,8 @@ ARG NEOLINK_VERSION=0.6.2
ARG NEOLINK_SHA256=0cb963b44dca7ccc5333154092186e1536c687aef0e1ad119b7f310a7471dbbb
ARG GOOGLE_TTS_VERSION=26.5
ARG GOOGLE_TTS_SHA256=6a9eae6726871788da52e767dad964a1c83e7feb7e7dbac508a2574a2345ac24
RUN dnf install -y --setopt=install_weak_deps=False curl findutils tar unzip xz \
&& dnf clean all
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-packaged-tools,target=/var/cache/libdnf5,sharing=locked \
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True curl findutils tar unzip xz
WORKDIR /build/tools
# Each external artifact is pinned and checked before extraction. A changed or
# truncated upstream download therefore fails the image build instead of being
@@ -100,11 +109,12 @@ RUN curl --fail --location --retry 3 \
FROM architecture-check AS learning-dependencies
# CPU-only learning dependencies are built once. Disabled installations never
# launch Python or install packages as a side effect of starting Node.
RUN dnf install -y --setopt=install_weak_deps=False python3 python3-pip \
&& dnf clean all
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-learning-dependencies,target=/var/cache/libdnf5,sharing=locked \
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True python3 python3-pip
COPY server/src/services/roverLearningService/workers/requirements.txt /tmp/learning-requirements.txt
RUN python3 -m venv /opt/rover-learning \
&& /opt/rover-learning/bin/pip install --no-cache-dir -r /tmp/learning-requirements.txt
RUN --mount=type=cache,target=/root/.cache/pip \
python3 -m venv /opt/rover-learning \
&& /opt/rover-learning/bin/pip install -r /tmp/learning-requirements.txt
FROM fedora:${FEDORA_VERSION} AS runtime
ARG FEDORA_VERSION
@@ -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
# so the image receives the complete FFmpeg build instead of requiring replay
# code to work around a deployment-only codec omission.
RUN dnf install -y --setopt=install_weak_deps=False \
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-runtime,target=/var/cache/libdnf5,sharing=locked \
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True \
"https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-${FEDORA_VERSION}.noarch.rpm"
# This is the complete runtime package set. Build headers and compilers live in
# earlier stages, while media, TTS, USB, and Bluetooth libraries remain here
# because enabled services invoke them after startup. Weak dependencies are
# deliberately disabled: Fedora otherwise installs desktop portals, graphical
# themes, and GPU drivers that a headless server neither starts nor uses.
RUN dnf install -y --setopt=install_weak_deps=False \
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-runtime,target=/var/cache/libdnf5,sharing=locked \
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True \
bluez \
bluez-libs \
espeak \
@@ -143,17 +155,11 @@ RUN dnf install -y --setopt=install_weak_deps=False \
tini \
wiiuse \
--allowerasing \
&& dnf clean all \
&& useradd --uid 1000 --create-home --home-dir /home/multirover --shell /sbin/nologin multirover \
&& install -d -o multirover -g multirover -m 0755 /data /opt/multirover/server
WORKDIR /opt/multirover/server
COPY server/index.js server/package.json server/package-lock.json ./
COPY server/src ./src
COPY server/assets ./assets
COPY server/prompts ./prompts
COPY --from=server-dependencies /build/server/node_modules ./node_modules
COPY --from=webui-build /build/server/public ./public
COPY --from=native-workers /build/kinect/kinect_worker ./src/services/kinectService/native/kinect_worker
COPY --from=native-workers /build/balance-board/balance_board_worker ./src/services/balanceBoardService/native/balance_board_worker
COPY --from=packaged-tools /output/ /
@@ -176,6 +182,14 @@ RUN setcap cap_net_admin,cap_net_bind_service+ep \
&& test -s /tmp/chromegtts-smoke.wav \
&& rm /tmp/chromegtts-smoke.wav
# Frequently edited application files come after dependencies and tool checks,
# so server changes do not invalidate the large runtime dependency layers.
COPY --from=webui-build /build/server/public ./public
COPY server/index.js server/package.json server/package-lock.json ./
COPY server/src ./src
COPY server/assets ./assets
COPY server/prompts ./prompts
ENV NODE_ENV=production \
SERVER_DATA_DIR=/data \
ROVER_SNAPSHOT_WRITER_BIN=/usr/local/bin/rover-snapshot-writer.sh
+5 -1
View File
@@ -23,9 +23,13 @@ services:
# Required for Bluetooth hardware such as the Balance Board.
- /run/dbus/system_bus_socket:/run/dbus/system_bus_socket:ro
# Required for Kinect USB access.
# Kinect USB access.
devices:
- /dev/bus/usb:/dev/bus/usb
# For a server-local microphone, uncomment this device and group_add below.
# - /dev/snd:/dev/snd
# group_add:
# - "${AUDIO_GID:?Set AUDIO_GID to the host sound device group ID}"
cap_add:
- NET_ADMIN
-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.
+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.
2. Otherwise, if exactly one discovered ESP32 declares the role, use its Firmata implementation.
3. Otherwise, leave the built-in feature disabled.
All native settings live under `piGpio`, whose parent switch defaults to disabled:
Native configuration deliberately wins. A Pi rover can attach an ESP32 for unrelated generic controls without unexpectedly moving its existing camera servo, headlight, or laser to the ESP32. To deliberately use the ESP32 for one of those features, disable only that native feature in rover YAML.
Any rover configuration that should use the ESP32 for these roles keeps the corresponding native GPIO features disabled:
```yaml
cameraServo:
enabled: false
headlight:
enabled: false
laser:
enabled: false
```json
{
"piGpio": {
"enabled": false,
"cameraServo": { "enabled": false },
"headlight": { "enabled": true, "gpioPin": 22, "activeLow": true },
"laser": { "enabled": false },
"brc": { "enabled": true, "gpioPin": 4, "pulseEvery": "1m", "pulseWidth": "1s" }
}
}
```
An attached ESP32 can then fill any or all of those roles automatically at the next `roverd` start. This works identically on Raspberry Pi and laptop rover hosts; no USB path or backend name is added to YAML.
This is a layout excerpt, not a complete configuration file. Use Fleet Management to edit the complete configuration, or `-print-default-config` to inspect all initial fields.
Conflict behavior is fixed and simple:
- Native feature enabled and ESP32 declares the same role: use native and log that the ESP32 role was ignored.
- Native feature disabled and one ESP32 declares the role: use that ESP32.
- Native feature disabled and no ESP32 declares the role: disable the feature.
- Native feature disabled and multiple ESP32s declare the same role: fail startup with a duplicate-role error rather than choosing by USB enumeration order.
While the parent is disabled, saved child settings cause no GPIO probing or initialization. When enabled, the internal peripheral appears as `pi-gpio` / “Pi GPIO” and offers its enabled roles. BRC runs as its automatic background function, not a user control. Pin, chip, servo calibration, and timing settings all remain inside this section. This applies to every architecture build. Configure these settings in the Fleet Management configuration editor.
### Shared controller interfaces
The current `WSClient` directly owns concrete `*CameraServo` and `*GPIOToggle` values. Supporting either physical backend cleanly requires it to depend on the behavior it uses instead of a platform-specific concrete type.
`WSClient` uses controller interfaces shared by the internal GPIO and external Firmata providers.
The intended interfaces are:
@@ -433,7 +423,7 @@ ToggleController
### Effective hello metadata
The current hello is built from `c.cfg.CameraServo`, `c.cfg.Headlight`, and `c.cfg.Laser`. That cannot remain the source of truth because an ESP32 role may enable a feature whose native YAML entry is disabled.
Hello uses the selected controllers’ effective configuration, since external roles are independent of saved native GPIO settings.
After startup resolution, the selected controller supplies the effective public configuration. `sendHello()` advertises that effective configuration:
@@ -794,7 +784,7 @@ Use `esp32-s3-devkitc-1` and the matching `/dev/ttyACM*` device for a
native-USB ESP32-S3.
```bash
cd pi/roverd
cd rover/roverd
go run ./cmd/peripheral-probe -port /dev/ttyUSB0
```
## Connection lifecycle
@@ -813,8 +803,8 @@ Peripheral discovery happens exactly once per `roverd` process. The currently im
8. Validates every advertised standard-output pin against Firmata capabilities.
9. Configures generic digital, PWM, and servo pin modes once.
10. Assigns process-local IDs such as `firmata-0` and `firmata-1` in discovery order.
11. Resolves `cameraServo`, `headlight`, and `laser` against the native configuration.
12. Rejects duplicate ESP32 providers only when the corresponding native role is disabled and Firmata selection would otherwise be ambiguous.
11. Registers the internal Pi GPIO peripheral if enabled and resolves camera-servo, headlight, and laser roles across providers.
12. Reports duplicate role providers and leaves conflicting roles unavailable.
13. Constructs the selected native or Firmata controllers and fixed generic inventory.
14. Constructs `WSClient` with those controllers and that inventory.
15. Connects to the server and includes the effective built-in configuration and renderable inventory in the normal rover hello.
@@ -1144,7 +1134,7 @@ repository reference firmware. The package manifest, README, and examples are
self-contained so the same directory can be published directly to the
PlatformIO Registry as `legop3/RoverPeripheral`.
### `pi/roverd`
### `rover/roverd`
`PeripheralManager` is responsible for:
@@ -1164,9 +1154,9 @@ Only renderable control metadata leaves `roverd`. Firmata pin numbers, output ma
The manager should remain independent of the existing Roomba Open Interface serial adapter. A peripheral serial connection is not the Roomba base serial connection and must not be routed through `SerialAdapter`.
The transport foundation is a focused Firmata parser/client in `pi/roverd/firmata.go`. It operates on `io.ReadWriteCloser`, which keeps byte-stream behavior testable without hardware and lets discovery pass either `/dev/ttyUSB*` or `/dev/ttyACM*` ports into the same client. `pi/roverd/cmd/peripheral-probe` remains the direct hardware diagnostic entry point, while `PeripheralManager` now connects the same client to automatic daemon startup discovery.
The transport foundation is a focused Firmata parser/client in `rover/roverd/firmata.go`. It operates on `io.ReadWriteCloser`, which keeps byte-stream behavior testable without hardware and lets discovery pass either `/dev/ttyUSB*` or `/dev/ttyACM*` ports into the same client. `rover/roverd/cmd/peripheral-probe` remains the direct hardware diagnostic entry point, while `PeripheralManager` now connects the same client to automatic daemon startup discovery.
`WSClient` now depends on shared camera-servo and toggle controller interfaces rather than platform-selected concrete types. The startup resolver uses the same native-first rule in the ARM Pi and amd64 laptop binaries. Firmata camera movement retains the established limits, home position, nudging, inversion, pulse calibration, raw-pulse policy, and movement-rate behavior; Firmata toggles retain logical state and polarity conversion.
`WSClient` now depends on shared camera-servo and toggle controller interfaces rather than platform-selected concrete types. The startup resolver uses the same unique-provider rule in every architecture binary. Firmata camera movement retains the established limits, home position, nudging, inversion, pulse calibration, raw-pulse policy, and movement-rate behavior; Firmata toggles retain logical state and polarity conversion.
### Server
@@ -1247,8 +1237,8 @@ The completed system should be verified with a real ESP32 and rover Linux comput
- Confirm camera angle limits, home position, nudge amount, inversion, pulse calibration, and rate limiting match the declared ESP32 configuration.
- Confirm headlight and laser toggle state events remain identical to the native Pi path.
- Confirm existing laser restrictions still apply with the Firmata backend.
- Enable a native role and declare the same ESP32 role; confirm native wins and the ignored role is logged.
- Disable native and declare the same role from two ESP32s; confirm startup fails with a clear duplicate-role error.
- Enable Pi GPIO and a native role also declared by an ESP32; confirm the conflict lists both providers and leaves that role unavailable.
- Declare the same role from two ESP32s; confirm a clear conflict and that unrelated roles remain available.
- Confirm a Pi rover can use native built-in controls and generic ESP32 controls simultaneously.
- Repeat ESP32 role selection on both the ARM Pi binary and amd64 laptop binary and confirm their commands and advertised configurations match.
+2
View File
@@ -26,6 +26,8 @@ Phase 1 must be complete and verified before Phase 2 begins. Containerization mu
## Decision log
- 2026-10-02: The admin container controls accept a tag within the repository supplied by Compose through `MULTIROVER_TARGET_IMAGE`. A successful healthy replacement saves the tag in the lifecycle status volume; failed replacements retain the previous selection. Checks and later updates follow that saved tag. Changing repositories in Compose resets the selection. Manual Compose deployments still use the Compose image and can replace a UI-selected image; the UI displays both references. The lifecycle helper itself is updated through Compose. Image rollback does not revert application data migrations. Deploy this feature to both the application and lifecycle services before using tag selection.
- 2026-09-14: Publish `ghcr.io/legop3/multiroombarover:latest` only from the repository's main branch. Every other repository branch publishes one moving development image named for that branch, with invalid tag separators normalized; these are development selectors rather than numbered releases. Pull requests only verify that the image builds. There are no release numbers, semantic-version tags, stable/edge channels, or operator-facing version selection. Docker image digests remain an internal mechanism for detecting an available update and retaining the previously running image for rollback.
- 2026-09-15: Support only `linux/amd64` for the central server image. Rover computers remain independently ARM-capable, but publishing an untested ARM server image would multiply native-worker, media-binary, TTS-library, and hardware validation without serving the current deployment. ARM server support can be added later when a real ARM server exists to verify it.
- 2026-09-15: Mount the application data directory from the Docker-managed `multirover-data` named volume instead of a host bind path. Docker initializes the empty volume with the image's non-root ownership, eliminating host UID matching, directory creation, ownership commands, and root application startup. The admin backup/restore system is the supported portable interface to the complete data tree.
+16
View File
@@ -64,6 +64,7 @@ socket.on('connect', async () => {
// previously stored session with this object instead of merging snapshots.
socket.on('session:sync', (session) => {
console.log('Session:', session);
console.log('Server mode:', session.mode);
});
// chat:init contains the recent chat history available when the bot connects.
@@ -105,6 +106,21 @@ Run it with:
node bot.js
```
## Reading server mode
Read `session.mode` from the `session:sync` snapshot to get the current server
mode. Its possible values are `open`, `turns`, `admin`, and `lockdown`.
The server sends a fresh session snapshot whenever the mode changes, so the
example's handler receives both the initial mode and subsequent updates. No
polling or separate mode listener is needed. If your bot stores session data for
its chat-handling logic, replace the stored session on every `session:sync` and
read the mode from that latest snapshot.
`session.mode` is the server-wide mode; `session.role` is this connection's role
(such as `spectator`), and `session.operatingMode` is a separate connection field.
Use `session.mode` when answering chat questions about the server's current mode.
## Events used
- `nickname:set` sets the bot's visible nickname.
+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)
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""CPU benchmark of published NoMaD exploration, without ROS or rover connections.
Run: python3 perf/nomad-benchmark.py --setup
Subsequent runs: python3 perf/nomad-benchmark.py
Quick run: python3 perf/nomad-benchmark.py --threads 4 --samples 1 --seconds 2 --iterations 2
--setup installs CPU dependencies in a private cached venv and downloads pinned
upstream source plus the official checkpoint. Nothing touches server packages.
Synthetic images measure compute, NOT navigation quality. Excludes capture,
video decode, network, physical control, training, and concurrent rover load.
"""
import argparse
import hashlib
import importlib.metadata
import json
import math
import os
from pathlib import Path
import platform
import resource
import statistics
import subprocess
import sys
import time
import urllib.request
import venv
VINT = 'dca79815b704e5aa9c6bdc3082351f9e3b2848c2'
DIFFUSION = '5ba07ac6661db573af695b419a7947ecb704690f'
CHECKPOINT_ID = '1YJhkkMJAYOiKNyCaelbS_alpUpAJsOUb'
SOURCES = {
('robodhruv/visualnav-transformer', VINT): [
'train/config/nomad.yaml', 'train/vint_train/data/data_config.yaml',
'train/vint_train/models/nomad/nomad.py',
'train/vint_train/models/nomad/nomad_vint.py',
'train/vint_train/models/vint/self_attention.py',
],
('real-stanford/diffusion_policy', DIFFUSION): [
'diffusion_policy/model/diffusion/conditional_unet1d.py',
'diffusion_policy/model/diffusion/conv1d_components.py',
'diffusion_policy/model/diffusion/positional_embedding.py',
],
}
def positive(value):
result = int(value)
if result < 1:
raise argparse.ArgumentTypeError('Must be positive')
return result
def arguments():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('--setup', action='store_true')
p.add_argument('--cache', type=Path, default=Path.home() / '.cache/rover-nomad-benchmark')
p.add_argument('--threads', type=positive, nargs='+', default=[4, 8, 16])
p.add_argument('--samples', type=positive, nargs='+', default=[1, 8], help='Candidate trajectories per decision, not rover count')
p.add_argument('--seconds', type=positive, default=10)
p.add_argument('--iterations', type=positive, default=10)
p.add_argument('--worker', action='store_true', help=argparse.SUPPRESS)
p.add_argument('--result', type=Path, help=argparse.SUPPRESS)
return p.parse_args()
def download(url, path):
if path.exists():
return
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + '.part')
print('Downloading', path.name, flush=True)
with urllib.request.urlopen(url, timeout=120) as response, temporary.open('wb') as output:
import shutil
shutil.copyfileobj(response, output)
temporary.replace(path)
def prepare(args):
python = args.cache / 'venv/bin/python'
if not python.exists():
venv.EnvBuilder(with_pip=True).create(args.cache / 'venv')
subprocess.run([str(python), '-m', 'pip', 'install', 'torch', 'torchvision',
'--index-url', 'https://download.pytorch.org/whl/cpu'], check=True)
subprocess.run([str(python), '-m', 'pip', 'install', 'numpy', 'diffusers',
'efficientnet-pytorch', 'einops', 'PyYAML', 'gdown'], check=True)
for (repo, revision), paths in SOURCES.items():
for path in paths:
download(f'https://raw.githubusercontent.com/{repo}/{revision}/{path}', args.cache / 'source' / revision / path)
checkpoint = args.cache / 'nomad.pth'
if not checkpoint.exists():
temporary = checkpoint.with_suffix('.part')
subprocess.run([str(python), '-m', 'gdown', CHECKPOINT_ID, '-O', str(temporary)], check=True)
temporary.replace(checkpoint)
def worker(args):
import numpy as np
import torch
import yaml
from diffusers.schedulers.scheduling_ddpm import DDPMScheduler
sys.path[:0] = [str(args.cache / 'source' / VINT / 'train'), str(args.cache / 'source' / DIFFUSION)]
from vint_train.models.nomad.nomad import NoMaD, DenseNetwork
from vint_train.models.nomad.nomad_vint import NoMaD_ViNT, replace_bn_with_gn
from diffusion_policy.model.diffusion.conditional_unet1d import ConditionalUnet1D
threads, samples = args.threads[0], args.samples[0]
torch.set_num_threads(threads)
torch.set_num_interop_threads(1)
torch.manual_seed(0)
c = yaml.safe_load((args.cache / 'source' / VINT / 'train/config/nomad.yaml').read_text())
vision = replace_bn_with_gn(NoMaD_ViNT(
context_size=c['context_size'], obs_encoding_size=c['encoding_size'],
mha_num_attention_heads=c['mha_num_attention_heads'],
mha_num_attention_layers=c['mha_num_attention_layers'], mha_ff_dim_factor=c['mha_ff_dim_factor']))
model = NoMaD(vision, ConditionalUnet1D(input_dim=2, global_cond_dim=c['encoding_size'],
down_dims=c['down_dims'], cond_predict_scale=c['cond_predict_scale']), DenseNetwork(c['encoding_size'])).eval()
# Strict loading prevents accidentally benchmarking a partly random model.
model.load_state_dict(torch.load(args.cache / 'nomad.pth', map_location='cpu', weights_only=True), strict=True)
scheduler = DDPMScheduler(num_train_timesteps=c['num_diffusion_iters'],
beta_schedule='squaredcos_cap_v2', clip_sample=True, prediction_type='epsilon')
width, height = c['image_size']
frames = torch.rand(c['context_size'] + 1, 3, height, width)
mean = torch.tensor([.485, .456, .406]).view(1, 3, 1, 1)
std = torch.tensor([.229, .224, .225]).view(1, 3, 1, 1)
mask = torch.ones(1, dtype=torch.long)
stats = yaml.safe_load((args.cache / 'source' / VINT / 'train/vint_train/data/data_config.yaml').read_text())['action_stats']
low, high = np.array(stats['min']), np.array(stats['max'])
def decision():
start = time.perf_counter()
obs = ((frames - mean) / std).reshape(1, -1, height, width)
goal = torch.randn(1, 3, height, width)
cond = model('vision_encoder', obs_img=obs, goal_img=goal, input_goal_mask=mask).repeat(samples, 1)
encoded = time.perf_counter()
action = torch.randn(samples, c['len_traj_pred'], 2)
scheduler.set_timesteps(c['num_diffusion_iters'])
for step in scheduler.timesteps:
noise = model('noise_pred_net', sample=action, timestep=step, global_cond=cond)
action = scheduler.step(noise, step, action).prev_sample
# Match upstream get_action: unnormalize deltas then accumulate waypoints.
waypoints = np.cumsum((action.numpy() + 1) / 2 * (high - low) + low, axis=1)
if not np.isfinite(waypoints).all():
raise RuntimeError('Non-finite model output')
end = time.perf_counter()
return (end - start) * 1000, (encoded - start) * 1000, (end - encoded) * 1000
rows = []
with torch.inference_mode():
for _ in range(3):
decision()
start, cpu = time.perf_counter(), time.process_time()
while len(rows) < args.iterations or time.perf_counter() - start < args.seconds:
rows.append(decision())
elapsed, cpu = time.perf_counter() - start, time.process_time() - cpu
total = sorted(r[0] for r in rows)
result = dict(threads=threads, candidateTrajectories=samples, iterations=len(rows),
p50Ms=statistics.median(total), p95Ms=total[math.ceil(.95 * len(total)) - 1], maxMs=max(total),
decisionsPerSecond=len(rows)/elapsed, cpuCores=cpu/elapsed,
peakMiB=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024,
visionMeanMs=statistics.mean(r[1] for r in rows), diffusionAndDecodeMeanMs=statistics.mean(r[2] for r in rows),
parameters=sum(p.numel() for p in model.parameters()), diffusionSteps=c['num_diffusion_iters'],
imageSize=c['image_size'], frames=c['context_size']+1,
versions={name: importlib.metadata.version(name) for name in ['torch','torchvision','diffusers','numpy','efficientnet-pytorch','einops']})
args.result.write_text(json.dumps(result))
def main():
args = arguments()
args.cache = args.cache.expanduser().resolve()
if args.worker:
worker(args)
return
if args.setup:
prepare(args)
python = args.cache / 'venv/bin/python'
if not python.exists() or not (args.cache / 'nomad.pth').exists():
raise RuntimeError('First run: python3 perf/nomad-benchmark.py --setup')
print('CPU FP32 NoMaD exploration; synthetic images; no driving-quality measurement.', flush=True)
print('Candidates are trajectories for ONE rover. Includes vision + all 10 diffusion steps.', flush=True)
print('threads candidates p50 ms p95 ms max ms decisions/s CPU cores peak MiB', flush=True)
results = []
import tempfile
with tempfile.TemporaryDirectory(prefix='nomad-bench-') as directory:
for threads in args.threads:
for samples in args.samples:
path = Path(directory) / 'result.json'
subprocess.run([str(python), str(Path(__file__).resolve()), '--worker', '--cache', str(args.cache),
'--threads', str(threads), '--samples', str(samples), '--seconds', str(args.seconds),
'--iterations', str(args.iterations), '--result', str(path)], check=True,
timeout=max(600, args.seconds*20), env={**os.environ, 'PYTHONDONTWRITEBYTECODE':'1'})
r = json.loads(path.read_text()); results.append(r)
print(f"{threads:7} {samples:10} {r['p50Ms']:7.1f} {r['p95Ms']:7.1f} {r['maxMs']:7.1f} {r['decisionsPerSecond']:11.2f} {r['cpuCores']:9.2f} {r['peakMiB']:8.0f}", flush=True)
with (args.cache / 'nomad.pth').open('rb') as f:
digest = hashlib.file_digest(f, 'sha256').hexdigest()
report = dict(benchmark='nomad-cpu-v1', platform=platform.platform(), logicalCpus=os.cpu_count(),
loadAverage=os.getloadavg(), sourceRevisions=dict(vint=VINT,diffusion=DIFFUSION), checkpointSha256=digest,
exclusions=['capture','video decode','network','physical control','training','concurrent model workloads'], results=results)
print('\nPaste this report back:\n' + json.dumps(report, separators=(',', ':')))
print('At 10 decisions/s the total budget is 100ms; at 5/s it is 200ms. Leave room for the excluded pipeline.')
if __name__ == '__main__':
try:
main()
except (Exception, KeyboardInterrupt) as error:
print(f'Benchmark failed: {error}', file=sys.stderr)
sys.exit(1)
-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
+113
View File
@@ -2,6 +2,19 @@
## Resume here
Latest repair: full learning-path audit. Fixed missing command labels between
video samples with a shared causal 100ms grid; added real-data score/baseline/
training-probe diagnostics and normalized saved control profiles for retained
recordings. Continues policy 5 / lineage v6; this audit does not reset progress.
See the final audit results section for measured synthetic evidence and limits.
Latest scope (authorized IPI): only drive, camera tilt, headlight and the four
operating-mode/dock commands (128/131/132/143). Exclude horn, song, laser and all
brush/vacuum motor commands from both learning and execution, including raw OI
bypasses. Raw recordings stay intact. Policy format 5, training lineage v6;
startup removes earlier models and lineages through v5. Earlier scope below is
historical. No configuration change required.
Latest change (2026-09-29 IPI): format 4 seeds known user-control command shapes
before training. Generic peripherals are excluded; sensorStream is ignored without
invalidating footage. Drive includes zero-speed drive, with no separate stop type.
@@ -962,3 +975,103 @@ and browser appearance remain unverified. No new tests or background processes.
Deploying starts a new learner using existing recordings; enabled-service startup
removes older policy models and optimizer/scheduler lineages through v4. Current
lineage is v5. No settings changes or prescribed human driving are required.
### Simplified controls, policy 5
User authorized removal of horn/song/laser/brush motors. Retained 13 seeded shapes:
four drive zero/nonzero combinations, two camera angle shapes, three headlight
actions, four raw operating-mode/dock constants. Generic peripherals remain excluded.
Removed excluded command history/targets via policy allowlist and execution via
Node allowlist; raw payloads must exactly match one of the four mode commands at
both boundaries. Controller shutdown now sends only zero-speed drive, leaving
manual brush/horn state alone. Raw recording and sensor telemetry unchanged.
Old policies are deleted on enabled startup; resume-v6.pt/schedule-v6.json begin a
fresh learner using retained recordings. Existing evaluation behavior unchanged.
Verification passed: production train.py --check-dependencies (policy 5, 13 seeded
shapes), infer.py --help, changed Node module syntax, focused card ESLint, and diff
whitespace checks. No live hardware/data available locally; actual learning and
driving quality remain unverified. No tests added or background processes left.
### Active full learning-path audit (authorized IPI)
User explicitly permits local training/inference with controlled synthetic input;
there are NO real recordings on this machine. Existing user-control simplification
edits were present at start and must be preserved. No new schema reset is planned.
Reproduced: production reader with a generated lossless 25 FPS video and 31 valid
human drive events labeled ZERO commands. Old sampler used 120ms frame intervals
with only 100ms target coverage. Fixed causal 100ms grid shared by dataset/inference
uses latest past image; no future pixels. The repaired fixture preserves all 31
commands. Sensor cutoff is strictly before decision in both paths.
Original objective experiment: 12 easy colored-frame samples, 120 steps, seed 7,
4 threads: loss 0.8206 -> 0.1996, mean true-command score 0.5106 -> 0.7268, recall
at 0.7 reached 2/3; at 80 steps recall was still zero. This disproves a wholly
broken gradient path; it does not diagnose real-data score suppression. Keep
existing loss/threshold until real-data diagnostics justify changing them.
New learning.py shares the actual objective for ongoing training and disposable
probe. Per-job before/after evaluation on <=96 unchanged training examples, full
held-out score distributions, threshold sweep, training-only frequency and no-op
baselines, decoded pre-server-limit parameter error, gradient norms and sampled
versus natural frequencies. Bounded <=20s/80-step memorization probe on <=12
training examples at first job/every 1000 steps; copy only, never published or
used for generalization gate. Continues current checkpoint/optimizer lineage.
Audit results (synthetic only):
- Round-tripped eight representative retained command payloads, including signed
drive/servo values, zero-speed drive, headlight and all four mode commands.
- Lossless 25 FPS recording with 31 command events: old sampler labeled 0; new
sampler labeled 31/31, including interleaved ignored sensorStream events.
- Full production train.py decoded five generated recordings, trained/exported
checkpoints, evaluated held-out sessions, and resumed optimizer/weights for a
second job. 120 -> 240 cumulative steps improved recall at unchanged 0.7 from
0 to 0.2553, with precision 1.0 at step 240. Mean true-event score rose 0.5346
-> 0.6303. Gate correctly remained failed. A lower 0.5 threshold had precision
0.6629/recall 0.8369 and 120 false-positive actions, so threshold was NOT lowered.
- Disposable diverse probe covered zero-speed drive, moving drive and servo;
reached recall 0.75 after 39 steps under its 20s budget. Sampling was corrected
to avoid probing only the first event category. Probe uses a copy and higher
learning rate for memorization; never adopts weights or changes main optimizer.
- Exported trained checkpoint reload, forward inference and decoding passed.
- Retained recordings had extra removed actuator fields, causing false model
incompatibility. Normalize saved and current profiles through controlProfile.
Direct Node exercise accepts removed laser/peripheral differences and still
rejects a changed retained camera configuration.
Diagnostics now report accepted vs represented command counts, request/dispatch
delay, maximum sensor/image age; sampled vs natural command frequencies; gradient
norms; same training-subset before/after scores; per-command score distributions;
threshold sweep and no-op/training-frequency baselines; pre-server-limit decoded
parameter errors; and bounded diverse memorization probe. Evaluation-step identity
separates last evaluation from current-job progress. Compact history avoids
repeating entire command/score tables for every job. Four concise numeric rows
were added to expanded details; full evidence is in Copy diagnostics.
The original loss and configured 0.7 threshold remain unchanged because experiments
did not establish that a different objective/threshold fixes real recordings.
Promotion keeps existing checks and additionally must beat the simple training-
frequency baseline F1. One-time retry of old reader-specific no-aligned-window
rejections preserves optimizer state and unrelated errors.
Limits: actual human footage and rover/RTSP transport unavailable. Isolated held-out
windows cannot measure sequential latch behavior or physical driving; decoded
parameter errors are explicitly before Node's rover limits/permission/safety
handling. Main model learned some synthetic cues but has not demonstrated useful
autonomous driving. Camera command encoding still uses whole-degree predictions.
The user must not be asked to drive prescribed routes or perform a manual checklist.
Verification: full synthetic worker jobs and checkpoint inference above passed;
focused Node syntax/card ESLint/diff checks passed before final report additions.
One experimental seeded run failed because its runpy launcher omitted worker
import path; corrected launcher succeeded. No production import failure occurred.
Synthetic inference-worker media exercise passed: eight prediction batches,
threshold update to 0.3, retained command types and discrete latching exercised.
This check used a generated checkpoint and a FIFO media adapter preserving
synthetic PTS (RTSP wall-clock override disabled in the experiment only); it does
not validate real network capture timing. Trained checkpoint forward/decode was
verified separately. Temporary media launchers needed fixes for file lifetime
and command-string escaping; these were experiment issues, not production fixes.
No repository tests added. Experiments finished and no background worker remains.
Final focused Node syntax and diff whitespace checks passed. Card lint passed.
No additional schema/optimizer reset introduced by this audit.
@@ -7,11 +7,11 @@ import subprocess
import sys
ASSET_ROOT = "/opt/roverd/googletts"
ASSET_ROOT = "/var/lib/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"
PLAYBACK_DEVICE = "rover_tts"
SAMPLE_RATE = "24000"
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
+16
View File
@@ -0,0 +1,16 @@
#!/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; }
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; }
apt-get update
apt-get install -y git ca-certificates python3
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; }
export ROVERD_INITIAL_NAME="$rover_name" ROVERD_INITIAL_SERVER="$server_address"
bash /opt/roverd/rover/install_roverd.sh
systemctl restart roverd
+50
View File
@@ -0,0 +1,50 @@
#!/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
# 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"
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
}
// 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)
if 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 {
// Prefer the active ALSA default route; fall back to card index for compatibility.
candidates := [][]string{
{"-q", "-D", "default", "sset", control, value},
{"-q", "-c", "0", "sset", control, value},
out, err := exec.Command("amixer", "-q", "-c", c.cfg.Audio.MixerCard, "sset", control, value).CombinedOutput()
if err != nil {
return fmt.Errorf("%w (%s)", err, string(out))
}
var lastErr error
for _, args := range candidates {
out, err := exec.Command("amixer", args...).CombinedOutput()
if err == nil {
return nil
}
lastErr = fmt.Errorf("%w (%s)", err, string(out))
}
return lastErr
return nil
}
+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 (
"context"
"log"
"sync"
"time"
)
const (
autoChargeTimeout = 1 * time.Second
autoChargeTimeout = 10 * time.Second
autoChargeCooldown = 0 * time.Minute
sourceHomeBase = 1 << 1
)
type AutoChargeController struct {
mu sync.Mutex
paused bool
adapter *SerialAdapter
events chan<- RoverEvent
logger *log.Logger
@@ -42,6 +45,11 @@ func (a *AutoChargeController) Run(ctx context.Context, samples <-chan SensorSam
}
func (a *AutoChargeController) processSample(sample SensorSample) {
a.mu.Lock()
defer a.mu.Unlock()
if a.paused {
return
}
now := time.Now()
docked := sample.ChargeSources&sourceHomeBase != 0
charging := isCharging(sample.ChargingState)
@@ -107,3 +115,12 @@ func (a *AutoChargeController) emitEvent(event string, data map[string]any) {
default:
}
}
// Pausing waits for any current dock attempt to finish before management stops
// motion, preventing the automatic timer from issuing a later movement command.
func (a *AutoChargeController) SetPaused(paused bool) {
a.mu.Lock()
defer a.mu.Unlock()
a.paused = paused
a.timerStart = time.Time{}
}
+19 -5
View File
@@ -1,4 +1,4 @@
//go:build !dummy && !debian_laptop
//go:build !dummy
package roverd
@@ -14,6 +14,7 @@ type BRCPulser struct {
cfg BRCConfig
logger *log.Logger
line *gpiocdev.Line
done chan struct{}
}
func NewBRCPulser(cfg BRCConfig, logger *log.Logger) (*BRCPulser, error) {
@@ -32,10 +33,12 @@ func NewBRCPulser(cfg BRCConfig, logger *log.Logger) (*BRCPulser, error) {
return nil, err
}
return &BRCPulser{cfg: cfg, logger: logger, line: line}, nil
return &BRCPulser{cfg: cfg, logger: logger, line: line, done: make(chan struct{})}, nil
}
func (b *BRCPulser) Close() {
// The owner cancels the pulse loop before closing its GPIO line.
<-b.done
if b.line != nil {
_ = b.line.SetValue(1)
b.line.Close()
@@ -44,11 +47,15 @@ func (b *BRCPulser) Close() {
func (b *BRCPulser) Start(ctx context.Context) {
go func() {
defer close(b.done)
ticker := time.NewTicker(b.cfg.PulseEvery.Duration)
defer ticker.Stop()
for {
b.pulseOnce()
if ctx.Err() != nil {
return
}
b.pulseOnce(ctx)
select {
case <-ctx.Done():
return
@@ -58,7 +65,7 @@ func (b *BRCPulser) Start(ctx context.Context) {
}()
}
func (b *BRCPulser) pulseOnce() {
func (b *BRCPulser) pulseOnce(ctx context.Context) {
if b.line == nil {
return
}
@@ -66,7 +73,14 @@ func (b *BRCPulser) pulseOnce() {
b.logger.Printf("brc pulse low: %v", err)
return
}
time.Sleep(b.cfg.PulseWidth.Duration)
// Cancellation ends a pulse promptly before peripheral shutdown releases
// the line, even when a long pulse width was configured.
timer := time.NewTimer(b.cfg.PulseWidth.Duration)
defer timer.Stop()
select {
case <-ctx.Done():
case <-timer.C:
}
if err := b.line.SetValue(1); err != nil {
b.logger.Printf("brc pulse high: %v", err)
}
@@ -1,4 +1,4 @@
//go:build !dummy && !debian_laptop
//go:build !dummy
package roverd
@@ -10,7 +10,7 @@ import (
"os"
"time"
roverd "multiroombarover/pi/roverd"
roverd "multiroombarover/rover/roverd"
"github.com/tarm/serial"
)
+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"`
Battery BatteryConfig `json:"battery"`
MaxWheelSpeed int `json:"maxWheelSpeed"`
Media MediaConfig `json:"media"`
Media any `json:"media"`
CameraServo CameraServoConfig `json:"cameraServo"`
Audio AudioConfig `json:"audio"`
Horn HornConfig `json:"horn"`
@@ -27,7 +27,7 @@ type sensorMessage struct {
// hostStatsMessage is intentionally separate from sensorMessage because sensor
// 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 string `json:"type"`
Timestamp int64 `json:"ts"`
@@ -41,7 +41,6 @@ type inboundMessage struct {
MotorPWM *motorPWMPayload `json:"motorPwm,omitempty"`
Raw string `json:"raw,omitempty"`
SensorStream *sensorStreamPayload `json:"sensorStream,omitempty"`
Media *mediaCommand `json:"media,omitempty"`
Servo *servoPayload `json:"servo,omitempty"`
TTS *ttsPayload `json:"tts,omitempty"`
Horn *hornPayload `json:"horn,omitempty"`
@@ -50,11 +49,6 @@ type inboundMessage struct {
Laser *togglePayload `json:"laser,omitempty"`
Peripheral *peripheralPayload `json:"peripheral,omitempty"`
Song *songPayload `json:"song,omitempty"`
Reboot *rebootPayload `json:"reboot,omitempty"`
// Update is intentionally just a marker payload. The server can request the
// fixed self-update workflow, but it cannot pass paths, commands, branches,
// or installer flags through the websocket into the privileged helper.
Update *updatePayload `json:"update,omitempty"`
}
type driveDirectPayload struct {
@@ -72,10 +66,6 @@ type sensorStreamPayload struct {
Enable bool `json:"enable"`
}
type mediaCommand struct {
Action string `json:"action"`
}
type servoPayload struct {
Angle *float64 `json:"angle,omitempty"`
Nudge *float64 `json:"nudge,omitempty"`
@@ -128,8 +118,6 @@ type rebootPayload struct {
DelayMs int `json:"delayMs,omitempty"`
}
type updatePayload struct{}
type ackMessage struct {
Type string `json:"type"`
ID string `json:"id"`
+246 -225
View File
@@ -11,21 +11,23 @@ import (
"strings"
"time"
"gopkg.in/yaml.v3"
"bytes"
"encoding/json"
"io"
)
type SerialConfig struct {
Device string `yaml:"device"`
Baud int `yaml:"baud"`
Device string `json:"device"`
Baud int `json:"baud" jsonschema:"minimum=1"`
}
type Duration struct {
time.Duration
}
func (d *Duration) UnmarshalYAML(value *yaml.Node) error {
func (d *Duration) UnmarshalJSON(data []byte) error {
var raw string
if err := value.Decode(&raw); err != nil {
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
parsed, err := time.ParseDuration(raw)
@@ -36,130 +38,119 @@ func (d *Duration) UnmarshalYAML(value *yaml.Node) error {
return nil
}
func (d Duration) MarshalYAML() (interface{}, error) {
return d.Duration.String(), nil
}
func (d Duration) MarshalJSON() ([]byte, error) { return json.Marshal(d.Duration.String()) }
type BRCConfig struct {
GPIOPin int `yaml:"gpioPin"`
GPIOChip string `yaml:"gpioChip"`
PulseEvery Duration `yaml:"pulseEvery"`
PulseWidth Duration `yaml:"pulseWidth"`
}
func (b BRCConfig) Enabled() bool {
return b.GPIOPin >= 0
Enabled bool `json:"enabled"`
GPIOPin int `json:"gpioPin"`
GPIOChip string `json:"gpioChip"`
PulseEvery Duration `json:"pulseEvery"`
PulseWidth Duration `json:"pulseWidth"`
}
type BatteryConfig struct {
Full int `yaml:"full"`
Warn int `yaml:"warn"`
Urgent int `yaml:"urgent"`
Full int `json:"full"`
Warn int `json:"warn"`
Urgent int `json:"urgent"`
}
type AudioConfig struct {
// AudioConfig is only for sounds generated by roverd itself. Live capture
// and playback are media-publisher concerns, so those settings live under
// MediaConfig where they can be written directly into media.env.
TTSEnabled bool `yaml:"ttsEnabled" json:"ttsEnabled"`
DefaultEngine string `yaml:"defaultEngine" json:"defaultEngine,omitempty"`
DefaultVoice string `yaml:"defaultVoice" json:"defaultVoice,omitempty"`
DefaultPitch int `yaml:"defaultPitch" json:"defaultPitch,omitempty"`
InputDevice string `json:"inputDevice" jsonschema:"minLength=1"`
OutputDevice string `json:"outputDevice" jsonschema:"minLength=1"`
MixerCard string `json:"mixerCard" jsonschema:"minLength=1"`
OutputSampleRate int `json:"outputSampleRate" jsonschema:"minimum=8000,maximum=192000"`
OutputChannels int `json:"outputChannels" jsonschema:"minimum=1,maximum=8"`
TTSEnabled bool `json:"ttsEnabled"`
DefaultEngine string `json:"defaultEngine"`
DefaultVoice string `json:"defaultVoice"`
DefaultPitch int `json:"defaultPitch"`
}
type HornConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
Volume float64 `yaml:"volume" json:"-"`
SampleRate int `yaml:"sampleRate" json:"-"`
Channels int `yaml:"channels" json:"-"`
Device string `yaml:"device" json:"-"`
SineGain float64 `yaml:"sineGain" json:"-"`
SawGain float64 `yaml:"sawGain" json:"-"`
MaxDuration Duration `yaml:"maxDuration" json:"-"`
Enabled bool `json:"enabled"`
Volume float64 `json:"volume"`
SampleRate int `json:"sampleRate"`
Channels int `json:"channels"`
SineGain float64 `json:"sineGain"`
SawGain float64 `json:"sawGain"`
MaxDuration Duration `json:"maxDuration"`
}
type MediaConfig struct {
// RTSPPort is shared by the derived video, microphone, and forwarded-audio
// RTSP URLs. Keeping it at this level prevents each nested block from needing
// to repeat the same server port when the common MediaMTX listener is used.
RTSPPort int `yaml:"rtspPort" json:"-"`
Manage bool `yaml:"manage" json:"manage"`
HealthURL string `yaml:"healthUrl" json:"healthUrl,omitempty"`
HealthInterval Duration `yaml:"healthInterval" json:"-"`
Video VideoMediaConfig `yaml:"video" json:"video"`
AudioCapture AudioCaptureConfig `yaml:"audioCapture" json:"audioCapture"`
AudioPlayback AudioPlaybackConfig `yaml:"audioPlayback" json:"audioPlayback"`
RTSPPort int `json:"rtspPort" jsonschema:"minimum=1,maximum=65535"`
Video VideoMediaConfig `json:"video"`
AudioCapture AudioCaptureConfig `json:"audioCapture"`
AudioPlayback AudioPlaybackConfig `json:"audioPlayback"`
}
type VideoMediaConfig struct {
// Publisher selects the installed publisher script/pipeline family. The
// first pass uses pi-libcamera for current rovers; laptop-v4l2 can be added
// without changing the server-facing media shape again.
Enabled bool `yaml:"enabled" json:"enabled"`
Service string `yaml:"service" json:"service,omitempty"`
Publisher string `yaml:"publisher" json:"publisher,omitempty"`
Profile string `json:"profile" jsonschema:"minLength=1"`
Enabled bool `json:"enabled"`
// PublishURL is derived during validation. It remains in rover metadata for server-side
// consumers, but is not a second hand-written endpoint in /etc/roverd.yaml.
PublishURL string `yaml:"-" json:"publishUrl,omitempty"`
Device string `yaml:"device" json:"device,omitempty"`
InputFormat string `yaml:"inputFormat" json:"-"`
Width int `yaml:"width" json:"-"`
Height int `yaml:"height" json:"-"`
FPS int `yaml:"fps" json:"-"`
Bitrate int `yaml:"bitrate" json:"-"`
Inverted bool `yaml:"inverted" json:"-"`
SensorMode string `yaml:"sensorMode" json:"-"`
// consumers through MediaMetadata, but is never persisted in configuration.
PublishURL string `json:"-"`
Device string `json:"device"`
InputFormat string `json:"inputFormat"`
Width int `json:"width"`
Height int `json:"height"`
FPS int `json:"fps"`
Bitrate int `json:"bitrate"`
Inverted bool `json:"inverted"`
SensorMode string `json:"sensorMode"`
}
type AudioCaptureConfig struct {
Profile string `json:"profile" jsonschema:"minLength=1"`
// AudioCapture describes the rover microphone stream that browsers can
// subscribe to as "<rover>-audio". A disabled capture block still has
// normalized defaults so enabling it only requires flipping enabled: true.
Enabled bool `yaml:"enabled" json:"enabled"`
Service string `yaml:"service" json:"service,omitempty"`
Enabled bool `json:"enabled"`
// PublishURL follows the same derived-only contract as the video path.
PublishURL string `yaml:"-" json:"publishUrl,omitempty"`
Device string `yaml:"device" json:"device,omitempty"`
SampleRate int `yaml:"sampleRate" json:"-"`
Channels int `yaml:"channels" json:"-"`
Bitrate int `yaml:"bitrate" json:"-"`
PublishURL string `json:"-"`
SampleRate int `json:"sampleRate"`
Channels int `json:"channels"`
Bitrate int `json:"bitrate"`
}
type AudioPlaybackConfig struct {
Profile string `json:"profile" jsonschema:"minLength=1"`
// AudioPlayback describes the reverse stream that VIP users publish into
// MediaMTX for playback on the rover speaker. The URL is a request/read URL
// for the rover listener, while the server converts it to publish mode when
// it needs to inject audio.
Enabled bool `yaml:"enabled" json:"enabled"`
Service string `yaml:"service" json:"service,omitempty"`
Enabled bool `json:"enabled"`
// ForwardURL is derived because the server and rover must agree on the exact -fwd path.
ForwardURL string `yaml:"-" json:"forwardUrl,omitempty"`
Device string `yaml:"device" json:"device,omitempty"`
Normalize bool `yaml:"normalize" json:"-"`
NormalizeFilter string `yaml:"normalizeFilter" json:"-"`
ForwardURL string `json:"-"`
Normalize bool `json:"normalize"`
NormalizeFilter string `json:"normalizeFilter"`
}
type CameraServoConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
Pin int `yaml:"pin" json:"pin"`
FreqHz int `yaml:"freqHz" json:"freqHz"`
CycleLen int `yaml:"cycleLen" json:"cycleLen"`
MinPulseUs int `yaml:"minPulseUs" json:"minPulseUs"`
MaxPulseUs int `yaml:"maxPulseUs" json:"maxPulseUs"`
MinAngle float64 `yaml:"minAngle" json:"minAngle"`
MaxAngle float64 `yaml:"maxAngle" json:"maxAngle"`
HomeAngle float64 `yaml:"homeAngle" json:"homeAngle"`
NudgeDegrees float64 `yaml:"nudgeDegrees" json:"nudgeDegrees"`
AllowRawPulse bool `yaml:"allowRawPulse" json:"allowRawPulse"`
Invert bool `yaml:"invert" json:"invert"`
Enabled bool `json:"enabled"`
Pin int `json:"pin"`
FreqHz int `json:"freqHz"`
CycleLen int `json:"cycleLen"`
MinPulseUs int `json:"minPulseUs"`
MaxPulseUs int `json:"maxPulseUs"`
MinAngle float64 `json:"minAngle"`
MaxAngle float64 `json:"maxAngle"`
HomeAngle float64 `json:"homeAngle"`
NudgeDegrees float64 `json:"nudgeDegrees"`
AllowRawPulse bool `json:"allowRawPulse"`
Invert bool `json:"invert"`
}
type GPIOToggleConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
GPIOPin int `yaml:"gpioPin" json:"gpioPin"`
GPIOChip string `yaml:"gpioChip" json:"gpioChip"`
InitialOn bool `yaml:"initialOn" json:"initialOn"`
ActiveLow bool `yaml:"activeLow" json:"activeLow"`
Enabled bool `json:"enabled"`
GPIOPin int `json:"gpioPin"`
GPIOChip string `json:"gpioChip"`
InitialOn bool `json:"initialOn"`
ActiveLow bool `json:"activeLow"`
}
func (g GPIOToggleConfig) LogicalToGPIO(on bool) int {
@@ -173,110 +164,135 @@ func (g GPIOToggleConfig) LogicalToGPIO(on bool) int {
}
type AutoSideBrushConfig struct {
Enabled bool `yaml:"enabled"`
Speed int `yaml:"speed"`
Enabled bool `json:"enabled"`
Speed int `json:"speed"`
}
type PrivateConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
Safety PrivateSafetyConfig `yaml:"safety" json:"safety"`
Enabled bool `json:"enabled"`
Safety PrivateSafetyConfig `json:"safety"`
}
type PrivateSafetyConfig struct {
SpeedLimitEnabled bool `yaml:"speedLimitEnabled" json:"speedLimitEnabled"`
SpeedLimitMaxWheelMMs int `yaml:"speedLimitMaxWheelSpeed" json:"speedLimitMaxWheelSpeed"`
HardOvercurrentEnabled bool `yaml:"hardOvercurrentEnabled" json:"hardOvercurrentEnabled"`
OvercurrentStopMs int `yaml:"overcurrentStopMs" json:"overcurrentStopMs"`
HardBumpEnabled bool `yaml:"hardBumpEnabled" json:"hardBumpEnabled"`
BumpBackoffSpeed int `yaml:"bumpBackoffSpeed" json:"bumpBackoffSpeed"`
BumpBackoffMs int `yaml:"bumpBackoffMs" json:"bumpBackoffMs"`
CliffEnabled bool `yaml:"cliffEnabled" json:"cliffEnabled"`
CliffBackoffSpeed int `yaml:"cliffBackoffSpeed" json:"cliffBackoffSpeed"`
CliffBackoffMs int `yaml:"cliffBackoffMs" json:"cliffBackoffMs"`
VirtualWallEnabled bool `yaml:"virtualWallEnabled" json:"virtualWallEnabled"`
VirtualWallBackoffSpeed int `yaml:"virtualWallBackoffSpeed" json:"virtualWallBackoffSpeed"`
VirtualWallBackoffMs int `yaml:"virtualWallBackoffMs" json:"virtualWallBackoffMs"`
TriggerCooldownMs int `yaml:"triggerCooldownMs" json:"triggerCooldownMs"`
SpeedLimitEnabled bool `json:"speedLimitEnabled"`
SpeedLimitMaxWheelMMs int `json:"speedLimitMaxWheelSpeed"`
HardOvercurrentEnabled bool `json:"hardOvercurrentEnabled"`
OvercurrentStopMs int `json:"overcurrentStopMs"`
HardBumpEnabled bool `json:"hardBumpEnabled"`
BumpBackoffSpeed int `json:"bumpBackoffSpeed"`
BumpBackoffMs int `json:"bumpBackoffMs"`
CliffEnabled bool `json:"cliffEnabled"`
CliffBackoffSpeed int `json:"cliffBackoffSpeed"`
CliffBackoffMs int `json:"cliffBackoffMs"`
VirtualWallEnabled bool `json:"virtualWallEnabled"`
VirtualWallBackoffSpeed int `json:"virtualWallBackoffSpeed"`
VirtualWallBackoffMs int `json:"virtualWallBackoffMs"`
TriggerCooldownMs int `json:"triggerCooldownMs"`
}
type PiGPIOConfig struct {
Enabled bool `json:"enabled"`
BRC BRCConfig `json:"brc"`
CameraServo CameraServoConfig `json:"cameraServo"`
Headlight GPIOToggleConfig `json:"headlight"`
Laser GPIOToggleConfig `json:"laser"`
}
type Config struct {
Name string `yaml:"name"`
Description string `yaml:"description" json:"description,omitempty"`
Color string `yaml:"color" json:"color,omitempty"`
ServerURL string `yaml:"serverUrl"`
Serial SerialConfig `yaml:"serial"`
BRC BRCConfig `yaml:"brc"`
Battery BatteryConfig `yaml:"battery"`
MaxWheelMMs int `yaml:"maxWheelSpeed"`
Media MediaConfig `yaml:"media"`
CameraServo CameraServoConfig `yaml:"cameraServo"`
Audio AudioConfig `yaml:"audio"`
Horn HornConfig `yaml:"horn"`
Headlight GPIOToggleConfig `yaml:"headlight" json:"headlight"`
Laser GPIOToggleConfig `yaml:"laser" json:"laser"`
AutoSideBrush AutoSideBrushConfig `yaml:"autoSideBrush"`
Private PrivateConfig `yaml:"private" json:"private"`
PiGPIO PiGPIOConfig `json:"piGpio"`
Name string `json:"name" jsonschema:"minLength=1"`
Description string `json:"description"`
Color string `json:"color"`
ServerURL string `json:"serverUrl" jsonschema:"minLength=1"`
Serial SerialConfig `json:"serial"`
Battery BatteryConfig `json:"battery"`
MaxWheelMMs int `json:"maxWheelSpeed" jsonschema:"minimum=1,maximum=500"`
Media MediaConfig `json:"media"`
Audio AudioConfig `json:"audio"`
Horn HornConfig `json:"horn"`
AutoSideBrush AutoSideBrushConfig `json:"autoSideBrush"`
Private PrivateConfig `json:"private"`
}
func LoadConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
// DefaultConfig supplies initial settings; persisted and remotely submitted
// configuration is always a complete object.
func DefaultConfig() Config {
cfg := Config{
MaxWheelMMs: 500,
BRC: BRCConfig{
GPIOPin: 4,
GPIOChip: "gpiochip0",
PulseEvery: Duration{
Duration: time.Minute,
Name: "rover", ServerURL: "ws://localhost:8080/rover",
Serial: SerialConfig{Device: "/dev/ttyUSB0", Baud: 115200},
Battery: BatteryConfig{Full: 2068, Warn: 1700, Urgent: 1650},
PiGPIO: PiGPIOConfig{
BRC: BRCConfig{
Enabled: true,
GPIOPin: 4,
GPIOChip: "gpiochip0",
PulseEvery: Duration{
Duration: time.Minute,
},
PulseWidth: Duration{
Duration: time.Second,
},
},
PulseWidth: Duration{
Duration: time.Second,
CameraServo: CameraServoConfig{
Pin: 12,
FreqHz: 50,
CycleLen: 20000,
MinPulseUs: 900,
MaxPulseUs: 2100,
MinAngle: -15,
MaxAngle: 30,
HomeAngle: 0,
NudgeDegrees: 2,
},
Headlight: GPIOToggleConfig{
Enabled: true,
GPIOPin: 22,
GPIOChip: "gpiochip0",
InitialOn: false,
ActiveLow: true,
},
Laser: GPIOToggleConfig{
Enabled: false,
GPIOPin: 27,
GPIOChip: "gpiochip0",
InitialOn: false,
ActiveLow: false,
},
},
MaxWheelMMs: 500,
Media: MediaConfig{
RTSPPort: 8554,
HealthInterval: Duration{Duration: 30 * time.Second},
RTSPPort: 8554,
Video: VideoMediaConfig{
Enabled: true,
Service: "video-publisher.service",
Publisher: "pi-libcamera",
Profile: "v4l2",
Enabled: false,
Device: "/dev/video0", InputFormat: "mjpeg",
Width: 640,
Height: 480,
FPS: 30,
Bitrate: 2000000,
Inverted: true,
SensorMode: "1296:972",
Inverted: false,
SensorMode: "",
},
AudioCapture: AudioCaptureConfig{
Enabled: false,
Service: "audio-only-publisher.service",
Device: "hw:0,0",
Profile: "alsa",
Enabled: false,
SampleRate: 48000,
Channels: 2,
Bitrate: 510000,
},
AudioPlayback: AudioPlaybackConfig{
Enabled: true,
Service: "audio-forward-listener.service",
Device: "forward",
Profile: "alsa",
Enabled: false,
Normalize: true,
NormalizeFilter: "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled",
},
},
CameraServo: CameraServoConfig{
Pin: 12,
FreqHz: 50,
CycleLen: 20000,
MinPulseUs: 900,
MaxPulseUs: 2100,
MinAngle: -15,
MaxAngle: 30,
HomeAngle: 0,
NudgeDegrees: 2,
},
Audio: AudioConfig{
InputDevice: "hw:0,0", OutputDevice: "hw:0,0", MixerCard: "0", OutputSampleRate: 48000, OutputChannels: 2,
TTSEnabled: false,
DefaultEngine: "flite",
DefaultVoice: "rms",
@@ -291,20 +307,6 @@ func LoadConfig(path string) (*Config, error) {
SawGain: 0.7,
MaxDuration: Duration{Duration: 10000 * time.Millisecond},
},
Headlight: GPIOToggleConfig{
Enabled: true,
GPIOPin: 22,
GPIOChip: "gpiochip0",
InitialOn: false,
ActiveLow: true,
},
Laser: GPIOToggleConfig{
Enabled: false,
GPIOPin: 27,
GPIOChip: "gpiochip0",
InitialOn: false,
ActiveLow: false,
},
AutoSideBrush: AutoSideBrushConfig{
Enabled: true,
Speed: 20,
@@ -329,51 +331,88 @@ func LoadConfig(path string) (*Config, error) {
},
},
}
if err := yaml.Unmarshal(data, &cfg); err != nil {
return nil, err
}
if cfg.Name == "" {
return nil, errors.New("missing name")
}
normalizedColor, err := normalizeHexColor(cfg.Color)
return cfg
}
func LoadConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return DecodeConfig(data)
}
func DecodeConfig(data []byte) (*Config, error) {
if err := ValidateConfigurationSchema(data); err != nil {
return nil, err
}
var cfg Config
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&cfg); err != nil {
return nil, err
}
if err := decoder.Decode(new(any)); err != io.EOF {
return nil, errors.New("expected one JSON object")
}
if err := validateConfig(&cfg); err != nil {
return nil, err
}
return &cfg, nil
}
func validateConfig(cfg *Config) error {
if cfg.Name == "" {
return errors.New("missing name")
}
normalizedColor, err := normalizeHexColor(cfg.Color)
if err != nil {
return err
}
cfg.Color = normalizedColor
if cfg.ServerURL == "" {
return nil, errors.New("missing serverUrl")
server, err := url.Parse(cfg.ServerURL)
if err != nil || server.Hostname() == "" || (server.Scheme != "ws" && server.Scheme != "wss") || server.Path != "/rover" || server.RawQuery != "" || server.Fragment != "" {
return errors.New("serverUrl must be ws://host[:port]/rover or wss://host[:port]/rover")
}
if cfg.Serial.Device == "" || cfg.Serial.Baud == 0 {
return nil, errors.New("serial device/baud required")
return errors.New("serial device/baud required")
}
if cfg.Battery.Full == 0 {
return nil, errors.New("battery thresholds required")
return errors.New("battery thresholds required")
}
if cfg.MaxWheelMMs <= 0 || cfg.MaxWheelMMs > 500 {
return nil, fmt.Errorf("maxWheelSpeed must be 1-500, got %d", cfg.MaxWheelMMs)
return fmt.Errorf("maxWheelSpeed must be 1-500, got %d", cfg.MaxWheelMMs)
}
if cfg.BRC.GPIOChip == "" {
cfg.BRC.GPIOChip = "gpiochip0"
if cfg.PiGPIO.BRC.GPIOChip == "" {
cfg.PiGPIO.BRC.GPIOChip = "gpiochip0"
}
if cfg.Media.RTSPPort <= 0 {
cfg.Media.RTSPPort = 8554
}
if err := validateMediaConfig(&cfg.Media, cfg.ServerURL, cfg.Name); err != nil {
return nil, fmt.Errorf("media: %w", err)
return fmt.Errorf("media: %w", err)
}
if err := validateServoConfig(&cfg.CameraServo); err != nil {
return nil, fmt.Errorf("cameraServo: %w", err)
if cfg.PiGPIO.Enabled {
if err := validateServoConfig(&cfg.PiGPIO.CameraServo); err != nil {
return fmt.Errorf("cameraServo: %w", err)
}
if err := validateGPIOToggleConfig(&cfg.PiGPIO.Headlight); err != nil {
return fmt.Errorf("headlight: %w", err)
}
if err := validateGPIOToggleConfig(&cfg.PiGPIO.Laser); err != nil {
return fmt.Errorf("laser: %w", err)
}
if cfg.PiGPIO.BRC.Enabled && (cfg.PiGPIO.BRC.GPIOPin < 0 || cfg.PiGPIO.BRC.PulseEvery.Duration <= 0 || cfg.PiGPIO.BRC.PulseWidth.Duration <= 0) {
return errors.New("piGpio.brc: nonnegative pin and positive pulse durations required")
}
}
if err := validateGPIOToggleConfig(&cfg.Headlight); err != nil {
return nil, fmt.Errorf("headlight: %w", err)
}
if err := validateGPIOToggleConfig(&cfg.Laser); err != nil {
return nil, fmt.Errorf("laser: %w", err)
if err := validateAudioRouting(cfg.Audio); err != nil {
return err
}
validateAudioConfig(&cfg.Audio)
validateHornConfig(&cfg.Horn)
validateAutoSideBrushConfig(&cfg.AutoSideBrush)
return &cfg, nil
return nil
}
func validateServoConfig(cfg *CameraServoConfig) error {
@@ -432,18 +471,10 @@ func validateAudioConfig(cfg *AudioConfig) {
}
func validateMediaConfig(cfg *MediaConfig, serverURL string, roverName string) error {
/*
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.
*/
// Normalize shared settings before they become profile command variables.
if cfg.RTSPPort <= 0 {
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 {
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 {
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
// mjpeg or yuyv422. Normalizing here keeps the publisher script simple and
// 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 {
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;
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 {
if cfg.Service == "" {
cfg.Service = "audio-only-publisher.service"
}
if cfg.Device == "" {
cfg.Device = "hw:0,0"
}
if cfg.SampleRate <= 0 {
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 {
if cfg.Service == "" {
cfg.Service = "audio-forward-listener.service"
}
if cfg.Device == "" {
cfg.Device = "forward"
}
if cfg.NormalizeFilter == "" {
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
}
// 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
// prompt.
type ConsoleNotifier struct {
events chan<- RoverEvent
path string
logger *log.Logger
mu sync.Mutex
@@ -44,6 +45,12 @@ func (n *ConsoleNotifier) Notify(message string) {
n.mu.Lock()
defer n.mu.Unlock()
if n.events != nil {
select {
case n.events <- RoverEvent{Type: "event", Event: "daemon.notice", Ts: time.Now().UnixMilli(), Data: map[string]any{"message": message}}:
default:
}
}
console, err := os.OpenFile(n.path, os.O_WRONLY|os.O_APPEND, 0)
if err != nil {
n.logFailure("open", err)
@@ -65,3 +72,9 @@ func (n *ConsoleNotifier) logFailure(operation string, err error) {
n.logger.Printf("console notification %s failed for %s: %v", operation, n.path, err)
}
}
func (n *ConsoleNotifier) SetEvents(events chan<- RoverEvent) {
n.mu.Lock()
defer n.mu.Unlock()
n.events = events
}
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"log"
"strings"
"testing"
)
@@ -33,10 +34,12 @@ func TestDisabledNativeRolesResolveToFirmataOnEveryHostBuild(t *testing.T) {
}
defer manager.Close()
// All native entries are disabled, exactly as they can be on either a Pi or
// laptop rover. The shared resolver must therefore select every ESP32 role.
// The parent switch suppresses every native role even with saved child
// settings enabled. No GPIO provider may displace the external peripheral.
baseline := len(connection.Bytes())
controllers, err := ResolveRoverHardwareControllers(&Config{}, manager, discardLogger())
controllers, err := ResolveRoverHardwareControllers(&Config{PiGPIO: PiGPIOConfig{
CameraServo: CameraServoConfig{Enabled: true}, Headlight: GPIOToggleConfig{Enabled: true}, Laser: GPIOToggleConfig{Enabled: true},
}}, manager, discardLogger())
if err != nil {
t.Fatalf("resolve: %v", err)
}
@@ -93,49 +96,41 @@ func TestMissingNativeAndFirmataRolesRemainDisabled(t *testing.T) {
}
}
func TestEnabledNativeRolesWinEvenWithSeveralFirmataProviders(t *testing.T) {
func TestConflictingRolesRemainUnavailableWithoutInitializingGPIO(t *testing.T) {
roleDescription := PeripheralDescription{RoverControls: PeripheralRoverControls{
CameraServo: &PeripheralCameraServo{},
Headlight: &PeripheralDigitalRole{},
Laser: &PeripheralDigitalRole{},
CameraServo: &PeripheralCameraServo{}, Headlight: &PeripheralDigitalRole{}, Laser: &PeripheralDigitalRole{},
}}
manager := &PeripheralManager{
byID: make(map[string]*managedPeripheral),
peripherals: []*managedPeripheral{
{metadata: RoverPeripheralMetadata{ID: "firmata-0"}, description: roleDescription},
{metadata: RoverPeripheralMetadata{ID: "firmata-1"}, description: roleDescription},
},
}
cfg := &Config{
manager := &PeripheralManager{peripherals: []*managedPeripheral{
{metadata: RoverPeripheralMetadata{ID: "firmata-0"}, description: roleDescription},
}}
cfg := &Config{PiGPIO: PiGPIOConfig{Enabled: true,
CameraServo: CameraServoConfig{Enabled: true},
Headlight: GPIOToggleConfig{Enabled: true},
Laser: GPIOToggleConfig{Enabled: true},
}
nativeCamera := &testCameraServoController{cfg: cfg.CameraServo}
nativeToggles := map[string]*testToggleController{}
Headlight: GPIOToggleConfig{Enabled: true}, Laser: GPIOToggleConfig{Enabled: true},
}}
factories := nativeHardwareControllerFactories{
newCameraServo: func(_ CameraServoConfig, _ *log.Logger) (CameraServoController, error) {
return nativeCamera, nil
newCameraServo: func(CameraServoConfig, *log.Logger) (CameraServoController, error) {
t.Fatal("conflicting GPIO servo must not initialize")
return nil, nil
},
newToggle: func(name string, config GPIOToggleConfig, _ *log.Logger) (ToggleController, error) {
controller := &testToggleController{cfg: config}
nativeToggles[name] = controller
return controller, nil
newToggle: func(string, GPIOToggleConfig, *log.Logger) (ToggleController, error) {
t.Fatal("conflicting GPIO toggle must not initialize")
return nil, nil
},
}
// Duplicate Firmata declarations are irrelevant when native hardware wins;
// selection must neither fail nor initialize either ESP32 provider.
controllers, err := resolveRoverHardwareControllers(cfg, manager, discardLogger(), factories)
if err != nil {
t.Fatalf("resolve native precedence: %v", err)
t.Fatal(err)
}
if controllers.CameraServo != nativeCamera || controllers.Headlight != nativeToggles["headlight"] || controllers.Laser != nativeToggles["laser"] {
t.Fatal("resolver did not retain native controllers")
if controllers.CameraServo != nil || controllers.Headlight != nil || controllers.Laser != nil {
t.Fatal("conflicting roles must remain unavailable")
}
messages := controllers.StartupBroadcasts()
if len(messages) != 2 || messages[0] != "Ignored ESP32 camera servo, headlight, laser because native GPIO is enabled." || messages[1] != "Rover hardware ready: camera servo via native GPIO, headlight via native GPIO, laser via native GPIO." {
t.Fatalf("native precedence broadcasts = %#v", messages)
if len(controllers.issues) != 3 {
t.Fatalf("expected three role conflicts, got %v", controllers.issues)
}
for _, issue := range controllers.issues {
if !strings.Contains(issue, "firmata-0, pi-gpio") {
t.Fatalf("missing provider identities: %s", issue)
}
}
}
+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/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/invopop/jsonschema v0.13.0 h1:KvpoAJWEjR3uD9Kbm2HWJmqsEaHt8lBUpd0qHcIi21E=
github.com/invopop/jsonschema v0.13.0/go.mod h1:ffZ5Km5SWWRAIN6wbDXItl95euhFz2uON45H2qjYt+0=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/stianeikeland/go-rpio/v4 v4.6.0 h1:eAJgtw3jTtvn/CqwbC82ntcS+dtzUTgo5qlZKe677EY=
github.com/stianeikeland/go-rpio/v4 v4.6.0/go.mod h1:A3GvHxC1Om5zaId+HqB3HKqx4K/AqeckxB7qRjxMK7o=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
@@ -14,8 +27,12 @@ github.com/warthog618/go-gpiocdev v0.9.1 h1:pwHPaqjJfhCipIQl78V+O3l9OKHivdRDdmgX
github.com/warthog618/go-gpiocdev v0.9.1/go.mod h1:dN3e3t/S2aSNC+hgigGE/dBW8jE1ONk9bDSEYfoPyl8=
github.com/warthog618/go-gpiosim v0.1.1 h1:MRAEv+T+itmw+3GeIGpQJBfanUVyg0l3JCTwHtwdre4=
github.com/warthog618/go-gpiosim v0.1.1/go.mod h1:YXsnB+I9jdCMY4YAlMSRrlts25ltjmuIsrnoUrBLdqU=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
@@ -1,4 +1,4 @@
//go:build !dummy && !debian_laptop
//go:build !dummy
package roverd
@@ -3,7 +3,6 @@ package roverd
import (
"fmt"
"log"
"strings"
"time"
)
@@ -40,26 +39,20 @@ type ToggleController interface {
}
// RoverHardwareControllers is the result of the single startup-time backend
// decision. Its effective configurations are derived from whichever backend
// won, making the normal rover hello accurate on both Pi and laptop hosts.
// decision. Effective configurations describe the selected role providers.
type RoverHardwareControllers struct {
CameraServo CameraServoController
Headlight ToggleController
Laser ToggleController
ignoredESP32Roles []string
CameraServo CameraServoController
Headlight ToggleController
Laser ToggleController
issues []string
}
// StartupBroadcasts returns short operator-facing messages. Detailed pin and
// protocol information remains in the journal; tty1 only explains which
// physical backend won and whether an advertised ESP32 role was ignored.
// protocol information remains in the journal; tty1 reports selected providers
// and unavailable roles.
func (controllers RoverHardwareControllers) StartupBroadcasts() []string {
var messages []string
if len(controllers.ignoredESP32Roles) > 0 {
messages = append(messages, fmt.Sprintf(
"Ignored ESP32 %s because native GPIO is enabled.",
strings.Join(controllers.ignoredESP32Roles, ", "),
))
}
messages = append(messages, controllers.issues...)
messages = append(messages, fmt.Sprintf(
"Rover hardware ready: camera servo via %s, headlight via %s, laser via %s.",
controllerBackend(controllers.CameraServo),
@@ -81,9 +74,8 @@ type nativeHardwareControllerFactories struct {
newToggle func(string, GPIOToggleConfig, *log.Logger) (ToggleController, error)
}
// ResolveRoverHardwareControllers applies one rule on every real rover build:
// enabled native GPIO wins, otherwise one discovered ESP32 may fill the role.
// The rule is intentionally not selected by GOARCH or the debian_laptop tag.
// ResolveRoverHardwareControllers selects one provider per role, independent of
// transport. Conflicts disable only the affected role and are reported locally.
func ResolveRoverHardwareControllers(cfg *Config, peripherals *PeripheralManager, logger *log.Logger) (RoverHardwareControllers, error) {
factories := nativeHardwareControllerFactories{
newCameraServo: func(config CameraServoConfig, logger *log.Logger) (CameraServoController, error) {
@@ -98,56 +90,37 @@ func ResolveRoverHardwareControllers(cfg *Config, peripherals *PeripheralManager
func resolveRoverHardwareControllers(cfg *Config, peripherals *PeripheralManager, logger *log.Logger, factories nativeHardwareControllerFactories) (RoverHardwareControllers, error) {
var controllers RoverHardwareControllers
if cfg.PiGPIO.Enabled {
peripherals.piGPIO = &piGPIOPeripheral{cfg: cfg.PiGPIO, factories: factories}
}
// Resolving each role separately leaves unrelated hardware usable when a
// declaration conflicts or an individual device cannot initialize.
var err error
// Record ignored declarations separately from selecting controllers so the
// same native-first decision can be explained on the local rover console.
if cfg.CameraServo.Enabled && peripherals.HasRoverRole("cameraServo") {
controllers.ignoredESP32Roles = append(controllers.ignoredESP32Roles, "camera servo")
report := func(role string, err error) {
if err != nil {
message := fmt.Sprintf("%s unavailable: %v", role, err)
controllers.issues = append(controllers.issues, message)
logger.Print(message)
}
}
if cfg.Headlight.Enabled && peripherals.HasRoverRole("headlight") {
controllers.ignoredESP32Roles = append(controllers.ignoredESP32Roles, "headlight")
}
if cfg.Laser.Enabled && peripherals.HasRoverRole("laser") {
controllers.ignoredESP32Roles = append(controllers.ignoredESP32Roles, "laser")
}
controllers.CameraServo, err = resolveCameraServoController(cfg.CameraServo, peripherals, logger, factories.newCameraServo)
controllers.CameraServo, err = peripherals.NewCameraServo(logger)
if err != nil {
return RoverHardwareControllers{}, fmt.Errorf("init camera servo: %w", err)
controllers.CameraServo = nil
}
controllers.Headlight, err = resolveToggleController("headlight", cfg.Headlight, peripherals, logger, factories.newToggle)
report("camera servo", err)
controllers.Headlight, err = peripherals.NewToggle("headlight", logger)
if err != nil {
controllers.Close()
return RoverHardwareControllers{}, fmt.Errorf("init headlight: %w", err)
controllers.Headlight = nil
}
controllers.Laser, err = resolveToggleController("laser", cfg.Laser, peripherals, logger, factories.newToggle)
report("headlight", err)
controllers.Laser, err = peripherals.NewToggle("laser", logger)
if err != nil {
controllers.Close()
return RoverHardwareControllers{}, fmt.Errorf("init laser: %w", err)
controllers.Laser = nil
}
report("laser", err)
return controllers, nil
}
func resolveCameraServoController(nativeConfig CameraServoConfig, peripherals *PeripheralManager, logger *log.Logger, newNative func(CameraServoConfig, *log.Logger) (CameraServoController, error)) (CameraServoController, error) {
if nativeConfig.Enabled {
if peripherals.HasRoverRole("cameraServo") {
logger.Printf("ignoring ESP32 cameraServo because native camera servo is enabled")
}
return newNative(nativeConfig, logger)
}
return peripherals.NewFirmataCameraServo(logger)
}
func resolveToggleController(name string, nativeConfig GPIOToggleConfig, peripherals *PeripheralManager, logger *log.Logger, newNative func(string, GPIOToggleConfig, *log.Logger) (ToggleController, error)) (ToggleController, error) {
if nativeConfig.Enabled {
if peripherals.HasRoverRole(name) {
logger.Printf("ignoring ESP32 %s because native %s is enabled", name, name)
}
return newNative(name, nativeConfig, logger)
}
return peripherals.NewFirmataToggle(name, logger)
}
// Close releases selected controller resources in reverse dependency order.
// Firmata controllers do not close the shared serial connection; that remains
// owned by PeripheralManager and is released by its separate shutdown defer.
+1 -4
View File
@@ -124,10 +124,7 @@ func (h *HornSynth) run(waveform string, freqs []float64, stop <-chan struct{})
h.mu.Unlock()
volume *= gain
device := strings.TrimSpace(h.cfg.Device)
if device == "" {
device = "horn"
}
device := "rover_horn"
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...)
stdin, err := cmd.StdinPipe()
@@ -20,7 +20,7 @@ const (
)
// 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.
type HostStats struct {
UptimeSec *float64 `json:"uptimeSec,omitempty"`
@@ -136,17 +136,21 @@ func CollectHostStats(ctx context.Context) HostStats {
}
}
if coreV, err := readCoreVoltage(ctx); err != nil {
stats.addError("coreVoltage", err)
} else {
stats.CoreVoltageV = &coreV
}
// Firmware voltage/throttle telemetry is optional on non-Pi hosts.
if _, err := exec.LookPath("vcgencmd"); err == nil {
if coreV, err := readCoreVoltage(ctx); err != nil {
stats.addError("coreVoltage", err)
} else {
stats.CoreVoltageV = &coreV
}
if raw, flags, err := readThrottleFlags(ctx); err != nil {
stats.addError("throttled", err)
} else {
stats.ThrottledRaw = raw
stats.applyThrottleFlags(flags)
}
if raw, flags, err := readThrottleFlags(ctx); err != nil {
stats.addError("throttled", err)
} else {
stats.ThrottledRaw = raw
stats.applyThrottleFlags(flags)
}
if wifi, err := collectWiFiStats(ctx); err != 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