forked from krisbuist/timeular-zei-linux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbluetooth_manager.go
134 lines (111 loc) · 2.39 KB
/
bluetooth_manager.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
package timeular
import (
"errors"
"github.com/muka/go-bluetooth/api"
"github.com/muka/go-bluetooth/bluez/profile/adapter"
"github.com/muka/go-bluetooth/bluez/profile/device"
"log"
"strings"
"time"
)
const (
orientationService = "c7e70010-c847-11e6-8175-8c89a55d403c"
orientationCharacteristic = "c7e70012-c847-11e6-8175-8c89a55d403c"
)
type BluetoothManager struct {
OnOrientationChanged func(side int)
}
func getTimeularDevice(a *adapter.Adapter1) (*device.Device1, error) {
list, err := a.GetDeviceList()
if err != nil {
return nil, err
}
for _, path := range list {
dev, err := device.NewDevice1(path)
if err != nil {
return nil, err
}
if strings.Contains(dev.Properties.Name, "Timeular") {
return dev, nil
}
}
return nil, errors.New("Timeular not found")
}
func (bm *BluetoothManager) Run() {
for {
err := bm.connectAndRun()
if err != nil {
log.Fatalf("connection error: %s", err)
}
}
}
func (bm *BluetoothManager) connectAndRun() error {
log.Println("Trying to connect to the Timeular")
a, err := api.GetDefaultAdapter()
if err != nil {
return err
}
dev, err := getTimeularDevice(a)
if err != nil {
return err
}
if err := dev.Connect(); err != nil {
return err
}
devWatch, err := dev.WatchProperties()
if err != nil {
return err
}
char, err := dev.GetCharByUUID(orientationCharacteristic)
if err != nil {
return err
}
val, err := char.ReadValue(nil)
if err != nil {
return err
}
go bm.OnOrientationChanged(int(val[0]))
charWatch, err := char.WatchProperties()
if err != nil {
return err
}
if err := char.StartNotify(); err != nil {
return err
}
log.Println("Subscribed to Timeular side changes")
tick := time.NewTicker(1 * time.Minute)
defer tick.Stop()
for {
select {
case prop := <-charWatch:
if prop == nil {
return errors.New("No property received")
}
if prop.Name != "Value" {
continue
}
val = prop.Value.([]byte)
go bm.OnOrientationChanged(int(val[0]))
case prop := <-devWatch:
if prop == nil {
return errors.New("No property received")
}
if prop.Name == "Connected" {
connected := prop.Value.(bool)
if !connected {
log.Println("Connection lost")
return nil
}
}
case <-tick.C:
connected, err := dev.GetConnected()
if err != nil {
return err
}
if !connected {
log.Println("tick: Connection lost")
return nil
}
}
}
}