/
discoverDeviceOwnership.go
86 lines (76 loc) · 2.67 KB
/
discoverDeviceOwnership.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package core
import (
"context"
"fmt"
"github.com/plgd-dev/device/pkg/net/coap"
"github.com/plgd-dev/device/schema/doxm"
"github.com/plgd-dev/go-coap/v2/message"
"github.com/plgd-dev/go-coap/v2/message/codes"
"github.com/plgd-dev/go-coap/v2/udp/client"
"github.com/plgd-dev/go-coap/v2/udp/message/pool"
"github.com/plgd-dev/kit/v2/codec/ocf"
)
// DiscoverDeviceOwnershipHandler receives devices ownership info.
type DiscoverDeviceOwnershipHandler interface {
Handle(ctx context.Context, client *client.ClientConn, device doxm.Doxm)
Error(err error)
}
// DiscoverOwnershipStatus type of discover ownership status.
type DiscoverOwnershipStatus int
const (
// DiscoverAllDevices discovers owned and disowned devices.
DiscoverAllDevices = DiscoverOwnershipStatus(0)
// DiscoverOwnedDevices discovers owned devices,
DiscoverOwnedDevices = DiscoverOwnershipStatus(1)
// DiscoverDisownedDevices discovers disowned devices,
DiscoverDisownedDevices = DiscoverOwnershipStatus(2)
)
// DiscoverDeviceOwnership discovers devices using a CoAP multicast request via UDP.
// It waits for device responses until the context is canceled.
func DiscoverDeviceOwnership(
ctx context.Context,
conn []*DiscoveryClient,
status DiscoverOwnershipStatus,
handler DiscoverDeviceOwnershipHandler,
) error {
var opt coap.OptionFunc
switch status {
case DiscoverAllDevices:
return Discover(ctx, conn, doxm.ResourceURI, handleDiscoverOwnershipResponse(ctx, handler))
case DiscoverOwnedDevices:
opt = func(m message.Options) message.Options {
buf := make([]byte, 16)
opts, _, _ := m.AddString(buf, message.URIQuery, "Owned=TRUE")
return opts
}
case DiscoverDisownedDevices:
opt = func(m message.Options) message.Options {
buf := make([]byte, 16)
opts, _, _ := m.AddString(buf, message.URIQuery, "Owned=FALSE")
return opts
}
default:
return MakeUnimplemented(fmt.Errorf("unsupported DiscoverOwnershipStatus(%v)", status))
}
return Discover(ctx, conn, doxm.ResourceURI, handleDiscoverOwnershipResponse(ctx, handler), opt)
}
func handleDiscoverOwnershipResponse(ctx context.Context, handler DiscoverDeviceOwnershipHandler) func(client *client.ClientConn, req *pool.Message) {
return func(client *client.ClientConn, r *pool.Message) {
req, err := pool.ConvertTo(r)
if err != nil {
handler.Error(fmt.Errorf("request failed: %w", err))
}
if req.Code != codes.Content {
handler.Error(fmt.Errorf("request failed: %s", ocf.Dump(req)))
return
}
var doxm doxm.Doxm
var codec ocf.VNDOCFCBORCodec
err = codec.Decode(req, &doxm)
if err != nil {
handler.Error(fmt.Errorf("decoding %v failed: %w", ocf.DumpHeader(req), err))
return
}
handler.Handle(ctx, client, doxm)
}
}