This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Confusing documentation of sd_ble_gattc_primary_services_discover

The documentation for this function states the following:

This function initiates or resumes a Primary Service discovery procedure, starting from the supplied handle. If the last service has not been reached, this function must be called again with an updated start handle value to continue the search.

But it does not state what return value corresponds to the case where the last service has not been reached. The return values are describe like this:

NRF_SUCCESS Successfully started or resumed the Primary Service Discovery procedure.

BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.

NRF_ERROR_INVALID_STATE Invalid Connection State.

NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.

NRF_ERROR_BUSY Client procedure already in progress.

None of these looks to indicate that there are more services to be discovered. What will the function return in that case?

  • It'll return NRF_SUCCESS, the success return relates to the success issuing the call, not the success of discovering the services, at all those error codes are errors related to the state of the connection when you issue the request.

    After you receive NRF_SUCCESS then you later get an event callback with BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP which contains the response, or as much of it fit in a packet, after processing, you call it again with one-higher handle than the max you were returned, and it keeps going. When you get a reply with the last handle as 0xffff, or (more commonly) 0 services, you've found them all.

    This is pretty much a straight implementation of the BLE "Read By Group Type Request". There is a message sequence diagram in the documentation for it, although it uses the notation BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP{ATTRIBUTE_NOT_FOUND} to indicate the end of the enumeration. That just means, service count == 0

Related