-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
observeResource.go
87 lines (75 loc) · 1.97 KB
/
observeResource.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
87
package client
import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/plgd-dev/device/v2/client/core"
"github.com/plgd-dev/hub/v2/resource-aggregate/commands"
"github.com/plgd-dev/hub/v2/resource-aggregate/events"
)
func (c *Client) ObserveResource(
ctx context.Context,
deviceID string,
href string,
handler core.ObservationHandler,
opts ...ObserveOption,
) (observationID string, _ error) {
cfg := observeOptions{
codec: GeneralMessageCodec{},
}
for _, o := range opts {
cfg = o.applyOnObserve(cfg)
}
ID, err := uuid.NewRandom()
if err != nil {
return "", err
}
sub, err := c.NewResourceSubscription(ctx, commands.NewResourceID(deviceID, href), &observationHandler{
codec: cfg.codec,
obs: handler,
removeSubscription: func() {
if _, errS := c.stopObservingResource(ID.String()); errS != nil {
handler.Error(fmt.Errorf("failed to stop resource('%v') observation: %w", ID.String(), errS))
}
},
})
if err != nil {
return "", err
}
c.insertSubscription(ID.String(), sub)
return ID.String(), err
}
func (c *Client) stopObservingResource(observationID string) (func(), error) {
s, err := c.popSubscription(observationID)
if err != nil {
return nil, err
}
return s.Cancel()
}
func (c *Client) StopObservingResource(observationID string) error {
wait, err := c.stopObservingResource(observationID)
if err != nil {
return err
}
wait()
return nil
}
type observationHandler struct {
obs core.ObservationHandler
codec Codec
removeSubscription func()
}
func (o *observationHandler) HandleResourceContentChanged(ctx context.Context, ev *events.ResourceChanged) error {
o.obs.Handle(ctx, func(v interface{}) error {
return DecodeContentWithCodec(o.codec, ev.GetContent().GetContentType(), ev.GetContent().GetData(), v)
})
return nil
}
func (o *observationHandler) OnClose() {
o.removeSubscription()
o.obs.OnClose()
}
func (o *observationHandler) Error(err error) {
o.removeSubscription()
o.obs.Error(err)
}