/
echo.go
58 lines (52 loc) · 1.18 KB
/
echo.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
package lib
import (
"log"
"sync"
"time"
"github.com/currantlabs/ble"
)
// NewEchoChar ...
func NewEchoChar() *ble.Characteristic {
e := &echoChar{m: make(map[string]chan []byte)}
c := ble.NewCharacteristic(EchoCharUUID)
c.HandleWrite(ble.WriteHandlerFunc(e.written))
c.HandleNotify(ble.NotifyHandlerFunc(e.echo))
c.HandleIndicate(ble.NotifyHandlerFunc(e.echo))
return c
}
type echoChar struct {
sync.Mutex
m map[string]chan []byte
}
func (e *echoChar) written(req ble.Request, rsp ble.ResponseWriter) {
e.Lock()
e.m[req.Conn().RemoteAddr().String()] <- req.Data()
e.Unlock()
}
func (e *echoChar) echo(req ble.Request, n ble.Notifier) {
ch := make(chan []byte)
e.Lock()
e.m[req.Conn().RemoteAddr().String()] = ch
e.Unlock()
log.Printf("echo: Notification subscribed")
defer func() {
e.Lock()
delete(e.m, req.Conn().RemoteAddr().String())
e.Unlock()
}()
for {
select {
case <-n.Context().Done():
log.Printf("echo: Notification unsubscribed")
return
case <-time.After(time.Second * 20):
log.Printf("echo: timeout")
return
case msg := <-ch:
if _, err := n.Write(msg); err != nil {
log.Printf("echo: can't indicate: %s", err)
return
}
}
}
}