Code: Select all
static SEMAPHORE_DECL(m_event_semaphore, 0);
mailbox_t m_event_mailbox;
msg_t m_mailbox_msg_buf[EVENT_MAILBOX_SIZE];
memory_pool_t m_event_pool;
event_t m_events_buf[EVENT_QUEUE_SIZE];
/**
* @brief Private: thread that fetches events from queue and feeds them to state machine
*
*/
static THD_WORKING_AREA(tick_working_area, 2048);
static THD_FUNCTION(tick_thread, arg) {
(void)arg;
chRegSetThreadName("tick");
while (1) {
event_t* e = NULL;
chSemWait(&m_event_semaphore);
while(1) {
if (false == m_get_event(&e)) {
// sleep if no more events to handle
break;
}
else {
m_tick(e);
}
}
}
}
event_t* sm_alloc_event_for_signal(void) {
event_t* e = NULL;
if (port_is_isr_context()) {
chSysLockFromISR();
e = chPoolAllocI(&m_event_pool);
chSysUnlockFromISR();
}
else {
e = chPoolAlloc(&m_event_pool);
}
return e;
}
/**
* @brief Signals event to state machine
* @details It is used to signal events to state machine.
*
* @param[in] e Pointer to the @p event_t object that must have been allocated
* using "sm_alloc_event_for_signal" function.
*
*/
void sm_signal_event(event_t* e) {
msg_t m = 0;
if (port_is_isr_context()) {
chSysLockFromISR();
m = chMBPostI(&m_event_mailbox, (msg_t)e);
chSysUnlockFromISR();
if (m != MSG_OK) {
log_info("sm: ASSERT mailbox full");
}
else {
chSysLockFromISR();
chSemSignalI(&m_event_semaphore);
chSysUnlockFromISR();
}
}
else {
m = chMBPost(&m_event_mailbox, (msg_t)e, TIME_IMMEDIATE);
if (m != MSG_OK) {
log_info("sm: ASSERT mailbox full");
}
else {
chSemSignal(&m_event_semaphore);
}
}
}
static bool m_get_event(event_t** e) {
msg_t msg;
// ........ some code missing
// check if we have some events from applicaton
if (chMBFetch(&m_event_mailbox, &msg, TIME_IMMEDIATE) == MSG_OK) {
*e = (event_t*)msg;
return true;
}
else {
return false;
}
}
For example new event can be sent to the statemachine from a thread:
Code: Select all
while (true) {
event_t* e = sm_alloc_event_for_signal();
if (e != NULL) {
e->sig = SIG_TOGGLE_LED;
sm_signal_event(e);
}
chThdSleepMilliseconds(100);
}
Or from a ISR:
Code: Select all
OSAL_IRQ_HANDLER(STM32_SPI3_HANDLER) {
OSAL_IRQ_PROLOGUE();
osalSysLockFromISR();
event_t* e = sm_alloc_event_for_signal();
if (e != NULL) {
e->sig = SIG_RANDOM_EVENT;
sm_signal_event(e);
}
osalSysUnlockFromISR();
OSAL_IRQ_EPILOGUE();
}
I have some concerns that locking logic might be faulty here.
I looked last example from there: http://www.chibios.org/dokuwiki/doku.ph ... el_mutexes and got impression that this might be more correct (in tick_thread).
Code: Select all
chSysLock();
chSemWaitS(&m_event_semaphore);
chSysUnlock();
Because chSemSignal might come from a thread or from ISR (chSemSignalI). Is this correct?