/
shadow.go
90 lines (79 loc) · 1.92 KB
/
shadow.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
88
89
90
package shadow
import (
"encoding/json"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iot"
"github.com/aws/aws-sdk-go/service/iotdataplane"
"github.com/aws/aws-sdk-go/service/iotdataplane/iotdataplaneiface"
"strconv"
"time"
)
type Timestamp struct {
time.Time
}
func (t *Timestamp) UnmarshalJSON(data []byte) error {
// Parse data to int
epoch, err := strconv.Atoi(string(data))
if err != nil {
return err
}
// Conver to a time
t.Time = time.Unix(int64(epoch), 0)
return nil
}
type client struct {
dp iotdataplaneiface.IoTDataPlaneAPI
}
type MetadataEntry struct {
Timestamp Timestamp `json:""`
}
type Metadata struct {
Reported map[string]MetadataEntry `json:""`
}
type State struct {
Reported map[string]interface{} `json:""`
}
type Shadow struct {
Timestamp Timestamp `json:""`
Metadata Metadata `json:""`
State State `json:""`
}
// New creates a new shadow client
func New(sess *session.Session) (Client, error) {
// We need to use an IoT control plane client to get an endpoint address
ctrlSvc := iot.New(sess)
descResp, err := ctrlSvc.DescribeEndpoint(&iot.DescribeEndpointInput{})
if err != nil {
return nil, err
}
// Create a IoT data plane client using the endpoint address we retrieved
svc := iotdataplane.New(sess, &aws.Config{
Endpoint: descResp.EndpointAddress,
})
// Return our client wrapper
return &client{
dp: svc,
}, nil
}
// Client represents a client to the device shadow service
type Client interface {
Get(deviceId string) (*Shadow, error)
}
func (c *client) Get(deviceId string) (*Shadow, error) {
// Request the shadow
resp, err := c.dp.GetThingShadow(&iotdataplane.GetThingShadowInput{
ThingName: aws.String(deviceId),
})
if err != nil {
return nil, err
}
// Unpack
var shadow Shadow
err = json.Unmarshal(resp.Payload, &shadow)
if err != nil {
return nil, err
}
// Return
return &shadow, nil
}