ESPHome 2026.9.0
Loading...
Searching...
No Matches
static_task.cpp
Go to the documentation of this file.
2
3#ifdef USE_ESP32
4
6
7namespace esphome {
8
9bool StaticTask::create(TaskFunction_t fn, const char *name, uint32_t stack_size, void *param, UBaseType_t priority,
10 bool use_psram) {
11 if (this->handle_ != nullptr) {
12 // Task is already created; must call destroy() first
13 return false;
14 }
15
16 if (this->stack_buffer_ != nullptr && (stack_size > this->stack_size_ || use_psram != this->use_psram_)) {
17 // Existing buffer is too small or wrong memory type; deallocate to reallocate below
20 allocator.deallocate(this->stack_buffer_, this->stack_size_);
21 this->stack_buffer_ = nullptr;
22 }
23
24 if (this->stack_buffer_ == nullptr) {
25 this->stack_size_ = stack_size;
26 this->use_psram_ = use_psram;
29 this->stack_buffer_ = allocator.allocate(stack_size);
30 }
31 if (this->stack_buffer_ == nullptr) {
32 return false;
33 }
34
35 this->handle_ = xTaskCreateStatic(fn, name, this->stack_size_, param, priority, this->stack_buffer_, &this->tcb_);
36 if (this->handle_ == nullptr) {
37 this->deallocate();
38 return false;
39 }
40 return true;
41}
42
44 if (this->handle_ == nullptr) {
45 return true;
46 }
47
48 // Suspending takes the task off the ready and event lists, so nothing can schedule it again. It only asks
49 // the other core to yield though, so the task may still be running on it for a moment.
50 vTaskSuspend(this->handle_);
51 if (eTaskGetState(this->handle_) != eSuspended) {
52 // The task is still running on the other core and using its stack. Deleting it now would only put it on
53 // the termination list and return, so the caller has to try again once it has been swapped out.
54 return false;
55 }
56
57 // The task cannot run again, so the delete completes right away instead of being left to the idle task.
58 TaskHandle_t handle = this->handle_;
59 this->handle_ = nullptr;
60 vTaskDelete(handle);
61 return true;
62}
63
65 if (!this->destroy()) {
66 return false;
67 }
68 if (this->stack_buffer_ != nullptr) {
71 allocator.deallocate(this->stack_buffer_, this->stack_size_);
72 this->stack_buffer_ = nullptr;
73 this->stack_size_ = 0;
74 }
75 return true;
76}
77
78} // namespace esphome
79
80#endif // USE_ESP32
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2142
void deallocate(T *p, size_t n)
Definition helpers.h:2199
T * allocate(size_t n)
Definition helpers.h:2169
bool create(TaskFunction_t fn, const char *name, uint32_t stack_size, void *param, UBaseType_t priority, bool use_psram)
Allocate stack and create task.
bool destroy()
Delete the task, keeping the stack buffer allocated for reuse by a subsequent create() call.
bool deallocate()
Delete the task (if created) and free the stack buffer.
TaskHandle_t handle_
Definition static_task.h:48
StackType_t * stack_buffer_
Definition static_task.h:50
StaticTask_t tcb_
Definition static_task.h:49
uint8_t priority
static void uint32_t
spi_device_handle_t handle