diff --git a/README.md b/README.md index 90fefecc..f4ad773f 100644 --- a/README.md +++ b/README.md @@ -64,11 +64,24 @@ To install roverd on your pi: 1. Install `Raspberry Pi OS (Legacy) Lite` (exactly what its called in the imager) on your SD card 2. Boot the pi up, plug in your good wifi adapter, use `nmtui` to set it up 3. Install `git`, clone this repo into your home folder -4. Move into the repo folder, run the roverd installer using `sudo pi/install_roverd.sh` +4. Move into the repo folder, run the roverd installer using `sudo rover/install_roverd.sh` 5. Reboot your raspberry pi -6. Roverd, along with the audio and video publishers should now be running. Roverd should have created it's default config file at `/etc/roverd.yaml` +6. Roverd, along with the audio and video publishers should now be running. Roverd should have created it's default config file at `/etc/roverd.json` -Edit the `/etc/roverd.yaml` config file to change settings like your rover's name, color, and set the server IP. +Edit the `/etc/roverd.json` config file to change settings like your rover's name, color, and set the server IP. + +Configuration is now a complete JSON object. See [roverd management](docs/roverd-management.md) +for schema/default export, local validation, the management API, and deployment checks. + +The roverd rework is in progress; see the [implementation tracker](docs/roverd-rework-plan.md). +Native GPIO now lives under `piGpio`, with its parent `enabled` switch disabled by default. +Enable that switch only on hosts using the internal Pi GPIO peripheral, and configure its camera servo, headlight, laser, and BRC children there. +See [hardware configuration notes](docs/rover-hardware-config.md) for the existing AIY Voice HAT setup and pin constraints. + +Build rover binaries with `make -C rover/roverd all`, or select one architecture with +`make -C rover/roverd build ARCH=armv6` (also `armv7`, `arm64`, or `amd64`). +Artifacts are `dist/roverd-linux-` and remain in the repository. +These builds share the same configuration and peripheral support; there is no laptop-specific build. ## Setting up the server diff --git a/dist/dummy1.json b/dist/dummy1.json new file mode 100644 index 00000000..b9f2388e --- /dev/null +++ b/dist/dummy1.json @@ -0,0 +1,127 @@ +{ + "piGpio": { + "enabled": false, + "brc": { + "enabled": true, + "gpioPin": 4, + "gpioChip": "gpiochip0", + "pulseEvery": "1m0s", + "pulseWidth": "1s" + }, + "cameraServo": { + "enabled": false, + "pin": 12, + "freqHz": 50, + "cycleLen": 20000, + "minPulseUs": 900, + "maxPulseUs": 2100, + "minAngle": -15, + "maxAngle": 30, + "homeAngle": 0, + "nudgeDegrees": 2, + "allowRawPulse": false, + "invert": false + }, + "headlight": { + "enabled": true, + "gpioPin": 22, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": true + }, + "laser": { + "enabled": false, + "gpioPin": 27, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": false + } + }, + "name": "dummy1", + "description": "", + "color": "", + "serverUrl": "ws://127.0.0.1:8080/rover", + "serial": { + "device": "/dev/ttyS0", + "baud": 115200 + }, + "battery": { + "full": 2068, + "warn": 1700, + "urgent": 1650 + }, + "maxWheelSpeed": 350, + "media": { + "rtspPort": 8554, + "manage": false, + "healthUrl": "http://127.0.0.1:9997/v3/paths/list", + "healthInterval": "30s", + "video": { + "enabled": true, + "service": "video-publisher.service", + "publisher": "pi-libcamera", + "device": "", + "inputFormat": "", + "width": 640, + "height": 480, + "fps": 30, + "bitrate": 2000000, + "inverted": true, + "sensorMode": "1296:972" + }, + "audioCapture": { + "enabled": false, + "service": "audio-only-publisher.service", + "device": "hw:0,0", + "sampleRate": 48000, + "channels": 2, + "bitrate": 510000 + }, + "audioPlayback": { + "enabled": true, + "service": "audio-forward-listener.service", + "device": "forward", + "normalize": true, + "normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled" + } + }, + "audio": { + "ttsEnabled": false, + "defaultEngine": "flite", + "defaultVoice": "rms", + "defaultPitch": 50 + }, + "horn": { + "enabled": false, + "volume": 0.25, + "sampleRate": 48000, + "channels": 1, + "device": "", + "sineGain": 1, + "sawGain": 0.7, + "maxDuration": "10s" + }, + "autoSideBrush": { + "enabled": true, + "speed": 20 + }, + "private": { + "enabled": false, + "safety": { + "speedLimitEnabled": false, + "speedLimitMaxWheelSpeed": 250, + "hardOvercurrentEnabled": false, + "overcurrentStopMs": 300, + "hardBumpEnabled": false, + "bumpBackoffSpeed": 250, + "bumpBackoffMs": 350, + "cliffEnabled": false, + "cliffBackoffSpeed": 250, + "cliffBackoffMs": 500, + "virtualWallEnabled": true, + "virtualWallBackoffSpeed": 250, + "virtualWallBackoffMs": 500, + "triggerCooldownMs": 800 + } + } +} diff --git a/dist/dummy1.yml b/dist/dummy1.yml deleted file mode 100644 index cf1bbf3a..00000000 --- a/dist/dummy1.yml +++ /dev/null @@ -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 diff --git a/dist/dummy2.json b/dist/dummy2.json new file mode 100644 index 00000000..71888904 --- /dev/null +++ b/dist/dummy2.json @@ -0,0 +1,127 @@ +{ + "piGpio": { + "enabled": false, + "brc": { + "enabled": true, + "gpioPin": 4, + "gpioChip": "gpiochip0", + "pulseEvery": "1m0s", + "pulseWidth": "1s" + }, + "cameraServo": { + "enabled": false, + "pin": 12, + "freqHz": 50, + "cycleLen": 20000, + "minPulseUs": 900, + "maxPulseUs": 2100, + "minAngle": -15, + "maxAngle": 30, + "homeAngle": 0, + "nudgeDegrees": 2, + "allowRawPulse": false, + "invert": false + }, + "headlight": { + "enabled": true, + "gpioPin": 22, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": true + }, + "laser": { + "enabled": false, + "gpioPin": 27, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": false + } + }, + "name": "dummy2", + "description": "", + "color": "", + "serverUrl": "ws://127.0.0.1:8080/rover", + "serial": { + "device": "/dev/ttyS0", + "baud": 115200 + }, + "battery": { + "full": 2068, + "warn": 1700, + "urgent": 1650 + }, + "maxWheelSpeed": 350, + "media": { + "rtspPort": 8554, + "manage": false, + "healthUrl": "http://127.0.0.1:9997/v3/paths/list", + "healthInterval": "30s", + "video": { + "enabled": true, + "service": "video-publisher.service", + "publisher": "pi-libcamera", + "device": "", + "inputFormat": "", + "width": 640, + "height": 480, + "fps": 30, + "bitrate": 2000000, + "inverted": true, + "sensorMode": "1296:972" + }, + "audioCapture": { + "enabled": false, + "service": "audio-only-publisher.service", + "device": "hw:0,0", + "sampleRate": 48000, + "channels": 2, + "bitrate": 510000 + }, + "audioPlayback": { + "enabled": true, + "service": "audio-forward-listener.service", + "device": "forward", + "normalize": true, + "normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled" + } + }, + "audio": { + "ttsEnabled": false, + "defaultEngine": "flite", + "defaultVoice": "rms", + "defaultPitch": 50 + }, + "horn": { + "enabled": false, + "volume": 0.25, + "sampleRate": 48000, + "channels": 1, + "device": "", + "sineGain": 1, + "sawGain": 0.7, + "maxDuration": "10s" + }, + "autoSideBrush": { + "enabled": true, + "speed": 20 + }, + "private": { + "enabled": false, + "safety": { + "speedLimitEnabled": false, + "speedLimitMaxWheelSpeed": 250, + "hardOvercurrentEnabled": false, + "overcurrentStopMs": 300, + "hardBumpEnabled": false, + "bumpBackoffSpeed": 250, + "bumpBackoffMs": 350, + "cliffEnabled": false, + "cliffBackoffSpeed": 250, + "cliffBackoffMs": 500, + "virtualWallEnabled": true, + "virtualWallBackoffSpeed": 250, + "virtualWallBackoffMs": 500, + "triggerCooldownMs": 800 + } + } +} diff --git a/dist/dummy2.yml b/dist/dummy2.yml deleted file mode 100644 index 895af997..00000000 --- a/dist/dummy2.yml +++ /dev/null @@ -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 diff --git a/dist/dummy3.json b/dist/dummy3.json new file mode 100644 index 00000000..c8e737ee --- /dev/null +++ b/dist/dummy3.json @@ -0,0 +1,127 @@ +{ + "piGpio": { + "enabled": false, + "brc": { + "enabled": true, + "gpioPin": 4, + "gpioChip": "gpiochip0", + "pulseEvery": "1m0s", + "pulseWidth": "1s" + }, + "cameraServo": { + "enabled": false, + "pin": 12, + "freqHz": 50, + "cycleLen": 20000, + "minPulseUs": 900, + "maxPulseUs": 2100, + "minAngle": -15, + "maxAngle": 30, + "homeAngle": 0, + "nudgeDegrees": 2, + "allowRawPulse": false, + "invert": false + }, + "headlight": { + "enabled": true, + "gpioPin": 22, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": true + }, + "laser": { + "enabled": false, + "gpioPin": 27, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": false + } + }, + "name": "dummy3", + "description": "", + "color": "", + "serverUrl": "ws://127.0.0.1:8080/rover", + "serial": { + "device": "/dev/ttyS0", + "baud": 115200 + }, + "battery": { + "full": 2068, + "warn": 1700, + "urgent": 1650 + }, + "maxWheelSpeed": 350, + "media": { + "rtspPort": 8554, + "manage": false, + "healthUrl": "http://127.0.0.1:9997/v3/paths/list", + "healthInterval": "30s", + "video": { + "enabled": true, + "service": "video-publisher.service", + "publisher": "pi-libcamera", + "device": "", + "inputFormat": "", + "width": 640, + "height": 480, + "fps": 30, + "bitrate": 2000000, + "inverted": true, + "sensorMode": "1296:972" + }, + "audioCapture": { + "enabled": false, + "service": "audio-only-publisher.service", + "device": "hw:0,0", + "sampleRate": 48000, + "channels": 2, + "bitrate": 510000 + }, + "audioPlayback": { + "enabled": true, + "service": "audio-forward-listener.service", + "device": "forward", + "normalize": true, + "normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled" + } + }, + "audio": { + "ttsEnabled": false, + "defaultEngine": "flite", + "defaultVoice": "rms", + "defaultPitch": 50 + }, + "horn": { + "enabled": false, + "volume": 0.25, + "sampleRate": 48000, + "channels": 1, + "device": "", + "sineGain": 1, + "sawGain": 0.7, + "maxDuration": "10s" + }, + "autoSideBrush": { + "enabled": true, + "speed": 20 + }, + "private": { + "enabled": false, + "safety": { + "speedLimitEnabled": false, + "speedLimitMaxWheelSpeed": 250, + "hardOvercurrentEnabled": false, + "overcurrentStopMs": 300, + "hardBumpEnabled": false, + "bumpBackoffSpeed": 250, + "bumpBackoffMs": 350, + "cliffEnabled": false, + "cliffBackoffSpeed": 250, + "cliffBackoffMs": 500, + "virtualWallEnabled": true, + "virtualWallBackoffSpeed": 250, + "virtualWallBackoffMs": 500, + "triggerCooldownMs": 800 + } + } +} diff --git a/dist/dummy3.yml b/dist/dummy3.yml deleted file mode 100644 index 921391dc..00000000 --- a/dist/dummy3.yml +++ /dev/null @@ -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 diff --git a/dist/roverd b/dist/roverd deleted file mode 100755 index b77dfda8..00000000 Binary files a/dist/roverd and /dev/null differ diff --git a/dist/roverd-debian-laptop b/dist/roverd-debian-laptop deleted file mode 100755 index 69b3940d..00000000 Binary files a/dist/roverd-debian-laptop and /dev/null differ diff --git a/dist/roverd-linux-amd64 b/dist/roverd-linux-amd64 new file mode 100755 index 00000000..97327b85 Binary files /dev/null and b/dist/roverd-linux-amd64 differ diff --git a/dist/roverd-linux-arm64 b/dist/roverd-linux-arm64 new file mode 100755 index 00000000..bcaccbad Binary files /dev/null and b/dist/roverd-linux-arm64 differ diff --git a/dist/roverd-linux-armv6 b/dist/roverd-linux-armv6 new file mode 100755 index 00000000..ba7cbaea Binary files /dev/null and b/dist/roverd-linux-armv6 differ diff --git a/dist/roverd-linux-armv7 b/dist/roverd-linux-armv7 new file mode 100755 index 00000000..e820ce87 Binary files /dev/null and b/dist/roverd-linux-armv7 differ diff --git a/docs/rover-hardware-config.md b/docs/rover-hardware-config.md new file mode 100644 index 00000000..52ce54ea --- /dev/null +++ b/docs/rover-hardware-config.md @@ -0,0 +1,51 @@ +# Rover hardware configuration notes + +This document records hardware-specific requirements while the roverd rework is in progress. The existing installer still contains machine-specific setup; the universal bootstrap and media profiles are not implemented yet. Final profile names and JSON examples will be added when those interfaces exist. + +## Universal configuration requirements + +- Audio capture and playback devices must be selectable on every supported architecture. An ARM machine need not use an AIY HAT, and an AMD64 machine need not use its first sound card. +- Keep the Google AIY Voice HAT as an explicit selectable profile, not a default applied to every Pi or every ARM binary. +- Prefer stable ALSA card identifiers over card numbers where supported; discover the actual identifier on the rover rather than assuming it from this document. +- Preserve concurrent TTS, horn, and forwarded audio playback and their independent volume controls. Device selection must cover these paths as well as the microphone streamer. +- Hardware-specific boot overlays, PWM pin allocation, and package setup belong to an explicit hardware choice or documented host setup. They must not be unconditional bootstrap side effects. + +## Agreed audio routing design + +Roverd configuration selects one physical input device and one physical output device. These may be on different sound cards. Roverd generates ALSA routing from those settings on startup, using the ordinary configuration save/restart flow when they change. + +The microphone streamer uses the selected input. TTS, horn, and forwarded audio share the selected output while retaining simultaneous playback and separate volume controls. Profiles use the generated logical devices supplied through their environment; they do not each hardcode or independently select physical audio hardware. Use ALSA conversion where supported instead of requiring all devices to accept the existing HAT playback format. + +AIY setup enables its hardware and uses this same routing system. The bootstrap still asks only for rover name and server address. This design is agreed but not yet implemented. + +## Existing AIY Voice HAT setup + +These facts come from the repository's existing installer/configuration, not a live hardware check: + +- The Pi installer enables `dtoverlay=googlevoicehat-soundcard` and `dtparam=i2s=on`, and disables onboard audio with `dtparam=audio=off`. +- The README records that this setup worked on Raspberry Pi OS Bookworm and had problems on Trixie. The rework must not imply that the HAT is verified on every Debian release. +- The current ALSA routing uses `hw:0,0` and mixer card `0`. A comment identifies the HAT card as `sndrpigooglevoi`; verify the actual card identifier on the deployed rover before replacing numeric device references. +- Logical playback devices are `tts`, `horn`, and `forward`; capture has the `rovermic` alias. They share a playback mixer configured for 16 kHz mono S16_LE and expose `TTSMaster`, `HornMaster`, and `ForwardMaster` volume controls. +- The existing source places a kernel-module `options` line in `asound.conf`. During audio-profile implementation, separate module configuration from ALSA PCM configuration instead of copying that assumption into the generic setup. +- The installer enables PWM on GPIO12/13 with `dtoverlay=pwm-2chan,pin=12,func=4,pin2=13,func2=4`, explicitly leaving GPIO18/19 free for I2S. The sample servo uses GPIO12, while the checked-in local config has a disabled servo on GPIO19. Do not enable that saved GPIO19 servo setting for the HAT setup without checking wiring and I2S ownership. + +For the new internal GPIO peripheral, enable `piGpio.enabled` on a rover that uses these GPIO features, then configure its children for the actual wiring: + +| Feature | Existing setup to preserve | +| --- | --- | +| BRC | Enabled, GPIO4 on `gpiochip0`, pulse every 1 minute for 1 second | +| Headlight | Enabled, GPIO22 on `gpiochip0`, active-low, initially off | +| Laser | Optional, GPIO27 on `gpiochip0`, active-high, initially off | +| Camera servo | Optional; sample GPIO12, 50 Hz, cycle length 20000, 900–2100 microseconds, -15 to 30 degrees, home 0, nudge 2 degrees | + +The parent switch now defaults to disabled. Saved child settings do not enable GPIO on their own. External peripherals must not advertise the same enabled role unless the conflicting internal role is disabled. + +## Remaining implementation work + +- [ ] Add AIY capture/playback profiles alongside generic selectable ALSA device profiles. +- [ ] Make TTS, horn, forwarded audio, and mixer routing use configured devices consistently. +- [ ] Generate ALSA routing from the shared input/output configuration, including distinct input/output cards, logical profile devices, format conversion, and independent playback volume controls. +- [ ] Audit fixed card numbers, named PCM assumptions, capture formats, camera orientation/sensor defaults, serial device defaults, and architecture-specific TTS assets. +- [ ] Keep required one-time host boot changes visible; distinguish a hardware-overlay reboot from ordinary roverd update/restart behavior. +- [ ] Add exact final profile selections and JSON settings for the existing AIY rover. +- [ ] Verify on the actual HAT and at least one non-HAT audio device; record results rather than assuming compatibility. diff --git a/docs/rover-peripherals.md b/docs/rover-peripherals.md index de93291e..f9d3e540 100644 --- a/docs/rover-peripherals.md +++ b/docs/rover-peripherals.md @@ -359,43 +359,33 @@ An ESP32 that supplies all three roles describes: } ``` -The ESP32 description owns the calibration for hardware attached to that ESP32. Rover YAML does not repeat the ESP32 pin numbers or servo calibration. +The ESP32 description owns the calibration for hardware attached to that ESP32. Rover configuration does not repeat the ESP32 pin numbers or servo calibration. -### Optional backend-selection rule +### Peripheral role selection -`roverd` resolves each built-in role once during startup: +Roverd resolves each built-in role once during startup across Firmata peripherals and the optional internal Pi GPIO peripheral. Exactly one provider enables a role; no providers leave it disabled. Multiple providers report a conflict identifying the devices and leave only that role unavailable. Native GPIO has no priority over external peripherals. -1. If that native Pi GPIO feature is enabled in rover YAML, use the native Pi implementation. -2. Otherwise, if exactly one discovered ESP32 declares the role, use its Firmata implementation. -3. Otherwise, leave the built-in feature disabled. +All native settings live under `piGpio`, whose parent switch defaults to disabled: -Native configuration deliberately wins. A Pi rover can attach an ESP32 for unrelated generic controls without unexpectedly moving its existing camera servo, headlight, or laser to the ESP32. To deliberately use the ESP32 for one of those features, disable only that native feature in rover YAML. - -Any rover configuration that should use the ESP32 for these roles keeps the corresponding native GPIO features disabled: - -```yaml -cameraServo: - enabled: false - -headlight: - enabled: false - -laser: - enabled: false +```json +{ + "piGpio": { + "enabled": false, + "cameraServo": { "enabled": false }, + "headlight": { "enabled": true, "gpioPin": 22, "activeLow": true }, + "laser": { "enabled": false }, + "brc": { "enabled": true, "gpioPin": 4, "pulseEvery": "1m", "pulseWidth": "1s" } + } +} ``` -An attached ESP32 can then fill any or all of those roles automatically at the next `roverd` start. This works identically on Raspberry Pi and laptop rover hosts; no USB path or backend name is added to YAML. +This is a layout excerpt, not a complete configuration file. Use the JSON sample or `-print-default-config` for all required fields. -Conflict behavior is fixed and simple: - -- Native feature enabled and ESP32 declares the same role: use native and log that the ESP32 role was ignored. -- Native feature disabled and one ESP32 declares the role: use that ESP32. -- Native feature disabled and no ESP32 declares the role: disable the feature. -- Native feature disabled and multiple ESP32s declare the same role: fail startup with a duplicate-role error rather than choosing by USB enumeration order. +While the parent is disabled, saved child settings cause no GPIO probing or initialization. When enabled, the internal peripheral appears as `pi-gpio` / “Pi GPIO” and offers its enabled roles. BRC runs as its automatic background function, not a user control. Pin, chip, servo calibration, and timing settings all remain inside this section. This applies to every architecture build. See the JSON sample config for complete settings; the WebUI configuration editor is a later rework step. ### Shared controller interfaces -The current `WSClient` directly owns concrete `*CameraServo` and `*GPIOToggle` values. Supporting either physical backend cleanly requires it to depend on the behavior it uses instead of a platform-specific concrete type. +`WSClient` uses controller interfaces shared by the internal GPIO and external Firmata providers. The intended interfaces are: @@ -433,7 +423,7 @@ ToggleController ### Effective hello metadata -The current hello is built from `c.cfg.CameraServo`, `c.cfg.Headlight`, and `c.cfg.Laser`. That cannot remain the source of truth because an ESP32 role may enable a feature whose native YAML entry is disabled. +Hello uses the selected controllers’ effective configuration, since external roles are independent of saved native GPIO settings. After startup resolution, the selected controller supplies the effective public configuration. `sendHello()` advertises that effective configuration: @@ -794,7 +784,7 @@ Use `esp32-s3-devkitc-1` and the matching `/dev/ttyACM*` device for a native-USB ESP32-S3. ```bash -cd pi/roverd +cd rover/roverd go run ./cmd/peripheral-probe -port /dev/ttyUSB0 ``` ## Connection lifecycle @@ -813,8 +803,8 @@ Peripheral discovery happens exactly once per `roverd` process. The currently im 8. Validates every advertised standard-output pin against Firmata capabilities. 9. Configures generic digital, PWM, and servo pin modes once. 10. Assigns process-local IDs such as `firmata-0` and `firmata-1` in discovery order. -11. Resolves `cameraServo`, `headlight`, and `laser` against the native configuration. -12. Rejects duplicate ESP32 providers only when the corresponding native role is disabled and Firmata selection would otherwise be ambiguous. +11. Registers the internal Pi GPIO peripheral if enabled and resolves camera-servo, headlight, and laser roles across providers. +12. Reports duplicate role providers and leaves conflicting roles unavailable. 13. Constructs the selected native or Firmata controllers and fixed generic inventory. 14. Constructs `WSClient` with those controllers and that inventory. 15. Connects to the server and includes the effective built-in configuration and renderable inventory in the normal rover hello. @@ -1144,7 +1134,7 @@ repository reference firmware. The package manifest, README, and examples are self-contained so the same directory can be published directly to the PlatformIO Registry as `legop3/RoverPeripheral`. -### `pi/roverd` +### `rover/roverd` `PeripheralManager` is responsible for: @@ -1164,9 +1154,9 @@ Only renderable control metadata leaves `roverd`. Firmata pin numbers, output ma The manager should remain independent of the existing Roomba Open Interface serial adapter. A peripheral serial connection is not the Roomba base serial connection and must not be routed through `SerialAdapter`. -The transport foundation is a focused Firmata parser/client in `pi/roverd/firmata.go`. It operates on `io.ReadWriteCloser`, which keeps byte-stream behavior testable without hardware and lets discovery pass either `/dev/ttyUSB*` or `/dev/ttyACM*` ports into the same client. `pi/roverd/cmd/peripheral-probe` remains the direct hardware diagnostic entry point, while `PeripheralManager` now connects the same client to automatic daemon startup discovery. +The transport foundation is a focused Firmata parser/client in `rover/roverd/firmata.go`. It operates on `io.ReadWriteCloser`, which keeps byte-stream behavior testable without hardware and lets discovery pass either `/dev/ttyUSB*` or `/dev/ttyACM*` ports into the same client. `rover/roverd/cmd/peripheral-probe` remains the direct hardware diagnostic entry point, while `PeripheralManager` now connects the same client to automatic daemon startup discovery. -`WSClient` now depends on shared camera-servo and toggle controller interfaces rather than platform-selected concrete types. The startup resolver uses the same native-first rule in the ARM Pi and amd64 laptop binaries. Firmata camera movement retains the established limits, home position, nudging, inversion, pulse calibration, raw-pulse policy, and movement-rate behavior; Firmata toggles retain logical state and polarity conversion. +`WSClient` now depends on shared camera-servo and toggle controller interfaces rather than platform-selected concrete types. The startup resolver uses the same unique-provider rule in every architecture binary. Firmata camera movement retains the established limits, home position, nudging, inversion, pulse calibration, raw-pulse policy, and movement-rate behavior; Firmata toggles retain logical state and polarity conversion. ### Server @@ -1247,8 +1237,8 @@ The completed system should be verified with a real ESP32 and rover Linux comput - Confirm camera angle limits, home position, nudge amount, inversion, pulse calibration, and rate limiting match the declared ESP32 configuration. - Confirm headlight and laser toggle state events remain identical to the native Pi path. - Confirm existing laser restrictions still apply with the Firmata backend. -- Enable a native role and declare the same ESP32 role; confirm native wins and the ignored role is logged. -- Disable native and declare the same role from two ESP32s; confirm startup fails with a clear duplicate-role error. +- Enable Pi GPIO and a native role also declared by an ESP32; confirm the conflict lists both providers and leaves that role unavailable. +- Declare the same role from two ESP32s; confirm a clear conflict and that unrelated roles remain available. - Confirm a Pi rover can use native built-in controls and generic ESP32 controls simultaneously. - Repeat ESP32 role selection on both the ARM Pi binary and amd64 laptop binary and confirm their commands and advertised configurations match. diff --git a/docs/roverd-management.md b/docs/roverd-management.md new file mode 100644 index 00000000..ed028014 --- /dev/null +++ b/docs/roverd-management.md @@ -0,0 +1,77 @@ +# Roverd configuration and management + +Roverd now reads `/etc/roverd.json`. YAML settings are no longer accepted. Repository samples and installer paths use JSON; there is no configuration migration or legacy reader. + +The schema is generated from the Go configuration types. Both configuration files and remote submissions must contain the complete object. Derived media URLs are excluded from saved settings and still included in control hello metadata. + +## Local configuration commands + +These commands do not open hardware, start media, or connect to the server: + +```sh +./dist/roverd-linux-amd64 -print-default-config +./dist/roverd-linux-amd64 -print-config-schema +./dist/roverd-linux-amd64 -config rover/roverd/roverd.sample.json -check-config +``` + +Select the appropriate architecture binary on a rover. The default object supplies initial values; edit the name and server URL before installing it. The initial serial path may need configuration for the actual hardware. + +## Connections and state + +- `/rover`: existing control commands, acknowledgements, sensors, and operational toggle state. The planned full `roverState` replacement is not implemented yet. +- `/rover/management`: configuration hello, management commands/acknowledgements, host statistics, and daemon events. +- Derive the management address from the configured `ws://host[:port]/rover` or `wss://host[:port]/rover` control URL; there is no second server address to maintain. +- Management starts independently of hardware initialization and remains available after serial/peripheral startup failure. +- Control disconnect docking/reboot behavior still depends on control connectivity. A live management connection does not count as a working control connection. +- The server maintains management records independently of the control roster, only in memory. Management disconnect removes the record; hello repopulates it. +- Profile catalogs in hello are currently empty. YAML media profiles are the next media implementation stage, not installed catalogs hidden elsewhere. + +## Configuration page + +Open `/admin?section=fleet` as an admin or lockdown admin. Select a management-connected rover, edit its schema-driven form, and use “Save to this rover”. For a fleet change, select the field below the form and use “Apply this field to all rovers”; its value comes from the current draft. Review individual results. Offline rovers are not queued. + +## Admin Socket.IO API + +Each request receives a callback containing either `{ success: true, ...result }` or `{ error: "..." }`. Authorization uses the existing admin/lockdown-admin role check. + +| Event | Payload | Result | +| --- | --- | --- | +| `roverManagement:list` | `{}` | `rovers`, including management-only rovers | +| `roverManagement:get` | `{ roverId }` | Current configuration, schema, profiles, host statistics, recent notices | +| `roverManagement:save` | `{ roverId, config }` | Request ID after roverd acknowledges the complete object | +| `roverManagement:applyField` | `{ path: ["piGpio", "enabled"], value: false }` | Individual `results` containing rover ID, success/error, and successful request ID | +| `roverManagement:command` | `{ roverId, type, reboot?, media? }` | Request ID after acknowledgement; types are `reboot`, `update`, `media` | + +Admin notifications are `roverManagement:changed`, `roverManagement:offline`, `roverManagement:hostStats`, and `roverManagement:event`. Requests time out if no acknowledgement arrives. Disconnect before acknowledgement reports an unknown outcome as an error; reconnect and read the actual configuration rather than assuming it was not saved. + +The existing reboot/update UI paths use management delivery and retain `commandAck` notifications. The separate user “reboot my rover” permission/cooldown checks remain in place. Generic media-management commands now require admin privileges. + +## Save lifecycle + +1. Validate the complete JSON object against the schema and existing semantic checks. +2. Block new control commands and stop motion when a control runtime exists. +3. Write and sync a temporary file, then atomically replace the configuration file with mode `0600`. +4. Attempt the acknowledgement, cancel the daemon runtime, and release hardware resources. +5. Re-execute roverd, reload the saved file, and send a new management hello. + +Once the file has been replaced, roverd restarts even if the acknowledgement cannot be delivered. The server does not optimistically overwrite its cached configuration. Invalid submissions leave the file untouched. + +## Deployment verification still required + +Do this on the intended server/rover, not the development machine: + +1. Deploy the changed server and the matching rover binary/config together. Capture `journalctl -u roverd -f` and server logs. +2. With an authenticated admin Socket.IO session, call `roverManagement:list` and `roverManagement:get`. Expect configuration and schema even when the rover's serial device cannot open. +3. Change a harmless setting such as description in the returned full object and call `roverManagement:save`. Expect an acknowledgement, disconnect/reconnect, and a new hello containing that setting. Confirm `/etc/roverd.json` matches and survives a service restart. +4. Submit an incomplete object. Expect an error, no file replacement, and no restart. +5. Confirm host statistics and autocharge/watchdog/daemon notices still reach their existing UI/alert consumers through management. Headlight/laser state must remain on control. +6. Verify reboot/update requests use management, the normal user reboot restrictions still apply, and non-admin clients cannot read/save configuration or invoke the admin command endpoint. +7. Confirm new movement commands cannot execute while a save/reboot/update is stopping the rover, and that control disconnect safety still works independently of management. + +Record acknowledgement errors, reconnect hello contents, relevant journal/server output, and physical stop behavior in the implementation tracker. Do not treat CLI validation or compilation as evidence of these deployed flows. + +## Pending stages + +Browser/live verification of the configuration page, shared `roverState`, YAML media catalogs/child supervision, universal ALSA routing, standalone bootstrap, and replacement update workflow remain pending. The current updater and systemd media supervisor have moved transport but retain their existing implementations until those stages. + +Apply-field targets the currently management-connected fleet. It clones each rover’s own configuration, replaces an existing field, and sends the complete object for rover-side validation. Inspect individual results for failures. Missing fields and changed connections are reported; offline changes are not queued. Paths traverse object fields, not array elements. Array-valued fields can be replaced as a whole. diff --git a/docs/roverd-rework-plan.md b/docs/roverd-rework-plan.md new file mode 100644 index 00000000..cff47c35 --- /dev/null +++ b/docs/roverd-rework-plan.md @@ -0,0 +1,266 @@ +# Roverd rework plan and implementation tracker + +Status: implementation authorized on 2026-11-16; repository/build, internal GPIO, and JSON/management backend implemented; live management verification and remaining stages pending. + +This is the persistent plan and progress record for the roverd rework. Update it as implementation proceeds, recording completed work, decisions, verification evidence, and remaining work. Keep unfinished work unchecked; distinguish implemented behavior from runtime-verified behavior. + +## Authorization and working rules + +- The user explicitly authorized implementation with `IPI` on 2026-11-16. +- No backward compatibility: no migrations, old-path aliases, legacy fallbacks, or dual protocols. Roverd, server, and WebUI move together. +- Prefer the simplest effective implementation. The behavior below is the intended outcome; avoid adding frameworks or bookkeeping without a concrete need. +- Follow repository verification rules: no new tests unless requested, no automatic full-project checks, and use the smallest useful verification. This development machine is not the deployed server or rover hardware. + +## Agreed design + +### Repository and builds + +- Rename `pi/` to `rover/`; update paths, imports, scripts, build commands, and documentation. +- Replace machine-specific builds and the `debian_laptop` distinction with architecture-specific Linux builds: ARMv6, ARMv7, ARM64, and AMD64. +- Hardware support depends on configuration and available hardware, not a Pi/laptop classification. Remove the existing laptop-specific hardware stubs as part of resolving this split. +- Keep prebuilt binaries committed in `dist/`. No published releases or release bundles are required. +- Detect the installed OS architecture during installation, including 32-bit ARM installations; do not select solely from CPU capability. +- Debian is the target platform across rover hardware. + +### Internal Pi GPIO peripheral + +- Provide one `piGpio` configuration section, presented as “Pi GPIO peripheral”, with a parent `enabled` switch defaulting to disabled. +- Keep all native GPIO settings inside this section, beneath the parent switch in the editor: + - Camera servo: enablement, pin, PWM, calibration, limits, and movement settings. + - Headlight and laser: individual enablement, pin/chip, polarity, and initial state. + - BRC: enablement, pin/chip, pulse interval, and pulse width. +- Disabling the parent switch disables the entire internal peripheral without probing, initializing, or accessing GPIO resources. Preserve its saved settings for later re-enablement. No Pi GPIO settings remain scattered elsewhere in configuration. +- When enabled, register one internal peripheral named “Pi GPIO”, with a stable ID such as `pi-gpio`, offering only the configured enabled camera-servo/headlight/laser roles. +- Separate peripheral identity and role ownership from the Firmata transport. Use a small common provider interface for external Firmata peripherals and the internal GPIO peripheral, reusing the existing camera-servo and toggle controller interfaces. +- Call GPIO implementations directly in process; do not simulate serial connections or Firmata messages. +- The internal peripheral owns BRC startup and shutdown as an automatic background function, not a fake user-facing control. +- Apply one role-conflict rule across providers: if multiple peripherals advertise the same role, report the providers and leave that role unavailable until corrected. Keep management accessible. Remove the current implicit native-GPIO priority; different roles may come from different peripherals. +- Operational state uses the same `roverState` object regardless of whether its provider is internal GPIO or an external peripheral. +- This runtime switch replaces the machine-specific GPIO build distinction. GPIO being disabled must permit operation on non-Pi hosts without GPIO errors. + +### Configuration ownership and saves + +- Roverd owns one `/etc/roverd.json` object containing all rover settings and supplies its JSON Schema. +- Include selected media profiles, enablement, devices, and media settings in configuration. Derive runtime values such as complete streaming URLs in roverd. +- Management hello sends current configuration, schema, and available media profiles. +- The server holds these only in memory. Reconnection repopulates them; there is no configuration database or offline change queue. +- Every save transmits the complete configuration object, even when only one field changed. +- Roverd validates the proposed configuration, atomically writes it, acknowledges the save, stops motion and child processes, and restarts. Its next hello reports the configuration actually loaded. +- Invalid submissions return an error without replacing the file. +- No deltas, configuration versions, or rollback system. +- Existing JSON tags omit some settings; do not mistake current hello metadata serialization for a complete configuration representation. + +### Communication channels + +Control channel: + +- Driving and other rover actions, with their acknowledgements. +- Roomba sensor telemetry. +- Complete `roverState` messages. + +Management channel (a separate WebSocket): + +- Configuration and profile management. +- Reboot and software update commands/results. +- Media process control, status, and output. +- Host statistics. +- Daemon status notices, including autocharge timer notices and watchdog diagnostics. + +Classify existing events by purpose rather than moving the entire existing event stream wholesale. Update server handlers and UI consumers along with their producers. Headlight and laser state are operational state, not management. + +Start management before hardware initialization so hardware configuration errors remain remotely diagnosable and fixable. Use the existing admin authorization path for management operations. Preserve motion-stop behavior for reboot, update, and configuration restart. Control-connection safety behavior must remain tied to control availability, not be satisfied by a live management connection. + +### One current rover state + +- Roverd owns one `roverState` JSON object for operational state such as headlight and laser states. +- Send the full object on control connection/reconnection and whenever its contents change. +- The server replaces its current object for that rover and uses that single copy for all consumers and UI updates. +- Remove separate headlight/laser state stores and per-field state events. No patches or deltas. +- Clear current state on disconnect so stale values are not presented as live. +- Roomba telemetry and management status remain separate from `roverState`. + +### WebUI + +- Reuse the existing React JSON Schema form library for each rover's configuration page. +- “Save to this rover” submits the complete configuration. +- “Apply this field to all rovers” replaces that field in each connected rover's own configuration, then sends each its complete resulting object. Preserve every rover's other settings. +- Show individual results; skip offline rovers without queued changes. +- Include profile selection, custom profile editing, media status/output, reboot, and software update controls. + +### Audio devices and ALSA routing + +- One audio configuration selects the physical input device and physical output device on every architecture. Input and output may belong to different sound cards; prefer stable ALSA device names over fixed card numbers. +- The microphone streamer uses the selected input. Forwarded audio, TTS, and horn share the selected output, with simultaneous playback and independent volume controls. +- Roverd generates ALSA routing from these settings as part of configuration startup. Supported format conversion belongs in the ALSA routing rather than assuming every device accepts the AIY format. +- Media profiles consume the resulting logical audio devices through the command environment instead of hardcoding physical devices such as `hw:0,0`. +- AIY-specific setup enables the HAT hardware; it uses this same audio configuration and routing system, not a separate set of device settings. +- Audio changes use the ordinary whole-object configuration save/restart flow. Device selection remains in the WebUI configuration, not the bootstrap questionnaire. + +### Media profiles + +- Keep three accessible YAML catalogs under `rover/profiles/`: video publishing, microphone publishing, and audio playback. +- Each profile has an identifier, name, description, optional `setup` command, and `run` command. Support multiline shell commands and pipelines. +- Read bundled profiles directly from the managed repository checkout. No separate profile installation or registration. +- Allow exactly one custom YAML profile per category under `/etc/roverd/profiles/`, editable through management. These files remain outside the checkout and survive updates. +- JSON configuration selects profiles and supplies settings such as devices, resolution, and bitrate. +- Profiles may contain hardware-specific configurations contributed by rover builders; no plugin API or custom code module is needed for each encoder. +- Preserve Google AIY Voice HAT support as an explicit option, while supporting configurable audio devices on every architecture. Do not treat Pi/ARM as synonymous with AIY hardware or assume sound card zero. +- Audit setup-specific assumptions beyond streamers, including TTS/horn/mixer routing, boot overlays, PWM/I2S pin conflicts, cameras, serial devices, and TTS assets. Generalize where useful and document the exact selections needed for the existing rover in [hardware configuration notes](rover-hardware-config.md). + +### Command variables and setup + +- Launch commands through a shell. Supply string values through environment variables rather than inserting them into shell source or creating a template language. +- Supply rover name, server host, audio/video devices, media settings, complete publish/playback URLs, and profile working directory to both setup and run commands. +- Example: `ffmpeg -i "$ROVER_VIDEO_DEVICE" … "$ROVER_VIDEO_PUBLISH_URL"`. +- Each profile gets a persistent working directory under `/var/lib/roverd/profiles/` for downloads, builds, and other generated files. +- At every roverd startup, run each selected enabled profile's setup command before its run command. Commands must be safe to repeat. +- No persistent setup-success tracking. Profile changes save configuration and restart roverd, naturally running setup for the newly selected profile. +- Routine streamer retries run only the run command. +- Setup failure is visible and prevents that streamer from launching, without stopping roverd or the other streamers. + +### Media supervision and output + +- Roverd directly supervises the three media commands as child processes. +- Restart exited commands after a short retry delay. Server restarts and Wi-Fi interruptions are routine retry situations. +- Streamer failure never stops or restarts roverd. Management connection loss does not stop streamers. +- Shutdown stops complete child process groups, including pipelines. +- Capture stdout/stderr and continuously forward output through management while connected. Use bounded buffering so noisy commands or disconnections cannot block streamers or consume unlimited memory. +- No viewer subscriptions or output-demand tracking. +- Remove old streamer systemd services and the code managing them. Systemd supervises only roverd, running as root. + +### Standalone bootstrap + +The bootstrap script works without an existing repository on the rover: + +1. Install basic Debian prerequisites. +2. Clone the repository into `/opt/roverd`. +3. Invoke the checkout's installation script. +4. Automatically select the committed binary matching the installed OS architecture. +5. Create initial configuration and working directories. +6. Install and start the single root roverd service. + +Ask for only rover name and server address. Everything else starts with defaults and is configured through management; no camera, encoder, audio, or machine-profile questionnaire. + +`/opt/roverd` belongs to roverd and is not a development working directory. Profile setup handles hardware-specific dependencies. + +### Self-update + +- Use a helper that survives roverd restarting. +- Update the managed checkout, invoke the same installation script used by bootstrap, install the matching committed binary, and restart roverd. +- Bundled profiles update with the checkout. Preserve local JSON configuration, custom profiles, and persistent profile working directories. +- Forward progress through management while available and make the update result available after reconnection. +- Routine updates restart the service without rebooting the computer. + +## Implementation checklist + +The order below is a working sequence, not a requirement to leave incompatible intermediate states deployed. + +- [x] Receive explicit `IPI` before code implementation (2026-11-16). +- [x] Rename `pi/` to `rover/` and update references. +- [x] Replace machine-specific build targets/tags with architecture-specific artifacts and resolve hardware support split. +- [x] Group every native GPIO setting under the disabled-by-default Pi GPIO peripheral switch in the current configuration and samples. +- [ ] Expose the grouped Pi GPIO configuration in the new JSON schema/UI. +- [x] Register Pi GPIO through the common peripheral provider path, including BRC lifecycle ownership and uniform role-conflict handling. +- [ ] Connect peripheral operational state to the new shared `roverState` object. +- [x] Gate GPIO provider registration, initialization, and BRC startup behind the parent switch; retain saved child settings. Hardware validation remains pending. +- [x] Implement complete JSON configuration serialization, schema, validation, atomic saves, and restart flow (live save/reconnect verification pending). +- [x] Implement separate management connection and in-memory server management state. +- [x] Move reboot, update, media management, host statistics, and daemon status messages to management; update consumers. Preserve the separately authorized user reboot path. +- [x] Separate management lifecycle from hardware startup failures (deployment verification pending). +- [ ] Implement full-object `roverState` and consolidate server/UI operational-state consumers. +- [ ] Add bundled YAML catalogs and one custom YAML profile per media category. +- [ ] Preserve AIY HAT as an explicit profile and expose ordinary audio-device selection on every architecture, including TTS/horn/mixer paths. +- [ ] Generate ALSA routing from shared input/output selections; connect microphone, TTS, horn, forwarded audio, and independent volume controls to the resulting logical devices. +- [ ] Document exact configuration for the existing AIY rover and audit other machine-specific assumptions. +- [ ] Implement command environments, persistent working directories, and setup on each daemon startup. +- [ ] Replace media systemd management with child-process supervision and continuous bounded output forwarding. +- [x] Implement per-rover schema editor and complete-object saves (browser/live verification pending). +- [x] Implement apply-one-field-to-all-connected-rovers with individual results (browser/live verification pending). +- [ ] Add profile editing/selection, media output/status, reboot, and update UI. +- [ ] Implement standalone bootstrap with only name/address input and automatic OS architecture selection. +- [ ] Implement shared checkout installation and self-update with reconnect-visible results. +- [ ] Remove obsolete services, configuration files, scripts, build distinctions, and documentation. +- [ ] Update user/contributor documentation, including profile variables, setup expectations, building, installation, and updates. +- [ ] Perform focused available verification and record results below. +- [ ] Record deployment/hardware checks still required; do not claim those verified locally. + +## Verification record + +2026-11-16, foundation stage: + +- Focused existing peripheral tests passed: `go test . -run 'Test(DisabledNativeRolesResolveToFirmataOnEveryHostBuild|MissingNativeAndFirmataRolesRemainDisabled|ConflictingRolesRemainUnavailableWithoutInitializingGPIO|Peripheral)' -count=1` in `rover/roverd`. Adapted existing expectations for the deliberately changed config/role-conflict behavior; no new test files were created. These exercise Firmata behavior, parent-disabled selection with enabled saved children, and conflicts that must not initialize native hardware. +- An initial test invocation from the repository root failed because the Go module is under `rover/roverd`; reran from that module as above. +- Architecture builds passed for ARMv6, ARMv7, ARM64, and AMD64. Regenerated all four artifacts after final shutdown/error-handling corrections; all builds passed. +- `git diff --check` passed for tracked changes. +- `bash -n rover/install/profiles.sh` passed. Actual installation was not run on this development machine. +- GPIO electrical behavior, BRC timing, and AIY audio remain unverified on hardware. On the actual rover, check startup inventory/role conflicts and exercise configured light/servo/BRC outputs; capture journal output and observed behavior. + + +Record each meaningful check with the affected behavior, command or action, result, and limitations. In particular, distinguish local evidence from actual rover/server verification of connection recovery, motion stopping, process cleanup, media streaming, and updates. + +## Progress and decisions + +- 2026-11-15: Consolidated the agreed design and user corrections into this persistent tracker. Implementation is pending `IPI`. +- 2026-11-16: Added the internal Pi GPIO peripheral design after inspecting current role ownership and BRC handling. All native GPIO options belong under one parent enable switch; disabled means no GPIO access. Implementation remains pending `IPI`. +- 2026-11-16: Received `IPI` and started the repository/build and internal GPIO foundation. The user additionally required universal device options while retaining an explicit AIY HAT setup; recorded existing assumptions in `rover-hardware-config.md`. +- Rejected complexity: release publishing, separate profile installation, persistent setup tracking, viewer-dependent output forwarding, and backward compatibility. +- Settled state boundary: operational state uses complete `roverState` objects on control; configuration/host/process/daemon management uses the management connection. + +## Remaining implementation details + +Resolve these with the simplest approach during implementation and record the result here; they do not change the agreed behavior: + +- Exact profile YAML shape, environment variable names, and architecture artifact names. +- Exact management message shapes and remaining existing event classifications. +- Update target selection using the existing repository workflow, without introducing release publishing. +- Startup defaults that let a newly installed rover connect for configuration before its hardware is configured. + +### Foundation implementation notes (2026-11-16) + +- Added common role providers and the internal `pi-gpio` peripheral. Conflicts and role initialization failures leave that role unavailable while other roles continue; existing hello/controller behavior remains until the communication rework. +- BRC belongs to the internal peripheral and waits for its writer to stop before releasing GPIO. Shutdown interrupts long pulses. +- The installer now chooses the architecture artifact independently of its existing media setup profile. Media setup profiles and YAML config are still the old implementation, pending their planned replacement; this is not a parallel compatibility path. +- Removed obsolete generic/laptop daemon artifacts and the duplicate daemon binary inside the source tree. New architecture binaries live in `dist/`. +- JSON configuration/schema and management backend were subsequently implemented below. Full rework and hardware deployment verification are not complete. + +### JSON and management backend (2026-11-16) + +- Replaced YAML settings with complete JSON configs, including repository samples and dummy configs. No legacy decoder or migration path. The existing media implementation remains until its planned replacement. +- Added generated draft-7 JSON Schema using `invopop/jsonschema` and validation using `santhosh-tekuri/jsonschema/v6`; retained semantic validation and excluded derived media URLs from persisted configuration. +- Added CLI default/schema export and hardware-free configuration checking. Atomic saves block new control commands, stop motion, acknowledge, unwind hardware, and re-execute roverd. +- Added `/rover/management` and admin Socket.IO read/save/command endpoints. Management state is separate from the control roster, so startup failures do not hide a rover from management. +- Moved host statistics and daemon events (including autocharge notices) to management. Operational toggle events remain on control until the unified state stage. +- Existing admin reboot/update and the user-owned-rover reboot path now use management transport. The existing user authorization/cooldown policy is preserved; generic media management now requires admin access. +- Management hello currently has empty profile catalogs: profiles are not implemented yet. Shared audio-device fields will be introduced with functioning ALSA routing, not exposed as inactive settings. +- See [protocol and deployment checks](roverd-management.md). No live server or rover services were started on this development machine. + +Verification for this stage: + +- The actual AMD64 daemon's `-check-config` accepted both JSON samples, the checked-in rover config, and the first dummy config. It rejected `{}` with missing-required-property errors before hardware initialization. Schema export also succeeded. +- Syntax checks passed for the new management server service, WebSocket routing, command routing, and control connection handler. +- Refreshed ARMv6, ARMv7, ARM64, and AMD64 artifacts successfully after the final shutdown changes. Server management syntax and tracked diff whitespace checks passed. +- Live acknowledgement/save/restart/reconnect, motion stopping, role authorization, and hardware-failure recovery remain unverified. Follow the deployment checks above and record their results here. + +### Handoff after usage-budget notice (2026-11-16) + +- Stopped after the JSON/management backend stage; no UI or ALSA implementation started in this stage. +- Final shutdown handling pauses automatic charging, blocks control commands and watchdog recovery, and cancels disconnect actions before stopping motion. If a management action fails before commitment, control and automatic charging resume. Live motion behavior remains unverified. +- Existing media helper scripts, machine-specific installer setup, and Chrome TTS variants are still present intentionally as unfinished rework items, not completed universal audio support. +- Next work: the schema-driven WebUI editor and field-to-all save flow against the documented management API, followed by unified rover state and the media/audio stages. Existing IPI authorization remains in effect. +- No live server/rover processes were launched or left running. No commits were made. Work remains in the shared working tree, including newly added files and generated architecture binaries. + +### Apply-field backend (2026-11-16) + +- Implemented admin-only `roverManagement:applyField` with object-field paths, independent whole-object submissions, connection-change detection, and individual outcomes. Offline rovers are not queued. +- Node syntax check passed. Live fleet saves remain unverified. WebUI editor and apply-field controls are still pending; the combined checklist item remains unchecked. + +### Configuration WebUI (2026-11-16) + +- Added `/admin?section=fleet` for admins and lockdown admins, independent of lockdown-only server configuration. +- The page lists management connections, renders the rover-supplied schema, saves complete objects, and lets an administrator select a field from the draft for fleet-wide application with individual results. +- Offline drafts remain mounted; server reconnection refreshes the roster. Authoritative changed configuration replaces the draft. Switching the selected rover starts its form from the latest reported configuration. +- Focused ESLint passed for the new component and AdminApp, after correcting the initial command working directory to `webui`. No full build or browser/server process was started. +- Verify the page against actual server/rover connections: admin access, hardware-failure management visibility, form validation, save/reconnect, and fleet success/error reporting. Production WebUI assets have not been regenerated. +- Configuration UI/backend implementation is now present; end-to-end deployment verification remains pending. Profile/status/output controls, unified rover state, audio/media supervision, and bootstrap/update rework are still separate outstanding stages. + +- Placement correction: rover configuration is embedded in the existing fleet management panel alongside the rover roster. Removed the separate administration tab. diff --git a/pi/roverd/Makefile b/pi/roverd/Makefile deleted file mode 100644 index d85f788a..00000000 --- a/pi/roverd/Makefile +++ /dev/null @@ -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 diff --git a/pi/roverd/brc_debian_laptop.go b/pi/roverd/brc_debian_laptop.go deleted file mode 100644 index 9e49e9ff..00000000 --- a/pi/roverd/brc_debian_laptop.go +++ /dev/null @@ -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) {} diff --git a/pi/roverd/camera_servo_debian_laptop.go b/pi/roverd/camera_servo_debian_laptop.go deleted file mode 100644 index 8f9ec186..00000000 --- a/pi/roverd/camera_servo_debian_laptop.go +++ /dev/null @@ -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" -} diff --git a/pi/roverd/go.mod b/pi/roverd/go.mod deleted file mode 100644 index d3611c75..00000000 --- a/pi/roverd/go.mod +++ /dev/null @@ -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 diff --git a/pi/roverd/gpio_toggle_debian_laptop.go b/pi/roverd/gpio_toggle_debian_laptop.go deleted file mode 100644 index 3b796020..00000000 --- a/pi/roverd/gpio_toggle_debian_laptop.go +++ /dev/null @@ -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" -} diff --git a/pi/roverd/roverd b/pi/roverd/roverd deleted file mode 100755 index dfc24cbf..00000000 Binary files a/pi/roverd/roverd and /dev/null differ diff --git a/pi/roverd/roverd.debian-laptop.sample.yaml b/pi/roverd/roverd.debian-laptop.sample.yaml deleted file mode 100644 index 77739636..00000000 --- a/pi/roverd/roverd.debian-laptop.sample.yaml +++ /dev/null @@ -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 diff --git a/pi/roverd/roverd.sample.yaml b/pi/roverd/roverd.sample.yaml deleted file mode 100644 index e9294ccc..00000000 --- a/pi/roverd/roverd.sample.yaml +++ /dev/null @@ -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 diff --git a/pi/roverd/roverd.yaml b/pi/roverd/roverd.yaml deleted file mode 100644 index f7086c29..00000000 --- a/pi/roverd/roverd.yaml +++ /dev/null @@ -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 diff --git a/pi/asound.conf b/rover/asound.conf similarity index 100% rename from pi/asound.conf rename to rover/asound.conf diff --git a/pi/asound.debian-laptop.conf b/rover/asound.debian-laptop.conf similarity index 96% rename from pi/asound.debian-laptop.conf rename to rover/asound.debian-laptop.conf index cbdb7700..f2275d39 100644 --- a/pi/asound.debian-laptop.conf +++ b/rover/asound.debian-laptop.conf @@ -1,6 +1,6 @@ # Reference ALSA routing for the Debian laptop rover profile. # -# This intentionally mirrors pi/asound.conf as closely as a normal PC can: +# This intentionally mirrors rover/asound.conf as closely as a normal PC can: # one fixed hardware card, one dmix playback engine, separate softvol controls # for TTS/horn/forwarded audio, and a raw capture alias for the rover mic. # diff --git a/pi/bin/audio-forward-listener.sh b/rover/bin/audio-forward-listener.sh similarity index 100% rename from pi/bin/audio-forward-listener.sh rename to rover/bin/audio-forward-listener.sh diff --git a/pi/bin/audio-only-publisher.sh b/rover/bin/audio-only-publisher.sh similarity index 99% rename from pi/bin/audio-only-publisher.sh rename to rover/bin/audio-only-publisher.sh index 74fe5422..f6e646d0 100644 --- a/pi/bin/audio-only-publisher.sh +++ b/rover/bin/audio-only-publisher.sh @@ -136,7 +136,7 @@ run_pipeline() { # The capture format comes from roverd's normalized media config. Keeping # arecord and ffmpeg on the same env-backed values prevents the publisher - # script from quietly disagreeing with roverd.yaml about sample rate or + # script from quietly disagreeing with roverd.json about sample rate or # channel count. # # The buffer and period are byte counts because arecord interprets -B/-F in diff --git a/pi/bin/chromegtts-daemon-laptop.py b/rover/bin/chromegtts-daemon-laptop.py similarity index 100% rename from pi/bin/chromegtts-daemon-laptop.py rename to rover/bin/chromegtts-daemon-laptop.py diff --git a/pi/bin/chromegtts-daemon.py b/rover/bin/chromegtts-daemon.py similarity index 100% rename from pi/bin/chromegtts-daemon.py rename to rover/bin/chromegtts-daemon.py diff --git a/pi/bin/debian-laptop-video-publisher.sh b/rover/bin/debian-laptop-video-publisher.sh similarity index 99% rename from pi/bin/debian-laptop-video-publisher.sh rename to rover/bin/debian-laptop-video-publisher.sh index 8a11d9c5..2185e3bf 100755 --- a/pi/bin/debian-laptop-video-publisher.sh +++ b/rover/bin/debian-laptop-video-publisher.sh @@ -80,7 +80,7 @@ if [[ -n "${ROVERD_VIDEO_INPUT_FORMAT}" ]]; then # wrong negotiated format can still produce a decodable stream, but the # picture appears as green/noisy mush because ffmpeg is interpreting the # frame bytes with the wrong pixel format. Passing input_format pins V4L2 to - # the camera mode selected in roverd.yaml. + # the camera mode selected in roverd.json. INPUT_FORMAT_ARGS=(-input_format "${ROVERD_VIDEO_INPUT_FORMAT}") fi diff --git a/pi/bin/media-transport.test.sh b/rover/bin/media-transport.test.sh similarity index 100% rename from pi/bin/media-transport.test.sh rename to rover/bin/media-transport.test.sh diff --git a/pi/bin/roverd-self-update.sh b/rover/bin/roverd-self-update.sh similarity index 92% rename from pi/bin/roverd-self-update.sh rename to rover/bin/roverd-self-update.sh index 2afc0167..bc0fcef9 100755 --- a/pi/bin/roverd-self-update.sh +++ b/rover/bin/roverd-self-update.sh @@ -39,7 +39,7 @@ if [[ "${ROVERD_SELF_UPDATE_SYSTEMD:-}" != "1" ]] && command -v systemd-run >/de fi if [[ ! -f "$ENV_FILE" ]]; then - echo "Missing $ENV_FILE; run pi/install_roverd.sh once to register the repository path" >&2 + echo "Missing $ENV_FILE; run rover/install_roverd.sh once to register the repository path" >&2 exit 1 fi @@ -56,8 +56,8 @@ if [[ ! -d "$ROVERD_REPO_DIR/.git" ]]; then exit 1 fi -if [[ ! -x "$ROVERD_REPO_DIR/pi/install_roverd.sh" ]]; then - echo "Installer is missing or not executable: $ROVERD_REPO_DIR/pi/install_roverd.sh" >&2 +if [[ ! -x "$ROVERD_REPO_DIR/rover/install_roverd.sh" ]]; then + echo "Installer is missing or not executable: $ROVERD_REPO_DIR/rover/install_roverd.sh" >&2 exit 1 fi @@ -93,6 +93,6 @@ log "Repository fast-forward pull complete" # The installer already owns the full desired rover host state. Reusing it here # prevents this update helper from becoming a second, partial installer that can # drift away from the normal manual install path. -"$ROVERD_REPO_DIR/pi/install_roverd.sh" +"$ROVERD_REPO_DIR/rover/install_roverd.sh" log "Installer completed successfully" systemctl reboot diff --git a/pi/bin/video-publisher.sh b/rover/bin/video-publisher.sh similarity index 98% rename from pi/bin/video-publisher.sh rename to rover/bin/video-publisher.sh index 1dab1774..1e5e82d5 100644 --- a/pi/bin/video-publisher.sh +++ b/rover/bin/video-publisher.sh @@ -77,7 +77,7 @@ if [[ "${ROVERD_VIDEO_ENABLE}" -ne 1 ]]; then exit 0 fi -# The inversion decision is made in roverd.yaml and written into media.env, so +# The inversion decision is made in roverd.json and written into media.env, so # this script only converts the configured logical value into libcamera flags. FLIP_ARGS=() if [[ "${ROVERD_VIDEO_INVERT}" -ne 0 ]]; then diff --git a/pi/install/common.sh b/rover/install/common.sh similarity index 87% rename from pi/install/common.sh rename to rover/install/common.sh index 37e8b689..9fca958e 100644 --- a/pi/install/common.sh +++ b/rover/install/common.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -CONFIG_DEST="/etc/roverd.yaml" +CONFIG_DEST="/etc/roverd.json" log() { echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*" @@ -58,7 +58,7 @@ validate_install_inputs() { install_roverd_binary() { ensure_user roverd "$ROVERD_GROUPS" - install -o roverd -g roverd -m 0755 "$BINARY_SRC" /usr/local/bin/roverd + install -o root -g root -m 0755 "$BINARY_SRC" /usr/local/bin/roverd log "Installed roverd binary for profile $PROFILE" } @@ -68,12 +68,12 @@ install_roverd_config() { CONFIG_EXISTS=1 log "Existing $CONFIG_DEST found; leaving it in place" else - install -D -o roverd -g roverd -m 0640 "$CONFIG_SRC" "$CONFIG_DEST" + install -D -o root -g root -m 0600 "$CONFIG_SRC" "$CONFIG_DEST" log "Installed sample config to $CONFIG_DEST (edit before starting service)" fi } install_roverd_unit() { - install -m 0644 pi/systemd/roverd.service /etc/systemd/system/roverd.service + install -m 0644 rover/systemd/roverd.service /etc/systemd/system/roverd.service log "Installed roverd systemd unit" } diff --git a/pi/install/debian_laptop_profile.sh b/rover/install/debian_laptop_profile.sh similarity index 98% rename from pi/install/debian_laptop_profile.sh rename to rover/install/debian_laptop_profile.sh index e95c6456..c9060022 100644 --- a/pi/install/debian_laptop_profile.sh +++ b/rover/install/debian_laptop_profile.sh @@ -184,7 +184,7 @@ load_or_create_debian_laptop_alsa_config() { else if ! { true /dev/tty; } 2>/dev/null; then echo "Missing $DEBIAN_LAPTOP_INSTALLER_CONFIG and no interactive terminal is available for ALSA setup." >&2 - echo "Run sudo ./pi/install_roverd.sh --debian-laptop once from a terminal, then reuse the generated config for future installs." >&2 + echo "Run sudo ./rover/install_roverd.sh --debian-laptop once from a terminal, then reuse the generated config for future installs." >&2 exit 1 fi @@ -337,7 +337,7 @@ install_debian_laptop_audio_support() { load_or_create_debian_laptop_alsa_config render_debian_laptop_asound_config - install -D -o root -g root -m 0755 pi/bin/chromegtts-daemon-laptop.py /usr/local/bin/chromegtts-daemon + install -D -o root -g root -m 0755 rover/bin/chromegtts-daemon-laptop.py /usr/local/bin/chromegtts-daemon log "Installed laptop chromegtts daemon" install_google_tts_assets_laptop diff --git a/pi/install/media_env.sh b/rover/install/media_env.sh similarity index 98% rename from pi/install/media_env.sh rename to rover/install/media_env.sh index 3a636f10..e4f7ddb5 100644 --- a/pi/install/media_env.sh +++ b/rover/install/media_env.sh @@ -5,7 +5,7 @@ write_media_env_placeholder() { case "$PROFILE" in pi) - # roverd rewrites media.env after loading /etc/roverd.yaml. These + # roverd rewrites media.env after loading /etc/roverd.json. These # values only make the services syntactically usable before the first # successful roverd run, so they mirror the Pi defaults instead of # trying to become a second source of truth. diff --git a/pi/install/pi_profile.sh b/rover/install/pi_profile.sh similarity index 95% rename from pi/install/pi_profile.sh rename to rover/install/pi_profile.sh index 599f114c..523c0733 100644 --- a/pi/install/pi_profile.sh +++ b/rover/install/pi_profile.sh @@ -73,12 +73,12 @@ install_pi_audio_support() { log "googlevoicehat-soundcard overlay already present in $boot_config" fi fi - if [[ -f pi/asound.conf ]]; then - install -m 0644 pi/asound.conf /etc/asound.conf + if [[ -f rover/asound.conf ]]; then + install -m 0644 rover/asound.conf /etc/asound.conf log "Installed ALSA config to /etc/asound.conf" alsa_reload_notice=1 else - log "WARNING: pi/asound.conf missing; skipping ALSA config install" + log "WARNING: rover/asound.conf missing; skipping ALSA config install" fi if [[ "${alsa_reload_notice:-0}" -eq 1 ]]; then @@ -102,7 +102,7 @@ install_pi_audio_support() { || apt-get install -y --no-install-recommends flite espeak python3 curl xz-utils unzip alsa-utils libc++1-14 libc++abi1-14 fi - install -D -o root -g root -m 0755 pi/bin/chromegtts-daemon.py /usr/local/bin/chromegtts-daemon + install -D -o root -g root -m 0755 rover/bin/chromegtts-daemon.py /usr/local/bin/chromegtts-daemon log "Installed chromegtts daemon" install_google_tts_assets diff --git a/pi/install/profiles.sh b/rover/install/profiles.sh similarity index 65% rename from pi/install/profiles.sh rename to rover/install/profiles.sh index 7245974a..d0b63dcb 100644 --- a/pi/install/profiles.sh +++ b/rover/install/profiles.sh @@ -6,19 +6,19 @@ CONFIG_SRC="" usage() { cat <<'USAGE' -Usage: sudo ./pi/install_roverd.sh [options] +Usage: sudo ./rover/install_roverd.sh [options] Options: --profile Install profile: pi or debian-laptop (default: pi) --debian-laptop Shortcut for --profile debian-laptop - -b, --binary Path to the roverd binary (default depends on profile) - -c, --config Source config to install if /etc/roverd.yaml is missing + -b, --binary Path to the roverd binary (default: detected OS architecture) + -c, --config Source config to install if /etc/roverd.json is missing (default depends on profile) -h, --help Show this help text The script must run from the repository root and as root (sudo). It will: * create system users/groups if needed - * install /usr/local/bin/roverd and /etc/roverd.yaml + * install /usr/local/bin/roverd and /etc/roverd.json * install profile-specific video helpers and shared audio helpers * install profile-specific ALSA/system audio setup * install the fixed-command self-update helper used by admin-triggered updates @@ -59,22 +59,33 @@ parse_args() { } select_profile() { + # Binary selection follows the installed userland, independent of the + # temporary media installer profiles removed later in the rework. + case "$(dpkg --print-architecture)" in + amd64) binary_arch=amd64 ;; + arm64) binary_arch=arm64 ;; + armhf) + # ARMv6 also runs on ARMv7; use the conservative artifact for + # 32-bit Debian derivatives whose armhf baseline differs. + binary_arch=armv6 ;; + *) echo "Unsupported OS architecture" >&2; exit 1 ;; + esac + BINARY_SRC="${BINARY_SRC:-dist/roverd-linux-$binary_arch}" + case "$PROFILE" in pi) - BINARY_SRC="${BINARY_SRC:-dist/roverd}" - CONFIG_SRC="${CONFIG_SRC:-pi/roverd/roverd.sample.yaml}" - VIDEO_HELPER_SRC="pi/bin/video-publisher.sh" + CONFIG_SRC="${CONFIG_SRC:-rover/roverd/roverd.sample.json}" + VIDEO_HELPER_SRC="rover/bin/video-publisher.sh" VIDEO_HELPER_DEST="/usr/local/bin/video-publisher" - VIDEO_SERVICE_SRC="pi/systemd/video-publisher.service" + VIDEO_SERVICE_SRC="rover/systemd/video-publisher.service" VIDEO_SERVICE_NAME="video-publisher.service" ROVERD_GROUPS="dialout,gpio,video,render,audio" ;; debian-laptop) - BINARY_SRC="${BINARY_SRC:-dist/roverd-debian-laptop}" - CONFIG_SRC="${CONFIG_SRC:-pi/roverd/roverd.debian-laptop.sample.yaml}" - VIDEO_HELPER_SRC="pi/bin/debian-laptop-video-publisher.sh" + CONFIG_SRC="${CONFIG_SRC:-rover/roverd/roverd.debian-laptop.sample.json}" + VIDEO_HELPER_SRC="rover/bin/debian-laptop-video-publisher.sh" VIDEO_HELPER_DEST="/usr/local/bin/debian-laptop-video-publisher" - VIDEO_SERVICE_SRC="pi/systemd/debian-laptop-video-publisher.service" + VIDEO_SERVICE_SRC="rover/systemd/debian-laptop-video-publisher.service" VIDEO_SERVICE_NAME="debian-laptop-video-publisher.service" ROVERD_GROUPS="dialout,video,render,audio" ;; diff --git a/pi/install/self_update.sh b/rover/install/self_update.sh similarity index 89% rename from pi/install/self_update.sh rename to rover/install/self_update.sh index 0dc8276a..201a2fd8 100644 --- a/pi/install/self_update.sh +++ b/rover/install/self_update.sh @@ -12,7 +12,7 @@ install_self_update_support() { printf -v quoted_repo_root '%q' "$REPO_ROOT" install -D -o root -g root -m 0644 /dev/null "$update_env" cat > "$update_env" < "$sudoers_file" <<'SUDOERS' -# Managed by pi/install_roverd.sh. +# Managed by rover/install_roverd.sh. # Allow only the roverd service account to run the fixed self-update helper. roverd ALL=(root) NOPASSWD: /usr/local/sbin/roverd-self-update SUDOERS diff --git a/pi/install/systemd.sh b/rover/install/systemd.sh similarity index 80% rename from pi/install/systemd.sh rename to rover/install/systemd.sh index a39bcb0f..b8d018d3 100644 --- a/pi/install/systemd.sh +++ b/rover/install/systemd.sh @@ -10,12 +10,12 @@ install_media_units() { # Audio capture publishing and forwarded-audio playback use the same ffmpeg # and ALSA contract on both profiles, so they stay as shared installer work. - install -D -o root -g root -m 0755 pi/bin/audio-only-publisher.sh /usr/local/bin/audio-only-publisher - install -m 0644 pi/systemd/audio-only-publisher.service /etc/systemd/system/audio-only-publisher.service + install -D -o root -g root -m 0755 rover/bin/audio-only-publisher.sh /usr/local/bin/audio-only-publisher + install -m 0644 rover/systemd/audio-only-publisher.service /etc/systemd/system/audio-only-publisher.service log "Installed audio-only publisher helper + systemd unit" - install -D -o root -g root -m 0755 pi/bin/audio-forward-listener.sh /usr/local/bin/audio-forward-listener - install -m 0644 pi/systemd/audio-forward-listener.service /etc/systemd/system/audio-forward-listener.service + install -D -o root -g root -m 0755 rover/bin/audio-forward-listener.sh /usr/local/bin/audio-forward-listener + install -m 0644 rover/systemd/audio-forward-listener.service /etc/systemd/system/audio-forward-listener.service log "Installed audio-forward listener helper + systemd unit" } diff --git a/pi/install_roverd.sh b/rover/install_roverd.sh similarity index 75% rename from pi/install_roverd.sh rename to rover/install_roverd.sh index 321b15df..11530cbc 100755 --- a/pi/install_roverd.sh +++ b/rover/install_roverd.sh @@ -2,7 +2,7 @@ # # Installer entry point for roverd hosts. # -# The detailed work lives in pi/install/*.sh so platform-specific setup stays +# The detailed work lives in rover/install/*.sh so platform-specific setup stays # local to the profile that needs it. This file should read like the install # order: choose a profile, validate inputs, install shared roverd pieces, # install profile support, then enable the services. @@ -17,13 +17,13 @@ REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)" # simple and prevents each function from needing its own path resolver. cd "$REPO_ROOT" -source pi/install/common.sh -source pi/install/profiles.sh -source pi/install/self_update.sh -source pi/install/pi_profile.sh -source pi/install/debian_laptop_profile.sh -source pi/install/media_env.sh -source pi/install/systemd.sh +source rover/install/common.sh +source rover/install/profiles.sh +source rover/install/self_update.sh +source rover/install/pi_profile.sh +source rover/install/debian_laptop_profile.sh +source rover/install/media_env.sh +source rover/install/systemd.sh main() { parse_args "$@" diff --git a/pi/rover-checklist.md b/rover/rover-checklist.md similarity index 100% rename from pi/rover-checklist.md rename to rover/rover-checklist.md diff --git a/rover/roverd/Makefile b/rover/roverd/Makefile new file mode 100644 index 00000000..3b9441f8 --- /dev/null +++ b/rover/roverd/Makefile @@ -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-* diff --git a/pi/roverd/audio_levels.go b/rover/roverd/audio_levels.go similarity index 100% rename from pi/roverd/audio_levels.go rename to rover/roverd/audio_levels.go diff --git a/pi/roverd/auto_charge.go b/rover/roverd/auto_charge.go similarity index 84% rename from pi/roverd/auto_charge.go rename to rover/roverd/auto_charge.go index 8d043fa1..32f6efb7 100644 --- a/pi/roverd/auto_charge.go +++ b/rover/roverd/auto_charge.go @@ -3,6 +3,7 @@ package roverd import ( "context" "log" + "sync" "time" ) @@ -13,6 +14,8 @@ const ( ) 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{} +} diff --git a/pi/roverd/brc.go b/rover/roverd/brc.go similarity index 63% rename from pi/roverd/brc.go rename to rover/roverd/brc.go index df96319e..f766e9f5 100644 --- a/pi/roverd/brc.go +++ b/rover/roverd/brc.go @@ -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) } diff --git a/pi/roverd/brc_dummy.go b/rover/roverd/brc_dummy.go similarity index 100% rename from pi/roverd/brc_dummy.go rename to rover/roverd/brc_dummy.go diff --git a/pi/roverd/camera_servo.go b/rover/roverd/camera_servo.go similarity index 99% rename from pi/roverd/camera_servo.go rename to rover/roverd/camera_servo.go index 50a1216b..31b0929a 100644 --- a/pi/roverd/camera_servo.go +++ b/rover/roverd/camera_servo.go @@ -1,4 +1,4 @@ -//go:build !dummy && !debian_laptop +//go:build !dummy package roverd diff --git a/pi/roverd/camera_servo_dummy.go b/rover/roverd/camera_servo_dummy.go similarity index 100% rename from pi/roverd/camera_servo_dummy.go rename to rover/roverd/camera_servo_dummy.go diff --git a/pi/roverd/chromegtts.go b/rover/roverd/chromegtts.go similarity index 100% rename from pi/roverd/chromegtts.go rename to rover/roverd/chromegtts.go diff --git a/pi/roverd/clamp.go b/rover/roverd/clamp.go similarity index 100% rename from pi/roverd/clamp.go rename to rover/roverd/clamp.go diff --git a/pi/roverd/cmd/hornverifier/main.go b/rover/roverd/cmd/hornverifier/main.go similarity index 100% rename from pi/roverd/cmd/hornverifier/main.go rename to rover/roverd/cmd/hornverifier/main.go diff --git a/pi/roverd/cmd/peripheral-probe/main.go b/rover/roverd/cmd/peripheral-probe/main.go similarity index 99% rename from pi/roverd/cmd/peripheral-probe/main.go rename to rover/roverd/cmd/peripheral-probe/main.go index 388aadee..12dfcb7f 100644 --- a/pi/roverd/cmd/peripheral-probe/main.go +++ b/rover/roverd/cmd/peripheral-probe/main.go @@ -10,7 +10,7 @@ import ( "os" "time" - roverd "multiroombarover/pi/roverd" + roverd "multiroombarover/rover/roverd" "github.com/tarm/serial" ) diff --git a/pi/roverd/cmd/roverd/main.go b/rover/roverd/cmd/roverd/main.go similarity index 50% rename from pi/roverd/cmd/roverd/main.go rename to rover/roverd/cmd/roverd/main.go index 89fd97b7..aad7b70e 100644 --- a/pi/roverd/cmd/roverd/main.go +++ b/rover/roverd/cmd/roverd/main.go @@ -2,39 +2,86 @@ package main import ( "context" + "encoding/json" "flag" "fmt" "log" "os" "os/signal" + "sync/atomic" "syscall" "time" - roverd "multiroombarover/pi/roverd" + roverd "multiroombarover/rover/roverd" ) func main() { var cfgPath string - flag.StringVar(&cfgPath, "config", "/etc/roverd.yaml", "path to roverd configuration file") + flag.StringVar(&cfgPath, "config", "/etc/roverd.json", "path to roverd JSON configuration") + printDefaults := flag.Bool("print-default-config", false, "print a complete initial JSON configuration and exit") + printSchema := flag.Bool("print-config-schema", false, "print the configuration JSON Schema and exit") + checkConfig := flag.Bool("check-config", false, "validate configuration without opening hardware or connecting") flag.Parse() - + if *printDefaults { + data, _ := json.MarshalIndent(roverd.DefaultConfig(), "", " ") + fmt.Println(string(data)) + return + } + if *printSchema { + fmt.Println(string(roverd.ConfigurationSchema())) + return + } cfg, err := roverd.LoadConfig(cfgPath) if err != nil { log.Fatalf("load config: %v", err) } - if err := roverd.UpdatePublisherEnv(cfg.Media); err != nil { - log.Fatalf("prepare media env: %v", err) + if *checkConfig { + fmt.Println("Configuration valid") + return } + if run(cfg, cfgPath) { + executable, err := os.Executable() + if err != nil { + log.Fatal(err) + } + if err := syscall.Exec(executable, os.Args, os.Environ()); err != nil { + log.Fatalf("restart roverd: %v", err) + } + } +} +func run(cfg *roverd.Config, cfgPath string) bool { ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel() - logger := log.New(os.Stdout, "roverd: ", log.LstdFlags|log.Lmicroseconds|log.LUTC) + events := make(chan roverd.RoverEvent, 128) console := roverd.NewConsoleNotifier(logger) + console.SetEvents(events) + var restarting atomic.Bool + management := roverd.NewManagementClient(cfg, cfgPath, events, logger, func() { restarting.Store(true); cancel() }) + managementDone := make(chan struct{}) + go func() { defer close(managementDone); management.Run(ctx) }() + // Hardware failures leave management connected until a corrected config + // requests restart. runHardware unwinds its own resources on failure. + media := roverd.NewMediaSupervisor(cfg.Media, logger) + management.SetMedia(media) + if media != nil { + media.Start(ctx) + } + if err := runHardware(ctx, cfg, events, management, media, logger, console); err != nil { + console.Notify(fmt.Sprintf("Hardware unavailable: %v. Management remains connected.", err)) + } + <-ctx.Done() + <-managementDone + return restarting.Load() +} +func runHardware(ctx context.Context, cfg *roverd.Config, eventStream chan roverd.RoverEvent, management *roverd.ManagementClient, mediaSupervisor *roverd.MediaSupervisor, logger *log.Logger, console *roverd.ConsoleNotifier) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() serialPort, err := roverd.OpenSerial(cfg.Serial) if err != nil { - logger.Fatalf("open serial: %v", err) + return fmt.Errorf("open serial: %w", err) } defer serialPort.Close() @@ -44,45 +91,33 @@ func main() { peripherals, err := roverd.DiscoverPeripheralManager(ctx, cfg.Serial.Device, logger) if err != nil { console.Notify(fmt.Sprintf("Rover peripheral startup failed: %v", err)) - logger.Fatalf("discover rover peripherals: %v", err) + return fmt.Errorf("discover rover peripherals: %w", err) } defer peripherals.Close() - for _, message := range peripherals.StartupBroadcasts() { - console.Notify(message) - } - - var pulser *roverd.BRCPulser - if cfg.BRC.Enabled() { - pulser, err = roverd.NewBRCPulser(cfg.BRC, logger) - if err != nil { - logger.Fatalf("init BRC pulser: %v", err) - } - defer pulser.Close() - pulser.Start(ctx) - } sensorFrames := make(chan []byte, 8) sensorSamples := make(chan roverd.SensorSample, 8) - eventStream := make(chan roverd.RoverEvent, 16) streamer := roverd.NewSensorStreamer(serialPort, sensorFrames, sensorSamples, logger) go streamer.Run(ctx) adapter := roverd.NewSerialAdapter(serialPort, logger) - mediaSupervisor := roverd.NewMediaSupervisor(cfg.Media, logger) - if mediaSupervisor != nil { - mediaSupervisor.Start(ctx) - } - - // Backend selection is identical on Pi and laptop hosts: enabled native - // GPIO wins, otherwise a discovered ESP32 may provide the built-in role. + // Resolve roles across external and internal peripherals without transport priority. hardwareControllers, err := roverd.ResolveRoverHardwareControllers(cfg, peripherals, logger) if err != nil { console.Notify(fmt.Sprintf("Rover peripheral startup failed while selecting hardware: %v", err)) - logger.Fatalf("resolve rover hardware controllers: %v", err) + return fmt.Errorf("resolve rover hardware controllers: %w", err) } defer hardwareControllers.Close() + if err := peripherals.StartInternal(ctx); err != nil { + logger.Printf("internal peripheral: %v", err) + console.Notify(fmt.Sprintf("Pi GPIO background function unavailable: %v", err)) + } + for _, message := range peripherals.StartupBroadcasts() { + console.Notify(message) + } + for _, message := range hardwareControllers.StartupBroadcasts() { console.Notify(message) } @@ -107,13 +142,17 @@ func main() { }() autoCharge := roverd.NewAutoChargeController(adapter, eventStream, logger) - go autoCharge.Run(ctx, sensorSamples) client := roverd.NewWSClient(cfg, adapter, sensorFrames, eventStream, mediaSupervisor, hardwareControllers.CameraServo, hardwareControllers.Headlight, hardwareControllers.Laser, peripherals, logger, console) + client.SetAutoCharge(autoCharge) + go autoCharge.Run(ctx, sensorSamples) + if !management.SetRuntime(client, mediaSupervisor) { + return nil + } + defer client.PrepareShutdown() - // Startup is announced only after every configured hardware dependency has - // initialized successfully. A message here therefore means the control loop - // is genuinely ready, rather than merely that systemd launched the process. + // The control loop is ready after startup resolution. Individual unavailable + // peripheral roles have already been reported and do not prevent connection. console.Notify("roverd started and hardware initialization completed.") defer console.Notify("roverd stopped.") @@ -125,7 +164,7 @@ func main() { select { case <-ctx.Done(): - return + return nil case <-time.After(retryDelay): } @@ -133,4 +172,6 @@ func main() { retryDelay *= 2 } } + + return nil } diff --git a/pi/roverd/cmd/servoverifier/main.go b/rover/roverd/cmd/servoverifier/main.go similarity index 100% rename from pi/roverd/cmd/servoverifier/main.go rename to rover/roverd/cmd/servoverifier/main.go diff --git a/pi/roverd/command.go b/rover/roverd/command.go similarity index 89% rename from pi/roverd/command.go rename to rover/roverd/command.go index 9621e11e..61f50ba7 100644 --- a/pi/roverd/command.go +++ b/rover/roverd/command.go @@ -9,7 +9,7 @@ type helloMessage struct { Color string `json:"color,omitempty"` Battery BatteryConfig `json:"battery"` MaxWheelSpeed int `json:"maxWheelSpeed"` - Media MediaConfig `json:"media"` + Media any `json:"media"` CameraServo CameraServoConfig `json:"cameraServo"` Audio AudioConfig `json:"audio"` Horn HornConfig `json:"horn"` @@ -41,7 +41,6 @@ type inboundMessage struct { MotorPWM *motorPWMPayload `json:"motorPwm,omitempty"` Raw string `json:"raw,omitempty"` SensorStream *sensorStreamPayload `json:"sensorStream,omitempty"` - Media *mediaCommand `json:"media,omitempty"` Servo *servoPayload `json:"servo,omitempty"` TTS *ttsPayload `json:"tts,omitempty"` Horn *hornPayload `json:"horn,omitempty"` @@ -50,11 +49,6 @@ type inboundMessage struct { Laser *togglePayload `json:"laser,omitempty"` Peripheral *peripheralPayload `json:"peripheral,omitempty"` Song *songPayload `json:"song,omitempty"` - Reboot *rebootPayload `json:"reboot,omitempty"` - // Update is intentionally just a marker payload. The server can request the - // fixed self-update workflow, but it cannot pass paths, commands, branches, - // or installer flags through the websocket into the privileged helper. - Update *updatePayload `json:"update,omitempty"` } type driveDirectPayload struct { diff --git a/pi/roverd/config.go b/rover/roverd/config.go similarity index 58% rename from pi/roverd/config.go rename to rover/roverd/config.go index bb462931..904976fb 100644 --- a/pi/roverd/config.go +++ b/rover/roverd/config.go @@ -11,21 +11,23 @@ import ( "strings" "time" - "gopkg.in/yaml.v3" + "bytes" + "encoding/json" + "io" ) type SerialConfig struct { - Device string `yaml:"device"` - Baud int `yaml:"baud"` + Device string `json:"device"` + Baud int `json:"baud" jsonschema:"minimum=1"` } type Duration struct { time.Duration } -func (d *Duration) UnmarshalYAML(value *yaml.Node) error { +func (d *Duration) UnmarshalJSON(data []byte) error { var raw string - if err := value.Decode(&raw); err != nil { + if err := json.Unmarshal(data, &raw); err != nil { return err } parsed, err := time.ParseDuration(raw) @@ -36,93 +38,88 @@ func (d *Duration) UnmarshalYAML(value *yaml.Node) error { return nil } -func (d Duration) MarshalYAML() (interface{}, error) { - return d.Duration.String(), nil -} +func (d Duration) MarshalJSON() ([]byte, error) { return json.Marshal(d.Duration.String()) } type BRCConfig struct { - GPIOPin int `yaml:"gpioPin"` - GPIOChip string `yaml:"gpioChip"` - PulseEvery Duration `yaml:"pulseEvery"` - PulseWidth Duration `yaml:"pulseWidth"` -} - -func (b BRCConfig) Enabled() bool { - return b.GPIOPin >= 0 + Enabled bool `json:"enabled"` + GPIOPin int `json:"gpioPin"` + GPIOChip string `json:"gpioChip"` + PulseEvery Duration `json:"pulseEvery"` + PulseWidth Duration `json:"pulseWidth"` } type BatteryConfig struct { - Full int `yaml:"full"` - Warn int `yaml:"warn"` - Urgent int `yaml:"urgent"` + Full int `json:"full"` + Warn int `json:"warn"` + Urgent int `json:"urgent"` } type AudioConfig struct { // AudioConfig is only for sounds generated by roverd itself. Live capture // and playback are media-publisher concerns, so those settings live under // MediaConfig where they can be written directly into media.env. - TTSEnabled bool `yaml:"ttsEnabled" json:"ttsEnabled"` - DefaultEngine string `yaml:"defaultEngine" json:"defaultEngine,omitempty"` - DefaultVoice string `yaml:"defaultVoice" json:"defaultVoice,omitempty"` - DefaultPitch int `yaml:"defaultPitch" json:"defaultPitch,omitempty"` + TTSEnabled bool `json:"ttsEnabled"` + DefaultEngine string `json:"defaultEngine"` + DefaultVoice string `json:"defaultVoice"` + DefaultPitch int `json:"defaultPitch"` } type HornConfig struct { - Enabled bool `yaml:"enabled" json:"enabled"` - Volume float64 `yaml:"volume" json:"-"` - SampleRate int `yaml:"sampleRate" json:"-"` - Channels int `yaml:"channels" json:"-"` - Device string `yaml:"device" json:"-"` - SineGain float64 `yaml:"sineGain" json:"-"` - SawGain float64 `yaml:"sawGain" json:"-"` - MaxDuration Duration `yaml:"maxDuration" json:"-"` + Enabled bool `json:"enabled"` + Volume float64 `json:"volume"` + SampleRate int `json:"sampleRate"` + Channels int `json:"channels"` + Device string `json:"device"` + SineGain float64 `json:"sineGain"` + SawGain float64 `json:"sawGain"` + MaxDuration Duration `json:"maxDuration"` } type MediaConfig struct { // RTSPPort is shared by the derived video, microphone, and forwarded-audio // RTSP URLs. Keeping it at this level prevents each nested block from needing // to repeat the same server port when the common MediaMTX listener is used. - RTSPPort int `yaml:"rtspPort" json:"-"` - Manage bool `yaml:"manage" json:"manage"` - HealthURL string `yaml:"healthUrl" json:"healthUrl,omitempty"` - HealthInterval Duration `yaml:"healthInterval" json:"-"` - Video VideoMediaConfig `yaml:"video" json:"video"` - AudioCapture AudioCaptureConfig `yaml:"audioCapture" json:"audioCapture"` - AudioPlayback AudioPlaybackConfig `yaml:"audioPlayback" json:"audioPlayback"` + RTSPPort int `json:"rtspPort" jsonschema:"minimum=1,maximum=65535"` + Manage bool `json:"manage"` + HealthURL string `json:"healthUrl"` + HealthInterval Duration `json:"healthInterval"` + Video VideoMediaConfig `json:"video"` + AudioCapture AudioCaptureConfig `json:"audioCapture"` + AudioPlayback AudioPlaybackConfig `json:"audioPlayback"` } type VideoMediaConfig struct { // Publisher selects the installed publisher script/pipeline family. The // first pass uses pi-libcamera for current rovers; laptop-v4l2 can be added // without changing the server-facing media shape again. - Enabled bool `yaml:"enabled" json:"enabled"` - Service string `yaml:"service" json:"service,omitempty"` - Publisher string `yaml:"publisher" json:"publisher,omitempty"` + Enabled bool `json:"enabled"` + Service string `json:"service"` + Publisher string `json:"publisher"` // PublishURL is derived during validation. It remains in rover metadata for server-side - // consumers, but is not a second hand-written endpoint in /etc/roverd.yaml. - PublishURL string `yaml:"-" json:"publishUrl,omitempty"` - Device string `yaml:"device" json:"device,omitempty"` - InputFormat string `yaml:"inputFormat" json:"-"` - Width int `yaml:"width" json:"-"` - Height int `yaml:"height" json:"-"` - FPS int `yaml:"fps" json:"-"` - Bitrate int `yaml:"bitrate" json:"-"` - Inverted bool `yaml:"inverted" json:"-"` - SensorMode string `yaml:"sensorMode" json:"-"` + // consumers through MediaMetadata, but is never persisted in configuration. + PublishURL string `json:"-"` + Device string `json:"device"` + InputFormat string `json:"inputFormat"` + Width int `json:"width"` + Height int `json:"height"` + FPS int `json:"fps"` + Bitrate int `json:"bitrate"` + Inverted bool `json:"inverted"` + SensorMode string `json:"sensorMode"` } type AudioCaptureConfig struct { // AudioCapture describes the rover microphone stream that browsers can // subscribe to as "-audio". A disabled capture block still has // normalized defaults so enabling it only requires flipping enabled: true. - Enabled bool `yaml:"enabled" json:"enabled"` - Service string `yaml:"service" json:"service,omitempty"` + Enabled bool `json:"enabled"` + Service string `json:"service"` // PublishURL follows the same derived-only contract as the video path. - PublishURL string `yaml:"-" json:"publishUrl,omitempty"` - Device string `yaml:"device" json:"device,omitempty"` - SampleRate int `yaml:"sampleRate" json:"-"` - Channels int `yaml:"channels" json:"-"` - Bitrate int `yaml:"bitrate" json:"-"` + PublishURL string `json:"-"` + Device string `json:"device"` + SampleRate int `json:"sampleRate"` + Channels int `json:"channels"` + Bitrate int `json:"bitrate"` } type AudioPlaybackConfig struct { @@ -130,36 +127,36 @@ type AudioPlaybackConfig struct { // MediaMTX for playback on the rover speaker. The URL is a request/read URL // for the rover listener, while the server converts it to publish mode when // it needs to inject audio. - Enabled bool `yaml:"enabled" json:"enabled"` - Service string `yaml:"service" json:"service,omitempty"` + Enabled bool `json:"enabled"` + Service string `json:"service"` // ForwardURL is derived because the server and rover must agree on the exact -fwd path. - ForwardURL string `yaml:"-" json:"forwardUrl,omitempty"` - Device string `yaml:"device" json:"device,omitempty"` - Normalize bool `yaml:"normalize" json:"-"` - NormalizeFilter string `yaml:"normalizeFilter" json:"-"` + ForwardURL string `json:"-"` + Device string `json:"device"` + Normalize bool `json:"normalize"` + NormalizeFilter string `json:"normalizeFilter"` } type CameraServoConfig struct { - Enabled bool `yaml:"enabled" json:"enabled"` - Pin int `yaml:"pin" json:"pin"` - FreqHz int `yaml:"freqHz" json:"freqHz"` - CycleLen int `yaml:"cycleLen" json:"cycleLen"` - MinPulseUs int `yaml:"minPulseUs" json:"minPulseUs"` - MaxPulseUs int `yaml:"maxPulseUs" json:"maxPulseUs"` - MinAngle float64 `yaml:"minAngle" json:"minAngle"` - MaxAngle float64 `yaml:"maxAngle" json:"maxAngle"` - HomeAngle float64 `yaml:"homeAngle" json:"homeAngle"` - NudgeDegrees float64 `yaml:"nudgeDegrees" json:"nudgeDegrees"` - AllowRawPulse bool `yaml:"allowRawPulse" json:"allowRawPulse"` - Invert bool `yaml:"invert" json:"invert"` + Enabled bool `json:"enabled"` + Pin int `json:"pin"` + FreqHz int `json:"freqHz"` + CycleLen int `json:"cycleLen"` + MinPulseUs int `json:"minPulseUs"` + MaxPulseUs int `json:"maxPulseUs"` + MinAngle float64 `json:"minAngle"` + MaxAngle float64 `json:"maxAngle"` + HomeAngle float64 `json:"homeAngle"` + NudgeDegrees float64 `json:"nudgeDegrees"` + AllowRawPulse bool `json:"allowRawPulse"` + Invert bool `json:"invert"` } type GPIOToggleConfig struct { - Enabled bool `yaml:"enabled" json:"enabled"` - GPIOPin int `yaml:"gpioPin" json:"gpioPin"` - GPIOChip string `yaml:"gpioChip" json:"gpioChip"` - InitialOn bool `yaml:"initialOn" json:"initialOn"` - ActiveLow bool `yaml:"activeLow" json:"activeLow"` + Enabled bool `json:"enabled"` + GPIOPin int `json:"gpioPin"` + GPIOChip string `json:"gpioChip"` + InitialOn bool `json:"initialOn"` + ActiveLow bool `json:"activeLow"` } func (g GPIOToggleConfig) LogicalToGPIO(on bool) int { @@ -173,68 +170,102 @@ func (g GPIOToggleConfig) LogicalToGPIO(on bool) int { } type AutoSideBrushConfig struct { - Enabled bool `yaml:"enabled"` - Speed int `yaml:"speed"` + Enabled bool `json:"enabled"` + Speed int `json:"speed"` } type PrivateConfig struct { - Enabled bool `yaml:"enabled" json:"enabled"` - Safety PrivateSafetyConfig `yaml:"safety" json:"safety"` + Enabled bool `json:"enabled"` + Safety PrivateSafetyConfig `json:"safety"` } type PrivateSafetyConfig struct { - SpeedLimitEnabled bool `yaml:"speedLimitEnabled" json:"speedLimitEnabled"` - SpeedLimitMaxWheelMMs int `yaml:"speedLimitMaxWheelSpeed" json:"speedLimitMaxWheelSpeed"` - HardOvercurrentEnabled bool `yaml:"hardOvercurrentEnabled" json:"hardOvercurrentEnabled"` - OvercurrentStopMs int `yaml:"overcurrentStopMs" json:"overcurrentStopMs"` - HardBumpEnabled bool `yaml:"hardBumpEnabled" json:"hardBumpEnabled"` - BumpBackoffSpeed int `yaml:"bumpBackoffSpeed" json:"bumpBackoffSpeed"` - BumpBackoffMs int `yaml:"bumpBackoffMs" json:"bumpBackoffMs"` - CliffEnabled bool `yaml:"cliffEnabled" json:"cliffEnabled"` - CliffBackoffSpeed int `yaml:"cliffBackoffSpeed" json:"cliffBackoffSpeed"` - CliffBackoffMs int `yaml:"cliffBackoffMs" json:"cliffBackoffMs"` - VirtualWallEnabled bool `yaml:"virtualWallEnabled" json:"virtualWallEnabled"` - VirtualWallBackoffSpeed int `yaml:"virtualWallBackoffSpeed" json:"virtualWallBackoffSpeed"` - VirtualWallBackoffMs int `yaml:"virtualWallBackoffMs" json:"virtualWallBackoffMs"` - TriggerCooldownMs int `yaml:"triggerCooldownMs" json:"triggerCooldownMs"` + SpeedLimitEnabled bool `json:"speedLimitEnabled"` + SpeedLimitMaxWheelMMs int `json:"speedLimitMaxWheelSpeed"` + HardOvercurrentEnabled bool `json:"hardOvercurrentEnabled"` + OvercurrentStopMs int `json:"overcurrentStopMs"` + HardBumpEnabled bool `json:"hardBumpEnabled"` + BumpBackoffSpeed int `json:"bumpBackoffSpeed"` + BumpBackoffMs int `json:"bumpBackoffMs"` + CliffEnabled bool `json:"cliffEnabled"` + CliffBackoffSpeed int `json:"cliffBackoffSpeed"` + CliffBackoffMs int `json:"cliffBackoffMs"` + VirtualWallEnabled bool `json:"virtualWallEnabled"` + VirtualWallBackoffSpeed int `json:"virtualWallBackoffSpeed"` + VirtualWallBackoffMs int `json:"virtualWallBackoffMs"` + TriggerCooldownMs int `json:"triggerCooldownMs"` +} + +type PiGPIOConfig struct { + Enabled bool `json:"enabled"` + BRC BRCConfig `json:"brc"` + CameraServo CameraServoConfig `json:"cameraServo"` + Headlight GPIOToggleConfig `json:"headlight"` + Laser GPIOToggleConfig `json:"laser"` } type Config struct { - Name string `yaml:"name"` - Description string `yaml:"description" json:"description,omitempty"` - Color string `yaml:"color" json:"color,omitempty"` - ServerURL string `yaml:"serverUrl"` - Serial SerialConfig `yaml:"serial"` - BRC BRCConfig `yaml:"brc"` - Battery BatteryConfig `yaml:"battery"` - MaxWheelMMs int `yaml:"maxWheelSpeed"` - Media MediaConfig `yaml:"media"` - CameraServo CameraServoConfig `yaml:"cameraServo"` - Audio AudioConfig `yaml:"audio"` - Horn HornConfig `yaml:"horn"` - Headlight GPIOToggleConfig `yaml:"headlight" json:"headlight"` - Laser GPIOToggleConfig `yaml:"laser" json:"laser"` - AutoSideBrush AutoSideBrushConfig `yaml:"autoSideBrush"` - Private PrivateConfig `yaml:"private" json:"private"` + PiGPIO PiGPIOConfig `json:"piGpio"` + Name string `json:"name" jsonschema:"minLength=1"` + Description string `json:"description"` + Color string `json:"color"` + ServerURL string `json:"serverUrl" jsonschema:"minLength=1"` + Serial SerialConfig `json:"serial"` + Battery BatteryConfig `json:"battery"` + MaxWheelMMs int `json:"maxWheelSpeed" jsonschema:"minimum=1,maximum=500"` + Media MediaConfig `json:"media"` + Audio AudioConfig `json:"audio"` + Horn HornConfig `json:"horn"` + AutoSideBrush AutoSideBrushConfig `json:"autoSideBrush"` + Private PrivateConfig `json:"private"` } -func LoadConfig(path string) (*Config, error) { - data, err := os.ReadFile(path) - if err != nil { - return nil, err - } +// DefaultConfig supplies initial settings; persisted and remotely submitted +// configuration is always a complete object. +func DefaultConfig() Config { cfg := Config{ - MaxWheelMMs: 500, - BRC: BRCConfig{ - GPIOPin: 4, - GPIOChip: "gpiochip0", - PulseEvery: Duration{ - Duration: time.Minute, + Name: "rover", ServerURL: "ws://localhost:8080/rover", + Serial: SerialConfig{Device: "/dev/ttyUSB0", Baud: 115200}, + Battery: BatteryConfig{Full: 2068, Warn: 1700, Urgent: 1650}, + PiGPIO: PiGPIOConfig{ + BRC: BRCConfig{ + Enabled: true, + GPIOPin: 4, + GPIOChip: "gpiochip0", + PulseEvery: Duration{ + Duration: time.Minute, + }, + PulseWidth: Duration{ + Duration: time.Second, + }, }, - PulseWidth: Duration{ - Duration: time.Second, + CameraServo: CameraServoConfig{ + Pin: 12, + FreqHz: 50, + CycleLen: 20000, + MinPulseUs: 900, + MaxPulseUs: 2100, + MinAngle: -15, + MaxAngle: 30, + HomeAngle: 0, + NudgeDegrees: 2, + }, + Headlight: GPIOToggleConfig{ + Enabled: true, + GPIOPin: 22, + GPIOChip: "gpiochip0", + InitialOn: false, + ActiveLow: true, + }, + Laser: GPIOToggleConfig{ + Enabled: false, + GPIOPin: 27, + GPIOChip: "gpiochip0", + InitialOn: false, + ActiveLow: false, }, }, + MaxWheelMMs: 500, Media: MediaConfig{ RTSPPort: 8554, HealthInterval: Duration{Duration: 30 * time.Second}, @@ -265,17 +296,6 @@ func LoadConfig(path string) (*Config, error) { NormalizeFilter: "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled", }, }, - CameraServo: CameraServoConfig{ - Pin: 12, - FreqHz: 50, - CycleLen: 20000, - MinPulseUs: 900, - MaxPulseUs: 2100, - MinAngle: -15, - MaxAngle: 30, - HomeAngle: 0, - NudgeDegrees: 2, - }, Audio: AudioConfig{ TTSEnabled: false, DefaultEngine: "flite", @@ -291,20 +311,6 @@ func LoadConfig(path string) (*Config, error) { SawGain: 0.7, MaxDuration: Duration{Duration: 10000 * time.Millisecond}, }, - Headlight: GPIOToggleConfig{ - Enabled: true, - GPIOPin: 22, - GPIOChip: "gpiochip0", - InitialOn: false, - ActiveLow: true, - }, - Laser: GPIOToggleConfig{ - Enabled: false, - GPIOPin: 27, - GPIOChip: "gpiochip0", - InitialOn: false, - ActiveLow: false, - }, AutoSideBrush: AutoSideBrushConfig{ Enabled: true, Speed: 20, @@ -329,51 +335,85 @@ func LoadConfig(path string) (*Config, error) { }, }, } - if err := yaml.Unmarshal(data, &cfg); err != nil { - return nil, err - } - if cfg.Name == "" { - return nil, errors.New("missing name") - } - normalizedColor, err := normalizeHexColor(cfg.Color) + return cfg +} + +func LoadConfig(path string) (*Config, error) { + data, err := os.ReadFile(path) if err != nil { return nil, err } + return DecodeConfig(data) +} + +func DecodeConfig(data []byte) (*Config, error) { + if err := ValidateConfigurationSchema(data); err != nil { + return nil, err + } + var cfg Config + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&cfg); err != nil { + return nil, err + } + if err := decoder.Decode(new(any)); err != io.EOF { + return nil, errors.New("expected one JSON object") + } + if err := validateConfig(&cfg); err != nil { + return nil, err + } + return &cfg, nil +} + +func validateConfig(cfg *Config) error { + if cfg.Name == "" { + return errors.New("missing name") + } + normalizedColor, err := normalizeHexColor(cfg.Color) + if err != nil { + return err + } cfg.Color = normalizedColor - if cfg.ServerURL == "" { - return nil, errors.New("missing serverUrl") + server, err := url.Parse(cfg.ServerURL) + if err != nil || server.Hostname() == "" || (server.Scheme != "ws" && server.Scheme != "wss") || server.Path != "/rover" || server.RawQuery != "" || server.Fragment != "" { + return errors.New("serverUrl must be ws://host[:port]/rover or wss://host[:port]/rover") } if cfg.Serial.Device == "" || cfg.Serial.Baud == 0 { - return nil, errors.New("serial device/baud required") + return errors.New("serial device/baud required") } if cfg.Battery.Full == 0 { - return nil, errors.New("battery thresholds required") + return errors.New("battery thresholds required") } if cfg.MaxWheelMMs <= 0 || cfg.MaxWheelMMs > 500 { - return nil, fmt.Errorf("maxWheelSpeed must be 1-500, got %d", cfg.MaxWheelMMs) + return fmt.Errorf("maxWheelSpeed must be 1-500, got %d", cfg.MaxWheelMMs) } - if cfg.BRC.GPIOChip == "" { - cfg.BRC.GPIOChip = "gpiochip0" + if cfg.PiGPIO.BRC.GPIOChip == "" { + cfg.PiGPIO.BRC.GPIOChip = "gpiochip0" } if cfg.Media.RTSPPort <= 0 { cfg.Media.RTSPPort = 8554 } if err := validateMediaConfig(&cfg.Media, cfg.ServerURL, cfg.Name); err != nil { - return nil, fmt.Errorf("media: %w", err) + return fmt.Errorf("media: %w", err) } - if err := validateServoConfig(&cfg.CameraServo); err != nil { - return nil, fmt.Errorf("cameraServo: %w", err) - } - if err := validateGPIOToggleConfig(&cfg.Headlight); err != nil { - return nil, fmt.Errorf("headlight: %w", err) - } - if err := validateGPIOToggleConfig(&cfg.Laser); err != nil { - return nil, fmt.Errorf("laser: %w", err) + if cfg.PiGPIO.Enabled { + if err := validateServoConfig(&cfg.PiGPIO.CameraServo); err != nil { + return fmt.Errorf("cameraServo: %w", err) + } + if err := validateGPIOToggleConfig(&cfg.PiGPIO.Headlight); err != nil { + return fmt.Errorf("headlight: %w", err) + } + if err := validateGPIOToggleConfig(&cfg.PiGPIO.Laser); err != nil { + return fmt.Errorf("laser: %w", err) + } + if cfg.PiGPIO.BRC.Enabled && (cfg.PiGPIO.BRC.GPIOPin < 0 || cfg.PiGPIO.BRC.PulseEvery.Duration <= 0 || cfg.PiGPIO.BRC.PulseWidth.Duration <= 0) { + return errors.New("piGpio.brc: nonnegative pin and positive pulse durations required") + } } validateAudioConfig(&cfg.Audio) validateHornConfig(&cfg.Horn) validateAutoSideBrushConfig(&cfg.AutoSideBrush) - return &cfg, nil + return nil } func validateServoConfig(cfg *CameraServoConfig) error { @@ -625,3 +665,14 @@ func normalizeHexColor(raw string) (string, error) { } return strings.ToUpper(trimmed), nil } + +// MediaMetadata adds derived endpoints only to the control hello. +func (cfg *Config) MediaMetadata() map[string]any { + data, _ := json.Marshal(cfg.Media) + var media map[string]any + json.Unmarshal(data, &media) + media["video"].(map[string]any)["publishUrl"] = cfg.Media.Video.PublishURL + media["audioCapture"].(map[string]any)["publishUrl"] = cfg.Media.AudioCapture.PublishURL + media["audioPlayback"].(map[string]any)["forwardUrl"] = cfg.Media.AudioPlayback.ForwardURL + return media +} diff --git a/rover/roverd/config_schema.go b/rover/roverd/config_schema.go new file mode 100644 index 00000000..a8c2f7c3 --- /dev/null +++ b/rover/roverd/config_schema.go @@ -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 +} diff --git a/pi/roverd/console_notifier.go b/rover/roverd/console_notifier.go similarity index 86% rename from pi/roverd/console_notifier.go rename to rover/roverd/console_notifier.go index ef0d6d3c..023c8dae 100644 --- a/pi/roverd/console_notifier.go +++ b/rover/roverd/console_notifier.go @@ -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 +} diff --git a/pi/roverd/console_notifier_test.go b/rover/roverd/console_notifier_test.go similarity index 100% rename from pi/roverd/console_notifier_test.go rename to rover/roverd/console_notifier_test.go diff --git a/pi/roverd/events.go b/rover/roverd/events.go similarity index 100% rename from pi/roverd/events.go rename to rover/roverd/events.go diff --git a/pi/roverd/firmata.go b/rover/roverd/firmata.go similarity index 100% rename from pi/roverd/firmata.go rename to rover/roverd/firmata.go diff --git a/pi/roverd/firmata_hardware_controllers.go b/rover/roverd/firmata_hardware_controllers.go similarity index 100% rename from pi/roverd/firmata_hardware_controllers.go rename to rover/roverd/firmata_hardware_controllers.go diff --git a/pi/roverd/firmata_hardware_controllers_test.go b/rover/roverd/firmata_hardware_controllers_test.go similarity index 71% rename from pi/roverd/firmata_hardware_controllers_test.go rename to rover/roverd/firmata_hardware_controllers_test.go index ce798ef9..7b3de898 100644 --- a/pi/roverd/firmata_hardware_controllers_test.go +++ b/rover/roverd/firmata_hardware_controllers_test.go @@ -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) + } } } diff --git a/pi/roverd/firmata_test.go b/rover/roverd/firmata_test.go similarity index 100% rename from pi/roverd/firmata_test.go rename to rover/roverd/firmata_test.go diff --git a/rover/roverd/go.mod b/rover/roverd/go.mod new file mode 100644 index 00000000..5d76dec6 --- /dev/null +++ b/rover/roverd/go.mod @@ -0,0 +1,22 @@ +module multiroombarover/rover/roverd + +go 1.25.4 + +require ( + github.com/invopop/jsonschema v0.13.0 + github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 + github.com/stianeikeland/go-rpio/v4 v4.6.0 + github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07 + github.com/warthog618/go-gpiocdev v0.9.1 + nhooyr.io/websocket v1.8.17 +) + +require ( + github.com/bahlo/generic-list-go v0.2.0 // indirect + github.com/buger/jsonparser v1.1.1 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect + golang.org/x/sys v0.38.0 // indirect + golang.org/x/text v0.14.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/pi/roverd/go.sum b/rover/roverd/go.sum similarity index 58% rename from pi/roverd/go.sum rename to rover/roverd/go.sum index e8c7baeb..92490c6e 100644 --- a/pi/roverd/go.sum +++ b/rover/roverd/go.sum @@ -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= diff --git a/pi/roverd/gpio_toggle.go b/rover/roverd/gpio_toggle.go similarity index 98% rename from pi/roverd/gpio_toggle.go rename to rover/roverd/gpio_toggle.go index cf30c4b4..fe3e4ee1 100644 --- a/pi/roverd/gpio_toggle.go +++ b/rover/roverd/gpio_toggle.go @@ -1,4 +1,4 @@ -//go:build !dummy && !debian_laptop +//go:build !dummy package roverd diff --git a/pi/roverd/gpio_toggle_dummy.go b/rover/roverd/gpio_toggle_dummy.go similarity index 100% rename from pi/roverd/gpio_toggle_dummy.go rename to rover/roverd/gpio_toggle_dummy.go diff --git a/pi/roverd/hardware_controllers.go b/rover/roverd/hardware_controllers.go similarity index 53% rename from pi/roverd/hardware_controllers.go rename to rover/roverd/hardware_controllers.go index 84b41566..aa709fcc 100644 --- a/pi/roverd/hardware_controllers.go +++ b/rover/roverd/hardware_controllers.go @@ -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. diff --git a/pi/roverd/horn.go b/rover/roverd/horn.go similarity index 100% rename from pi/roverd/horn.go rename to rover/roverd/horn.go diff --git a/pi/roverd/host_stats.go b/rover/roverd/host_stats.go similarity index 100% rename from pi/roverd/host_stats.go rename to rover/roverd/host_stats.go diff --git a/pi/roverd/host_stats_test.go b/rover/roverd/host_stats_test.go similarity index 100% rename from pi/roverd/host_stats_test.go rename to rover/roverd/host_stats_test.go diff --git a/rover/roverd/management.go b/rover/roverd/management.go new file mode 100644 index 00000000..c629dbc5 --- /dev/null +++ b/rover/roverd/management.go @@ -0,0 +1,273 @@ +package roverd + +import ( + "context" + "encoding/json" + "fmt" + "log" + "net/url" + "os/exec" + "sync" + "time" + + "nhooyr.io/websocket" +) + +type ManagementClient struct { + cfg *Config + configPath string + events chan RoverEvent + log *log.Logger + restart func() + mu sync.Mutex + runtime *WSClient + media *MediaSupervisor + stopping bool +} + +type managementCommand struct { + Type string `json:"type"` + ID string `json:"id"` + Config json.RawMessage `json:"config"` + Reboot *rebootPayload `json:"reboot"` + Media *mediaCommand `json:"media"` +} + +func NewManagementClient(cfg *Config, path string, events chan RoverEvent, logger *log.Logger, restart func()) *ManagementClient { + return &ManagementClient{cfg: cfg, configPath: path, events: events, log: logger, restart: restart} +} + +// Startup can finish while a management action is being accepted. Do not attach +// a new command source once shutdown has begun. +func (m *ManagementClient) SetRuntime(client *WSClient, media *MediaSupervisor) bool { + m.mu.Lock() + defer m.mu.Unlock() + if m.stopping { + client.PrepareShutdown() + return false + } + m.runtime, m.media = client, media + return true +} + +func (m *ManagementClient) Run(ctx context.Context) { + for ctx.Err() == nil { + if err := m.connect(ctx); err != nil && ctx.Err() == nil { + m.log.Printf("management connection: %v", err) + } + select { + case <-ctx.Done(): + return + case <-time.After(2 * time.Second): + } + } +} + +func (m *ManagementClient) connect(parent context.Context) error { + ctx, cancel := context.WithCancel(parent) + defer cancel() + endpoint, _ := url.Parse(m.cfg.ServerURL) + endpoint.Path = "/rover/management" + dialCtx, dialCancel := context.WithTimeout(ctx, dialTimeout) + conn, _, err := websocket.Dial(dialCtx, endpoint.String(), nil) + dialCancel() + if err != nil { + return err + } + defer conn.CloseNow() + conn.SetReadLimit(1024 * 1024) + if err := writeJSON(ctx, conn, map[string]any{ + "type": "hello", "name": m.cfg.Name, "config": m.cfg, + "schema": ConfigurationSchema(), "profiles": map[string]any{"video": []any{}, "audioCapture": []any{}, "audioPlayback": []any{}}, + }); err != nil { + return err + } + errors := make(chan error, 3) + go func() { errors <- keepalive(ctx, conn) }() + go func() { errors <- m.read(ctx, conn) }() + go func() { + for { + select { + case <-ctx.Done(): + return + case event := <-m.events: + if err := writeJSON(ctx, conn, event); err != nil { + errors <- err + return + } + } + } + }() + go m.forwardHostStats(ctx, conn) + select { + case <-ctx.Done(): + return ctx.Err() + case err := <-errors: + return err + } +} + +func (m *ManagementClient) read(ctx context.Context, conn *websocket.Conn) error { + for { + _, data, err := conn.Read(ctx) + if err != nil { + return err + } + var command managementCommand + if err := json.Unmarshal(data, &command); err != nil { + return err + } + if command.ID == "" { + continue + } + after, commandErr := m.execute(ctx, command) + ack := ackMessage{Type: "ack", ID: command.ID, Status: "ok"} + if commandErr != nil { + ack.Status = "error" + ack.Error = commandErr.Error() + } + err = writeJSON(ctx, conn, ack) + // Once configuration is committed, restart even if the acknowledgement + // cannot reach the server. Reconnection reports the actual saved object. + if after != nil { + after() + } + if err != nil { + return err + } + } +} + +func (m *ManagementClient) execute(ctx context.Context, command managementCommand) (func(), error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.stopping { + return nil, fmt.Errorf("management action already pending") + } + if command.Type == "media" { + if m.media == nil || command.Media == nil { + return nil, fmt.Errorf("media supervisor unavailable") + } + return nil, m.media.HandleAction(ctx, command.Media.Action) + } + var config *Config + var err error + switch command.Type { + case "config.set": + config, err = DecodeConfig(command.Config) + if err != nil { + return nil, err + } + case "reboot", "update": + default: + return nil, fmt.Errorf("unsupported management command: %s", command.Type) + } + if m.runtime != nil { + if err := m.runtime.PrepareShutdown(); err != nil { + m.runtime.ResumeControl() + return nil, err + } + } + resume := func() { + if m.runtime != nil { + m.runtime.ResumeControl() + } + } + if command.Type == "config.set" { + if err := SaveConfig(m.configPath, config); err != nil { + resume() + return nil, err + } + m.stopping = true + return m.restart, nil + } + // The updater remains a fixed-purpose helper; browser input cannot select + // executable paths or shell arguments. Its implementation is a later stage. + path, args := "systemctl", []string{"reboot"} + if command.Type == "update" { + path, args = "/usr/local/sbin/roverd-self-update", nil + } + if _, err := exec.LookPath(path); err != nil { + resume() + return nil, err + } + m.stopping = true + delay := 300 * time.Millisecond + if command.Reboot != nil && command.Reboot.DelayMs > 0 { + delay = time.Duration(clampInt(command.Reboot.DelayMs, 50, 5000)) * time.Millisecond + } + return func() { + go func() { + select { + case <-ctx.Done(): + case <-time.After(delay): + } + m.emit("system."+command.Type+"Starting", nil) + cmd := exec.Command(path, args...) + if err := cmd.Run(); err != nil { + m.log.Printf("management %s failed: %v", command.Type, err) + m.emit("system."+command.Type+"Failed", map[string]any{"error": err.Error()}) + m.mu.Lock() + m.stopping = false + resume() + m.mu.Unlock() + } + }() + }, nil +} +func (c *ManagementClient) forwardHostStats(ctx context.Context, conn *websocket.Conn) { + var previousNetworkSample *networkRateSample + + send := func() bool { + // Host stats are collected on demand so each outbound message describes + // the current Pi state. Collection failures are encoded into the stats + // payload, which keeps this telemetry path from closing the rover socket. + stats := CollectHostStats(ctx) + // Throughput is derived here because this loop owns the ordered, periodic + // samples for one connection. CollectHostStats stays independent, while a + // reconnect automatically receives a clean counter baseline. + previousNetworkSample = applyNetworkThroughput(stats.WiFi, previousNetworkSample) + msg := hostStatsMessage{ + Type: "hostStats", + Timestamp: time.Now().UnixMilli(), + Stats: stats, + } + if err := writeJSON(ctx, conn, msg); err != nil { + c.log.Printf("host stats send failed: %v", err) + return false + } + return true + } + + // Send once immediately so a newly connected rover can populate the UI + // without waiting for the first ticker interval. + if !send() { + return + } + + ticker := time.NewTicker(hostStatsInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + if !send() { + return + } + } + } +} + +func (m *ManagementClient) SetMedia(media *MediaSupervisor) { + m.mu.Lock() + defer m.mu.Unlock() + m.media = media +} + +func (m *ManagementClient) emit(event string, data map[string]any) { + select { + case m.events <- RoverEvent{Type: "event", Event: event, Ts: time.Now().UnixMilli(), Data: data}: + default: + } +} diff --git a/pi/roverd/media_env.go b/rover/roverd/media_env.go similarity index 97% rename from pi/roverd/media_env.go rename to rover/roverd/media_env.go index a72dba03..e3b1d38d 100644 --- a/pi/roverd/media_env.go +++ b/rover/roverd/media_env.go @@ -29,7 +29,7 @@ func UpdatePublisherEnv(media MediaConfig) error { /* The env file is intentionally verbose: every publisher receives concrete values instead of silently falling back to script-local defaults. That - makes roverd.yaml the owner of media behavior while keeping the shell + makes roverd.json the owner of media behavior while keeping the shell scripts as small pipeline launchers. */ fmt.Fprintf(&buf, "ROVERD_VIDEO_ENABLE=%d\n", boolToInt(media.Video.Enabled)) diff --git a/pi/roverd/media_supervisor.go b/rover/roverd/media_supervisor.go similarity index 100% rename from pi/roverd/media_supervisor.go rename to rover/roverd/media_supervisor.go diff --git a/pi/roverd/media_url_test.go b/rover/roverd/media_url_test.go similarity index 100% rename from pi/roverd/media_url_test.go rename to rover/roverd/media_url_test.go diff --git a/pi/roverd/peripheral_command_test.go b/rover/roverd/peripheral_command_test.go similarity index 100% rename from pi/roverd/peripheral_command_test.go rename to rover/roverd/peripheral_command_test.go diff --git a/pi/roverd/peripheral_discovery_dummy.go b/rover/roverd/peripheral_discovery_dummy.go similarity index 100% rename from pi/roverd/peripheral_discovery_dummy.go rename to rover/roverd/peripheral_discovery_dummy.go diff --git a/pi/roverd/peripheral_discovery_serial.go b/rover/roverd/peripheral_discovery_serial.go similarity index 100% rename from pi/roverd/peripheral_discovery_serial.go rename to rover/roverd/peripheral_discovery_serial.go diff --git a/pi/roverd/peripheral_manager.go b/rover/roverd/peripheral_manager.go similarity index 86% rename from pi/roverd/peripheral_manager.go rename to rover/roverd/peripheral_manager.go index 81456435..f07f63df 100644 --- a/pi/roverd/peripheral_manager.go +++ b/rover/roverd/peripheral_manager.go @@ -57,6 +57,7 @@ type managedPeripheral struct { // connection behind it. The inventory never changes after discovery, even if a // USB device later disappears; a process restart is the only rescan mechanism. type PeripheralManager struct { + piGPIO *piGPIOPeripheral mu sync.RWMutex peripherals []*managedPeripheral byID map[string]*managedPeripheral @@ -172,7 +173,7 @@ func discoverPeripheralManager(ctx context.Context, excludedDevice string, logge func (manager *PeripheralManager) StartupBroadcasts() []string { inventory := manager.Inventory() if len(inventory) == 0 { - return []string{"No ESP32 rover peripherals detected during startup."} + return []string{"No rover peripherals enabled or detected during startup."} } messages := make([]string, 0, len(inventory)) for _, peripheral := range inventory { @@ -387,83 +388,87 @@ func (peripheral *managedPeripheral) requirePinMode(owner string, pin int, requi return fmt.Errorf("%s advertises pin %d without required Firmata mode 0x%02x", owner, pin, requiredMode) } -// HasRoverRole reports whether discovery found an ESP32 implementation of one -// established rover control. It is used only for startup selection and logging; -// commands continue to target the selected controller interface directly. -func (manager *PeripheralManager) HasRoverRole(role string) bool { - return len(manager.roverRoleProviders(role)) > 0 +// Role providers share identity and controller construction, without requiring +// internal hardware to pretend it has a Firmata client or serial connection. +type roverRoleProvider interface { + roleID() string + hasRole(string) bool + cameraServo(*log.Logger) (CameraServoController, error) + toggle(string, *log.Logger) (ToggleController, error) } -func (manager *PeripheralManager) roverRoleProviders(role string) []*managedPeripheral { +func (p *managedPeripheral) roleID() string { return p.metadata.ID } +func (p *managedPeripheral) hasRole(role string) bool { + switch role { + case "cameraServo": + return p.description.RoverControls.CameraServo != nil + case "headlight": + return p.description.RoverControls.Headlight != nil + case "laser": + return p.description.RoverControls.Laser != nil + } + return false +} +func (p *managedPeripheral) cameraServo(logger *log.Logger) (CameraServoController, error) { + return newFirmataCameraServo(p, *p.description.RoverControls.CameraServo, logger) +} +func (p *managedPeripheral) toggle(role string, logger *log.Logger) (ToggleController, error) { + declaration := p.description.RoverControls.Headlight + if role == "laser" { + declaration = p.description.RoverControls.Laser + } + return newFirmataToggle(role, p, *declaration, logger) +} + +func (manager *PeripheralManager) roleProvider(role string) (roverRoleProvider, error) { if manager == nil { - return nil + return nil, nil } manager.mu.RLock() defer manager.mu.RUnlock() - var providers []*managedPeripheral - for _, peripheral := range manager.peripherals { - switch role { - case "cameraServo": - if peripheral.description.RoverControls.CameraServo != nil { - providers = append(providers, peripheral) - } - case "headlight": - if peripheral.description.RoverControls.Headlight != nil { - providers = append(providers, peripheral) - } - case "laser": - if peripheral.description.RoverControls.Laser != nil { - providers = append(providers, peripheral) - } + var selected roverRoleProvider + var ids []string + consider := func(provider roverRoleProvider) { + if provider.hasRole(role) { + selected = provider + ids = append(ids, provider.roleID()) } } - return providers + for _, peripheral := range manager.peripherals { + consider(peripheral) + } + if manager.piGPIO != nil { + consider(manager.piGPIO) + } + if len(ids) > 1 { + return nil, fmt.Errorf("rover peripheral role %s has multiple providers: %s", role, strings.Join(ids, ", ")) + } + return selected, nil } -// NewFirmataCameraServo constructs the shared camera controller only when a -// discovered peripheral declared that standardized role. Absence is a normal -// disabled-feature result rather than an error. -func (manager *PeripheralManager) NewFirmataCameraServo(logger *log.Logger) (CameraServoController, error) { - providers := manager.roverRoleProviders("cameraServo") - if len(providers) == 0 { - return nil, nil +func (manager *PeripheralManager) NewCameraServo(logger *log.Logger) (CameraServoController, error) { + provider, err := manager.roleProvider("cameraServo") + if err != nil || provider == nil { + return nil, err } - if len(providers) > 1 { - return nil, duplicateRoverRoleError("cameraServo", providers) - } - peripheral := providers[0] - return newFirmataCameraServo(peripheral, *peripheral.description.RoverControls.CameraServo, logger) + return provider.cameraServo(logger) } -// NewFirmataToggle resolves either standardized digital role without exposing -// the peripheral connection or ESP32 pin to WSClient. -func (manager *PeripheralManager) NewFirmataToggle(role string, logger *log.Logger) (ToggleController, error) { - providers := manager.roverRoleProviders(role) - if len(providers) == 0 { - return nil, nil +func (manager *PeripheralManager) NewToggle(role string, logger *log.Logger) (ToggleController, error) { + provider, err := manager.roleProvider(role) + if err != nil || provider == nil { + return nil, err } - if len(providers) > 1 { - return nil, duplicateRoverRoleError(role, providers) - } - peripheral := providers[0] - var declaration *PeripheralDigitalRole - switch role { - case "headlight": - declaration = peripheral.description.RoverControls.Headlight - case "laser": - declaration = peripheral.description.RoverControls.Laser - default: - return nil, fmt.Errorf("unknown Firmata toggle role %q", role) - } - return newFirmataToggle(role, peripheral, *declaration, logger) + return provider.toggle(role, logger) } -func duplicateRoverRoleError(role string, providers []*managedPeripheral) error { - providerIDs := make([]string, 0, len(providers)) - for _, provider := range providers { - providerIDs = append(providerIDs, provider.metadata.ID) +// StartInternal starts automatic functions after role registration. BRC belongs +// to the internal peripheral lifecycle rather than the daemon entry point. +func (manager *PeripheralManager) StartInternal(ctx context.Context) error { + if manager == nil || manager.piGPIO == nil { + return nil } - return fmt.Errorf("rover peripheral role %s has multiple providers: %s", role, strings.Join(providerIDs, ", ")) + return manager.piGPIO.start(ctx, manager.logger) } // Inventory returns a defensive copy in startup order. Server reconnects reuse @@ -487,6 +492,9 @@ func (manager *PeripheralManager) Inventory() []RoverPeripheralMetadata { } inventory = append(inventory, metadata) } + if manager.piGPIO != nil { + inventory = append(inventory, RoverPeripheralMetadata{ID: "pi-gpio", Name: "Pi GPIO", Controls: []RoverPeripheralControl{}}) + } return inventory } @@ -572,7 +580,12 @@ func (manager *PeripheralManager) Close() { return } manager.closeOnce.Do(func() { - manager.cancel() + if manager.cancel != nil { + manager.cancel() + } + if manager.piGPIO != nil { + manager.piGPIO.close() + } manager.mu.Lock() defer manager.mu.Unlock() for _, peripheral := range manager.peripherals { diff --git a/pi/roverd/peripheral_manager_test.go b/rover/roverd/peripheral_manager_test.go similarity index 98% rename from pi/roverd/peripheral_manager_test.go rename to rover/roverd/peripheral_manager_test.go index c262b647..14995d41 100644 --- a/pi/roverd/peripheral_manager_test.go +++ b/rover/roverd/peripheral_manager_test.go @@ -85,7 +85,7 @@ func TestPeripheralManagerDiscoversInventoryAndDispatchesControls(t *testing.T) func TestPeripheralManagerBroadcastsNoDevices(t *testing.T) { manager := &PeripheralManager{byID: make(map[string]*managedPeripheral)} - want := "No ESP32 rover peripherals detected during startup." + want := "No rover peripherals enabled or detected during startup." if messages := manager.StartupBroadcasts(); len(messages) != 1 || messages[0] != want { t.Fatalf("startup broadcasts = %#v, want %q", messages, want) } @@ -246,7 +246,7 @@ func TestPeripheralManagerRejectsDuplicateBuiltInProvidersWhenRoleIsSelected(t * t.Fatalf("discovery should retain providers until native precedence is known: %v", err) } defer manager.Close() - if _, err := manager.NewFirmataToggle("headlight", discardLogger()); err == nil || !strings.Contains(err.Error(), "role headlight has multiple providers") { + if _, err := manager.NewToggle("headlight", discardLogger()); err == nil || !strings.Contains(err.Error(), "role headlight has multiple providers") { t.Fatalf("expected duplicate provider selection error, got %v", err) } if first.Closed() || second.Closed() { diff --git a/rover/roverd/pi_gpio_peripheral.go b/rover/roverd/pi_gpio_peripheral.go new file mode 100644 index 00000000..e05e7e84 --- /dev/null +++ b/rover/roverd/pi_gpio_peripheral.go @@ -0,0 +1,64 @@ +package roverd + +import ( + "context" + "log" +) + +// piGPIOPeripheral is an in-process provider. It exists only when the parent +// switch is enabled; merely loading saved GPIO settings never opens hardware. +type piGPIOPeripheral struct { + cfg PiGPIOConfig + factories nativeHardwareControllerFactories + pulser *BRCPulser + cancel context.CancelFunc +} + +func (p *piGPIOPeripheral) roleID() string { return "pi-gpio" } + +func (p *piGPIOPeripheral) hasRole(role string) bool { + switch role { + case "cameraServo": + return p.cfg.CameraServo.Enabled + case "headlight": + return p.cfg.Headlight.Enabled + case "laser": + return p.cfg.Laser.Enabled + } + return false +} + +func (p *piGPIOPeripheral) cameraServo(logger *log.Logger) (CameraServoController, error) { + return p.factories.newCameraServo(p.cfg.CameraServo, logger) +} + +func (p *piGPIOPeripheral) toggle(role string, logger *log.Logger) (ToggleController, error) { + cfg := p.cfg.Headlight + if role == "laser" { + cfg = p.cfg.Laser + } + return p.factories.newToggle(role, cfg, logger) +} + +func (p *piGPIOPeripheral) start(ctx context.Context, logger *log.Logger) error { + if !p.cfg.BRC.Enabled { + return nil + } + pulser, err := NewBRCPulser(p.cfg.BRC, logger) + if err != nil { + return err + } + p.pulser = pulser + ctx, p.cancel = context.WithCancel(ctx) + p.pulser.Start(ctx) + return nil +} + +func (p *piGPIOPeripheral) close() { + if p.cancel != nil { + p.cancel() + } + if p.pulser != nil { + p.pulser.Close() + } +} diff --git a/rover/roverd/roverd.debian-laptop.sample.json b/rover/roverd/roverd.debian-laptop.sample.json new file mode 100644 index 00000000..d1e0f098 --- /dev/null +++ b/rover/roverd/roverd.debian-laptop.sample.json @@ -0,0 +1,127 @@ +{ + "piGpio": { + "enabled": false, + "brc": { + "enabled": false, + "gpioPin": 4, + "gpioChip": "gpiochip0", + "pulseEvery": "1m0s", + "pulseWidth": "1s" + }, + "cameraServo": { + "enabled": false, + "pin": 12, + "freqHz": 50, + "cycleLen": 20000, + "minPulseUs": 900, + "maxPulseUs": 2100, + "minAngle": -15, + "maxAngle": 30, + "homeAngle": 0, + "nudgeDegrees": 2, + "allowRawPulse": false, + "invert": false + }, + "headlight": { + "enabled": false, + "gpioPin": 22, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": true + }, + "laser": { + "enabled": false, + "gpioPin": 27, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": false + } + }, + "name": "laptop-rover", + "description": "Debian laptop rover using USB serial, webcam, mic, and speakers.", + "color": "#4DB6AC", + "serverUrl": "ws://control-server.local:8080/rover", + "serial": { + "device": "/dev/ttyUSB0", + "baud": 115200 + }, + "battery": { + "full": 2068, + "warn": 1700, + "urgent": 1650 + }, + "maxWheelSpeed": 350, + "media": { + "rtspPort": 8554, + "manage": true, + "healthUrl": "", + "healthInterval": "30s", + "video": { + "enabled": true, + "service": "debian-laptop-video-publisher.service", + "publisher": "debian-laptop-v4l2", + "device": "/dev/video0", + "inputFormat": "mjpeg", + "width": 640, + "height": 480, + "fps": 30, + "bitrate": 2000000, + "inverted": false, + "sensorMode": "1296:972" + }, + "audioCapture": { + "enabled": true, + "service": "audio-only-publisher.service", + "device": "default", + "sampleRate": 48000, + "channels": 2, + "bitrate": 510000 + }, + "audioPlayback": { + "enabled": true, + "service": "audio-forward-listener.service", + "device": "forward", + "normalize": true, + "normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled" + } + }, + "audio": { + "ttsEnabled": true, + "defaultEngine": "flite", + "defaultVoice": "rms", + "defaultPitch": 50 + }, + "horn": { + "enabled": true, + "volume": 0.25, + "sampleRate": 48000, + "channels": 1, + "device": "", + "sineGain": 1, + "sawGain": 0.7, + "maxDuration": "10s" + }, + "autoSideBrush": { + "enabled": true, + "speed": 20 + }, + "private": { + "enabled": false, + "safety": { + "speedLimitEnabled": false, + "speedLimitMaxWheelSpeed": 250, + "hardOvercurrentEnabled": false, + "overcurrentStopMs": 300, + "hardBumpEnabled": false, + "bumpBackoffSpeed": 250, + "bumpBackoffMs": 350, + "cliffEnabled": false, + "cliffBackoffSpeed": 250, + "cliffBackoffMs": 500, + "virtualWallEnabled": true, + "virtualWallBackoffSpeed": 250, + "virtualWallBackoffMs": 500, + "triggerCooldownMs": 800 + } + } +} diff --git a/rover/roverd/roverd.json b/rover/roverd/roverd.json new file mode 100644 index 00000000..1516179b --- /dev/null +++ b/rover/roverd/roverd.json @@ -0,0 +1,127 @@ +{ + "piGpio": { + "enabled": false, + "brc": { + "enabled": true, + "gpioPin": 4, + "gpioChip": "gpiochip0", + "pulseEvery": "1m", + "pulseWidth": "1s" + }, + "cameraServo": { + "enabled": false, + "pin": 19, + "freqHz": 50, + "cycleLen": 20000, + "minPulseUs": 900, + "maxPulseUs": 2100, + "minAngle": -15, + "maxAngle": 30, + "homeAngle": 0, + "nudgeDegrees": 2, + "allowRawPulse": false, + "invert": false + }, + "headlight": { + "enabled": true, + "gpioPin": 22, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": true + }, + "laser": { + "enabled": false, + "gpioPin": 27, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": false + } + }, + "name": "roomba-alpha", + "description": "Loves corners, hates cords.", + "color": "", + "serverUrl": "ws://control-server.local:8080/rover", + "serial": { + "device": "/dev/ttyAMA0", + "baud": 115200 + }, + "battery": { + "full": 2068, + "warn": 1700, + "urgent": 1650 + }, + "maxWheelSpeed": 350, + "media": { + "rtspPort": 8554, + "manage": false, + "healthUrl": "http://127.0.0.1:9997/v3/paths/list", + "healthInterval": "30s", + "video": { + "enabled": true, + "service": "video-publisher.service", + "publisher": "pi-libcamera", + "device": "", + "inputFormat": "", + "width": 640, + "height": 480, + "fps": 30, + "bitrate": 2000000, + "inverted": true, + "sensorMode": "1296:972" + }, + "audioCapture": { + "enabled": false, + "service": "audio-only-publisher.service", + "device": "hw:0,0", + "sampleRate": 48000, + "channels": 2, + "bitrate": 510000 + }, + "audioPlayback": { + "enabled": true, + "service": "audio-forward-listener.service", + "device": "forward", + "normalize": true, + "normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled" + } + }, + "audio": { + "ttsEnabled": false, + "defaultEngine": "flite", + "defaultVoice": "rms", + "defaultPitch": 50 + }, + "horn": { + "enabled": false, + "volume": 0.25, + "sampleRate": 48000, + "channels": 1, + "device": "", + "sineGain": 1, + "sawGain": 0.7, + "maxDuration": "10s" + }, + "autoSideBrush": { + "enabled": true, + "speed": 20 + }, + "private": { + "enabled": false, + "safety": { + "speedLimitEnabled": false, + "speedLimitMaxWheelSpeed": 250, + "hardOvercurrentEnabled": false, + "overcurrentStopMs": 300, + "hardBumpEnabled": false, + "bumpBackoffSpeed": 250, + "bumpBackoffMs": 350, + "cliffEnabled": false, + "cliffBackoffSpeed": 250, + "cliffBackoffMs": 500, + "virtualWallEnabled": true, + "virtualWallBackoffSpeed": 250, + "virtualWallBackoffMs": 500, + "triggerCooldownMs": 800 + } + } +} diff --git a/rover/roverd/roverd.sample.json b/rover/roverd/roverd.sample.json new file mode 100644 index 00000000..102327af --- /dev/null +++ b/rover/roverd/roverd.sample.json @@ -0,0 +1,127 @@ +{ + "piGpio": { + "enabled": false, + "brc": { + "enabled": true, + "gpioPin": 4, + "gpioChip": "gpiochip0", + "pulseEvery": "1m", + "pulseWidth": "1s" + }, + "cameraServo": { + "enabled": false, + "pin": 12, + "freqHz": 50, + "cycleLen": 20000, + "minPulseUs": 900, + "maxPulseUs": 2100, + "minAngle": -15, + "maxAngle": 30, + "homeAngle": 0, + "nudgeDegrees": 2, + "allowRawPulse": false, + "invert": false + }, + "headlight": { + "enabled": true, + "gpioPin": 22, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": true + }, + "laser": { + "enabled": false, + "gpioPin": 27, + "gpioChip": "gpiochip0", + "initialOn": false, + "activeLow": false + } + }, + "name": "roomba-alpha", + "description": "Loves corners, hates cords.", + "color": "#4DB6AC", + "serverUrl": "ws://control-server.local:8080/rover", + "serial": { + "device": "/dev/ttyAMA0", + "baud": 115200 + }, + "battery": { + "full": 2068, + "warn": 1700, + "urgent": 1650 + }, + "maxWheelSpeed": 350, + "media": { + "rtspPort": 8554, + "manage": true, + "healthUrl": "", + "healthInterval": "30s", + "video": { + "enabled": true, + "service": "video-publisher.service", + "publisher": "pi-libcamera", + "device": "", + "inputFormat": "", + "width": 640, + "height": 480, + "fps": 30, + "bitrate": 2000000, + "inverted": true, + "sensorMode": "1296:972" + }, + "audioCapture": { + "enabled": false, + "service": "audio-only-publisher.service", + "device": "hw:0,0", + "sampleRate": 48000, + "channels": 2, + "bitrate": 510000 + }, + "audioPlayback": { + "enabled": true, + "service": "audio-forward-listener.service", + "device": "forward", + "normalize": true, + "normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled" + } + }, + "audio": { + "ttsEnabled": false, + "defaultEngine": "flite", + "defaultVoice": "rms", + "defaultPitch": 50 + }, + "horn": { + "enabled": false, + "volume": 0.25, + "sampleRate": 48000, + "channels": 1, + "device": "", + "sineGain": 1, + "sawGain": 0.7, + "maxDuration": "1.2s" + }, + "autoSideBrush": { + "enabled": true, + "speed": 20 + }, + "private": { + "enabled": false, + "safety": { + "speedLimitEnabled": false, + "speedLimitMaxWheelSpeed": 250, + "hardOvercurrentEnabled": false, + "overcurrentStopMs": 300, + "hardBumpEnabled": false, + "bumpBackoffSpeed": 250, + "bumpBackoffMs": 350, + "cliffEnabled": false, + "cliffBackoffSpeed": 250, + "cliffBackoffMs": 500, + "virtualWallEnabled": true, + "virtualWallBackoffSpeed": 250, + "virtualWallBackoffMs": 500, + "triggerCooldownMs": 800 + } + } +} diff --git a/pi/roverd/sensor_defs.go b/rover/roverd/sensor_defs.go similarity index 100% rename from pi/roverd/sensor_defs.go rename to rover/roverd/sensor_defs.go diff --git a/pi/roverd/sensor_stream.go b/rover/roverd/sensor_stream.go similarity index 100% rename from pi/roverd/sensor_stream.go rename to rover/roverd/sensor_stream.go diff --git a/pi/roverd/sensor_stream_dummy.go b/rover/roverd/sensor_stream_dummy.go similarity index 100% rename from pi/roverd/sensor_stream_dummy.go rename to rover/roverd/sensor_stream_dummy.go diff --git a/pi/roverd/serial.go b/rover/roverd/serial.go similarity index 100% rename from pi/roverd/serial.go rename to rover/roverd/serial.go diff --git a/pi/roverd/serial_dummy.go b/rover/roverd/serial_dummy.go similarity index 100% rename from pi/roverd/serial_dummy.go rename to rover/roverd/serial_dummy.go diff --git a/pi/roverd/tts.go b/rover/roverd/tts.go similarity index 100% rename from pi/roverd/tts.go rename to rover/roverd/tts.go diff --git a/pi/roverd/wsclient.go b/rover/roverd/wsclient.go similarity index 77% rename from pi/roverd/wsclient.go rename to rover/roverd/wsclient.go index 6a82f7df..a11b6fa0 100644 --- a/pi/roverd/wsclient.go +++ b/rover/roverd/wsclient.go @@ -8,42 +8,46 @@ import ( "log" "os/exec" "sync" + "sync/atomic" "time" "nhooyr.io/websocket" ) type WSClient struct { - cfg *Config - adapter *SerialAdapter - sensorFrames <-chan []byte - events chan RoverEvent - media *MediaSupervisor - servo CameraServoController - horn *HornSynth - headlight ToggleController - laser ToggleController - peripherals *PeripheralManager - log *log.Logger - console *ConsoleNotifier - recoverMu sync.Mutex - recovering bool - watchdogMu sync.Mutex - watchdogOpen bool - watchdogOK bool - ttsQueue chan *ttsPayload - chromeTTS *chromeTTSDaemon - lastAux motorPWMPayload - autoSideOn bool - connMu sync.Mutex - connected bool - disconnectT *time.Timer - rebootT *time.Timer - seekIssued bool - rebootIssued bool - updateIssued bool - audioLevels AudioLevels - audioMu sync.RWMutex + autoCharge *AutoChargeController + commandMu sync.Mutex + stopping atomic.Bool + controlEvents chan RoverEvent + cfg *Config + adapter *SerialAdapter + sensorFrames <-chan []byte + events chan RoverEvent + media *MediaSupervisor + servo CameraServoController + horn *HornSynth + headlight ToggleController + laser ToggleController + peripherals *PeripheralManager + log *log.Logger + console *ConsoleNotifier + recoverMu sync.Mutex + recovering bool + watchdogMu sync.Mutex + watchdogOpen bool + watchdogOK bool + ttsQueue chan *ttsPayload + chromeTTS *chromeTTSDaemon + lastAux motorPWMPayload + autoSideOn bool + connMu sync.Mutex + connected bool + disconnectT *time.Timer + rebootT *time.Timer + seekIssued bool + rebootIssued bool + audioLevels AudioLevels + audioMu sync.RWMutex } func NewWSClient(cfg *Config, adapter *SerialAdapter, frames <-chan []byte, events chan RoverEvent, media *MediaSupervisor, servo CameraServoController, headlight ToggleController, laser ToggleController, peripherals *PeripheralManager, logger *log.Logger, console *ConsoleNotifier) *WSClient { @@ -60,20 +64,21 @@ func NewWSClient(cfg *Config, adapter *SerialAdapter, frames <-chan []byte, even horn = NewHornSynth(cfg.Horn, logger) } client := &WSClient{ - cfg: cfg, - adapter: adapter, - sensorFrames: frames, - events: events, - media: media, - servo: servo, - horn: horn, - headlight: headlight, - laser: laser, - peripherals: peripherals, - log: logger, - console: console, - ttsQueue: ttsQueue, - chromeTTS: chromeTTS, + controlEvents: make(chan RoverEvent, 16), + cfg: cfg, + adapter: adapter, + sensorFrames: frames, + events: events, + media: media, + servo: servo, + horn: horn, + headlight: headlight, + laser: laser, + peripherals: peripherals, + log: logger, + console: console, + ttsQueue: ttsQueue, + chromeTTS: chromeTTS, audioLevels: AudioLevels{ HornGain: 1.0, TTSGain: 1.0, @@ -85,6 +90,11 @@ func NewWSClient(cfg *Config, adapter *SerialAdapter, frames <-chan []byte, even } func (c *WSClient) Run(ctx context.Context) error { + if c.stopping.Load() { + return fmt.Errorf("roverd is stopping") + } + ctx, stop := context.WithCancel(ctx) + defer stop() dialCtx, cancel := context.WithTimeout(ctx, dialTimeout) conn, _, err := websocket.Dial(dialCtx, c.cfg.ServerURL, nil) cancel() @@ -113,13 +123,12 @@ func (c *WSClient) Run(ctx context.Context) error { errCh <- c.readLoop(ctx, conn) }() go func() { - if err := c.keepalive(ctx, conn); err != nil { + if err := keepalive(ctx, conn); err != nil { errCh <- err } }() go c.forwardSensors(ctx, conn) go c.forwardEvents(ctx, conn) - go c.forwardHostStats(ctx, conn) select { case <-ctx.Done(): @@ -132,7 +141,7 @@ func (c *WSClient) Run(ctx context.Context) error { func (c *WSClient) sendHello(ctx context.Context, conn *websocket.Conn) error { // Built-in metadata comes from the selected controller, not necessarily - // YAML. An ESP32 can enable a role whose native GPIO entry is disabled. + // saved configuration. An ESP32 can enable a role whose native GPIO entry is disabled. cameraServoConfig := CameraServoConfig{} if c.servo != nil { cameraServoConfig = c.servo.Configuration() @@ -152,7 +161,7 @@ func (c *WSClient) sendHello(ctx context.Context, conn *websocket.Conn) error { Color: c.cfg.Color, Battery: c.cfg.Battery, MaxWheelSpeed: c.cfg.MaxWheelMMs, - Media: c.cfg.Media, + Media: c.cfg.MediaMetadata(), CameraServo: cameraServoConfig, Audio: c.cfg.Audio, Horn: c.cfg.Horn, @@ -199,6 +208,11 @@ func (c *WSClient) readLoop(ctx context.Context, conn *websocket.Conn) error { } func (c *WSClient) dispatch(ctx context.Context, msg *inboundMessage) error { + c.commandMu.Lock() + defer c.commandMu.Unlock() + if c.stopping.Load() { + return fmt.Errorf("roverd is stopping") + } switch { case msg.DriveDirect != nil: left := clamp(msg.DriveDirect.Left, -c.cfg.MaxWheelMMs, c.cfg.MaxWheelMMs) @@ -232,11 +246,6 @@ func (c *WSClient) dispatch(ctx context.Context, msg *inboundMessage) error { return c.ensureSensorStream() } return nil - case msg.Media != nil: - if c.media == nil { - return fmt.Errorf("media supervisor disabled") - } - return c.media.HandleAction(ctx, msg.Media.Action) case msg.Servo != nil: if c.servo == nil { return fmt.Errorf("camera servo disabled") @@ -263,10 +272,6 @@ func (c *WSClient) dispatch(ctx context.Context, msg *inboundMessage) error { slot = clampInt(*msg.Song.Slot, 0, 4) } return c.adapter.PlaySong(slot, msg.Song.Notes) - case msg.Reboot != nil || msg.Type == "reboot": - return c.handleRebootCommand(msg.Reboot) - case msg.Update != nil || msg.Type == "update": - return c.handleUpdateCommand() default: return fmt.Errorf("unsupported command type: %s", msg.Type) } @@ -304,79 +309,6 @@ func (c *WSClient) stopMotionForSystemCommand(reason string) error { return nil } -func (c *WSClient) handleRebootCommand(payload *rebootPayload) error { - if err := c.stopMotionForSystemCommand("reboot"); err != nil { - return err - } - - delay := 300 * time.Millisecond - if payload != nil && payload.DelayMs > 0 { - delay = time.Duration(clampInt(payload.DelayMs, 50, 5000)) * time.Millisecond - } - - c.connMu.Lock() - if c.rebootIssued { - c.connMu.Unlock() - return fmt.Errorf("reboot already pending") - } - c.rebootIssued = true - c.connMu.Unlock() - - c.emitEvent("system.rebooting", map[string]any{ - "source": "remoteCommand", - "delayMs": delay.Milliseconds(), - }) - - go func() { - time.Sleep(delay) - c.console.Notify("Remote reboot requested. Rebooting the rover now.") - c.log.Printf("rebooting pi after remote reboot command") - cmd := exec.Command("systemctl", "reboot") - if err := cmd.Start(); err != nil { - c.log.Printf("reboot command failed: %v", err) - } - }() - - return nil -} - -func (c *WSClient) handleUpdateCommand() error { - if err := c.stopMotionForSystemCommand("self-update"); err != nil { - return err - } - - c.connMu.Lock() - if c.updateIssued { - c.connMu.Unlock() - return fmt.Errorf("update already pending") - } - c.updateIssued = true - c.connMu.Unlock() - - c.emitEvent("system.updateStarting", map[string]any{ - "source": "remoteCommand", - }) - c.console.Notify("Remote software update requested. roverd will restart if the update succeeds.") - - // The helper is launched asynchronously because a successful update may - // restart roverd before this websocket command could stream progress back to - // the server. sudo is intentionally limited by /etc/sudoers.d/roverd-self-update - // to one root-owned helper with no caller-controlled arguments. - cmd := exec.Command("sudo", "-n", "/usr/local/sbin/roverd-self-update") - if err := cmd.Start(); err != nil { - c.connMu.Lock() - c.updateIssued = false - c.connMu.Unlock() - return fmt.Errorf("start self-update helper: %w", err) - } - if err := cmd.Process.Release(); err != nil { - c.log.Printf("release self-update helper process handle failed: %v", err) - } - - c.log.Printf("started roverd self-update helper with pid %d", cmd.Process.Pid) - return nil -} - func (c *WSClient) applyAutoSideBrush(left, right int) { if c.cfg == nil || !c.cfg.AutoSideBrush.Enabled { if c.autoSideOn { @@ -548,7 +480,7 @@ func (c *WSClient) forwardEvents(ctx context.Context, conn *websocket.Conn) { select { case <-ctx.Done(): return - case evt := <-c.events: + case evt := <-c.controlEvents: if evt.Type == "" { evt.Type = "event" } @@ -560,56 +492,16 @@ func (c *WSClient) forwardEvents(ctx context.Context, conn *websocket.Conn) { } } -func (c *WSClient) forwardHostStats(ctx context.Context, conn *websocket.Conn) { - var previousNetworkSample *networkRateSample - - send := func() bool { - // Host stats are collected on demand so each outbound message describes - // the current Pi state. Collection failures are encoded into the stats - // payload, which keeps this telemetry path from closing the rover socket. - stats := CollectHostStats(ctx) - // Throughput is derived here because this loop owns the ordered, periodic - // samples for one connection. CollectHostStats stays independent, while a - // reconnect automatically receives a clean counter baseline. - previousNetworkSample = applyNetworkThroughput(stats.WiFi, previousNetworkSample) - msg := hostStatsMessage{ - Type: "hostStats", - Timestamp: time.Now().UnixMilli(), - Stats: stats, - } - if err := writeJSON(ctx, conn, msg); err != nil { - c.log.Printf("host stats send failed: %v", err) - return false - } - return true - } - - // Send once immediately so a newly connected rover can populate the UI - // without waiting for the first ticker interval. - if !send() { - return - } - - ticker := time.NewTicker(hostStatsInterval) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - if !send() { - return - } - } - } -} - func (c *WSClient) emitEvent(event string, data map[string]any) { - if c.events == nil { + events := c.events + if event == "headlight.state" || event == "laser.state" { + events = c.controlEvents + } + if events == nil { return } select { - case c.events <- RoverEvent{ + case events <- RoverEvent{ Type: "event", Event: event, Ts: time.Now().UnixMilli(), @@ -650,7 +542,7 @@ const dialTimeout = 10 * time.Second const pingInterval = 15 * time.Second const pingTimeout = 5 * time.Second -func (c *WSClient) keepalive(ctx context.Context, conn *websocket.Conn) error { +func keepalive(ctx context.Context, conn *websocket.Conn) error { ticker := time.NewTicker(pingInterval) defer ticker.Stop() @@ -675,7 +567,6 @@ func (c *WSClient) markConnected() { c.connected = true c.seekIssued = false c.rebootIssued = false - c.updateIssued = false if c.disconnectT != nil { c.disconnectT.Stop() c.disconnectT = nil @@ -695,6 +586,9 @@ func (c *WSClient) markConnected() { } func (c *WSClient) markDisconnected() { + if c.stopping.Load() { + return + } c.connMu.Lock() wasConnected := c.connected c.connected = false @@ -715,6 +609,11 @@ func (c *WSClient) markDisconnected() { } func (c *WSClient) handleDisconnectTimeout() { + c.commandMu.Lock() + defer c.commandMu.Unlock() + if c.stopping.Load() { + return + } c.connMu.Lock() if c.connected || c.seekIssued { c.connMu.Unlock() @@ -732,6 +631,9 @@ func (c *WSClient) handleDisconnectTimeout() { } func (c *WSClient) handleRebootTimeout() { + if c.stopping.Load() { + return + } c.connMu.Lock() if c.connected || c.rebootIssued { c.connMu.Unlock() @@ -749,6 +651,11 @@ func (c *WSClient) handleRebootTimeout() { } func (c *WSClient) recoverSensorStream(idleFor time.Duration, cmdPause time.Duration) { + c.commandMu.Lock() + defer c.commandMu.Unlock() + if c.stopping.Load() { + return + } c.recoverMu.Lock() if c.recovering { c.recoverMu.Unlock() @@ -842,3 +749,42 @@ func isModeOpcode(op byte) bool { return false } } + +// PrepareShutdown blocks new control commands before stopping the hardware. +func (c *WSClient) PrepareShutdown() error { + c.commandMu.Lock() + defer c.commandMu.Unlock() + c.stopping.Store(true) + if c.autoCharge != nil { + c.autoCharge.SetPaused(true) + } + c.connMu.Lock() + if c.disconnectT != nil { + c.disconnectT.Stop() + } + if c.rebootT != nil { + c.rebootT.Stop() + } + c.connMu.Unlock() + if c.horn != nil { + c.horn.HandlePayload(&hornPayload{Action: "stop"}) + } + return c.stopMotionForSystemCommand("management action") +} + +func (c *WSClient) ResumeControl() { + c.commandMu.Lock() + defer c.commandMu.Unlock() + if c.autoCharge != nil { + c.autoCharge.SetPaused(false) + } + c.stopping.Store(false) + // A rejected management action must restore disconnect safety timers too. + c.connMu.Lock() + connected := c.connected + c.connMu.Unlock() + if !connected { + c.markDisconnected() + } +} +func (c *WSClient) SetAutoCharge(controller *AutoChargeController) { c.autoCharge = controller } diff --git a/pi/roverd/wsclient_watchdog_test.go b/rover/roverd/wsclient_watchdog_test.go similarity index 100% rename from pi/roverd/wsclient_watchdog_test.go rename to rover/roverd/wsclient_watchdog_test.go diff --git a/pi/systemd/audio-forward-listener.service b/rover/systemd/audio-forward-listener.service similarity index 100% rename from pi/systemd/audio-forward-listener.service rename to rover/systemd/audio-forward-listener.service diff --git a/pi/systemd/audio-only-publisher.service b/rover/systemd/audio-only-publisher.service similarity index 100% rename from pi/systemd/audio-only-publisher.service rename to rover/systemd/audio-only-publisher.service diff --git a/pi/systemd/debian-laptop-video-publisher.service b/rover/systemd/debian-laptop-video-publisher.service similarity index 100% rename from pi/systemd/debian-laptop-video-publisher.service rename to rover/systemd/debian-laptop-video-publisher.service diff --git a/pi/systemd/roverd.service b/rover/systemd/roverd.service similarity index 89% rename from pi/systemd/roverd.service rename to rover/systemd/roverd.service index 71c75572..6a260137 100644 --- a/pi/systemd/roverd.service +++ b/rover/systemd/roverd.service @@ -5,7 +5,9 @@ Wants=network-online.target [Service] Type=simple -ExecStart=/usr/local/bin/roverd -config /etc/roverd.yaml +User=root +Group=root +ExecStart=/usr/local/bin/roverd -config /etc/roverd.json # roverd cannot report an unexpected exit after its process is already gone. # ExecStopPost fills only that gap; ordinary lifecycle messages remain owned by # roverd, and SERVICE_RESULT prevents clean stops from being labeled failures. diff --git a/pi/systemd/video-publisher.service b/rover/systemd/video-publisher.service similarity index 100% rename from pi/systemd/video-publisher.service rename to rover/systemd/video-publisher.service diff --git a/server/index.js b/server/index.js index 46b0692e..bc79469e 100644 --- a/server/index.js +++ b/server/index.js @@ -28,6 +28,7 @@ require('./src/services/roverManager'); require('./src/services/roverHelpService'); require('./src/services/commandService'); require('./src/services/roverConnectionService'); +require('./src/services/roverManagementService'); require('./src/services/assignmentService'); require('./src/services/roverRebootService'); require('./src/services/nicknameService'); diff --git a/server/src/globals/ws.js b/server/src/globals/ws.js index 91c3dd28..24dd481e 100644 --- a/server/src/globals/ws.js +++ b/server/src/globals/ws.js @@ -5,11 +5,14 @@ const { httpServer } = require('./http'); const logger = require('./logger'); const roverWSS = new WebSocketServer({ noServer: true }); +const managementWSS = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024 }); httpServer.on('upgrade', (req, socket, head) => { - if (req.url.startsWith('/rover')) { - roverWSS.handleUpgrade(req, socket, head, (ws) => { - roverWSS.emit('connection', ws, req); + const path = new URL(req.url, 'http://localhost').pathname; + const target = path === '/rover/management' ? managementWSS : path === '/rover' ? roverWSS : null; + if (target) { + target.handleUpgrade(req, socket, head, (ws) => { + target.emit('connection', ws, req); }); } }); @@ -19,3 +22,5 @@ roverWSS.on('connection', () => { }); module.exports = roverWSS; + +module.exports.managementWSS = managementWSS; diff --git a/server/src/services/commandService/index.js b/server/src/services/commandService/index.js index 880daa6a..5fdbed89 100644 --- a/server/src/services/commandService/index.js +++ b/server/src/services/commandService/index.js @@ -2,6 +2,7 @@ // Purpose: Defines the command Service module and the helpers/state used by this service unit. // Scope: Keeps runtime behavior unchanged while isolating responsibilities into a clear module boundary. const { v4: uuidv4 } = require('uuid'); +const roverManagement = require('../roverManagementService'); const EventEmitter = require('events'); const io = require('../../globals/io'); const roverManager = require('../roverManager'); @@ -86,6 +87,9 @@ function normalizeOutboundCommandPayload(payload = {}) { } function issueCommand(roverId, payload, options = {}) { + if (['reboot', 'update', 'media'].includes(payload?.type)) { + return roverManagement.issueCommand(roverId, payload); + } const record = roverManager.rovers.get(roverId); if (!record || !record.ws) { throw new Error('Rover offline'); @@ -168,10 +172,10 @@ function issueUpdateToAllRovers() { const updated = []; const failed = []; - roverManager.rovers.forEach((record) => { + roverManagement.rovers.forEach((record) => { if (!record?.ws) return; - const roverId = String(record.id); + const roverId = String(record.roverId); try { // Use the same narrow update payload as the per-rover admin action. The // browser only asks for "update all"; the Pi still owns the privileged @@ -304,6 +308,7 @@ function submitCommand(socket, { roverId, type, data } = {}, cb) { } const isRebootCommand = type === 'reboot'; const isUpdateCommand = type === 'update'; + const isManagementCommand = isRebootCommand || isUpdateCommand || type === 'media'; const isSongCommand = type === 'song' || (type === 'raw' && isSongRawPayload(payload)); const isAdminSocket = isAdmin(socket); if (!isAdminSocket && isDeterred(socket)) { @@ -321,10 +326,14 @@ function submitCommand(socket, { roverId, type, data } = {}, cb) { // in the same explicit admin-only branch as reboot instead of relying on // drive ownership checks, because having a turn should not grant system // maintenance privileges. - if ((isRebootCommand || isUpdateCommand) && !isAdminSocket) { + if (isManagementCommand && !isAdminSocket) { throw new Error('Not authorized'); } - if (!isSongCommand && !isRebootCommand && !isUpdateCommand && !roverManager.canDrive(roverId, socket)) { + if (isManagementCommand) { + reply({ id: issueCommand(roverId, { ...payload, type }) }); + return; + } + if (!isSongCommand && !roverManager.canDrive(roverId, socket)) { throw new Error('Not your turn or no control'); } const record = roverManager.rovers.get(roverId); diff --git a/server/src/services/roverConnectionService/index.js b/server/src/services/roverConnectionService/index.js index 56e3054c..75639419 100644 --- a/server/src/services/roverConnectionService/index.js +++ b/server/src/services/roverConnectionService/index.js @@ -41,32 +41,6 @@ function handleToggleEvent(roverId, msg) { return false; } -function handleMessage(roverId, msg) { - switch (msg.type) { - case 'hello': - roverManager.upsertRover(msg, this); - sendAlert({ color: ALERT_COLOR, title: 'Rover Connected', message: roverId }); - break; - case 'sensor': - roverManager.handleSensorFrame(roverId, msg); - break; - case 'hostStats': - // Host stats are periodic Pi metadata, not user-facing rover events, so - // they are routed directly to roverManager instead of becoming alerts. - roverManager.handleHostStats(roverId, msg); - break; - case 'event': { - if (handleToggleEvent(roverId, msg)) { - break; - } - sendAlert({ color: ALERT_COLOR, title: `${roverId} event`, message: msg.event }); - break; - } - default: - break; - } -} - roverWSS.on('connection', (ws) => { let roverId = null; ws.isAlive = true; @@ -109,16 +83,10 @@ roverWSS.on('connection', (ws) => { if (!roverId) return; if (msg.type === 'sensor') { roverManager.handleSensorFrame(roverId, msg); - } else if (msg.type === 'hostStats') { - // Keep the Pi health stream separate from both Roomba sensorFrame data - // and generic rover events, which are surfaced as alerts. - roverManager.handleHostStats(roverId, msg); } else if (msg.type === 'ack') { handleAck(msg); } else if (msg.type === 'event') { - if (!handleToggleEvent(roverId, msg)) { - sendAlert({ color: ALERT_COLOR, title: `${roverId}`, message: msg.event }); - } + handleToggleEvent(roverId, msg); } }); diff --git a/server/src/services/roverManagementService/index.js b/server/src/services/roverManagementService/index.js new file mode 100644 index 00000000..67493997 --- /dev/null +++ b/server/src/services/roverManagementService/index.js @@ -0,0 +1,184 @@ +const { randomUUID } = require('node:crypto'); +const io = require('../../globals/io'); +const { managementWSS } = require('../../globals/ws'); +const { isAdmin } = require('../roleService'); +const { sendAlert } = require('../alertService'); +const logger = require('../../globals/logger').child('roverManagement'); + +// Management availability is independent of the control roster: a rover with +// failed hardware must still be configurable. All state here is memory-only. +const rovers = new Map(); +const pending = new Map(); +const MAX_MESSAGE_BYTES = 1024 * 1024; + +function snapshot(record) { + return { + roverId: record.roverId, + config: record.config, + schema: record.schema, + profiles: record.profiles, + hostStats: record.hostStats || null, + notices: record.notices, + }; +} + +function notifyAdmins(event, value) { + for (const socket of io.sockets.sockets.values()) { + if (isAdmin(socket)) socket.emit(event, value); + } +} + +function finish(id, error, ack) { + const item = pending.get(id); + if (!item) return; + clearTimeout(item.timer); + pending.delete(id); + if (error) item.reject(error); else item.resolve(ack); +} + +function request(roverId, payload) { + const record = rovers.get(String(roverId)); + if (!record || record.ws.readyState !== 1) throw new Error('Rover management offline'); + const id = randomUUID(); + const data = JSON.stringify({ ...payload, id }); + if (Buffer.byteLength(data) > MAX_MESSAGE_BYTES) throw new Error('Management request too large'); + const result = new Promise((resolve, reject) => { + const timer = setTimeout(() => finish(id, new Error('Rover management acknowledgement timed out')), 30000); + pending.set(id, { roverId: record.roverId, ws: record.ws, resolve, reject, timer }); + try { + record.ws.send(data, (error) => { if (error) finish(id, error); }); + } catch (error) { finish(id, error); } + }); + return { id, result }; +} + +// Existing reboot/update callers retain their permission gates and commandAck +// UI, but transport and acknowledgement ownership now live on management. +function issueCommand(roverId, payload) { + const { id, result } = request(roverId, payload); + result.then( + () => io.emit('commandAck', { roverId, id, status: 'ok' }), + (error) => io.emit('commandAck', { roverId, id, status: 'error', error: error.message }), + ); + return id; +} + +managementWSS.on('connection', (ws) => { + let record; + let alive = true; + const helloTimeout = setTimeout(() => ws.terminate(), 10000); + const heartbeat = setInterval(() => { + if (!alive) return ws.terminate(); + alive = false; + ws.ping(); + }, 15000); + ws.on('pong', () => { alive = true; }); + ws.on('error', (error) => logger.warn('Management socket error', error.message)); + ws.on('message', (raw) => { + alive = true; + try { + const msg = JSON.parse(raw.toString()); + if (msg.type === 'hello' && !record) { + if (typeof msg.name !== 'string' || !msg.name || !msg.config || !msg.schema) throw new Error('Invalid management hello'); + clearTimeout(helloTimeout); + const previous = rovers.get(msg.name); + record = { roverId: msg.name, ws, config: msg.config, schema: msg.schema, profiles: msg.profiles, notices: [] }; + rovers.set(record.roverId, record); + previous?.ws.close(1000, 'Replaced by new connection'); + notifyAdmins('roverManagement:changed', snapshot(record)); + return; + } + if (!record || rovers.get(record.roverId) !== record) return; + if (msg.type === 'ack') { + if (pending.get(msg.id)?.ws !== ws) return; + finish(msg.id, msg.status === 'ok' ? null : new Error(msg.error || 'Management action failed'), msg); + } else if (msg.type === 'hostStats') { + record.hostStats = msg; + require('../roverManager').handleHostStats(record.roverId, msg); + notifyAdmins('roverManagement:hostStats', { roverId: record.roverId, ...msg }); + } else if (msg.type === 'event') { + record.notices.push(msg); + if (record.notices.length > 100) record.notices.shift(); + notifyAdmins('roverManagement:event', { roverId: record.roverId, ...msg }); + sendAlert({ color: '#00bcd4', title: record.roverId, message: msg.data?.message || msg.event }); + } + } catch (error) { + logger.warn('Invalid management message', error.message); + ws.close(1008, 'Invalid management message'); + } + }); + ws.on('close', () => { + clearTimeout(helloTimeout); + clearInterval(heartbeat); + for (const [id, item] of pending) { + if (item.ws === ws) finish(id, new Error('Rover management disconnected before acknowledgement')); + } + if (record && rovers.get(record.roverId) === record) { + rovers.delete(record.roverId); + notifyAdmins('roverManagement:offline', { roverId: record.roverId }); + } + }); +}); + +io.on('connection', (socket) => { + const bind = (event, handler) => socket.on(event, async (payload = {}, callback) => { + const reply = typeof callback === 'function' ? callback : () => {}; + try { + if (!isAdmin(socket)) throw new Error('Not authorized'); + reply({ success: true, ...await handler(payload) }); + } catch (error) { reply({ error: error.message }); } + }); + bind('roverManagement:list', () => ({ rovers: [...rovers.values()].map(snapshot) })); + bind('roverManagement:get', ({ roverId }) => { + const record = rovers.get(String(roverId)); + if (!record) throw new Error('Rover management offline'); + return snapshot(record); + }); + bind('roverManagement:save', async ({ roverId, config }) => { + const { id, result } = request(roverId, { type: 'config.set', config }); + await result; + // The next hello is authoritative; do not replace cached state optimistically. + return { id }; + }); + bind('roverManagement:applyField', async ({ path, value }) => { + if (!Array.isArray(path) || path.length === 0 || value === undefined + || path.some((key) => typeof key !== 'string' || !key + || ['__proto__', 'constructor', 'prototype'].includes(key))) { + throw new Error('A nonempty field path and value are required'); + } + // Snapshot the connected fleet before any save restarts a rover. Each + // object is independent; never copy one rover's unrelated settings across. + const targets = [...rovers.values()]; + const results = await Promise.all(targets.map(async (record) => { + try { + const config = structuredClone(record.config); + let parent = config; + for (const key of path.slice(0, -1)) { + if (!parent || typeof parent !== 'object' || Array.isArray(parent) + || !Object.hasOwn(parent, key)) throw new Error('Field does not exist on this rover'); + parent = parent[key]; + } + const key = path.at(-1); + if (!parent || typeof parent !== 'object' || Array.isArray(parent) + || !Object.hasOwn(parent, key)) throw new Error('Field does not exist on this rover'); + parent[key] = structuredClone(value); + // Do not submit a stale snapshot to a replacement connection. + if (rovers.get(record.roverId) !== record) throw new Error('Rover connection changed'); + const { id, result } = request(record.roverId, { type: 'config.set', config }); + await result; + return { roverId: record.roverId, success: true, id }; + } catch (error) { + return { roverId: record.roverId, success: false, error: error.message }; + } + })); + return { results }; + }); + bind('roverManagement:command', async ({ roverId, type, reboot, media }) => { + if (!['reboot', 'update', 'media'].includes(type)) throw new Error('Unsupported management command'); + const { id, result } = request(roverId, { type, reboot, media }); + await result; + return { id }; + }); +}); + +module.exports = { rovers, request, issueCommand }; diff --git a/webui/src/admin/AdminApp.jsx b/webui/src/admin/AdminApp.jsx index a03cc201..834e54f5 100644 --- a/webui/src/admin/AdminApp.jsx +++ b/webui/src/admin/AdminApp.jsx @@ -124,6 +124,7 @@ export default function AdminApp() { content =
; } else if (activeSection === 'fleet') { content = ; + } else if (!isLockdown) { content = ( diff --git a/webui/src/admin/components/RoverConfigurationEditor.jsx b/webui/src/admin/components/RoverConfigurationEditor.jsx new file mode 100644 index 00000000..099606f9 --- /dev/null +++ b/webui/src/admin/components/RoverConfigurationEditor.jsx @@ -0,0 +1,115 @@ +import { useEffect, useState } from 'react'; +import Form from '@rjsf/core'; +import validator from '@rjsf/validator-ajv8'; + +function request(socket, event, payload = {}) { + return new Promise((resolve, reject) => { + if (!socket.connected) return reject(new Error('Server disconnected')); + socket.timeout(35000).emit(event, payload, (error, response) => { + if (error || response?.error) reject(new Error(response?.error || 'Request timed out; reconnect and check the rover configuration.')); + else resolve(response); + }); + }); +} + +function fields(schema, prefix = []) { + return Object.entries(schema?.properties || {}).flatMap(([key, child]) => { + const path = [...prefix, key]; + return child.type === 'object' ? fields(child, path) : [{ path, label: path.join(' / ') }]; + }); +} + +function RoverForm({ socket, record, online }) { + const [draft, setDraft] = useState(() => structuredClone(record.config)); + const [field, setField] = useState(''); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(''); + const [results, setResults] = useState([]); + const options = fields(record.schema); + async function save(all) { + setBusy(true); + setMessage(''); + setResults([]); + try { + if (all) { + const path = JSON.parse(field); + const value = path.reduce((object, key) => object?.[key], draft); + if (value === undefined) throw new Error('Selected field has no value'); + const response = await request(socket, 'roverManagement:applyField', { path, value }); + setResults(response.results); + setMessage(response.results.length ? 'Fleet save finished. Successful rovers restart to apply their settings.' : 'No rovers are connected.'); + } else { + await request(socket, 'roverManagement:save', { roverId: record.roverId, config: draft }); + setMessage('Saved. Rover is restarting; its next connection reports the loaded configuration.'); + } + } catch (error) { setMessage(error.message); } + finally { setBusy(false); } + } + return
+

{online ? 'Management connected' : 'Management offline — edits are retained locally.'}

+

{message}

+ {results.length > 0 &&
    {results.map((result) =>
  • {result.roverId}: {result.success ? 'Saved' : result.error}
  • )}
} +
+
setDraft(formData)} onSubmit={() => save(false)}> + +
+ + +
+
; +} + +export default function RoverConfigurationEditor({ socket }) { + const [records, setRecords] = useState({}); + const [selected, setSelected] = useState(''); + const [error, setError] = useState(''); + useEffect(() => { + let active = true; + // Keep drafts mounted on disconnect. Only an authoritative new hello + // replaces the form, including when configuration changes the rover name. + const changed = (record) => setRecords((previous) => ({ ...previous, [record.roverId]: { ...record, online: true } })); + const offline = ({ roverId }) => setRecords((previous) => previous[roverId] + ? { ...previous, [roverId]: { ...previous[roverId], online: false } } : previous); + const disconnected = () => setRecords((previous) => Object.fromEntries(Object.entries(previous).map(([id, record]) => [id, { ...record, online: false }]))); + const refresh = async () => { + try { + const response = await request(socket, 'roverManagement:list'); + if (!active) return; + setError(''); + setRecords((previous) => ({ + ...Object.fromEntries(Object.entries(previous).map(([id, record]) => [id, { ...record, online: false }])), + ...Object.fromEntries(response.rovers.map((record) => [record.roverId, { ...record, online: true }])), + })); + } catch (failure) { if (active) setError(failure.message); } + }; + socket.on('roverManagement:changed', changed); + socket.on('roverManagement:offline', offline); + socket.on('connect', refresh); + socket.on('disconnect', disconnected); + refresh(); + return () => { + active = false; + socket.off('roverManagement:changed', changed); + socket.off('roverManagement:offline', offline); + socket.off('connect', refresh); + socket.off('disconnect', disconnected); + }; + }, [socket]); + const id = selected || Object.keys(records)[0] || ''; + const record = records[id]; + return
+

Rover configuration

+ {error &&

{error}

} + + {record && } +
; +} diff --git a/webui/src/components/AdminPanel/AdminPanelContent.jsx b/webui/src/components/AdminPanel/AdminPanelContent.jsx index a5ceb626..5ab55580 100644 --- a/webui/src/components/AdminPanel/AdminPanelContent.jsx +++ b/webui/src/components/AdminPanel/AdminPanelContent.jsx @@ -3,6 +3,8 @@ // Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit. import { useEffect, useMemo, useState } from 'react'; import { useSession } from '../../context/SessionContext.jsx'; +import { useSocket } from '../../context/SocketContext.jsx'; +import RoverConfigurationEditor from '../../admin/components/RoverConfigurationEditor.jsx'; import RoverRoster from '../RoverRoster/index.jsx'; import LlmCommentaryPanel from './LlmCommentaryPanel.jsx'; import OverseerControlPanel from './OverseerControlPanel.jsx'; @@ -95,6 +97,7 @@ function buildPrivateSafetyDraft(rover) { } export default function AdminPanelContent() { + const socket = useSocket(); const { session, lockRover, @@ -635,6 +638,7 @@ export default function AdminPanelContent() { )} /> +