prototooth/gap_darwin.go
Ron Evans a620bacdb8 macos: able to retrieve some of the info when scanning
Signed-off-by: Ron Evans <ron@hybridgroup.com>
2020-09-02 08:37:04 +02:00

60 lines
1.5 KiB
Go

package bluetooth
import (
"errors"
"github.com/JuulLabs-OSS/cbgo"
)
// Scan starts a BLE scan. It is stopped by a call to StopScan. A common pattern
// is to cancel the scan when a particular device has been found.
func (a *Adapter) Scan(callback func(*Adapter, ScanResult)) (err error) {
if callback == nil {
return errors.New("must provide callback to Scan function")
}
if a.cancelChan != nil {
return errors.New("already calling Scan function")
}
a.peripheralFoundHandler = callback
// Channel that will be closed when the scan is stopped.
// Detecting whether the scan is stopped can be done by doing a non-blocking
// read from it. If it succeeds, the scan is stopped.
cancelChan := make(chan struct{})
a.cancelChan = cancelChan
a.cm.Scan(nil, &cbgo.CentralManagerScanOpts{
AllowDuplicates: true,
})
for {
// Check whether the scan is stopped. This is necessary to avoid a race
// condition between the signal channel and the cancelScan channel when
// the callback calls StopScan() (no new callbacks may be called after
// StopScan is called).
select {
case <-cancelChan:
// stop scanning here?
return nil
default:
}
}
}
// StopScan stops any in-progress scan. It can be called from within a Scan
// callback to stop the current scan. If no scan is in progress, an error will
// be returned.
func (a *Adapter) StopScan() error {
if a.cancelChan != nil {
return errors.New("already calling Scan function")
}
a.cm.StopScan()
close(a.cancelChan)
a.cancelChan = nil
return nil
}