go-ble / ble

Bluetooth Low Energy for Linux / macOS
BSD 3-Clause "New" or "Revised" License
302 stars 108 forks source link

delegate communicates scan results via channels #100

Closed dnesting closed 1 year ago

dnesting commented 2 years ago

This fixes https://github.com/go-ble/ble/issues/73 for Darwin. The problem here is that the OS may deliver scan results to d.advHandler even after the Scan call has returned. This violates the usual contract for callbacks and makes it hard to implement common callback patterns since callbacks can occur long after the code that called Scan has moved on to other things.

I'm not thrilled with the complexity of this solution but I think it reliably fixes the issue. It works by communicating results from the delegate to the Scan call through channels.

I believe the Linux version of the code has the same problem and a similar fix could be applied there, but didn't want to do too much in one MR.

dnesting commented 2 years ago

I adapted my test case from issue #73 and can't reproduce the original problem with this change applied.

1.147988583s: 11 calls, no problem
1.1488545s: 11 calls, no problem
1.147610291s: 11 calls, no problem
1.1499915s: 11 calls, no problem
1.145267s: 7 calls, no problem
1.146460209s: 11 calls, no problem
1.149309167s: 9 calls, no problem
1.138770625s: 11 calls, no problem
1.1639775s: 11 calls, no problem
1.144412334s: 11 calls, no problem
estutzenberger commented 1 year ago

Thanks for the PR!