-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdevice.go
79 lines (69 loc) · 2.23 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
package main
import (
"log"
"time"
"github.com/currantlabs/ble"
"github.com/currantlabs/ble/linux"
"golang.org/x/net/context"
)
var (
service = ble.MustParse("ebe0ccb0-7a0a-4b0c-8a1a-6ff2997da3a6")
)
var (
characteristix = map[uint8]ble.UUID{
36: ble.MustParse("ebe0ccc1-7a0a-4b0c-8a1a-6ff2997da3a6"),
38: ble.MustParse("00002902-0000-1000-8000-00805f9b34fb"),
}
)
// Device represents a BLE Device
type Device struct {
Name string
Addr string
Client ble.Client
}
// Connect to a Device
func (d *Device) Connect(host *linux.Device) (err error) {
ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), 1*time.Minute))
d.Client, err = host.Dial(ctx, ble.NewAddr(d.Addr))
return err
}
// Disconnect from a Device
func (d *Device) Disconnect() error {
return d.Client.CancelConnection()
}
// RegisterHandler registers a Temperature|Humidity handler
func (d *Device) RegisterHandler(mqtt MQTT) {
// Thanks to other developers
// Write to handle `0x0038` with value `0x0100` is required to trigger notification of humidity|temperature
log.Printf("[Device:RegisterHandler:%s] Publish", d.Name)
d.pub(characteristix[38], []byte{0x01, 0x00})
log.Printf("[Device:RegisterHandler:%s] Subscribe", d.Name)
d.sub(characteristix[36], mqtt)
}
func (d *Device) pub(c ble.UUID, b []byte) {
log.Printf("[Device:pub:%s] Handler: %s (%x)", d.Name, c.String(), b)
if p, err := d.Client.DiscoverProfile(true); err == nil {
if u := p.Find(ble.NewCharacteristic(c)); u != nil {
c := u.(*ble.Characteristic)
if err := d.Client.WriteCharacteristic(c, b, false); err != nil {
log.Print(err)
}
}
}
}
func (d *Device) sub(c ble.UUID, mqtt MQTT) {
log.Printf("[Device:sub:%s] Handler: %s", d.Name, c.String())
if p, err := d.Client.DiscoverProfile(true); err == nil {
if u := p.Find(ble.NewCharacteristic(c)); u != nil {
c := u.(*ble.Characteristic)
// If this Characteristic suports notifications and there's a CCCD
// Then subscribe to it
if (c.Property&ble.CharNotify) != 0 && c.CCCD != nil {
log.Printf("[Device:sub:%s] (%04x) Registering Temperature|Humidity Handler", d.Name, c.Handle)
if err := d.Client.Subscribe(c, false, handlerPublisher(mqtt, d.Name)); err != nil {
log.Print(err)
}
}
}
}
}