How to synchronize processing of received BLE data to prevent overwrites

I have a custom BLE characteristic that I want to use to allow an app to send commands to my device. I use an on-write() function that is called whenever a BLE_GATTS_EVT_WRITE event happens to detect the write to the command characteristic and process the command. The characteristic is set up to use my own data buffer instead of one within the BLE stack (called commandJSON).  See code below.

The problem is that, while I'm processing one command, another command can come in and overwrite the one I'm working on. What is the "correct" way to prevent this from happening?

I'm using SDK 15.3.0 and the S140 soft device.

static void on_write(ble_cus_t * p_cus, ble_evt_t const * p_ble_evt)
{
    ble_gatts_evt_write_t const * p_evt_write = &p_ble_evt->evt.gatts_evt.params.write;
    NRF_LOG_INFO("on_write() called. Event write handle is = %d\r\n", p_evt_write->handle); 
    
    // Handle writes to json command characteristic
    if (p_evt_write->handle == p_cus->custom_value_json_command_handles.value_handle)
    {
        NRF_LOG_DEBUG("Write to JSON command characteristic.");
        commandJSON[p_evt_write->len] = 0;  // Add a null terminator
        NRF_LOG_HEXDUMP_INFO(commandJSON, strlen(commandJSON));
        ParseJsonCommand();
    }

}
Related