bluetooth/examples/heartrate/main.go

60 lines
1.6 KiB
Go
Raw Normal View History

2019-06-02 20:12:36 +03:00
package main
import (
"time"
"github.com/tinygo-org/bluetooth"
2019-06-02 20:12:36 +03:00
)
var adapter = bluetooth.DefaultAdapter
// TODO: use atomics to access this value.
var heartRate uint8 = 75 // 75bpm
2019-06-02 20:12:36 +03:00
func main() {
println("starting")
must("enable BLE stack", adapter.Enable())
adv := adapter.DefaultAdvertisement()
must("config adv", adv.Configure(bluetooth.AdvertisementOptions{
LocalName: "Go HRS",
ServiceUUIDs: []bluetooth.UUID{bluetooth.New16BitUUID(0x2A37)},
Interval: bluetooth.NewAdvertisementInterval(100),
}))
2019-06-02 20:12:36 +03:00
must("start adv", adv.Start())
var heartRateMeasurement bluetooth.Characteristic
2019-06-02 20:12:36 +03:00
must("add service", adapter.AddService(&bluetooth.Service{
UUID: bluetooth.New16BitUUID(0x180D), // Heart Rate
Characteristics: []bluetooth.CharacteristicConfig{
{
Handle: &heartRateMeasurement,
UUID: bluetooth.New16BitUUID(0x2A37), // Heart Rate Measurement
Value: []byte{0, heartRate},
Flags: bluetooth.CharacteristicReadPermission | bluetooth.CharacteristicWritePermission,
WriteEvent: func(client bluetooth.Connection, offset int, value []byte) {
if offset != 0 || len(value) < 2 {
return
}
if value[1] != 0 { // avoid divide by zero
heartRate = value[1]
println("heart rate is now:", heartRate)
}
},
2019-06-02 20:12:36 +03:00
},
},
}))
nextBeat := time.Now()
2019-06-02 20:12:36 +03:00
for {
nextBeat = nextBeat.Add(time.Minute / time.Duration(heartRate))
println("tick", time.Now().Format("04:05.000"))
time.Sleep(nextBeat.Sub(time.Now()))
2019-06-02 20:12:36 +03:00
}
}
func must(action string, err error) {
if err != nil {
panic("failed to " + action + ": " + err.Error())
}
}