forked from amenzhinsky/iothub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
348 lines (308 loc) · 8.56 KB
/
client.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package iotdevice
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"sync"
"github.com/amenzhinsky/iothub/common"
"github.com/amenzhinsky/iothub/iotdevice/transport"
"github.com/amenzhinsky/iothub/logger"
)
// ClientOption is a client configuration option.
type ClientOption func(c *Client)
// WithLogger changes default logger, default it an stdout logger.
func WithLogger(l logger.Logger) ClientOption {
return func(c *Client) {
c.logger = l
}
}
// NewFromConnectionString creates a device client based on the given connection string.
func NewFromConnectionString(
transport transport.Transport, cs string, opts ...ClientOption,
) (*Client, error) {
creds, err := ParseConnectionString(cs)
if err != nil {
return nil, err
}
return New(transport, creds, opts...)
}
func ParseConnectionString(cs string) (*SharedAccessKeyCredentials, error) {
m, err := common.ParseConnectionString(cs, "DeviceId", "SharedAccessKey")
if err != nil {
return nil, err
}
return &SharedAccessKeyCredentials{
DeviceID: m["DeviceId"],
SharedAccessKey: common.SharedAccessKey{
HostName: m["HostName"],
SharedAccessKeyName: m["SharedAccessKeyName"],
SharedAccessKey: m["SharedAccessKey"],
},
}, nil
}
func NewFromX509Cert(
transport transport.Transport,
deviceID, hostName string, crt *tls.Certificate,
opts ...ClientOption,
) (*Client, error) {
return New(transport, &X509Credentials{
DeviceID: deviceID,
HostName: hostName,
Certificate: crt,
}, opts...)
}
func NewFromX509FromFile(
transport transport.Transport,
deviceID, hostname, certFile, keyFile string,
opts ...ClientOption,
) (*Client, error) {
crt, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
return NewFromX509Cert(transport, deviceID, hostname, &crt, opts...)
}
// New returns new iothub client.
func New(
transport transport.Transport, creds transport.Credentials, opts ...ClientOption,
) (*Client, error) {
c := &Client{
tr: transport,
creds: creds,
ready: make(chan struct{}),
done: make(chan struct{}),
logger: logger.New(logger.LevelWarn, nil),
evMux: newEventsMux(),
tsMux: newTwinStateMux(),
dmMux: newMethodMux(),
}
for _, opt := range opts {
opt(c)
}
// transport uses the same logger as the client
c.tr.SetLogger(c.logger)
return c, nil
}
// Client is iothub device client.
type Client struct {
creds transport.Credentials
tr transport.Transport
logger logger.Logger
mu sync.RWMutex
ready chan struct{}
done chan struct{}
evMux *eventsMux
tsMux *twinStateMux
dmMux *methodMux
}
// DirectMethodHandler handles direct method invocations.
type DirectMethodHandler func(p map[string]interface{}) (map[string]interface{}, error)
// DeviceID returns iothub device id.
func (c *Client) DeviceID() string {
return c.creds.GetDeviceID()
}
// Connect connects to the iothub all subsequent calls
// will block until this function finishes with no error so it's clien's
// responsibility to connect in the background by running it in a goroutine
// and control other method invocations or call in in a synchronous way.
func (c *Client) Connect(ctx context.Context) error {
c.mu.Lock()
select {
case <-c.ready:
c.mu.Unlock()
return errors.New("already connected")
default:
}
err := c.tr.Connect(ctx, c.creds)
if err == nil {
close(c.ready)
}
c.mu.Unlock()
// TODO: c.err = err
return err
}
// ErrClosed the client is already closed.
var ErrClosed = errors.New("closed")
func (c *Client) checkConnection(ctx context.Context) error {
select {
case <-c.ready:
return nil
case <-c.done:
return ErrClosed
case <-ctx.Done():
return ctx.Err()
}
}
// SubscribeEvents subscribes to cloud-to-device events and returns a subscription struct.
func (c *Client) SubscribeEvents(ctx context.Context) (*EventSub, error) {
if err := c.checkConnection(ctx); err != nil {
return nil, err
}
if err := c.evMux.once(func() error {
return c.tr.SubscribeEvents(ctx, c.evMux)
}); err != nil {
return nil, err
}
return c.evMux.sub(), nil
}
// UnsubscribeEvents makes the given subscription to stop receiving messages.
func (c *Client) UnsubscribeEvents(sub *EventSub) {
c.evMux.unsub(sub)
}
// RegisterMethod registers the given direct method handler,
// returns an error when method is already registered.
// If f returns an error and empty body its error string
// used as value of the error attribute in the result json.
func (c *Client) RegisterMethod(ctx context.Context, name string, fn DirectMethodHandler) error {
if err := c.checkConnection(ctx); err != nil {
return err
}
if name == "" {
return errors.New("name cannot be blank")
}
if err := c.dmMux.once(func() error {
return c.tr.RegisterDirectMethods(ctx, c.dmMux)
}); err != nil {
return err
}
return c.dmMux.handle(name, fn)
}
// UnregisterMethod unregisters the named method.
func (c *Client) UnregisterMethod(name string) {
c.dmMux.remove(name)
}
// TwinState is both desired and reported twin device's state.
type TwinState map[string]interface{}
// Version is state version.
func (s TwinState) Version() int {
v, _ := s["$version"].(float64)
return int(v)
}
// RetrieveTwinState returns desired and reported twin device states.
func (c *Client) RetrieveTwinState(ctx context.Context) (desired TwinState, reported TwinState, err error) {
if err := c.checkConnection(ctx); err != nil {
return nil, nil, err
}
b, err := c.tr.RetrieveTwinProperties(ctx)
if err != nil {
return nil, nil, err
}
var v struct {
Desired TwinState `json:"desired"`
Reported TwinState `json:"reported"`
}
if err := json.Unmarshal(b, &v); err != nil {
return nil, nil, err
}
return v.Desired, v.Reported, nil
}
// UpdateTwinState updates twin device's state and returns new version.
// To remove any attribute set its value to nil.
func (c *Client) UpdateTwinState(ctx context.Context, s TwinState) (int, error) {
if err := c.checkConnection(ctx); err != nil {
return 0, err
}
b, err := json.Marshal(s)
if err != nil {
return 0, err
}
return c.tr.UpdateTwinProperties(ctx, b)
}
// SubscribeTwinUpdates registers fn as a desired state changes handler.
func (c *Client) SubscribeTwinUpdates(ctx context.Context) (*TwinStateSub, error) {
if err := c.checkConnection(ctx); err != nil {
return nil, err
}
if err := c.tsMux.once(func() error {
return c.tr.SubscribeTwinUpdates(ctx, c.tsMux)
}); err != nil {
return nil, err
}
return c.tsMux.sub(), nil
}
// UnsubscribeTwinUpdates unsubscribes the given handler from twin state updates.
func (c *Client) UnsubscribeTwinUpdates(sub *TwinStateSub) {
c.tsMux.unsub(sub)
}
// SendOption is a send event options.
type SendOption func(msg *common.Message) error
// WithSendQoS sets the quality of service (MQTT only).
// Only 0 and 1 values are supported, defaults to 1.
func WithSendQoS(qos int) SendOption {
return func(msg *common.Message) error {
if msg.TransportOptions == nil {
msg.TransportOptions = map[string]interface{}{}
}
msg.TransportOptions["qos"] = qos
return nil
}
}
// WithSendMessageID sets message id.
func WithSendMessageID(mid string) SendOption {
return func(msg *common.Message) error {
msg.MessageID = mid
return nil
}
}
// WithSendCorrelationID sets message correlation id.
func WithSendCorrelationID(cid string) SendOption {
return func(msg *common.Message) error {
msg.CorrelationID = cid
return nil
}
}
// WithSendProperty sets a message option.
func WithSendProperty(k, v string) SendOption {
return func(msg *common.Message) error {
if msg.Properties == nil {
msg.Properties = map[string]string{}
}
msg.Properties[k] = v
return nil
}
}
// WithSendProperties same as `WithSendProperty` but accepts map of keys and values.
func WithSendProperties(m map[string]string) SendOption {
return func(msg *common.Message) error {
if msg.Properties == nil {
msg.Properties = map[string]string{}
}
for k, v := range m {
msg.Properties[k] = v
}
return nil
}
}
// SendEvent sends a device-to-cloud message.
// Panics when event is nil.
func (c *Client) SendEvent(ctx context.Context, payload []byte, opts ...SendOption) error {
if err := c.checkConnection(ctx); err != nil {
return err
}
msg := &common.Message{Payload: payload}
for _, opt := range opts {
if err := opt(msg); err != nil {
return err
}
}
if err := c.tr.Send(ctx, msg); err != nil {
return err
}
c.logger.Debugf("device-to-cloud: %#v", msg)
return nil
}
// Close closes transport connection.
func (c *Client) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.done:
return nil
default:
close(c.done)
c.evMux.close(ErrClosed)
c.tsMux.close(ErrClosed)
return c.tr.Close()
}
}