@@ -16,6 +16,7 @@ import (
1616import "C"
1717
1818var errAlreadyConnecting = errors .New ("bluetooth: already in a connection attempt" )
19+ var errConnectionTimeout = errors .New ("bluetooth: timeout while connecting" )
1920
2021// Memory buffers needed by sd_ble_gap_scan_start.
2122var (
@@ -94,7 +95,7 @@ func (a *Adapter) StopScan() error {
9495
9596// In-progress connection attempt.
9697var connectionAttempt struct {
97- state volatile.Register8 // 0 means unused, 1 means connecting, 2 means ready ( connected or timeout)
98+ state volatile.Register8 // 0 means unused, 1 means connecting, 2 means connected, 3 means timeout
9899 connectionHandle C.uint16_t
99100}
100101
@@ -165,18 +166,25 @@ func (a *Adapter) Connect(address Address, params ConnectionParams) (Device, err
165166 }
166167
167168 // Wait until the connection is established.
168- // TODO: use some sort of condition variable once the scheduler supports
169- // them.
170- for connectionAttempt .state .Get () != 2 {
171- arm .Asm ("wfe" )
169+ for {
170+ state := connectionAttempt .state .Get ()
171+ if state == 2 {
172+ // Successfully connected.
173+ connectionAttempt .state .Set (0 )
174+ connectionHandle := connectionAttempt .connectionHandle
175+ return Device {
176+ connectionHandle : connectionHandle ,
177+ }, nil
178+ } else if state == 3 {
179+ // Timeout while connecting.
180+ connectionAttempt .state .Set (0 )
181+ return Device {}, errConnectionTimeout
182+ } else {
183+ // TODO: use some sort of condition variable once the scheduler
184+ // supports them.
185+ arm .Asm ("wfe" )
186+ }
172187 }
173- connectionHandle := connectionAttempt .connectionHandle
174- connectionAttempt .state .Set (0 )
175-
176- // Connection has been established.
177- return Device {
178- connectionHandle : connectionHandle ,
179- }, nil
180188}
181189
182190// Disconnect from the BLE device.
0 commit comments