Skip to content

Add MQTT features: routing, device control, discovery, notifications, sleep tracking - #38

Closed
stuart22 wants to merge 22 commits into
indiefan:mainfrom
stuart22:feature/mqtt-features
Closed

Add MQTT features: routing, device control, discovery, notifications, sleep tracking#38
stuart22 wants to merge 22 commits into
indiefan:mainfrom
stuart22:feature/mqtt-features

Conversation

@stuart22

Copy link
Copy Markdown

Summary

  • Multi-camera MQTT routing (from tanvach PR feat: Enhance Nanit integration with WebSocket resilience and improved controls #33): Global connection registry routes commands to correct camera by baby UID, with auto-reconnect on failed commands
  • Device control: Night light brightness, sound playback (start/stop with soundtrack), and volume via MQTT JSON payloads
  • HA MQTT auto-discovery: Sensors (temp, humidity, motion, sound), binary sensors (crying, standing, alerts, sleep state), and switches (night light, standby) auto-registered in Home Assistant
  • Notification event polling: Polls Nanit REST API with jitter/backoff for motion, sound, crying, standing, left bed, alert zone, camera online/offline, breathing/temp/humidity alerts, low battery
  • Sleep tracking: Sleep event poller (fell asleep, woke up, put in bed, removed) with state machine + sleep stats poller (times woke up, interventions, awake/sleep time)
  • Updated protobuf schema: Added brightness (Settings), duration/soundtrack (Playback), SoundtrackStorage enum

All features gated behind env vars (NANIT_MQTT_ENABLED, NANIT_NOTIFICATIONS_ENABLED). See README for full env var table.

Test plan

  • Build passes (go build ./cmd/nanit/)
  • Container starts with NANIT_MQTT_ENABLED=true and NANIT_MQTT_BROKER_URL set
  • HA auto-discovers Nanit devices with sensors and switches
  • Toggle night light switch in HA → camera responds
  • Trigger motion → HA binary sensor updates
  • Sleep events appear in HA

stuart22 added 22 commits April 11, 2026 19:38
The upstream container reconnects to Nanit's cloud websocket after
disconnections but never re-requests the camera to push its RTMP
stream, leaving the RTMP server running with no publisher indefinitely.

Root cause: StreamState and StreamRequestState are not reset on
websocket disconnect, so the reconnection handler sees the stream as
"Alive" and skips the re-request.

Changes:
- Reset StreamState and StreamRequestState on websocket disconnect
- Add /health HTTP endpoint (port 8080) for stream liveness checks
- Add Docker HEALTHCHECK (3min interval, 2 retries) for auto-recovery
- Fix nil pointer bug in GetIsWebsocketAlive (checked wrong field)
- Add GitHub Actions CI to build and push to GHCR
- Update README with fork attribution and changelog
Buster is EOL and its apt repositories are no longer available,
causing build failures.
Give the Go reconnection fix 10 minutes to recover the stream before
reporting unhealthy. The health endpoint tracks how long the stream
has been down and returns healthy during the grace period. After the
grace period, the HEALTHCHECK kills PID 1 so restart: unless-stopped
restarts the container.

Timeline on stream drop:
- 0-10min: Go fix retries (30s, 2min backoff) — health reports OK
- 10-16min: Grace expired, HEALTHCHECK fails twice, container restarts
Covers PersistentBroadcaster, go2rtc bundling for UniFi Protect,
multi-camera MQTT routing, device control, auto-discovery,
notification events, and sleep tracking.
Wrapper script that:
- Generates go2rtc config from session.json baby UIDs/names
- Starts go2rtc in background for RTSP/ONVIF output
- Starts nanit as main process
- Forwards SIGTERM/SIGINT to both processes
- Exits if either process dies

go2rtc is gated behind NANIT_RTSP_ENABLED (default: true) and
requires a session.json file to be present.
- Add go2rtc v1.9.8 download stage (multi-arch: amd64/arm64)
- Copy go2rtc binary to /app/bin/go2rtc in runtime image
- Switch ENTRYPOINT from nanit binary to entrypoint.sh wrapper
- Expose port 8554 for RTSP

go2rtc reads from the local RTMP server and exposes RTSP/ONVIF
endpoints, enabling UniFi Protect integration.
…ions

Adapted from scgreenhalgh/home_assistant_nanit. Keeps subscribers
connected when the camera's RTMP publisher disconnects and reconnects.
Timestamps are remapped to be monotonically increasing across
reconnections. Simplified from the reference: no hot standby, source
switching, or stall detection.
…ions

Adapted from scgreenhalgh/home_assistant_nanit. Keeps subscribers
connected when the camera's RTMP publisher disconnects and reconnects.
Timestamps are remapped to be monotonically increasing across
reconnections. Simplified from the reference: no hot standby, source
switching, or stall detection.
Replace per-connection broadcaster with a persistent broadcaster per
baby UID. Subscribers now stay connected across publisher reconnections.
Remove old broadcaster.go (superseded by PersistentBroadcaster).
Split StartRTMPServer into NewRTMPServer + Run so callers can hold a
reference to the server for querying broadcaster state.
Add PersistentBroadcaster for stream continuity across reconnections
Bundle go2rtc for RTSP/ONVIF output
…diefan#33)

- Connection registry routes MQTT commands to correct camera by baby UID
- Manager registry tracks websocket connection managers per baby
- Global MQTT handler registration (moved from per-connection to app-level)
- Handler signatures now include babyUID for proper multi-camera routing
- ForceReconnect() with cooldown skip for failed command recovery
- Pending retry queue replays failed commands after reconnection
- New env vars: NANIT_MQTT_RESET_WHEN_FAILED, NANIT_WEBSOCKET_TIMEOUT
- Extend protobuf schema with brightness (Settings), duration/soundtrack (Playback)
- Add MQTT subscriptions for brightness, playback (start/stop), and volume commands
- Route all commands through connection registry for multi-camera support
- JSON payloads for brightness, playback, and volume topics
- Publish discovery configs on MQTT connect for each registered baby
- Sensors: temperature, humidity, last motion/sound, stream URL
- Binary sensors: night, stream active, camera online, crying, standing,
  left bed, alert zone, temp/humidity/breathing alerts, low battery,
  asleep, in bed
- Switches: night light, standby mode
- Gated behind NANIT_MQTT_DISCOVERY env var (default true when MQTT enabled)
- New notification package with event poller, deduplication, and publisher
- Polls Nanit REST API for events with jitter and exponential backoff
- Publishes events to MQTT: motion, sound, crying, standing, left bed,
  alert zone, temperature/humidity/breathing alerts, camera online/offline
- New env vars: NANIT_NOTIFICATIONS_ENABLED, NANIT_NOTIFICATIONS_POLL_INTERVAL,
  NANIT_NOTIFICATIONS_MAX_BACKOFF
@stuart22 stuart22 closed this Apr 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant