Documentation
¶
Overview ¶
Package discovery finds ONVIF devices on the network with WS-Discovery, and can also answer those probes on behalf of devices of your own.
Finding cameras ¶
Discover sends a WS-Discovery Probe to the multicast group and collects the ProbeMatches that come back until the timeout expires:
devices, err := discovery.Discover(ctx, 5*time.Second)
for _, d := range devices {
fmt.Println(d.GetName(), d.GetDeviceEndpoint())
}
Use DiscoverWithOptions to choose the network interface, or to probe a single address by unicast with DiscoverOptions.ProbeAddress, which needs no multicast routing and so works in containers and CI.
Answering probes ¶
A Responder is a WS-Discovery target service. Register one or more Device values and it answers matching Probes, and announces them with Hello and Bye messages. The server package builds on this: its DiscoveryDevice method describes a virtual camera in the form a Responder expects.
r := discovery.NewResponder(&discovery.ResponderConfig{})
r.Register(device)
go r.Start(ctx)
Scope and type matching follow the WS-Discovery 2005/04 rules, including the default rfc3986 scope match.
Stable identities ¶
A device is identified by its endpoint reference, a "urn:uuid:" URI. StableEndpointRef derives one from a name, so a service that restarts gets the same identity back without storing anything.
Index ¶
Examples ¶
Constants ¶
const DefaultType = "{" + nsONVIFNet + "}NetworkVideoTransmitter"
DefaultType is the type a registered device advertises when it lists none: dn:NetworkVideoTransmitter, which is what ONVIF clients probe for.
Variables ¶
var ( // ErrNoProbeMatches is returned when no probe matches are found during discovery. ErrNoProbeMatches = errors.New("no probe matches found") // ErrNetworkInterfaceNotFound is returned when a network interface is not found. ErrNetworkInterfaceNotFound = errors.New("network interface not found") )
var ErrInvalidDevice = errors.New("invalid device")
ErrInvalidDevice is returned by Responder.Register for a device that cannot be advertised.
var ErrMalformedProbe = errors.New("malformed probe")
ErrMalformedProbe marks a Probe the responder cannot interpret.
Functions ¶
func StableEndpointRef ¶ added in v1.2.0
StableEndpointRef derives a "urn:uuid:" endpoint reference from seed. The same seed always yields the same reference, on any host and across restarts, so a device keeps its identity without anything being persisted. Use a name that is stable for the device (for example "farm1/cam-07"); an empty seed is valid but gives every caller the same reference.
Example ¶
The same name always gives the same identity, so a service that restarts keeps the IDs its clients already know.
package main
import (
"fmt"
"strings"
"github.com/0x524a/onvif-go/discovery"
)
func main() {
first := discovery.StableEndpointRef("lobby-camera")
again := discovery.StableEndpointRef("lobby-camera")
other := discovery.StableEndpointRef("dock-ptz")
fmt.Println(strings.HasPrefix(first, "urn:uuid:"))
fmt.Println(first == again)
fmt.Println(first == other)
}
Output: true true false
Types ¶
type Device ¶
type Device struct {
// Device endpoint address
EndpointRef string
// XAddrs contains the device service addresses
XAddrs []string
// Types contains the device types
Types []string
// Scopes contains the device scopes (name, location, etc.)
Scopes []string
// Metadata version
MetadataVersion int
}
Device represents a discovered ONVIF device.
func Discover ¶
Discover performs ONVIF device discovery using WS-Discovery protocol. For advanced options like specifying a network interface, use DiscoverWithOptions.
Example ¶
Probe the local network for five seconds and list what answers.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/0x524a/onvif-go/discovery"
)
func main() {
devices, err := discovery.Discover(context.Background(), 5*time.Second)
if err != nil {
log.Fatal(err)
}
for _, d := range devices {
fmt.Printf("%s at %s\n", d.GetName(), d.GetDeviceEndpoint())
}
}
Output:
func DiscoverWithOptions ¶ added in v1.1.0
func DiscoverWithOptions(ctx context.Context, timeout time.Duration, opts *DiscoverOptions) ([]*Device, error)
DiscoverWithOptions discovers ONVIF devices with custom options.
Example ¶
On a host with several network interfaces, choose which one to probe from, by name or by IP address.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/0x524a/onvif-go/discovery"
)
func main() {
opts := &discovery.DiscoverOptions{NetworkInterface: "eth0"}
devices, err := discovery.DiscoverWithOptions(context.Background(), 5*time.Second, opts)
if err != nil {
log.Fatal(err)
}
fmt.Println(len(devices), "devices found")
}
Output:
func (*Device) GetDeviceEndpoint ¶
GetDeviceEndpoint extracts the primary device endpoint from XAddrs.
func (*Device) GetLocation ¶
GetLocation extracts the device location from scopes.
type DiscoverOptions ¶ added in v1.1.0
type DiscoverOptions struct {
// NetworkInterface specifies the network interface to use for multicast.
// If empty, the system will choose the default interface.
// Examples: "eth0", "wlan0", "192.168.1.100"
NetworkInterface string
// ProbeAddress, when set, sends the probe by unicast to this UDP address
// ("host:port") from an ephemeral local port instead of using the
// WS-Discovery multicast group. It needs no multicast routing, so it works
// in containers and CI, and it pairs with ResponderConfig.ListenAddr.
// NetworkInterface is ignored when it is set.
ProbeAddress string
}
DiscoverOptions contains options for device discovery.
type NetworkInterface ¶ added in v1.1.0
type NetworkInterface struct {
// Name of the interface (e.g., "eth0", "wlan0")
Name string
// IP addresses assigned to this interface
Addresses []string
// Up indicates if the interface is up
Up bool
// Multicast indicates if the interface supports multicast
Multicast bool
}
NetworkInterface represents a network interface.
func ListNetworkInterfaces ¶ added in v1.1.0
func ListNetworkInterfaces() ([]NetworkInterface, error)
ListNetworkInterfaces returns all available network interfaces with their addresses.
type ProbeMatch ¶
type ProbeMatch struct {
XMLName xml.Name `xml:"ProbeMatch"`
EndpointRef string `xml:"EndpointReference>Address"`
Types string `xml:"Types"`
Scopes string `xml:"Scopes"`
XAddrs string `xml:"XAddrs"`
MetadataVersion int `xml:"MetadataVersion"`
}
ProbeMatch represents a WS-Discovery probe match.
type ProbeMatches ¶
type ProbeMatches struct {
XMLName xml.Name `xml:"ProbeMatches"`
ProbeMatch []ProbeMatch `xml:"ProbeMatch"`
}
ProbeMatches represents WS-Discovery probe matches.
type Responder ¶ added in v1.2.0
type Responder struct {
// contains filtered or unexported fields
}
Responder is a WS-Discovery target service. One Responder owns one socket and answers Probe messages on behalf of every registered Device, so a fleet of virtual cameras on one host shares a single multicast membership.
Supported: Probe/ProbeMatches with Types and Scopes filtering (MatchBy rfc3986, strcmp0 and none), Hello on start, Bye on stop. Not supported: Resolve/ResolveMatches, the ldap and uuid scope rules (such a probe matches nothing), the 2009/01 (WS-Discovery 1.1) namespace, and managed mode with a discovery proxy. Duplicate probes are answered each time.
Example ¶
Announce a device and answer probes for it. ListenAddr switches the responder to unicast, which needs no multicast routing; leave it empty to join the WS-Discovery multicast group on a real network.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/0x524a/onvif-go/discovery"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
ready := make(chan struct{})
responder := discovery.NewResponder(&discovery.ResponderConfig{
ListenAddr: "127.0.0.1:0",
Ready: ready,
})
err := responder.Register(&discovery.Device{
EndpointRef: discovery.StableEndpointRef("lobby-camera"),
XAddrs: []string{"http://192.168.1.21:8080/onvif/device_service"},
Types: []string{discovery.DefaultType},
Scopes: []string{"onvif://www.onvif.org/name/lobby-camera"},
})
if err != nil {
log.Fatal(err)
}
go func() { _ = responder.Start(ctx) }()
<-ready
// A client probes responder.Addr() with DiscoverOptions.ProbeAddress.
opts := &discovery.DiscoverOptions{ProbeAddress: responder.Addr().String()}
devices, err := discovery.DiscoverWithOptions(ctx, 300*time.Millisecond, opts)
if err != nil {
log.Fatal(err)
}
name := devices[0].GetName()
cancel() // stops the responder
fmt.Println(name)
}
Output: lobby-camera
func NewResponder ¶ added in v1.2.0
func NewResponder(cfg *ResponderConfig) *Responder
NewResponder returns a Responder. A nil cfg uses multicast defaults.
func (*Responder) Addr ¶ added in v1.2.0
Addr returns the bound socket address, or nil before Start has bound it.
func (*Responder) Register ¶ added in v1.2.0
Register advertises d. EndpointRef is required and identifies the device; a second Register with the same EndpointRef replaces the first. Types entries are "{namespace}Local" or the prefixed forms "dn:Local" (ONVIF network namespace) and "tds:Local" (ONVIF device namespace); no Types means DefaultType. If the responder is running, Register sends a Hello.
func (*Responder) Start ¶ added in v1.2.0
Start binds the socket, sends Hello for every registered device, and answers probes until ctx is canceled, then sends Bye for every device still registered and returns nil. A bind failure is returned immediately.
func (*Responder) Unregister ¶ added in v1.2.0
Unregister stops advertising the device with the given EndpointRef. If the responder is running, it sends a Bye.
type ResponderConfig ¶ added in v1.2.0
type ResponderConfig struct {
// NetworkInterface selects the interface that joins the multicast group,
// by name or IP address, as in DiscoverOptions. Ignored when ListenAddr
// is set.
NetworkInterface string
// ListenAddr switches the responder to unicast mode. It binds this UDP
// address (for example "127.0.0.1:0") instead of joining
// 239.255.255.250:3702, so it needs no multicast routing and several
// responders can coexist on one host. Pair it with
// DiscoverOptions.ProbeAddress. Intended for tests and CI.
ListenAddr string
// AnnounceAddr is where Hello and Bye messages are sent. It defaults to
// the WS-Discovery multicast group in multicast mode. In unicast mode it
// defaults to empty, which disables announcements.
AnnounceAddr string
// MaxResponseDelay bounds a random pause before each ProbeMatches reply,
// which WS-Discovery recommends (APP_MAX_DELAY, 500ms) to keep a large
// fleet from answering one probe in the same instant. The default, zero,
// replies immediately.
MaxResponseDelay time.Duration
// Ready, when non-nil, is closed by Start once the socket is bound and
// Addr is valid. It is closed at most once.
Ready chan<- struct{}
}
ResponderConfig configures a Responder.