mirror of
https://github.com/usatiuk/cardboy.git
synced 2025-10-28 23:27:49 +01:00
82 lines
2.2 KiB
C++
82 lines
2.2 KiB
C++
#include "cardboy/backend/esp/event_bus.hpp"
|
|
|
|
#include "cardboy/sdk/event_bus.hpp"
|
|
|
|
#include "freertos/portmacro.h"
|
|
|
|
#include <algorithm>
|
|
|
|
namespace cardboy::backend::esp {
|
|
|
|
namespace {
|
|
[[nodiscard]] TickType_t toTicks(std::uint32_t timeout_ms) {
|
|
if (timeout_ms == cardboy::sdk::IEventBus::kWaitForever)
|
|
return portMAX_DELAY;
|
|
return pdMS_TO_TICKS(timeout_ms);
|
|
}
|
|
} // namespace
|
|
|
|
static void timerCallback(TimerHandle_t handle) {
|
|
auto* bus = static_cast<EventBus*>(pvTimerGetTimerID(handle));
|
|
if (bus)
|
|
bus->signal(cardboy::sdk::to_event_bits(cardboy::sdk::EventBusSignal::Timer));
|
|
}
|
|
|
|
EventBus::EventBus() :
|
|
group(xEventGroupCreate()), timer(xTimerCreate("EventBusTimer", pdMS_TO_TICKS(1), pdFALSE, this, timerCallback)) {}
|
|
|
|
EventBus::~EventBus() {
|
|
if (timer)
|
|
xTimerDelete(timer, portMAX_DELAY);
|
|
if (group)
|
|
vEventGroupDelete(group);
|
|
}
|
|
|
|
void EventBus::signal(std::uint32_t bits) {
|
|
if (!group || bits == 0)
|
|
return;
|
|
xEventGroupSetBits(group, bits);
|
|
}
|
|
|
|
void EventBus::signalFromISR(std::uint32_t bits) {
|
|
if (!group || bits == 0)
|
|
return;
|
|
BaseType_t higherPriorityTaskWoken = pdFALSE;
|
|
xEventGroupSetBitsFromISR(group, bits, &higherPriorityTaskWoken);
|
|
if (higherPriorityTaskWoken == pdTRUE)
|
|
portYIELD_FROM_ISR(higherPriorityTaskWoken);
|
|
}
|
|
|
|
std::uint32_t EventBus::wait(std::uint32_t mask, std::uint32_t timeout_ms) {
|
|
if (!group || mask == 0)
|
|
return 0;
|
|
const EventBits_t bits = xEventGroupWaitBits(group, mask, pdTRUE, pdFALSE, toTicks(timeout_ms));
|
|
return static_cast<std::uint32_t>(bits & mask);
|
|
}
|
|
|
|
void EventBus::scheduleTimerSignal(std::uint32_t delay_ms) {
|
|
if (!timer)
|
|
return;
|
|
xTimerStop(timer, 0);
|
|
|
|
if (delay_ms == cardboy::sdk::IEventBus::kWaitForever)
|
|
return;
|
|
|
|
if (delay_ms == 0) {
|
|
signal(cardboy::sdk::to_event_bits(cardboy::sdk::EventBusSignal::Timer));
|
|
return;
|
|
}
|
|
|
|
const TickType_t ticks = std::max<TickType_t>(pdMS_TO_TICKS(delay_ms), 1);
|
|
if (xTimerChangePeriod(timer, ticks, 0) == pdPASS)
|
|
xTimerStart(timer, 0);
|
|
}
|
|
|
|
void EventBus::cancelTimerSignal() {
|
|
if (!timer)
|
|
return;
|
|
xTimerStop(timer, 0);
|
|
}
|
|
|
|
} // namespace cardboy::backend::esp
|