Debian Codegraph @

peripheral_linux.go

raw symbols SCIP
1 package gatt
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "io"
9 "log"
10 "net"
11 "strings"
12
13 "github.com/paypal/gatt/linux"
14 )
15
16 type peripheral struct {
17 // NameChanged is called whenever the peripheral GAP device name has changed.
18 NameChanged func(*peripheral)
19
20 // ServicedModified is called when one or more service of a peripheral have changed.
21 // A list of invalid service is provided in the parameter.
22 ServicesModified func(*peripheral, []*Service)
23
24 d *device
25 svcs []*Service
26
27 sub *subscriber
28
29 mtu uint16
30 l2c io.ReadWriteCloser
31
32 reqc chan message
33 quitc chan struct{}
34
35 pd *linux.PlatData // platform specific data
36 }
37
38 func (p *peripheral) Device() Device { return p.d }
39 func (p *peripheral) ID() string { return strings.ToUpper(net.HardwareAddr(p.pd.Address[:]).String()) }
40 func (p *peripheral) Name() string { return p.pd.Name }
41 func (p *peripheral) Services() []*Service { return p.svcs }
42
43 func finish(op byte, h uint16, b []byte) bool {
44 done := b[0] == attOpError && b[1] == op && b[2] == byte(h) && b[3] == byte(h>>8)
45 e := attEcode(b[4])
46 if e != attEcodeAttrNotFound {
47 // log.Printf("unexpected protocol error: %s", e)
48 // FIXME: terminate the connection
49 }
50 return done
51 }
52
53 func (p *peripheral) DiscoverServices(s []UUID) ([]*Service, error) {
54 // TODO: implement the UUID filters
55 // p.pd.Conn.Write([]byte{0x02, 0x87, 0x00}) // MTU
56 done := false
57 start := uint16(0x0001)
58 for !done {
59 op := byte(attOpReadByGroupReq)
60 b := make([]byte, 7)
61 b[0] = op
62 binary.LittleEndian.PutUint16(b[1:3], start)
63 binary.LittleEndian.PutUint16(b[3:5], 0xFFFF)
64 binary.LittleEndian.PutUint16(b[5:7], 0x2800)
65
66 b = p.sendReq(op, b)
67 if finish(op, start, b) {
68 break
69 }
70 b = b[1:]
71 l, b := int(b[0]), b[1:]
72 switch {
73 case l == 6 && (len(b)%6 == 0):
74 case l == 20 && (len(b)%20 == 0):
75 default:
76 return nil, ErrInvalidLength
77 }
78
79 for len(b) != 0 {
80 h := binary.LittleEndian.Uint16(b[:2])
81 endh := binary.LittleEndian.Uint16(b[2:4])
82 s := &Service{
83 uuid: UUID{b[4:l]},
84 h: h,
85 endh: endh,
86 }
87 p.svcs = append(p.svcs, s)
88 b = b[l:]
89 done = endh == 0xFFFF
90 start = endh + 1
91 }
92 }
93 return p.svcs, nil
94 }
95
96 func (p *peripheral) DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error) {
97 // TODO
98 return nil, nil
99 }
100
101 func (p *peripheral) DiscoverCharacteristics(cs []UUID, s *Service) ([]*Characteristic, error) {
102 // TODO: implement the UUID filters
103 done := false
104 start := s.h
105 var prev *Characteristic
106 for !done {
107 op := byte(attOpReadByTypeReq)
108 b := make([]byte, 7)
109 b[0] = op
110 binary.LittleEndian.PutUint16(b[1:3], start)
111 binary.LittleEndian.PutUint16(b[3:5], s.endh)
112 binary.LittleEndian.PutUint16(b[5:7], 0x2803)
113
114 b = p.sendReq(op, b)
115 if finish(op, start, b) {
116 break
117 }
118 b = b[1:]
119
120 l, b := int(b[0]), b[1:]
121 switch {
122 case l == 7 && (len(b)%7 == 0):
123 case l == 21 && (len(b)%21 == 0):
124 default:
125 return nil, ErrInvalidLength
126 }
127
128 for len(b) != 0 {
129 h := binary.LittleEndian.Uint16(b[:2])
130 props := Property(b[2])
131 vh := binary.LittleEndian.Uint16(b[3:5])
132 u := UUID{b[5:l]}
133 s := searchService(p.svcs, h, vh)
134 if s == nil {
135 log.Printf("Can't find service range that contains 0x%04X - 0x%04X", h, vh)
136 return nil, fmt.Errorf("Can't find service range that contains 0x%04X - 0x%04X", h, vh)
137 }
138 c := &Characteristic{
139 uuid: u,
140 svc: s,
141 props: props,
142 h: h,
143 vh: vh,
144 }
145 s.chars = append(s.chars, c)
146 b = b[l:]
147 done = vh == s.endh
148 start = vh + 1
149 if prev != nil {
150 prev.endh = c.h - 1
151 }
152 prev = c
153 }
154 }
155 if len(s.chars) > 1 {
156 s.chars[len(s.chars)-1].endh = s.endh
157 }
158 return s.chars, nil
159 }
160
161 func (p *peripheral) DiscoverDescriptors(ds []UUID, c *Characteristic) ([]*Descriptor, error) {
162 // TODO: implement the UUID filters
163 done := false
164 start := c.vh + 1
165 for !done {
166 if c.endh == 0 {
167 c.endh = c.svc.endh
168 }
169 op := byte(attOpFindInfoReq)
170 b := make([]byte, 5)
171 b[0] = op
172 binary.LittleEndian.PutUint16(b[1:3], start)
173 binary.LittleEndian.PutUint16(b[3:5], c.endh)
174
175 b = p.sendReq(op, b)
176 if finish(attOpFindInfoReq, start, b) {
177 break
178 }
179 b = b[1:]
180
181 var l int
182 f, b := int(b[0]), b[1:]
183 switch {
184 case f == 1 && (len(b)%4 == 0):
185 l = 4
186 case f == 2 && (len(b)%18 == 0):
187 l = 18
188 default:
189 return nil, ErrInvalidLength
190 }
191
192 for len(b) != 0 {
193 h := binary.LittleEndian.Uint16(b[:2])
194 u := UUID{b[2:l]}
195 d := &Descriptor{uuid: u, h: h, char: c}
196 c.descs = append(c.descs, d)
197 if u.Equal(attrClientCharacteristicConfigUUID) {
198 c.cccd = d
199 }
200 b = b[l:]
201 done = h == c.endh
202 start = h + 1
203 }
204 }
205 return c.descs, nil
206 }
207
208 func (p *peripheral) ReadCharacteristic(c *Characteristic) ([]byte, error) {
209 b := make([]byte, 3)
210 op := byte(attOpReadReq)
211 b[0] = op
212 binary.LittleEndian.PutUint16(b[1:3], c.vh)
213
214 b = p.sendReq(op, b)
215 b = b[1:]
216 return b, nil
217 }
218
219 func (p *peripheral) ReadLongCharacteristic(c *Characteristic) ([]byte, error) {
220 // The spec says that a read blob request should fail if the characteristic
221 // is smaller than mtu - 1. To simplify the API, the first read is done
222 // with a regular read request. If the buffer received is equal to mtu -1,
223 // then we read the rest of the data using read blob.
224 firstRead, err := p.ReadCharacteristic(c)
225 if err != nil {
226 return nil, err
227 }
228 if len(firstRead) < int(p.mtu)-1 {
229 return firstRead, nil
230 }
231
232 var buf bytes.Buffer
233 buf.Write(firstRead)
234 off := uint16(len(firstRead))
235 for {
236 b := make([]byte, 5)
237 op := byte(attOpReadBlobReq)
238 b[0] = op
239 binary.LittleEndian.PutUint16(b[1:3], c.vh)
240 binary.LittleEndian.PutUint16(b[3:5], off)
241
242 b = p.sendReq(op, b)
243 b = b[1:]
244 if len(b) == 0 {
245 break
246 }
247 buf.Write(b)
248 off += uint16(len(b))
249 if len(b) < int(p.mtu)-1 {
250 break
251 }
252 }
253 return buf.Bytes(), nil
254 }
255
256 func (p *peripheral) WriteCharacteristic(c *Characteristic, value []byte, noRsp bool) error {
257 b := make([]byte, 3+len(value))
258 op := byte(attOpWriteReq)
259 b[0] = op
260 if noRsp {
261 b[0] = attOpWriteCmd
262 }
263 binary.LittleEndian.PutUint16(b[1:3], c.vh)
264 copy(b[3:], value)
265
266 if noRsp {
267 p.sendCmd(op, b)
268 return nil
269 }
270 b = p.sendReq(op, b)
271 // TODO: error handling
272 b = b[1:]
273 return nil
274 }
275
276 func (p *peripheral) ReadDescriptor(d *Descriptor) ([]byte, error) {
277 b := make([]byte, 3)
278 op := byte(attOpReadReq)
279 b[0] = op
280 binary.LittleEndian.PutUint16(b[1:3], d.h)
281
282 b = p.sendReq(op, b)
283 b = b[1:]
284 // TODO: error handling
285 return b, nil
286 }
287
288 func (p *peripheral) WriteDescriptor(d *Descriptor, value []byte) error {
289 b := make([]byte, 3+len(value))
290 op := byte(attOpWriteReq)
291 b[0] = op
292 binary.LittleEndian.PutUint16(b[1:3], d.h)
293 copy(b[3:], value)
294
295 b = p.sendReq(op, b)
296 b = b[1:]
297 // TODO: error handling
298 return nil
299 }
300
301 func (p *peripheral) setNotifyValue(c *Characteristic, flag uint16,
302 f func(*Characteristic, []byte, error)) error {
303 if c.cccd == nil {
304 return errors.New("no cccd") // FIXME
305 }
306 ccc := uint16(0)
307 if f != nil {
308 ccc = flag
309 p.sub.subscribe(c.vh, func(b []byte, err error) { f(c, b, err) })
310 }
311 b := make([]byte, 5)
312 op := byte(attOpWriteReq)
313 b[0] = op
314 binary.LittleEndian.PutUint16(b[1:3], c.cccd.h)
315 binary.LittleEndian.PutUint16(b[3:5], ccc)
316
317 b = p.sendReq(op, b)
318 b = b[1:]
319 // TODO: error handling
320 if f == nil {
321 p.sub.unsubscribe(c.vh)
322 }
323 return nil
324 }
325
326 func (p *peripheral) SetNotifyValue(c *Characteristic,
327 f func(*Characteristic, []byte, error)) error {
328 return p.setNotifyValue(c, gattCCCNotifyFlag, f)
329 }
330
331 func (p *peripheral) SetIndicateValue(c *Characteristic,
332 f func(*Characteristic, []byte, error)) error {
333 return p.setNotifyValue(c, gattCCCIndicateFlag, f)
334 }
335
336 func (p *peripheral) ReadRSSI() int {
337 // TODO: implement
338 return -1
339 }
340
341 func searchService(ss []*Service, start, end uint16) *Service {
342 for _, s := range ss {
343 if s.h < start && s.endh >= end {
344 return s
345 }
346 }
347 return nil
348 }
349
350 // TODO: unifiy the message with OS X pots and refactor
351 type message struct {
352 op byte
353 b []byte
354 rspc chan []byte
355 }
356
357 func (p *peripheral) sendCmd(op byte, b []byte) {
358 p.reqc <- message{op: op, b: b}
359 }
360
361 func (p *peripheral) sendReq(op byte, b []byte) []byte {
362 m := message{op: op, b: b, rspc: make(chan []byte)}
363 p.reqc <- m
364 return <-m.rspc
365 }
366
367 func (p *peripheral) loop() {
368 // Serialize the request.
369 rspc := make(chan []byte)
370
371 // Dequeue request loop
372 go func() {
373 for {
374 select {
375 case req := <-p.reqc:
376 p.l2c.Write(req.b)
377 if req.rspc == nil {
378 break
379 }
380 r := <-rspc
381 switch reqOp, rspOp := req.b[0], r[0]; {
382 case rspOp == attRspFor[reqOp]:
383 case rspOp == attOpError && r[1] == reqOp:
384 default:
385 log.Printf("Request 0x%02x got a mismatched response: 0x%02x", reqOp, rspOp)
386 // FIXME: terminate the connection?
387 }
388 req.rspc <- r
389 case <-p.quitc:
390 return
391 }
392 }
393 }()
394
395 // L2CAP implementations shall support a minimum MTU size of 48 bytes.
396 // The default value is 672 bytes
397 buf := make([]byte, 672)
398
399 // Handling response or notification/indication
400 for {
401 n, err := p.l2c.Read(buf)
402 if n == 0 || err != nil {
403 close(p.quitc)
404 return
405 }
406
407 b := make([]byte, n)
408 copy(b, buf)
409
410 if (b[0] != attOpHandleNotify) && (b[0] != attOpHandleInd) {
411 rspc <- b
412 continue
413 }
414
415 h := binary.LittleEndian.Uint16(b[1:3])
416 f := p.sub.fn(h)
417 if f == nil {
418 log.Printf("notified by unsubscribed handle")
419 // FIXME: terminate the connection?
420 } else {
421 go f(b[3:], nil)
422 }
423
424 if b[0] == attOpHandleInd {
425 // write aknowledgement for indication
426 p.l2c.Write([]byte{attOpHandleCnf})
427 }
428
429 }
430 }
431
432 func (p *peripheral) SetMTU(mtu uint16) error {
433 b := make([]byte, 3)
434 op := byte(attOpMtuReq)
435 b[0] = op
436 binary.LittleEndian.PutUint16(b[1:3], uint16(mtu))
437
438 b = p.sendReq(op, b)
439 serverMTU := binary.LittleEndian.Uint16(b[1:3])
440 if serverMTU < mtu {
441 mtu = serverMTU
442 }
443 p.mtu = mtu
444 return nil
445 }