I've got some code below that I have simplified as much as possible for reference:
Code: Select all
static ble_action_t* action;
static THD_FUNCTION(bleActionThread, arg)
{
for(;;)
{
if (chMBFetch(&action_mailbox, &mail, TIME_INFINITE) == MSG_OK)
{
action = (ble_action_t*)mail;
chBSemReset(&action->semaphore, true);
if (sdWriteTimeout(&BLE_SERIAL_DRIVER, action->packet, num_bytes, MS2ST(BLE_ACTION_TIMEOUT_MS)) == num_bytes)
{
if (chBSemWaitTimeout(&action->semaphore, MS2ST(BLE_ACTION_TIMEOUT_MS)) != MSG_OK)
{
//TIMEOUT HERE!!!
}
//if I replace the above chBSemWaitTimeout with a 5ms sleep, everything works great
//chThdSleepMilliseconds(5);
}
}
}
}
static THD_FUNCTION(bleResponseThread, arg)
{
static uint8_t ble_resp_data[BLE_ACTION_MAX_PACKET_SIZE - sizeof(ble_resp_header)];
for(;;)
{
num_bytes = sizeof(ble_header_t);
while (sdReadTimeout(&BLE_SERIAL_DRIVER, &resp_header, num_bytes, MS2ST(BLE_RESPONSE_TIMEOUT_MS)) == num_bytes)
{
if (bleRespIsCommand(&resp_header))
{
if (bleRespHasData(resp_header))
{
num_bytes = resp_header.data_length;
sdReadTimeout(&BLE_SERIAL_DRIVER, ble_resp_data, num_bytes, MS2ST(BLE_RX_TIMEOUT_MS));
}
chBSemSignal(&action->semaphore);
}
else
{
bleProcessEvent(&resp_header);
}
}
}
}
The response thread never receives the response from the module which means the action semaphore is never released, causing a timeout in the action thread. I've verified with a logic analyzer that the proper command bytes are being sent to the module and that the module responds as expected, a little less than a millisecond later. I've tried all 3 combinations of relative thread priorities between the action and response threads. I've also tried using the USART DMA driver instead of the serial driver and I see the exact same behavior. As noted in the comments, if I simply sleep for 5ms instead of waiting for the semaphore (and just assume the command response is received correctly), everything works great, even when queuing actions in rapid succession. It also works if I manually sleep ~100ms between queuing up each command, even with the semaphore in place. It's only when I queue several commands in a row that the response thread fails to catch the response bytes from the BLE module.
I'm wondering if anybody can spot a race condition with the pattern I'm using or can suggest something else I might try. Are synchronous messages a better approach to a problem like this? Or should I refactor this into a single thread somehow? Any advice greatly appreciated!!