Page 1 of 1

Synchronizing separate USART TX and RX threads

Posted: Tue Dec 13, 2016 7:19 am
by jayalfredprufrock
I have a bluetooth module that my STM32F4 communicates with over USART. The module is controlled by sending command byte sequences over USART, which in turn generate responses. The module can only process commands one at a time so you must wait for a response before issuing the next command. The module can also generate events at any time that need to be processed by the MCU. For this reason I use two separate threads, one that waits for bytes in the RX buffer to process as either events or command responses, and another that is responsible for sending commands one at a time.

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!!

Re: Synchronizing separate USART TX and RX threads

Posted: Tue Dec 13, 2016 8:33 am
by Giovanni
Hi,

The problem I see is that you don't handle errors and loss of synchronization. Does those message have delimiters? if so you should handle them.

You don't need two threads, just one listening for events. I suggest making one thread implementing a state machine driven by the RX, TX and error events plus timeouts while waiting for events. The best approach is if you design the state machine before trying to implement it.

Giovanni

Re: Synchronizing separate USART TX and RX threads

Posted: Tue Dec 13, 2016 9:35 am
by jayalfredprufrock
Thanks for the response Giovanni.

Responses and events from the module have a fixed length header. That's what the first read waits to receive. Then depending on the response/event there may be an additional data payload. All commands produce exactly one response packet and events can be emitted at any time (not necessarily in response to a command).

Also, I am handling timeouts/resets and corrupted messages too, but I tried to simplify the example as much as possible. The thing is, I'm seeing the proper command and response packets on the scope so the only way I can explain the behavior is that maybe the first byte is getting dropped by the driver, preventing the sdRead for the header from completing.

I guess I'll try working off a state machine as you suggest, but I still feel like I'm missing something here...

Re: Synchronizing separate USART TX and RX threads

Posted: Tue Dec 13, 2016 9:38 am
by Giovanni
Hi,

How can you guarantee that the first byte arrives after the serial driver has been initialized? you should also assume that some bytes could be dropped so reading/writing fixed lengths will likely not work reliably.

Giovanni

Re: Synchronizing separate USART TX and RX threads

Posted: Tue Dec 13, 2016 11:42 am
by Tabulous
Hi this the same way a GSM modem works.

You send a cmd
Wait for a response

But they can also send un-solicited responses too.

with GSM they use AT interface and thus one can use a state machine and sync to the CR NL

Managing the sending should be as easy as

your send routine has a binary lock on it, thus any parts of your software wanting to send a msg out needs to acquire the lock.

thus you end up with

get lock
send msg
wait response
release lock

This will synchronize the process and make it sequential

you only need a thread for the recieve part, as the transmit is effectively done from another thread, hence you can block whilst waiting for the response.

Re: Synchronizing separate USART TX and RX threads

Posted: Tue Dec 13, 2016 9:34 pm
by jayalfredprufrock
Great advice guys, thanks a lot for taking the time to respond. I'm going to refactor things and use the events emitted by the serial driver to buffer each byte as it is received, parse the bytes using a state machine, and use a timeout to catch the case where a portion of a header packet gets dropped. I guess I forgot just how primitive of a protocol USART is and I stupidly assumed flow control would keep things in sync...