I am developing an application as a peripheral based on the NRF52 SoC which regularly reads a sensor and publishes the reading to a BLE characteristic. A central (a smartphone app) connects to the NRF52 peripheral and immediately requests the current value of the characteristic value so it can display its UI.
The problem I'm having is that the characteristic value retrieved is out of date. This is because I am following the SDK examples and surrounding calls to sd_ble_gatts_hvx with a conditional statement such that they are only executed if the connection is valid, eg:
if(peripheral->conn_handle != BLE_CONN_HANDLE_INVALID) {
hvx_params = [sensor reading]
err_code = sd_ble_gatts_hvx(p_datalogger->conn_handle, &hvx_params);
return err_code;
}
What is the best way to ensure that the characteristic value is reflective of the latest sensor reading when the central connects? I thought about calling sd_ble_gatts_hvx immediately when a connection is established, but I am concerned this could lead to a race condition.
Any advice gratefully received!