Skip to content

Commit 458028f

Browse files
committed
examples: add channelscan example that shows use of goroutines and channels
Signed-off-by: deadprogram <[email protected]>
1 parent 9daf720 commit 458028f

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

examples/channelscan/main.go

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// This example program shows using Go routines and channels to coordinate
2+
// BLE scanning.
3+
//
4+
// The first Go routine starts scanning using the BLE adaptor. When it finds
5+
// a new device, it puts the information into a channel so it can be displayed.
6+
//
7+
// The second Go routine is a ticker that puts a "true" value into a channel every 3 seconds.
8+
//
9+
// The main function uses a select{} statement to wait until one of the two channels is unblocked
10+
// by receiving data. If a new device is found, the boolean variable named "found" will
11+
// be set to true, so that the timeout is reset for each 3 second period.
12+
//
13+
package main
14+
15+
import (
16+
"time"
17+
18+
"tinygo.org/x/bluetooth"
19+
)
20+
21+
var (
22+
adapter = bluetooth.DefaultAdapter
23+
devices = make(chan *bluetooth.ScanResult, 1)
24+
ticker = make(chan bool, 1)
25+
found = true
26+
)
27+
28+
func main() {
29+
// Enable BLE interface.
30+
if err := adapter.Enable(); err != nil {
31+
panic("failed to enable adaptor:" + err.Error())
32+
}
33+
34+
// Start scanning
35+
go performScan()
36+
37+
// Start timeout ticker
38+
go startTicker()
39+
40+
// Wait for devices to be scanned
41+
for {
42+
select {
43+
case device := <-devices:
44+
found = true
45+
println("found device:", device.Address.String(), device.RSSI, device.LocalName())
46+
case <-ticker:
47+
if !found {
48+
println("no devices found in last 3 seconds...")
49+
}
50+
found = false
51+
}
52+
}
53+
}
54+
55+
func performScan() {
56+
println("scanning...")
57+
58+
err := adapter.Scan(func(adapter *bluetooth.Adapter, device bluetooth.ScanResult) {
59+
devices <- &device
60+
})
61+
if err != nil {
62+
panic("failed to scan:" + err.Error())
63+
}
64+
}
65+
66+
func startTicker() {
67+
for {
68+
time.Sleep(3 * time.Second)
69+
ticker <- true
70+
}
71+
72+
}

0 commit comments

Comments
 (0)