-
Notifications
You must be signed in to change notification settings - Fork 0
/
chip.go
79 lines (62 loc) · 1.82 KB
/
chip.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 chip
import (
"errors"
"tinygo.org/x/bluetooth"
)
type Robot struct {
device *bluetooth.Device
receive *bluetooth.DeviceService
receiveNotify *bluetooth.DeviceCharacteristic
send *bluetooth.DeviceService
sendData *bluetooth.DeviceCharacteristic
buf []byte
}
var (
// BLE services
chipReceiveDataService = bluetooth.New16BitUUID(0xffe0)
chipReceiveDataNotifyCharacteristic = bluetooth.New16BitUUID(0xffe4)
chipSendDataService = bluetooth.New16BitUUID(0xffe5)
chipSendDataWriteCharacteristic = bluetooth.New16BitUUID(0xffe9)
)
// NewRobot creates a new CHiP robot.
func NewRobot(dev *bluetooth.Device) *Robot {
r := &Robot{
device: dev,
buf: make([]byte, 255),
}
return r
}
func (r *Robot) Start() (err error) {
srvcs, err := r.device.DiscoverServices([]bluetooth.UUID{
chipReceiveDataService,
chipSendDataService,
})
if err != nil || len(srvcs) == 0 {
return errors.New("could not find services")
}
r.receive = &srvcs[0]
r.send = &srvcs[1]
println("found chip receive service", r.receive.UUID().String())
println("found chip send service", r.send.UUID().String())
chars, err := r.receive.DiscoverCharacteristics([]bluetooth.UUID{
chipReceiveDataNotifyCharacteristic,
})
if err != nil || len(chars) == 0 {
return errors.New("could not find chip receive characteristic")
}
r.receiveNotify = &chars[0]
chars, err = r.send.DiscoverCharacteristics([]bluetooth.UUID{
chipSendDataWriteCharacteristic,
})
if err != nil || len(chars) == 0 {
return errors.New("could not find chip write characteristic")
}
r.sendData = &chars[0]
return
}
// Action performs one of the actions of the Chip robot.
func (r *Robot) Action(action ActionType) (err error) {
buf := []byte{Action, uint8(action)}
_, err = r.sendData.WriteWithoutResponse(buf)
return
}