Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

introduce peripheralPool #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
97 changes: 82 additions & 15 deletions hrm.go
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ import (
"fmt" "fmt"
"log" "log"
"os" "os"
"os/signal"
"strings" "strings"
"sync"
"time"


"github.com/cfreeman/gatt" "github.com/cfreeman/gatt"
"github.com/cfreeman/gatt/examples/option" "github.com/cfreeman/gatt/examples/option"
Expand All @@ -46,7 +49,7 @@ func onStateChanged(d gatt.Device, s gatt.State) {
} }


// onPeriphDiscovered is called when a new BLE peripheral is detected by the device. // onPeriphDiscovered is called when a new BLE peripheral is detected by the device.
func onPeriphDiscovered(p gatt.Peripheral, a *gatt.Advertisement, rssi int, deviceID string) { func onPeriphDiscovered(p gatt.Peripheral, a *gatt.Advertisement, rssi int, deviceID string, pPool *peripheralPool) {
if strings.ToUpper(p.ID()) != strings.ToUpper(deviceID) { if strings.ToUpper(p.ID()) != strings.ToUpper(deviceID) {
return // This is not the peripheral we're looking for, keep looking. return // This is not the peripheral we're looking for, keep looking.
} }
Expand All @@ -62,13 +65,16 @@ func onPeriphDiscovered(p gatt.Peripheral, a *gatt.Advertisement, rssi int, devi
log.Println("INFO: Manufacturer Data =", a.ManufacturerData) log.Println("INFO: Manufacturer Data =", a.ManufacturerData)
log.Println("INFO: Service Data =", a.ServiceData) log.Println("INFO: Service Data =", a.ServiceData)
log.Println() log.Println()

// Connect to the peripheral once we have found it if it's not already connected.
// Connect to the peripheral once we have found it. _, err := pPool.Add(p.ID())
if err != nil {
return
}
p.Device().Connect(p) p.Device().Connect(p)
} }


// onPeriphConnected is called when we connect to a BLE peripheral. // onPeriphConnected is called when we connect to a BLE peripheral.
func onPeriphConnected(p gatt.Peripheral, done chan bool, err error) { func onPeriphConnected(p gatt.Peripheral, err error, pPool *peripheralPool) {
log.Println("INFO:CONNECTED") log.Println("INFO:CONNECTED")
log.Println() log.Println()


Expand All @@ -85,6 +91,18 @@ func onPeriphConnected(p gatt.Peripheral, done chan bool, err error) {
return return
} }


ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
done, err := pPool.Get(p.ID())
if err != nil {
log.Printf("ERROR: %s\n", err)
return
}
for {
select {
case <-done:
return
case <-ticker.C:
for _, s := range ss { for _, s := range ss {
// Get the heart rate measurement characteristic which is identified by the UUID: \x2a37 // Get the heart rate measurement characteristic which is identified by the UUID: \x2a37
cs, err := p.DiscoverCharacteristics([]gatt.UUID{gatt.MustParseUUID("2a37")}, s) cs, err := p.DiscoverCharacteristics([]gatt.UUID{gatt.MustParseUUID("2a37")}, s)
Expand Down Expand Up @@ -134,15 +152,15 @@ func onPeriphConnected(p gatt.Peripheral, done chan bool, err error) {
} }
log.Println() log.Println()
} }
}
}


// Wait till we are disconnected from the HRM.
<-done
} }


// onPeriphDisconnected is called when a BLE Peripheral is disconnected. // onPeriphDisconnected is called when a BLE Peripheral is disconnected.
func onPeriphDisconnected(p gatt.Peripheral, done chan bool, err error) { func onPeriphDisconnected(p gatt.Peripheral, err error, pPool *peripheralPool) {
log.Println("INFO: Disconnected from BLE peripheral.") log.Println("INFO: Disconnected from BLE peripheral.")
close(done) pPool.RemoveAndNotify(p.ID())
} }


// pollHeartRateMonitor connects to the BLE heart rate monitor at deviceID and // pollHeartRateMonitor connects to the BLE heart rate monitor at deviceID and
Expand All @@ -159,29 +177,78 @@ func main() {
flag.StringVar(&deviceID, "deviceID", "h", "The ID of the bluetooth heart rate monitor.") flag.StringVar(&deviceID, "deviceID", "h", "The ID of the bluetooth heart rate monitor.")
flag.Parse() flag.Parse()


done := make(chan bool)

d, err := gatt.NewDevice(option.DefaultClientOptions...) d, err := gatt.NewDevice(option.DefaultClientOptions...)
if err != nil { if err != nil {
log.Printf("ERROR: Unable to get bluetooth device.") log.Printf("ERROR: Unable to get bluetooth device.")
return return
} }


pPool := newPeripheralPool()

// Register handlers. // Register handlers.
d.Handle( d.Handle(
gatt.PeripheralDiscovered(func(p gatt.Peripheral, a *gatt.Advertisement, rssi int) { gatt.PeripheralDiscovered(func(p gatt.Peripheral, a *gatt.Advertisement, rssi int) {
onPeriphDiscovered(p, a, rssi, deviceID) onPeriphDiscovered(p, a, rssi, deviceID, pPool)
}), }),
gatt.PeripheralConnected(func(p gatt.Peripheral, err error) { gatt.PeripheralConnected(func(p gatt.Peripheral, err error) {
onPeriphConnected(p, done, err) onPeriphConnected(p, err, pPool)
}), }),
gatt.PeripheralDisconnected(func(p gatt.Peripheral, err error) { gatt.PeripheralDisconnected(func(p gatt.Peripheral, err error) {
onPeriphDisconnected(p, done, err) onPeriphDisconnected(p, err, pPool)
}), }),
) )


d.Init(onStateChanged) d.Init(onStateChanged)


// Wait till we are disconnected from the HRM. // Listen for the interrupt signal (Ctrl+C)
<-done interruptCh := make(chan os.Signal, 1)
signal.Notify(interruptCh, os.Interrupt)

// Wait till the program is interrupted
<-interruptCh
}

type peripheralPool struct {
pool map[string]chan bool
mu sync.Mutex
}

func newPeripheralPool() *peripheralPool {
p := &peripheralPool{}
p.pool = make(map[string]chan bool)
return p
}

func (p *peripheralPool) Add(pID string) (<-chan bool, error) {
p.mu.Lock()
defer p.mu.Unlock()
_, ok := p.pool[pID]
if ok {
return nil, fmt.Errorf("peripheralPool.Add: peripheral with the %v ID already exists", pID)
}
done := make(chan bool)
p.pool[pID] = done
return done, nil
}

func (p *peripheralPool) Get(pID string) (<-chan bool, error) {
p.mu.Lock()
defer p.mu.Unlock()
done, ok := p.pool[pID]
if !ok {
return nil, fmt.Errorf("peripheralPool.Get: peripheral with the %v ID not found", pID)
}
return done, nil
}

func (p *peripheralPool) RemoveAndNotify(pID string) error {
p.mu.Lock()
defer p.mu.Unlock()
done, ok := p.pool[pID]
if !ok {
return fmt.Errorf("peripheralPool.RemoveAndNotify: peripheral with the %v ID not found", pID)
}
delete(p.pool, pID)
close(done)
return nil
} }