Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions internal/homekit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,101 @@ motion: status baseline=5000 ratio=1.40 ← shadow/wind

Set threshold between "noise" and "real motion". In this example, 2.0 is a good choice (ignores 1.4, catches 3.2).

**Motion via ONVIF:**

```yaml
homekit:
outdoor:
hksv: true
motion: onvif
onvif_url: onvif://user:pass@192.168.1.123:80 # optional - auto-discovered
# from the stream's sources
# if omitted
motion_hold_time: 30 # seconds motion stays "true" after the last event
# (default: 30)
```

Subscribes to the camera's ONVIF PullPoint event service and forwards real
motion events, instead of inferring them from the video. Requires the camera's
ONVIF *credentials* specifically - some cameras (Axis, notably) use a separate
ONVIF user configured in the camera's own settings, distinct from the admin
login used for RTSP and the web UI, so the same password that works everywhere
else may still get rejected here with a SOAP `NotAuthorized` fault. Also
requires an `http://` ONVIF service - an HTTPS-only camera web interface isn't
supported by the ONVIF client yet.

**The ONVIF port is often not 80.** It is not discoverable from an RTSP URL, so
`onvif_url` usually has to name it explicitly. Ports seen in practice: Axis on
80, TP-Link Tapo on **2020** (80 is closed entirely), Reolink on **8000**.
Auto-discovery only finds a URL if one of the stream's sources is itself an
`onvif://` URL, so a stream built from `rtsp://` or `ffmpeg:` needs
`onvif_url` set or the watcher never starts.

**Using the camera's own analytics instead of plain motion**

By default the accessory listens for the standard ONVIF motion topics. A
camera that runs its own analytics usually reports them under a vendor topic,
which is both more accurate and less noisy than a raw pixel-change alarm.
`onvif_topic` selects one, as a case-insensitive substring of the event topic:

```yaml
homekit:
driveway:
hksv: true
motion: onvif
onvif_url: onvif://user:pass@192.168.1.123
onvif_topic: ObjectAnalytics/Device1Scenario1 # AXIS Object Analytics
```

On an Axis running AXIS Object Analytics, `Device1Scenario1` is the first
configured scenario and `Device1ScenarioANY` fires for any of them. Scoping the
scenario to people or vehicles is done in the camera's own AOA configuration,
so HomeKit only sees the events you care about. A camera typically emits a
great deal besides motion (one tested Axis sent 137 events in 75 seconds, all
but 3 of them PTZ and hardware status), and the topic filter discards the rest.

Reolink models with AI detection expose a topic per class, so the trigger can
be narrowed to exactly one without touching the camera's configuration:

```yaml
onvif_topic: MyRuleDetector/PeopleDetect # or VehicleDetect, DogCatDetect,
# Package, FaceDetect, Visitor
```

A list triggers on any one of several topics, which is how to combine a
person detector with plain motion so neither is missed:

```yaml
onvif_topic:
- MyRuleDetector/PeopleDetect
- CellMotionDetector
```

An Axis with a PIR sensor can use that instead of anything video-based. It
detects body heat, so it is unaffected by a noisy scene or by the gradual
brightness change at dawn and dusk:

```yaml
onvif_topic: Sensor/PIR
```

**Finding a camera's topics: watch it, do not ask it.** Set `log: onvif:
trace` and read the `[onvif] parse: topic` lines, which print every topic
received. Do *not* rely on the topic list the camera advertises through
`GetEventProperties`: a tested Reolink advertises five topics while actually
emitting eight, hiding every one of its AI detectors, and still sets
`FixedTopicSet` to `true` claiming the list is complete. Subscribing without
a topic filter for a minute shows the truth, including the initial property
state most cameras send on subscribe.

`onvif_items` overrides which `SimpleItem` carries the state. The defaults
(`IsMotion`, `State`, `active`) cover every camera tested, including Axis
application topics, so this is rarely needed:

```yaml
onvif_items: [MyCustomState]
```

**Motion API:**

```bash
Expand Down
19 changes: 16 additions & 3 deletions internal/homekit/homekit.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,19 @@ func Init() {
MotionThreshold float64 `yaml:"motion_threshold"`
MotionHoldTime float64 `yaml:"motion_hold_time"`
OnvifURL string `yaml:"onvif_url"`
Speaker *bool `yaml:"speaker"`
// OnvifTopic selects which ONVIF events drive motion, as a
// substring of the event topic. Empty uses the standard motion
// topics. Set this to use a camera's own analytics instead, e.g.
// "ObjectAnalytics/Device1Scenario1" for an Axis AOA scenario.
// Accepts a list to trigger on any of several, such as a person
// detector plus plain motion.
OnvifTopic multiString `yaml:"onvif_topic"`
// OnvifItems are the SimpleItem names carrying the state. Empty
// uses IsMotion, State and active, which covers every camera
// tested; only needed for a device that reports under some other
// name.
OnvifItems []string `yaml:"onvif_items"`
Speaker *bool `yaml:"speaker"`
} `yaml:"homekit"`
}
app.LoadConfig(&cfg)
Expand Down Expand Up @@ -124,8 +136,9 @@ func Init() {
holdTime = 30 * time.Second
}
log.Info().Str("stream", id).Str("onvif_url", onvifURL).
Dur("hold_time", holdTime).Msg("[homekit] starting ONVIF motion watcher")
startOnvifMotionWatcher(srv, onvifURL, holdTime, log)
Dur("hold_time", holdTime).Strs("topics", conf.OnvifTopic).
Msg("[homekit] starting ONVIF motion watcher")
startOnvifMotionWatcher(srv, onvifURL, holdTime, conf.OnvifTopic, conf.OnvifItems, log)
}
}

