scheduler.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. #include "esphome/core/component.h"
  3. #include <vector>
  4. #include <memory>
  5. namespace esphome {
  6. class Component;
  7. class Scheduler {
  8. public:
  9. void set_timeout(Component *component, const std::string &name, uint32_t timeout, std::function<void()> &&func);
  10. bool cancel_timeout(Component *component, const std::string &name);
  11. void set_interval(Component *component, const std::string &name, uint32_t interval, std::function<void()> &&func);
  12. bool cancel_interval(Component *component, const std::string &name);
  13. optional<uint32_t> next_schedule_in();
  14. void call();
  15. void process_to_add();
  16. protected:
  17. struct SchedulerItem {
  18. Component *component;
  19. std::string name;
  20. enum Type { TIMEOUT, INTERVAL } type;
  21. union {
  22. uint32_t interval;
  23. uint32_t timeout;
  24. };
  25. uint32_t last_execution;
  26. std::function<void()> f;
  27. bool remove;
  28. uint8_t last_execution_major;
  29. inline uint32_t next_execution() { return this->last_execution + this->timeout; }
  30. inline uint8_t next_execution_major() {
  31. uint32_t next_exec = this->next_execution();
  32. uint8_t next_exec_major = this->last_execution_major;
  33. if (next_exec < this->last_execution)
  34. next_exec_major++;
  35. return next_exec_major;
  36. }
  37. static bool cmp(const std::unique_ptr<SchedulerItem> &a, const std::unique_ptr<SchedulerItem> &b);
  38. };
  39. uint32_t millis_();
  40. void cleanup_();
  41. void pop_raw_();
  42. void push_(std::unique_ptr<SchedulerItem> item);
  43. bool cancel_item_(Component *component, const std::string &name, SchedulerItem::Type type);
  44. bool empty_() {
  45. this->cleanup_();
  46. return this->items_.empty();
  47. }
  48. std::vector<std::unique_ptr<SchedulerItem>> items_;
  49. std::vector<std::unique_ptr<SchedulerItem>> to_add_;
  50. uint32_t last_millis_{0};
  51. uint8_t millis_major_{0};
  52. uint32_t to_remove_{0};
  53. };
  54. } // namespace esphome