Skip to content

Commit 58d88cd

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

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

examples/channelscan/main.go

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
package main
13+
14+
import (
15+
"time"
16+
17+
"tinygo.org/x/bluetooth"
18+
)
19+
20+
var (
21+
adapter = bluetooth.DefaultAdapter
22+
devices = make(chan bluetooth.ScanResult, 1)
23+
ticker = make(chan bool, 1)
24+
found = true
25+
)
26+
27+
func main() {
28+
// Enable BLE interface.
29+
if err := adapter.Enable(); err != nil {
30+
panic("failed to enable adaptor:" + err.Error())
31+
}
32+
33+
// Start scanning
34+
go performScan()
35+
36+
// Start timeout ticker
37+
go startTicker()
38+
39+
// Wait for devices to be scanned
40+
for {
41+
select {
42+
case device := <-devices:
43+
found = true
44+
println("found device:", device.Address.String(), device.RSSI, device.LocalName())
45+
case <-ticker:
46+
if !found {
47+
println("no devices found in last 3 seconds...")
48+
}
49+
found = false
50+
}
51+
}
52+
}
53+
54+
func performScan() {
55+
println("scanning...")
56+
57+
err := adapter.Scan(func(adapter *bluetooth.Adapter, device bluetooth.ScanResult) {
58+
devices <- device
59+
})
60+
if err != nil {
61+
panic("failed to scan:" + err.Error())
62+
}
63+
}
64+
65+
func startTicker() {
66+
for {
67+
time.Sleep(3 * time.Second)
68+
ticker <- true
69+
}
70+
71+
}

0 commit comments

Comments
 (0)