Skip to content

feat(onvif): add Events service with PullPoint motion events - #2722

Open
machadolucas wants to merge 2 commits into
AlexxIT:masterfrom
machadolucas:feat/onvif-events
Open

machadolucas wants to merge 2 commits into
AlexxIT:masterfrom
machadolucas:feat/onvif-events

Conversation

@machadolucas

@machadolucas machadolucas commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

The ONVIF server has no Events service, so NVRs that read motion over ONVIF get nothing from a go2rtc camera. This adds a protocol-neutral motion state for streams, settable from any external detector (go2rtc doesn't detect motion itself), and a PullPoint Events service in the ONVIF server that reports it.

UniFi Protect reads ONVIF motion from third-party cameras since 7.1. According to the docs and tests of danielwoz/ubiquiti-protect-onvif-event-listener (I haven't seen Protect's code), it calls GetEventProperties (needs PullPoint support and a motion topic in the TopicSet), then CreatePullPointSubscription, PullMessages in a loop (Timeout PT2S, MessageLimit 10), Renew about every 60 s and Unsubscribe on stop. It sends no SOAPAction and no WS-Addressing on Pull/Renew/Unsubscribe, reads both motion topics below, and needs the false message to end an event.

Related: #1520 (Protect support for the ONVIF server), #2639 (missing get_event_properties / motion topic), #2130 (HomeKit Secure Video, see below).

1. Motion state of streams (internal/streams/motion.go)

  • streams.SetMotion(name, motion), streams.GetMotion(name) (motion, ok bool), streams.GetMotions() and streams.HandleMotionFunc(handler) for change handlers (named like HandleFunc / HandleConsumerFunc). Handlers are called on the first state of a stream and on every change, under the motion lock, so their order is the order of the changes.
  • API, next to api/streams and api/preload:
curl -X POST "http://localhost:1984/api/motion?src=camera1"   # motion started
curl -X DELETE "http://localhost:1984/api/motion?src=camera1" # motion ended
curl "http://localhost:1984/api/motion"                       # {"camera1":false}

Unknown stream: 404, other methods: 405. A stream has no state until the first call. States are kept in memory only. Added to website/api/openapi.yaml and the streams README.

2. ONVIF Events service (pkg/onvif/server_events.go, internal/onvif)

  • Thread safe Events store (subscriptions with their own message queue, long-poll Pull, Subscribe/Renew/Unsubscribe/Sync) and the SOAP responses for GetEventProperties, CreatePullPointSubscription, PullMessages, Renew, Unsubscribe and SetSynchronizationPoint. internal/onvif registers events.SetMotion with streams.HandleMotionFunc; it has no motion API of its own.
  • Each state change is sent with both topics: tns1:RuleEngine/CellMotionDetector/Motion (IsMotion) and tns1:VideoSource/MotionAlarm (State). The source token is the stream name, XML escaped.
  • A new subscription gets one Initialized message per stream with a known motion state; streams never reported send nothing until their first change, which comes as Changed. SetSynchronizationPoint queues the current states again.
  • The events GetServiceCapabilities is a StaticResponse entry under its own key EventsGetServiceCapabilities, chosen when the request path is /onvif/events_service (the operation name is the same as in the Media service). The media answer is unchanged.
  • GetCapabilities and GetServices always advertise the Events service.
  • The event operations go through the existing ONVIF auth check like the other operations; GetServiceCapabilities stays open like the media one.
  • Limits: 16 subscriptions (HTTP 503 after that), 64 queued messages per subscription (oldest dropped), TTL clamped to 10 s ... 1 h (60 s default), pull timeout up to 1 min. Expired subscriptions are removed lazily. A pending PullMessages keeps its subscription alive, returns early when the subscription is removed, and ends with the request context when the client disconnects.
  • xs:duration (PT60S, PT1M, P1D) and absolute xs:dateTime are accepted for InitialTerminationTime, TerminationTime and Timeout.
  • Dispatch on the Body element as before (no SOAPAction needed). The subscription id is in the URL path /onvif/subscription/<id>. Unknown or expired subscription: SOAP ResourceUnknownFault with HTTP 400.

Trade-off: because Events is always advertised, an NVR will assume every go2rtc camera can report motion, even when nothing ever sets its state.

Relation to #2130

#2130 adds an ONVIF events client in pkg/onvif/events.go; the server side here is in server_events.go (next to client.go / server.go) and no exported identifiers clash. The neutral motion state could serve #2130 too: api/homekit/motion could become a streams.HandleMotionFunc handler that sets MotionDetected on the HomeKit server of the stream, and its ONVIF watcher could call streams.SetMotion.

Testing

  • go test -race ./pkg/onvif/ ./internal/streams/: well-formed XML of all responses (also with "<&> in the stream name and host), events always advertised in GetCapabilities/GetServices, static events capabilities next to the unchanged media one, Initialized only for streams with a known state, long poll woken by a change, timeout, sync point, renew, unsubscribe, expiry, subscription limit, unsubscribe and client disconnect during a pending pull, concurrent SetMotion/Pull/Sync/Renew/Unsubscribe; motion state changes and handlers, concurrent use, and the api/motion handler.
  • A scripted SOAP client walking the Protect sequence above against a local build with ONVIF auth on (no SOAPAction, PullMessages PT2S/10): capabilities, event properties, a subscription before any state (no messages, then Changed on the first state), 401 for an unauthenticated pull, subscription with Initialized, idle/motion on/motion off pulls via /api/motion, renew, sync point, unsubscribe, fault after unsubscribe.
  • UniFi Protect on one setup: with an earlier revision of this code, fed by a real camera's motion sensor, motion events show up in Protect for a camera served by go2rtc. This revision was not run against Protect.

Not tested: Home Assistant ONVIF integration, Scrypted, Frigate, ONVIF Device Manager, or other NVRs. WS-BaseNotification (push Subscribe) and pausable subscriptions are not implemented and are reported as unsupported in the capabilities.

@skrashevich

Copy link
Copy Markdown
Collaborator

conflict with #2130

@AlexxIT

AlexxIT commented Nov 22, 2026

Copy link
Copy Markdown
Owner

What I don't like:

  • /api/onvif/motion - this feature shouldn't be tied to ONVIF; motion events may also be supported by HomeKit, RTSP, or other protocols
  • EventsServiceCapabilitiesResponse should be a StaticResponse
  • GetCapabilitiesResponse and GetServicesResponse shouldn't be tied to HasSources

I haven't compared this implementation to #2130; there might be some good ideas there.

@AlexxIT AlexxIT added kind/feature Proposes or implements a new capability or enhancement resolution/declined Maintainer declined the proposal or change in its current form area/onvif ONVIF client and server behavior, discovery, and device services labels Nov 22, 2026
Protocol-neutral motion state per stream with change handlers, so any
module can report motion to its clients. The state is set from any
external detector with POST/DELETE /api/motion?src=<stream>, and
GET /api/motion returns the states of all streams with a known state.
ONVIF server now has an Events service (PullPoint subscriptions) with the
motion topics tns1:RuleEngine/CellMotionDetector/Motion and
tns1:VideoSource/MotionAlarm, so NVRs like UniFi Protect can receive
motion from go2rtc cameras. Events come from the motion state of streams.
The service is always advertised in GetCapabilities and GetServices.
@machadolucas

Copy link
Copy Markdown
Contributor Author

Reworked and rebased on master:

  • Motion is no longer tied to ONVIF. internal/streams/motion.go keeps a per-stream motion state (streams.SetMotion, GetMotion, HandleMotionFunc for change handlers) with POST/DELETE /api/motion?src=camera1 and GET /api/motion. The ONVIF Events service is one handler of it.
  • The events GetServiceCapabilities is now a StaticResponse entry with its own key (same operation name as Media, so it is picked by the request path; the media answer is unchanged).
  • GetCapabilities/GetServices always advertise Events. A new subscription gets Initialized only for streams with a known state.

#2130: the server code is in pkg/onvif/server_events.go, so it doesn't collide with the client in events.go, and no exported names clash. Its HomeKit motion API could become a HandleMotionFunc handler, and its ONVIF watcher could call SetMotion.

Caveat: an NVR will now assume every go2rtc camera can report motion.

Tested: unit tests with -race, and a scripted ONVIF client against a local build.

@AlexxIT AlexxIT self-assigned this Nov 24, 2026
@AlexxIT

AlexxIT commented Nov 24, 2026

Copy link
Copy Markdown
Owner

The approval of this PR will be delayed until the event architecture for the entire project has been reviewed.

@AlexxIT

AlexxIT commented Nov 24, 2026

Copy link
Copy Markdown
Owner

I took a quick look at the implementation. It looks pretty clean.

How do you see this API being used in real life? What software will manage this flag, and how?

@machadolucas

Copy link
Copy Markdown
Contributor Author

In my setup nothing external manages it. The camera is HomeKit-only (Eve Outdoor Cam). go2rtc keeps a HAP session to it, subscribes to its MotionDetected characteristic and calls streams.SetMotion in-process. The ONVIF Events service then delivers that to UniFi Protect, which shows and records the motion events. That HomeKit part is in my fork (branch eve-full) and has been running this way since Nov 20.

So the main users are inside go2rtc: sources (a HomeKit client, or the ONVIF events client and the detector from #2130) set the state, and servers (ONVIF Events, a HomeKit motion sensor) read it.

The HTTP endpoint is for cameras with no such source: Home Assistant or a script calling it from a PIR sensor, Frigate, or a camera's own HTTP alarm push. I haven't used it that way myself.

@AlexxIT AlexxIT added the size/XXL PR with 1000+ lines changed, excluding generated files. label Nov 26, 2026
@AlexxIT AlexxIT removed their assignment Nov 28, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/onvif ONVIF client and server behavior, discovery, and device services kind/feature Proposes or implements a new capability or enhancement resolution/declined Maintainer declined the proposal or change in its current form size/XXL PR with 1000+ lines changed, excluding generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants