task.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "kbf/task.h"
  2. #include <esp_log.h>
  3. using std::string;
  4. using std::vector;
  5. using std::shared_ptr;
  6. using std::make_shared;
  7. using namespace kbf;
  8. static uint32_t taskId = 0;
  9. std::vector<std::shared_ptr<Task>> Task::TaskList::tasks;
  10. void Task::TaskList::add(const shared_ptr<Task> &task) {
  11. ESP_LOGD(TAG, "%s(%d), refcount=%ld", __func__, task->id, task.use_count());
  12. tasks.push_back(task);
  13. };
  14. void Task::TaskList::remove(uint32_t id) {
  15. ESP_LOGD(TAG, "%s(%d)", __func__, id);
  16. for (auto it = tasks.begin(); it != tasks.end(); it++) {
  17. if ((*it)->id == id) {
  18. tasks.erase(it);
  19. return;
  20. }
  21. }
  22. ESP_LOGE(TAG, "%s(%d): not found", __func__, id);
  23. throw exception::KBFError("TaskList::remove(" + std::to_string(id) + ") failed");
  24. }
  25. Task::Task(string name, void *arg, const uint32_t stackSize, const uint32_t priority) :
  26. name(std::move(name)),
  27. stackSize(stackSize),
  28. priority(priority),
  29. id(taskId++),
  30. arg(arg) {
  31. ESP_LOGI(TAG, "%s(): id=%d, name=\"%s\"", __func__, id, this->name.c_str());
  32. }
  33. Task::~Task() {
  34. ESP_LOGI(TAG, "%s(%d)", __func__, id);
  35. }
  36. [[maybe_unused]] void Task::runInternal(void *arg) {
  37. ESP_LOGD(TAG, "%s()", __func__);
  38. auto task = static_cast<Task *>(arg);
  39. task->running_ = true;
  40. task->run(task->arg);
  41. ESP_LOGI(TAG, "task (%d, %s) finished", task->id, task->name.c_str());
  42. // TODO call onFinish
  43. task->running_ = false;
  44. TaskList::remove(task->id);
  45. vTaskDelete(nullptr);
  46. }
  47. void Task::stop() {
  48. if (!running_) {
  49. ESP_LOGW(TAG, "%s(%d): not running", __func__, id);
  50. return;
  51. }
  52. ESP_LOGI(TAG, "%s(%d)", __func__, id);
  53. TaskList::remove(id);
  54. vTaskDelete(handle);
  55. running_ = false;
  56. }