-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathruuvitag.go
125 lines (112 loc) · 2.49 KB
/
ruuvitag.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
package ruuvitag
import (
"encoding/binary"
"fmt"
"sync"
"time"
"github.com/peknur/gatt"
)
var manufacturerDataID uint16 = 0x0499
// Measurement represents RuuviTag sensor readings
type Measurement interface {
DeviceID() string
Format() uint8
Humidity() float32
Temperature() float32
Pressure() uint32
AccelerationX() float32
AccelerationY() float32
AccelerationZ() float32
BatteryVoltage() float32
TXPower() int8
MovementCounter() uint8
Sequence() uint16
Timestamp() time.Time
}
// NewMeasurement creates Measurement from ble manufacturer data
func NewMeasurement(ID string, data []byte) (Measurement, error) {
// switch data format
switch data[2] {
case 3:
return NewDataFormat3(ID, data)
case 5:
return NewDataFormat5(ID, data)
}
return nil, fmt.Errorf("format '%d' if not supported", data[2])
}
func isRuuviDevice(data []byte) bool {
if len(data) < 2 {
return false
}
return binary.LittleEndian.Uint16(data[0:2]) == manufacturerDataID
}
// Scanner handles ble scanning
type Scanner interface {
Start() chan Measurement
Stop()
}
// scanner implements Scanner
type scanner struct {
device gatt.Device
output chan Measurement
running bool
started time.Time
state gatt.State
mu sync.Mutex
}
var instance *scanner
// Stop Scanner
func (s *scanner) Stop() {
s.mu.Lock()
defer s.mu.Unlock()
if s.running == true {
s.device.StopScanning()
s.running = false
close(s.output)
}
}
// Start Scanner
func (s *scanner) Start() chan Measurement {
s.mu.Lock()
defer s.mu.Unlock()
if s.running == true {
return s.output
}
s.device.Handle(gatt.PeripheralDiscovered(func(p gatt.Peripheral, a *gatt.Advertisement, rssi int) {
if isRuuviDevice(a.ManufacturerData) {
data, err := NewMeasurement(p.ID(), a.ManufacturerData)
if err == nil {
s.output <- data
}
}
}))
s.device.Init(func(d gatt.Device, state gatt.State) {
switch state {
case gatt.StatePoweredOn:
d.Scan([]gatt.UUID{}, true)
default:
s.Stop()
}
s.state = state
})
s.started = time.Now()
s.running = true
return s.output
}
var once sync.Once
// OpenScanner takes output buffer size as parameter
// and creates new Scanner singleton
func OpenScanner(bufferSize int) (Scanner, error) {
var err error
once.Do(func() {
var device gatt.Device
device, err = gatt.NewDevice([]gatt.Option{
gatt.LnxMaxConnections(1),
gatt.LnxDeviceID(-1, true),
}...)
if err == nil {
instance = &scanner{device: device, output: make(chan Measurement, bufferSize)}
}
})
return instance, err
}