~fnux/yggdrasil-go-coap

ref: 614f652b70b2 yggdrasil-go-coap/clientcommander.go -rw-r--r-- 9.6 KiB
614f652bTimothée Floure Add syntax highlighting to code snippets in README 1 year, 4 months ago
                                                                                
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
package coap

import (
	"bytes"
	"context"
	"io"
	"io/ioutil"
	"net"
	"time"
)

// ClientCommander provides commands Get,Post,Put,Delete,Observe
// For compare use ClientCommander.Equal
type ClientCommander struct {
	networkSession networkSession
}

// NewMessage creates message for request
func (cc *ClientCommander) NewMessage(p MessageParams) Message {
	return cc.networkSession.NewMessage(p)
}

func (cc *ClientCommander) newGetDeleteRequest(path string, code COAPCode) (Message, error) {
	token, err := GenerateToken()
	if err != nil {
		return nil, err
	}
	req := cc.NewMessage(MessageParams{
		Type:      Confirmable,
		Code:      code,
		MessageID: GenerateMessageID(),
		Token:     token,
	})
	req.SetPathString(path)
	return req, nil
}

func (cc *ClientCommander) newPostPutRequest(path string, contentFormat MediaType, body io.Reader, code COAPCode) (Message, error) {
	token, err := GenerateToken()
	if err != nil {
		return nil, err
	}
	req := cc.networkSession.NewMessage(MessageParams{
		Type:      Confirmable,
		Code:      code,
		MessageID: GenerateMessageID(),
		Token:     token,
	})
	req.SetPathString(path)
	req.SetOption(ContentFormat, contentFormat)
	payload, err := ioutil.ReadAll(body)
	if err != nil {
		return nil, err
	}
	req.SetPayload(payload)
	return req, nil
}

// NewGetRequest creates get request
func (cc *ClientCommander) NewGetRequest(path string) (Message, error) {
	return cc.newGetDeleteRequest(path, GET)
}

// NewPostRequest creates post request
func (cc *ClientCommander) NewPostRequest(path string, contentFormat MediaType, body io.Reader) (Message, error) {
	return cc.newPostPutRequest(path, contentFormat, body, POST)
}

// NewPutRequest creates put request
func (cc *ClientCommander) NewPutRequest(path string, contentFormat MediaType, body io.Reader) (Message, error) {
	return cc.newPostPutRequest(path, contentFormat, body, PUT)
}

// NewDeleteRequest creates delete request
func (cc *ClientCommander) NewDeleteRequest(path string) (Message, error) {
	return cc.newGetDeleteRequest(path, DELETE)
}

// LocalAddr implements the networkSession.LocalAddr method.
func (cc *ClientCommander) LocalAddr() net.Addr {
	return cc.networkSession.LocalAddr()
}

// RemoteAddr implements the networkSession.RemoteAddr method.
func (cc *ClientCommander) RemoteAddr() net.Addr {
	return cc.networkSession.RemoteAddr()
}

// Equal compare two ClientCommanders
func (cc *ClientCommander) Equal(cc1 *ClientCommander) bool {
	return cc.RemoteAddr().String() == cc1.RemoteAddr().String() && cc.LocalAddr().String() == cc1.LocalAddr().String()
}

// Exchange same as ExchangeContext without context
func (cc *ClientCommander) Exchange(m Message) (Message, error) {
	return cc.ExchangeWithContext(context.Background(), m)
}

// ExchangeContext performs a synchronous query with context. It sends the message m to the address
// contained in a and waits for a reply.
//
// ExchangeContext does not retry a failed query, nor will it fall back to TCP in
// case of truncation.
func (cc *ClientCommander) ExchangeWithContext(ctx context.Context, m Message) (Message, error) {
	return cc.networkSession.ExchangeWithContext(ctx, m)
}

// WriteMsg sends  direct a message through the connection
func (cc *ClientCommander) WriteMsg(m Message) error {
	return cc.WriteMsgWithContext(context.Background(), m)
}

// WriteContextMsg sends with context direct a message through the connection
func (cc *ClientCommander) WriteMsgWithContext(ctx context.Context, m Message) error {
	return cc.networkSession.WriteMsgWithContext(ctx, m)
}

// Ping send a ping message and wait for a pong response
func (cc *ClientCommander) Ping(timeout time.Duration) error {
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()
	return cc.networkSession.PingWithContext(ctx)
}

// PingContext send with context a ping message and wait for a pong response
func (cc *ClientCommander) PingWithContext(ctx context.Context) error {
	return cc.networkSession.PingWithContext(ctx)
}

// Get retrieves the resource identified by the request path
func (cc *ClientCommander) Get(path string) (Message, error) {
	return cc.GetWithContext(context.Background(), path)
}

// GetContext retrieves with context the resource identified by the request path
func (cc *ClientCommander) GetWithContext(ctx context.Context, path string) (Message, error) {
	req, err := cc.NewGetRequest(path)
	if err != nil {
		return nil, err
	}
	return cc.networkSession.ExchangeWithContext(ctx, req)
}

// Post updates the resource identified by the request path
func (cc *ClientCommander) Post(path string, contentFormat MediaType, body io.Reader) (Message, error) {
	return cc.PostWithContext(context.Background(), path, contentFormat, body)
}