Expand Down
44 changes: 40 additions & 4 deletions internal/homekit/onvif_motion.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package homekit

import (
"errors"
"strings"
"sync"
"time"

"github.com/AlexxIT/go2rtc/pkg/hksv"
"github.com/AlexxIT/go2rtc/pkg/onvif"
"github.com/rs/zerolog"
"gopkg.in/yaml.v3"
)

const (
Expand All @@ -19,6 +21,32 @@ const (
onvifMaxReconnectDelay = 60 * time.Second
)

// multiString is a config value that accepts either one entry or a list, so
// a camera needing a single topic does not have to be written as a list.
type multiString []string

func (m *multiString) UnmarshalYAML(node *yaml.Node) error {
switch node.Kind {
case yaml.ScalarNode:
var s string
if err := node.Decode(&s); err != nil {
return err
}
if s != "" {
*m = multiString{s}
}
return nil
case yaml.SequenceNode:
var ss []string
if err := node.Decode(&ss); err != nil {
return err
}
*m = ss
return nil
}
return errors.New("expected a string or a list of strings")
}

type onvifPullPoint interface {
PullMessages(timeout time.Duration, limit int) ([]byte, error)
Renew(timeout time.Duration) error
Expand All @@ -35,6 +63,12 @@ type onvifMotionWatcher struct {
holdTime time.Duration
log zerolog.Logger

// topics select which event topics drive motion (substring match, any
// one matching counts). Empty uses the built-in motion topics.
topics []string
// items are the SimpleItem names carrying the state; nil uses the defaults.
items []string

now func() time.Time
newPullPoint onvifPullPointFactory
subscriptionTimeout time.Duration
Expand All @@ -46,11 +80,13 @@ type onvifMotionWatcher struct {
once sync.Once
}

func newOnvifMotionWatcher(srv *hksv.Server, onvifURL string, holdTime time.Duration, log zerolog.Logger) *onvifMotionWatcher {
func newOnvifMotionWatcher(srv *hksv.Server, onvifURL string, holdTime time.Duration, topics []string, items []string, log zerolog.Logger) *onvifMotionWatcher {
return &onvifMotionWatcher{
srv: srv,
onvifURL: onvifURL,
holdTime: holdTime,
topics: topics,
items: items,
log: log,
now: time.Now,
newPullPoint: newOnvifPullPoint,
Expand All @@ -63,8 +99,8 @@ func newOnvifMotionWatcher(srv *hksv.Server, onvifURL string, holdTime time.Dura
}

// startOnvifMotionWatcher creates and starts a new ONVIF motion watcher.
func startOnvifMotionWatcher(srv *hksv.Server, onvifURL string, holdTime time.Duration, log zerolog.Logger) *onvifMotionWatcher {
w := newOnvifMotionWatcher(srv, onvifURL, holdTime, log)
func startOnvifMotionWatcher(srv *hksv.Server, onvifURL string, holdTime time.Duration, topics []string, items []string, log zerolog.Logger) *onvifMotionWatcher {
w := newOnvifMotionWatcher(srv, onvifURL, holdTime, topics, items, log)
go w.run()
return w
}
Expand Down Expand Up @@ -199,7 +235,7 @@ func (w *onvifMotionWatcher) connectAndPoll() error {
l.Str("body", string(b)).Msg("[homekit] onvif motion: raw response")
}

motion, found := onvif.ParseMotionEvents(b)
motion, found := onvif.ParseEvents(b, w.topics, w.items)

w.log.Trace().Bool("found", found).Bool("motion", motion).
Bool("active", motionActive).Msg("[homekit] onvif motion: parse result")
Expand Down
2 changes: 1 addition & 1 deletion internal/homekit/onvif_motion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func TestOnvifMotionWatcherConnectAndPollRenewsBeforeLeaseExpires(t *testing.T)
pullErr: stopErr,
}

w := newOnvifMotionWatcher(&hksv.Server{}, "onvif://camera", 30*time.Second, zerolog.Nop())
w := newOnvifMotionWatcher(&hksv.Server{}, "onvif://camera", 30*time.Second, nil, nil, zerolog.Nop())
w.now = func() time.Time { return now }
w.newPullPoint = func(rawURL string, timeout time.Duration) (onvifPullPoint, error) {
if rawURL != "onvif://camera" {
Expand Down
19 changes: 16 additions & 3 deletions pkg/onvif/envelope.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,20 @@ func NewEventEnvelope() *Envelope {
}

func NewEventEnvelopeWithUser(user *url.Userinfo) *Envelope {
return NewEventEnvelopeWithHeaders(user, "")
}

// NewEventEnvelopeWithHeaders builds an event envelope carrying the security
// header plus any extra SOAP headers the request needs, such as WS-Addressing
// or a subscription's reference parameters.
func NewEventEnvelopeWithHeaders(user *url.Userinfo, extraHeaders string) *Envelope {
if user == nil {
return NewEventEnvelope()
if extraHeaders == "" {
return NewEventEnvelope()
}
e := &Envelope{buf: make([]byte, 0, 1024)}
e.Append(eventPrefix, `<s:Header>`, extraHeaders, `</s:Header>`, prefix2)
return e
}

nonce := core.RandString(16, 36)
Expand All @@ -108,12 +120,13 @@ func NewEventEnvelopeWithUser(user *url.Userinfo) *Envelope {
<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">%s</wsse:Nonce>
<wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">%s</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
</wsse:Security>%s
</s:Header>`,
user.Username(),
base64.StdEncoding.EncodeToString(h.Sum(nil)),
base64.StdEncoding.EncodeToString([]byte(nonce)),
created)
created,
extraHeaders)
e.Append(prefix2)
return e
}
Loading