-
Notifications
You must be signed in to change notification settings - Fork 0
/
nrg_linux.go
95 lines (79 loc) · 1.86 KB
/
nrg_linux.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
package ble
import (
"errors"
"fmt"
"strings"
"time"
"github.com/muka/go-bluetooth/api"
"github.com/muka/go-bluetooth/bluez/profile/adapter"
"github.com/muka/go-bluetooth/bluez/profile/agent"
"github.com/muka/go-bluetooth/bluez/profile/device"
)
func FindDevice(a *adapter.Adapter1, hwaddr string, timeout time.Duration) (*device.Device1, error) {
dev, err := Discover(a, hwaddr, timeout)
if err != nil {
return nil, err
}
if dev == nil {
return nil, errors.New("device not found, is it advertising?")
}
return dev, nil
}
func Discover(a *adapter.Adapter1, hwaddr string, timeout time.Duration) (*device.Device1, error) {
err := a.FlushDevices()
if err != nil {
return nil, err
}
discovery, cancel, err := api.Discover(a, nil)
if err != nil {
return nil, err
}
timer := time.NewTimer(timeout)
for {
select {
case ev := <-discovery:
dev, err := device.NewDevice1(ev.Path)
if err != nil {
return nil, err
}
if dev == nil || dev.Properties == nil {
continue
}
p := dev.Properties
if p.Address != hwaddr {
continue
}
cancel()
return dev, nil
case <-timer.C:
cancel()
return nil, errors.New("discovery timeout exceeded")
}
}
}
func Connect(dev *device.Device1, ag *agent.SimpleAgent, adapterID string) error {
props, err := dev.GetProperties()
if err != nil {
return fmt.Errorf("Failed to load props: %s", err)
}
if props.Connected {
return nil
}
if !props.Paired || !props.Trusted {
if err := dev.Pair(); err != nil {
return fmt.Errorf("Pair failed: %s", err)
}
if err := agent.SetTrusted(adapterID, dev.Path()); err != nil {
return fmt.Errorf("Set trusted failed: %s", err)
}
}
if !props.Connected {
err = dev.Connect()
if err != nil {
if !strings.Contains(err.Error(), "Connection refused") {
return fmt.Errorf("Connect failed: %s", err)
}
}
}
return nil
}