forked from plgd-dev/go-coap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clientcommander.go
286 lines (255 loc) · 7.71 KB
/
clientcommander.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
package coap
import (
"bytes"
"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 performs a synchronous query. It sends the message m to the address
// contained in a and waits for a reply.
//
// Exchange does not retry a failed query, nor will it fall back to TCP in
// case of truncation.
// To specify a local address or a timeout, the caller has to set the `Client.Dialer`
// attribute appropriately
func (cc *ClientCommander) Exchange(m Message) (Message, error) {
return cc.networkSession.Exchange(m)
}
// WriteMsg sends direct a message through the connection
func (cc *ClientCommander) WriteMsg(m Message) error {
return cc.networkSession.WriteMsg(m)
}
// Ping send a ping message and wait for a pong response
func (cc *ClientCommander) Ping(timeout time.Duration) error {
return cc.networkSession.Ping(timeout)
}
// Get retrieve the resource identified by the request path
func (cc *ClientCommander) Get(path string) (Message, error) {
req, err := cc.NewGetRequest(path)
if err != nil {
return nil, err
}
return cc.networkSession.Exchange(req)
}
// Post update the resource identified by the request path
func (cc *ClientCommander) Post(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.Exchange(req)
}
// Put create the resource identified by the request path
func (cc *ClientCommander) Put(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.Exchange(req)
}
// Delete delete the resource identified by the request path
func (cc *ClientCommander) Delete(path string) (Message, error) {
req, err := cc.NewDeleteRequest(path)
if err != nil {
return nil, err
}
return cc.networkSession.Exchange(req)
}
//Observation represents subscription to resource on the server
type Observation struct {
token []byte
path string
obsSeqNum uint32
client *ClientCommander
}
// Cancel remove observation from server. For recreate observation use Observe.
func (o *Observation) Cancel() 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.WriteMsg(req)
err2 := o.client.networkSession.TokenHandler().Remove(o.token)
if err1 != nil {
return err1
}
return err2
}
// Observe subscribe to severon path. After subscription and every change on path,
// server sends immediately response
func (cc *ClientCommander) Observe(path string, observeFunc func(req *Request)) (*Observation, error) {
req, err := cc.NewGetRequest(path)
if err != nil {
return nil, err
}
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,
obsSeqNum: 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.Get(path)
if err != nil {
return
}
}
setObsSeqNum := func() bool {
if r.Msg.Option(Observe) != nil {
obsSeqNum := r.Msg.Option(Observe).(uint32)
//obs starts with 0, after that check obsSeqNum
if obsSeqNum != 0 && o.obsSeqNum > obsSeqNum {
return false
}
o.obsSeqNum = obsSeqNum
}
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 setObsSeqNum() {
observeFunc(&Request{Msg: resp, Client: r.Client})
}
}
default:
if setObsSeqNum() {
observeFunc(&Request{Msg: resp, Client: r.Client})
}
}
return
})
if err != nil {
return nil, err
}
err = cc.WriteMsg(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()
}
// SetReadDeadline set read deadline for timeout for Exchange
func (cc *ClientCommander) SetReadDeadline(timeout time.Duration) {
cc.networkSession.SetReadDeadline(timeout)
}
// SetWriteDeadline set write deadline for timeout for Exchange and Write
func (cc *ClientCommander) SetWriteDeadline(timeout time.Duration) {
cc.networkSession.SetWriteDeadline(timeout)
}
// ReadDeadline get read deadline
func (cc *ClientCommander) ReadDeadline() time.Duration {
return cc.networkSession.ReadDeadline()
}
// WriteDeadline get read writeline
func (cc *ClientCommander) WriteDeadline() time.Duration {
return cc.networkSession.WriteDeadline()
}