Using ble_conn_state_conn_idx() to get separate central/peripheral indexes

I would like to store context information for each connection, but with central and peripheral connections storing different information.  Ideally, this is done in two separate arrays.

I see that ble_conn_state_conn_idx() gives an array index in the range 0 to BLE_CONN_STATE_MAX_CONNECTIONS - 1, as long as the connection state is valid.

Experimentally, the central connections' indexes are always in the lower segment of these index values.  For example, with 10 central and 1 peripheral, the connection handles are always [0-9] central and [10] peripheral.  I tested on nRF52840 with SDK 17.1.0 and SD s140 7.2.0, repeatedly connecting and disconnecting in different combinations.

From this, it looks like I can get separate central/peripheral indexes simply by subtracting.  Something like the following is consistently working for us:

uint16_t get_central_array_index(uint16_t conn_handle)
{
    uint16_t conn_index = ble_conn_state_conn_idx(conn_handle);
     
    if (conn_index >= NRF_SDH_BLE_CENTRAL_LINK_COUNT)
    {
        // not central, handle error
        return UINT16_MAX;  // or some other terrible thing
    }
    
    return conn_index;
}

uint16_t get_peripheral_array_index(uint16_t conn_handle)
{
    uint16_t conn_index = ble_conn_state_conn_idx(conn_handle);
    
    if ((conn_index < NRF_SDH_BLE_CENTRAL_LINK_COUNT) || (conn_index >= NRF_SDH_BLE_TOTAL_LINK_COUNT))
    {
        // not peripheral, handle error
        return UINT16_MAX;  // or some other terrible thing
    }
    
    return conn_index - NRF_SDH_BLE_CENTRAL_LINK_COUNT;
}

Can I rely on this index segmentation?  There are of course other more complex approaches with looped lookups, but this seems really clean if the index segmentation is guaranteed.

Thanks for the help!

Related