-
Notifications
You must be signed in to change notification settings - Fork 3
/
handler.go
345 lines (279 loc) · 7.44 KB
/
handler.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
/**
* Copyright 2019 Rightech IoT. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package handler
import (
"context"
"encoding/base64"
"errors"
"time"
"unsafe"
"github.com/Rightech/ric-edge/pkg/jsonrpc"
"github.com/Rightech/ric-edge/third_party/go-ble/ble"
jsoniter "github.com/json-iterator/go"
"github.com/stretchr/objx"
)
func init() { // nolint: gochecknoinits
// custom uuid decoder decode uuid as string
// default decoder decode uuid as byte slice (base64)
jsoniter.RegisterTypeEncoder("ble.UUID", bleUUIDDecoder{})
}
type Service struct {
dev ble.Device
rpc jsonrpc.RPC
// this map address to client
// it's required because only one client can exists
// so when subscriptions starts we remember client and use it in next calls
// when subscription dies client removes from map
conns map[string]ble.Client
}
func (s *Service) InjectRPC(rpc jsonrpc.RPC) {
// this method required for lazy initialization of rpc client
// this client needs to send notifications (see subscribe)
s.rpc = rpc
}
func (s Service) Call(req jsonrpc.Request) (res interface{}, err error) {
switch req.Method {
case "ble-scan":
res, err = s.scan(req.Params)
case "ble-discover":
res, err = s.discover(req.Params)
case "ble-read":
res, err = s.read(req.Params)
case "ble-write":
res, err = s.write(req.Params)
case "ble-subscribe":
res, err = s.subscribe(req.Params)
case "ble-subscribe-cancel":
res, err = s.subscribeCancel(req.Params)
default:
err = jsonrpc.ErrMethodNotFound.AddData("method", req.Method)
}
return
}
type dev struct {
Addr string `json:"addr"`
RSSI int `json:"rssi"`
Name string `json:"name"`
Connectable bool `json:"connectable"`
}
func (s Service) scan(params objx.Map) (interface{}, error) {
timeout, err := time.ParseDuration(params.Get("timeout").Str("5s"))
if err != nil {
return nil, jsonrpc.ErrInvalidParams.AddData("msg", err.Error())
}
ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), timeout))
devices := make(map[string]*dev)
advHandler := func(a ble.Advertisement) {
v, ok := devices[a.Addr().String()]
if ok {
v.Name = a.LocalName()
v.RSSI = a.RSSI()
v.Connectable = a.Connectable()
return
}
devices[a.Addr().String()] = &dev{
Addr: a.Addr().String(),
RSSI: a.RSSI(),
Name: a.LocalName(),
Connectable: a.Connectable(),
}
}
err = s.dev.Scan(ctx, false, advHandler)
if err != nil && !errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
return mapToList(devices), nil
}
func mapToList(mp map[string]*dev) []dev {
lst := make([]dev, 0, len(mp))
for _, v := range mp {
lst = append(lst, *v)
}
return lst
}
func (s Service) discover(params objx.Map) (interface{}, error) {
address := params.Get("device").Str()
if address == "" {
return nil, jsonrpc.ErrInvalidParams.AddData("msg", "empty device")
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
var err error
cli, ok := s.conns[address]
if !ok {
cli, err = s.dev.Dial(ctx, ble.NewAddr(address))
if err != nil {
return nil, err
}
}
defer func() {
if !ok {
cli.CancelConnection() // nolint: errcheck
}
}()
return cli.DiscoverProfile(true)
}
func parseRequest(params objx.Map) (a string, s ble.UUID, c ble.UUID, err error) {
a = params.Get("device").Str()
if a == "" {
err = jsonrpc.ErrInvalidParams.AddData("msg", "empty device")
return
}
s, err = ble.Parse(params.Get("service_uuid").Str())
if err != nil {
err = jsonrpc.ErrInvalidParams.AddData("p", "service_uuid").
AddData("msg", err.Error())
return
}
c, err = ble.Parse(params.Get("characteristic_uuid").Str())
if err != nil {
err = jsonrpc.ErrInvalidParams.AddData("p", "characteristic_uuid").
AddData("msg", err.Error())
return
}
return
}
func (s Service) read(params objx.Map) (interface{}, error) {
address, srvUUID, chUUID, err := parseRequest(params)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
cli, ok := s.conns[address]
if !ok {
cli, err = s.dev.Dial(ctx, ble.NewAddr(address))
if err != nil {
return nil, err
}
}
defer func() {
if !ok {
cli.CancelConnection() // nolint: errcheck
}
}()
srv, err := cli.DiscoverServices([]ble.UUID{srvUUID})
if err != nil {
return nil, err
}
ch, err := cli.DiscoverCharacteristics([]ble.UUID{chUUID}, srv[0])
if err != nil {
return nil, err
}
return cli.ReadCharacteristic(ch[0])
}
func (s Service) write(params objx.Map) (interface{}, error) {
address, srvUUID, chUUID, err := parseRequest(params)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
cli, ok := s.conns[address]
if !ok {
cli, err = s.dev.Dial(ctx, ble.NewAddr(address))
if err != nil {
return nil, err
}
}
defer func() {
if !ok {
cli.CancelConnection() // nolint: errcheck
}
}()
srv, err := cli.DiscoverServices([]ble.UUID{srvUUID})
if err != nil {
return nil, err
}
ch, err := cli.DiscoverCharacteristics([]ble.UUID{chUUID}, srv[0])
if err != nil {
return nil, err
}
vaL := params.Get("value").Str()
value, err := base64.StdEncoding.DecodeString(vaL)
if err != nil {
value = []byte(vaL)
}
err = cli.WriteCharacteristic(ch[0], value, false)
if err != nil {
return nil, err
}
return true, nil
}
func (s Service) subscribe(params objx.Map) (interface{}, error) {
address, srvUUID, chUUID, err := parseRequest(params)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
cli, ok := s.conns[address]
if !ok {
cli, err = s.dev.Dial(ctx, ble.NewAddr(address))
if err != nil {
return nil, err
}
}
srv, err := cli.DiscoverServices([]ble.UUID{srvUUID})
if err != nil {
return nil, err
}
ch, err := cli.DiscoverCharacteristics([]ble.UUID{chUUID}, srv[0])
if err != nil {
return nil, err
}
_, err = cli.DiscoverDescriptors(nil, ch[0])
if err != nil {
return nil, err
}
nfSrv := s.rpc.NewNotification(params)
err = cli.Subscribe(ch[0], params.Get("indicator").Bool(), func(req []byte) {
nfSrv.Send(req)
})
if err != nil {
return nil, err
}
if !ok {
s.conns[address] = cli
}
return nfSrv, nil
}
func (s Service) subscribeCancel(params objx.Map) (interface{}, error) {
address := params.Get("device").Str()
cli, ok := s.conns[address]
if !ok {
return nil, jsonrpc.ErrInvalidRequest.AddData("msg", "sub not found")
}
err := cli.ClearSubscriptions()
if err != nil {
return nil, err
}
err = cli.CancelConnection()
if err != nil {
return nil, err
}
delete(s.conns, address)
return true, nil
}
type bleUUIDDecoder struct{}
func (bleUUIDDecoder) IsEmpty(ptr unsafe.Pointer) bool {
v := *((*ble.UUID)(ptr))
return v.Len() == 0
}
func (bleUUIDDecoder) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
v := *((*ble.UUID)(ptr))
stream.WriteString(v.String())
}