/
device.go
315 lines (271 loc) · 7.49 KB
/
device.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright ©2022 The aranet4 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package aranet4
import (
"bytes"
"encoding/binary"
// "errors"
"fmt"
// "io"
"time"
// "github.com/muka/go-bluetooth/bluez/profile/adapter"
// "github.com/muka/go-bluetooth/bluez/profile/device"
"tinygo.org/x/bluetooth"
)
type Device struct {
addr string
dev *bluetooth.Device
scan bluetooth.ScanResult
svc *bluetooth.DeviceService
}
func New(addr string) (*Device, error) {
ad := bluetooth.DefaultAdapter
err := ad.Enable()
if err != nil {
return nil, fmt.Errorf("could not set default adapter power: %w", err)
}
var foundDevice bluetooth.ScanResult
err = ad.Scan(func(adapter *bluetooth.Adapter, result bluetooth.ScanResult) {
if (result.Address.String() != addr) {
return
}
foundDevice = result
// Stop the scan.
adapter.StopScan()
})
if err != nil {
return nil, fmt.Errorf("could not start a scan %q: %w", addr, err)
}
dev, err := ad.Connect(foundDevice.Address, bluetooth.ConnectionParams{})
if err != nil {
return nil, fmt.Errorf("could not connect to %q: %w", addr, err)
}
return &Device{addr: addr, dev: dev}, nil
}
func (dev *Device) Close() error {
if dev.dev == nil {
return nil
}
err := dev.dev.Disconnect()
if err != nil {
return fmt.Errorf("could not disconnect: %w", err)
}
return nil
}
func (dev *Device) Name() (string, error) {
return dev.scan.LocalName(), nil
}
func toUUID(str string) bluetooth.UUID {
u, _ := bluetooth.ParseUUID(str)
return u
}
func (dev *Device) getCharByUUID(uuidstr string) (*bluetooth.DeviceCharacteristic, error) {
uuid := toUUID(uuidstr)
if dev.svc == nil {
svcs, err := dev.dev.DiscoverServices(nil)
if err != nil {
return nil, fmt.Errorf("could not find service: %w", err)
}
for _, s := range svcs {
if s.UUID() == toUUID(uuidDeviceService) {
dev.svc = &s
}
}
}
if dev.svc == nil {
return nil, fmt.Errorf("no service found", nil)
}
chars, err := dev.svc.DiscoverCharacteristics([]bluetooth.UUID{uuid})
if err != nil {
return nil, fmt.Errorf("could not get characteristic %q: %w", uuidCommonReadSWRevision, err)
}
var foundChar bluetooth.DeviceCharacteristic
for _, char := range chars {
if char.UUID() == uuid {
foundChar = char
}
}
return &foundChar, nil
}
func (dev *Device) Version() (string, error) {
char, err := dev.getCharByUUID(uuidCommonReadSWRevision)
if err != nil {
return "", fmt.Errorf("could not get characteristic %q: %w", uuidCommonReadSWRevision, err)
}
raw := make([]byte, 255)
if n, err := char.Read(raw); err != nil || n == 0 {
return "", fmt.Errorf("could not read device name: %w", err)
}
return string(raw), nil
}
func (dev *Device) Read() (Data, error) {
var data Data
c, err := dev.getCharByUUID(uuidReadAll)
if err != nil {
return data, fmt.Errorf("could not get characteristic %q: %w", uuidReadAll, err)
}
raw := make([]byte, 255)
if n, err := c.Read(raw); err != nil || n == 0 {
return data, fmt.Errorf("could not get value: %w", err)
}
dec := newDecoder(bytes.NewReader(raw))
dec.readCO2(&data.CO2)
dec.readT(&data.T)
dec.readP(&data.P)
dec.readH(&data.H)
dec.readBattery(&data.Battery)
dec.readQuality(&data.Quality)
dec.readInterval(&data.Interval)
dec.readTime(&data.Time)
if dec.err != nil {
return data, fmt.Errorf("could not decode data sample: %w", dec.err)
}
return data, nil
}
func (dev *Device) NumData() (int, error) {
c, err := dev.getCharByUUID(uuidReadTotalReadings)
if err != nil {
return 0, fmt.Errorf("could not get characteristic %q: %w", uuidReadTotalReadings, err)
}
raw := make([]byte, 255)
if n, err := c.Read(raw); err != nil || n == 0 {
return 0, fmt.Errorf("could not get value: %w", err)
}
return int(binary.LittleEndian.Uint16(raw)), nil
}
func (dev *Device) Since() (time.Duration, error) {
c, err := dev.getCharByUUID(uuidReadSecondsSinceUpdate)
if err != nil {
return 0, fmt.Errorf("could not get characteristic %q: %w", uuidReadSecondsSinceUpdate, err)
}
raw := make([]byte, 255)
if n, err := c.Read(raw); err != nil || n == 0 {
return 0, fmt.Errorf("could not get value: %w", err)
}
var (
ago time.Duration
dec = newDecoder(bytes.NewReader(raw))
)
err = dec.readInterval(&ago)
if err != nil {
return 0, fmt.Errorf("could not decode interval value %q: %w", raw, err)
}
return ago, nil
}
func (dev *Device) Interval() (time.Duration, error) {
c, err := dev.getCharByUUID(uuidReadInterval)
if err != nil {
return 0, fmt.Errorf("could not get characteristic %q: %w", uuidReadInterval, err)
}
raw := make([]byte, 255)
if n, err := c.Read(raw); err != nil || n == 0 {
return 0, fmt.Errorf("could not get value: %w", err)
}
var (
ago time.Duration
dec = newDecoder(bytes.NewReader(raw))
)
err = dec.readInterval(&ago)
if err != nil {
return 0, fmt.Errorf("could not decode interval value %q: %w", raw, err)
}
return ago, nil
}
// This doesnt really work right now.
func (dev *Device) ReadAll() ([]Data, error) {
now := time.Now().UTC()
ago, err := dev.Since()
if err != nil {
return nil, fmt.Errorf("could not get last measurement update: %w", err)
}
delta, err := dev.Interval()
if err != nil {
return nil, fmt.Errorf("could not get sampling: %w", err)
}
n, err := dev.NumData()
if err != nil {
return nil, fmt.Errorf("could not get total number of samples: %w", err)
}
out := make([]Data, n)
for _, id := range []byte{paramT, paramH, paramP, paramCO2} {
err = dev.readN(out, id)
if err != nil {
return nil, fmt.Errorf("could not read param=%d: %w", id, err)
}
}
beg := now.Add(-ago - time.Duration(n-1)*delta)
for i := range out {
out[i].Battery = -1 // no battery information when fetching history.
out[i].Quality = qualityFrom(out[i].CO2)
out[i].Interval = delta
out[i].Time = beg.Add(time.Duration(i) * delta)
}
return out, nil
}
// type btOptions = map[string]interface{}
// var opReqCmd = btOptions{
// "type": "request",
// }
func (dev *Device) readN(dst []Data, id byte) error {
{
cmd := []byte{
0x82, 0x00, 0x00, 0x00, 0x01, 0x00, 0xff, 0xff,
}
cmd[1] = id
binary.LittleEndian.PutUint16(cmd[4:], 0x0001)
binary.LittleEndian.PutUint16(cmd[6:], 0xffff)
c, err := dev.getCharByUUID(uuidWriteCmd)
if err != nil {
return fmt.Errorf("could not get characteristic %q: %w", uuidWriteCmd, err)
}
_, err = c.WriteWithoutResponse(cmd)
if err != nil {
return fmt.Errorf("could not write command: %w", err)
}
}
c, err := dev.getCharByUUID(uuidReadTimeSeries)
if err != nil {
return fmt.Errorf("could not get characteristic %q: %w", uuidReadTimeSeries, err)
}
done := make(chan struct{})
var errLoop error
err = c.EnableNotifications(func(p []byte) {
param := p[0]
fmt.Println("param")
fmt.Println(param)
if param != id {
errLoop = fmt.Errorf("invalid parameter: got=0x%x, want=0x%x", param, id)
return
}
idx := int(binary.LittleEndian.Uint16(p[1:]) - 1)
cnt := int(p[3])
if cnt == 0 {
close(done)
return
}
max := min(idx+cnt, len(dst)) // a new sample may have appeared
dec := newDecoder(bytes.NewReader(p[4:]))
for i := idx; i < max; i++ {
err := dec.readField(id, &dst[i])
if err != nil {
errLoop = fmt.Errorf("could not read param=%d, idx=%d: %w", id, i, err)
return
}
}
return
})
if err != nil {
return fmt.Errorf("could not watch props: %w", err)
}
if errLoop != nil {
return fmt.Errorf("could not read notified data: %w", errLoop)
}
return nil
}
func min(a, b int) int {
if a < b {
return a
}
return b
}