Beware that this post is related to an SDK in maintenance mode
More Info: Consider nRF Connect SDK for new designs
This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Keeping track of BLE connection state: connected or not, advertising or not, etc

Hello.

First some background:

I have an application running on nRF52840. Development began with the nRF52832 using nRF SDK 13 or 14. Then migrated to 15.2, 15.3, and finally to 17.0.2. The application is a BLE peripheral. The basic bluetooth connection code was written following the examples of those SDKs plus a Nordic tutorial on adding a custom BLE service. The code related to making and maintaining a BLE connection has been fairly stable for a long time. But recently I had a need to add a simple new feature, and that got me looking at the code more closely again. And to compare it to the examples of the current SDK 17.0.2.

My question really is what is the current best practice for keeping track of the state of the BLE connection? Ie, Are we currently connected? Are we currently advertising? Bonded or not? Etc.

My code is based on the examples of earlier SDKs, so I'm keeping track of state in the application code. For instance the connection state is held in a variable called m_conn_handle, and updated whenever the application code receives events from the BLE libraries. This is similar as in many of the examples. I was aware that the Connection State module existed, but had not looked at it closely before. It looks like I could simply use the ble_conn_state_peripheral_conn_count() -function to tell if I'm currently connected or not. But even the newer examples aren't using this.

Likewise for the advertising module. I'm keeping the state (currently advertising or not) in application code, updating the variable based on events. My recent changes revealed that I wasn't reacting to all possible events, and the application level state variable wasn't always in sync with the advertising module. I'm not sure how I could ask the current advertising state from the advertising module, but surely the module must know it. If I could let the module keep the state and just ask for it when needed, I could eliminate the source of the error I just encountered.

A third example is the whitelist. I was keeping (a copy of) that too in application code. I believe that in some earlier SDK it was necessary. Also you got duplicates on the list if you allowed repairing. It looks like this might no longer be necessary.

So what is the current best practice? Could I let the BLE libraries handle all state management? I'm mainly concerned that the application level state variables might not stay accurate if I fail to catch all events.

Parents Reply Children
No Data
Related