-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbluetooth.go
65 lines (54 loc) · 1.31 KB
/
bluetooth.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
// +build !windows
package main
import (
"strings"
"sync"
"time"
log "github.com/cihub/seelog"
"github.com/schollz/gatt"
)
var bdata map[string]map[string]interface{}
var bdatasync sync.Mutex
func onStateChanged(d gatt.Device, s gatt.State) {
switch s {
case gatt.StatePoweredOn:
log.Debug("gatt powered on")
return
default:
d.StopScanning()
}
}
func onPeriphDiscovered(p gatt.Peripheral, a *gatt.Advertisement, rssi int) {
bdatasync.Lock()
defer bdatasync.Unlock()
bdata["bluetooth"][strings.ToLower(p.ID())] = rssi
}
var d gatt.Device
var bluetoothInitiated bool
func scanBluetooth(out chan map[string]map[string]interface{}) (err error) {
log.Debug("scanning bluetooth")
bdatasync.Lock()
bdata = make(map[string]map[string]interface{})
bdata["bluetooth"] = make(map[string]interface{})
bdatasync.Unlock()
if !bluetoothInitiated {
log.Debug("initiating bluetooth")
d, err = gatt.NewDevice()
if err != nil {
log.Debugf("Failed to open device, err: %s", err.Error())
out <- bdata
return
}
d.Handle(gatt.PeripheralDiscovered(onPeriphDiscovered))
d.Init(onStateChanged)
bluetoothInitiated = true
}
d.Scan([]gatt.UUID{}, false)
select {
case <-time.After(time.Duration(scanSeconds) * time.Second):
log.Debug("bluetooth scan finished")
}
d.StopScanning()
out <- bdata
return
}