// PostContext updates with context the resource identified by the request path
func (cc *ClientCommander) PostWithContext(ctx context.Context, path string, contentFormat MediaType, body io.Reader) (Message, error) {
	req, err := cc.NewPostRequest(path, contentFormat, body)
	if err != nil {
		return nil, err
	}
	return cc.networkSession.ExchangeWithContext(ctx, req)
}

// Put creates the resource identified by the request path
func (cc *ClientCommander) Put(path string, contentFormat MediaType, body io.Reader) (Message, error) {
	return cc.PutWithContext(context.Background(), path, contentFormat, body)
}

// PutContext creates with context the resource identified by the request path
func (cc *ClientCommander) PutWithContext(ctx context.Context, path string, contentFormat MediaType, body io.Reader) (Message, error) {
	req, err := cc.NewPutRequest(path, contentFormat, body)
	if err != nil {
		return nil, err
	}
	return cc.networkSession.ExchangeWithContext(ctx, req)
}

// Delete deletes the resource identified by the request path
func (cc *ClientCommander) Delete(path string) (Message, error) {
	return cc.DeleteWithContext(context.Background(), path)
}

// DeleteContext deletes with context the resource identified by the request path
func (cc *ClientCommander) DeleteWithContext(ctx context.Context, path string) (Message, error) {
	req, err := cc.NewDeleteRequest(path)
	if err != nil {
		return nil, err
	}
	return cc.networkSession.ExchangeWithContext(ctx, req)
}

//Observation represents subscription to resource on the server
type Observation struct {
	token       []byte
	path        string
	obsSequence uint32
	client      *ClientCommander
}

func (o *Observation) Cancel() error {
	return o.CancelWithContext(context.Background())
}

// CancelContext remove observation from server. For recreate observation use Observe.
func (o *Observation) CancelWithContext(ctx context.Context) error {
	req := o.client.NewMessage(MessageParams{
		Type:      NonConfirmable,
		Code:      GET,
		MessageID: GenerateMessageID(),
		Token:     o.token,
	})
	req.SetPathString(o.path)
	req.SetOption(Observe, 1)
	err1 := o.client.WriteMsgWithContext(ctx, req)
	err2 := o.client.networkSession.TokenHandler().Remove(o.token)
	if err1 != nil {
		return err1
	}
	return err2
}

func (cc *ClientCommander) Observe(path string, observeFunc func(req *Request)) (*Observation, error) {
	return cc.ObserveWithContext(context.Background(), path, observeFunc)
}

// ObserveContext subscribe to severon path. After subscription and every change on path,
// server sends immediately response
func (cc *ClientCommander) ObserveWithContext(
	ctx context.Context,
	path string,
	observeFunc func(req *Request),
	options ...func(Message),
) (*Observation, error) {
	req, err := cc.NewGetRequest(path)
	if err != nil {
		return nil, err
	}
	for _, option := range options {
		option(req)
	}

	req.SetOption(Observe, 0)
	/*
		IoTivity doesn't support Block2 in first request for GET
		block, err := MarshalBlockOption(cc.networkSession.blockWiseSzx(), 0, false)
		if err != nil {
			return nil, err
		}
		req.SetOption(Block2, block)
	*/
	o := &Observation{
		token:       req.Token(),
		path:        path,
		obsSequence: 0,
		client:      cc,
	}
	err = cc.networkSession.TokenHandler().Add(req.Token(), func(w ResponseWriter, r *Request) {
		var err error
		needGet := false
		resp := r.Msg
		if r.Msg.Option(Size2) != nil {
			if len(r.Msg.Payload()) != int(r.Msg.Option(Size2).(uint32)) {
				needGet = true
			}
		}
		if !needGet {
			if block, ok := r.Msg.Option(Block2).(uint32); ok {
				_, _, more, err := UnmarshalBlockOption(block)
				if err != nil {
					return
				}
				needGet = more
			}
		}

		if needGet {
			resp, err = r.Client.GetWithContext(ctx, path)
			if err != nil {
				return
			}
		}
		setObsSequence := func() bool {
			if r.Msg.Option(Observe) != nil {
				obsSequence := r.Msg.Option(Observe).(uint32)
				//obs starts with 0, after that check obsSequence
				if obsSequence != 0 && o.obsSequence > obsSequence {
					return false
				}
				o.obsSequence = obsSequence
			}
			return true
		}

		switch {
		case r.Msg.Option(ETag) != nil && resp.Option(ETag) != nil:
			//during processing observation, check if notification is still valid
			if bytes.Equal(resp.Option(ETag).([]byte), r.Msg.Option(ETag).([]byte)) {
				if setObsSequence() {
					observeFunc(&Request{Msg: resp, Client: r.Client, Ctx: r.Ctx, Sequence: r.Sequence})
				}
			}
		default:
			if setObsSequence() {
				observeFunc(&Request{Msg: resp, Client: r.Client, Ctx: r.Ctx, Sequence: r.Sequence})
			}
		}
		return
	})
	if err != nil {
		return nil, err
	}
	err = cc.WriteMsgWithContext(ctx, req)
	if err != nil {
		cc.networkSession.TokenHandler().Remove(o.token)
		return nil, err
	}

	return o, nil
}

// Close close connection
func (cc *ClientCommander) Close() error {
	return cc.networkSession.Close()
}

// Sequence discontinuously unique growing number for connection.
func (cc *ClientCommander) Sequence() uint64 {
	return cc.networkSession.Sequence()
}