@@ -16,6 +16,7 @@ import (
16
16
import "C"
17
17
18
18
var errAlreadyConnecting = errors .New ("bluetooth: already in a connection attempt" )
19
+ var errConnectionTimeout = errors .New ("bluetooth: timeout while connecting" )
19
20
20
21
// Memory buffers needed by sd_ble_gap_scan_start.
21
22
var (
@@ -94,7 +95,7 @@ func (a *Adapter) StopScan() error {
94
95
95
96
// In-progress connection attempt.
96
97
var 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
98
99
connectionHandle C.uint16_t
99
100
}
100
101
@@ -165,18 +166,25 @@ func (a *Adapter) Connect(address Address, params ConnectionParams) (Device, err
165
166
}
166
167
167
168
// 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
+ }
172
187
}
173
- connectionHandle := connectionAttempt .connectionHandle
174
- connectionAttempt .state .Set (0 )
175
-
176
- // Connection has been established.
177
- return Device {
178
- connectionHandle : connectionHandle ,
179
- }, nil
180
188
}
181
189
182
190
// Disconnect from the BLE device.
0 commit comments