Add cancel functions to battery level and heart rate

This commit is contained in:
Elara 2021-10-22 21:26:33 -07:00
parent 45baea1048
commit 53aa6f8a0c
1 changed files with 38 additions and 20 deletions

View File

@ -383,70 +383,88 @@ func (i *Device) HeartRate() (uint8, error) {
return uint8(heartRate[1]), nil
}
func (i *Device) WatchHeartRate() (<-chan uint8, error) {
func (i *Device) WatchHeartRate() (<-chan uint8, func(), error) {
if !i.device.Properties.Connected {
return make(<-chan uint8), nil
return make(<-chan uint8), nil, nil
}
// Start notifications on heart rate characteristic
err := i.heartRateChar.StartNotify()
if err != nil {
return nil, err
return nil, nil, err
}
// Watch characteristics of heart rate characteristic
ch, err := i.heartRateChar.WatchProperties()
if err != nil {
return nil, err
return nil, nil, err
}
out := make(chan uint8, 2)
currentHeartRate, err := i.HeartRate()
if err != nil {
return nil, err
return nil, nil, err
}
out <- currentHeartRate
cancel, done := cancelFunc()
go func() {
// For every event
for event := range ch {
// If value changed
if event.Name == "Value" {
// Send heart rate to channel
out <- uint8(event.Value.([]byte)[1])
select {
case <-done:
close(out)
close(done)
i.heartRateChar.StopNotify()
return
default:
// If value changed
if event.Name == "Value" {
// Send heart rate to channel
out <- uint8(event.Value.([]byte)[1])
}
}
}
}()
return out, nil
return out, cancel, nil
}
func (i *Device) WatchBatteryLevel() (<-chan uint8, error) {
func (i *Device) WatchBatteryLevel() (<-chan uint8, func(), error) {
if !i.device.Properties.Connected {
return make(<-chan uint8), nil
return make(<-chan uint8), nil, nil
}
// Start notifications on heart rate characteristic
err := i.battLevelChar.StartNotify()
if err != nil {
return nil, err
return nil, nil, err
}
// Watch characteristics of heart rate characteristic
ch, err := i.battLevelChar.WatchProperties()
if err != nil {
return nil, err
return nil, nil, err
}
out := make(chan uint8, 2)
currentBattLevel, err := i.BatteryLevel()
if err != nil {
return nil, err
return nil, nil, err
}
out <- currentBattLevel
cancel, done := cancelFunc()
go func() {
// For every event
for event := range ch {
// If value changed
if event.Name == "Value" {
// Send heart rate to channel
out <- uint8(event.Value.([]byte)[0])
select {
case <-done:
close(out)
close(done)
i.battLevelChar.StopNotify()
return
default:
// If value changed
if event.Name == "Value" {
// Send heart rate to channel
out <- uint8(event.Value.([]byte)[0])
}
}
}
}()
return out, nil
return out, cancel, nil
}
func (i *Device) WatchStepCount() (<-chan uint32, func(), error) {