/
getResource.go
81 lines (72 loc) · 1.99 KB
/
getResource.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
package core
import (
"context"
"fmt"
"github.com/plgd-dev/device/pkg/net/coap"
"github.com/plgd-dev/device/schema"
"github.com/plgd-dev/kit/v2/codec/ocf"
)
// GetResource queries a device for a resource value in CBOR.
func (d *Device) GetResource(
ctx context.Context,
link schema.ResourceLink,
response interface{},
options ...coap.OptionFunc,
) error {
codec := ocf.VNDOCFCBORCodec{}
return d.GetResourceWithCodec(ctx, link, codec, response, options...)
}
// GetResourceWithCodec queries a device for a resource value.
func (d *Device) GetResourceWithCodec(
ctx context.Context,
link schema.ResourceLink,
codec coap.Codec,
response interface{},
options ...coap.OptionFunc,
) error {
options = append(options, coap.WithAccept(codec.ContentFormat()))
_, client, err := d.connectToEndpoints(ctx, link.GetEndpoints())
if err != nil {
return fmt.Errorf("cannot get resource %v: %w", link.Href, err)
}
return client.GetResourceWithCodec(ctx, link.Href, codec, response, options...)
}
// GetResources resolves URIs and returns an iterator for querying resources of given resource types.
func (d *Device) GetResources(ctx context.Context, links schema.ResourceLinks) *ResourceIterator {
return &ResourceIterator{
device: d,
links: links,
}
}
// ResourceIterator queries resource values.
type ResourceIterator struct {
Err error
links schema.ResourceLinks
i int
device *Device
}
// Next queries the next resource value.
// Returns false when failed or having no more items.
// Check it.Err for errors.
// Usage:
//
// for {
// var v MyStruct
// if !it.Next(ctx, &v) {
// break
// }
// }
// if it.Err != nil {
// }
func (it *ResourceIterator) Next(ctx context.Context, v interface{}) bool {
if it.Err != nil || it.i >= len(it.links) {
return false
}
err := it.device.GetResource(ctx, it.links[it.i], v)
if err != nil {
it.Err = MakeDataLoss(fmt.Errorf("could not get a resource value for the device %s: %w", it.device.DeviceID(), err))
return false
}
it.i++
return true
}