Uniot Core
0.9.0
Loading...
Searching...
No Matches
TaskScheduler.h
Go to the documentation of this file.
1/*
2 * This is a part of the Uniot project.
3 * Copyright (C) 2016-2020 Uniot <contact@uniot.io>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
26
32
33#pragma once
34
35#if defined(ESP8266)
36#include "ESP8266Task.h"
37#elif defined(ESP32)
38#include "ESP32Task.h"
39#endif
40
41#include <Common.h>
42#include <IExecutor.h>
44#include <IterableQueue.h>
45
46#include <functional>
47#include <memory>
48
49namespace uniot {
50
51#if defined(ESP8266)
53#elif defined(ESP32)
54using Task = ESP32Task;
55#endif
56
67class SchedulerTask : public Task {
68 public:
75 using SchedulerTaskCallback = std::function<void(SchedulerTask &, short)>; // TODO: add ms to callback
76
81
88 : SchedulerTask([&](SchedulerTask &, short times) { executor.execute(times); }) {}
89
96 : Task(), mTotalElapsedMs(0), mRepeatTimes(0), mCanDoHardWork(false) {
97 mspCallback = std::make_shared<SchedulerTaskCallback>(callback);
98 }
99
106 void attach(uint32_t ms, short times = 0) { // TODO: auto detach
107 mRepeatTimes = times > 0 ? times : -1;
108 Task::attach<volatile bool *>(ms, mRepeatTimes != 1, [](volatile bool *can) { *can = true; }, &mCanDoHardWork);
109 }
110
116 void once(uint32_t ms) {
117 attach(ms, 1);
118 }
119
135 void trigger() {
136 mCanDoHardWork = true;
137 }
138
145 inline void loop() {
146 auto startMs = millis();
147 if (mCanDoHardWork) {
148 mCanDoHardWork = false;
149
150 if (mRepeatTimes > 0 && !--mRepeatTimes) {
151 Task::detach();
152 }
153 (*mspCallback)(*this, mRepeatTimes);
154 }
155 mTotalElapsedMs += millis() - startMs;
156 }
157
163 uint64_t getTotalElapsedMs() const {
164 return mTotalElapsedMs;
165 }
166
167 private:
168 uint64_t mTotalElapsedMs;
169 short mRepeatTimes;
170 volatile bool mCanDoHardWork;
171 spSchedulerTaskCallback mspCallback;
172};
173
174
186 public:
191
199 using TaskInfoCallback = std::function<void(const char *, bool, uint64_t)>;
200
204 TaskScheduler() : mTotalElapsedMs(0) {}
205
213 return std::make_shared<SchedulerTask>(callback);
214 }
215
222 static TaskPtr make(IExecutor &executor) {
223 return std::make_shared<SchedulerTask>(executor);
224 }
225
233 TaskScheduler &push(const char *name, TaskPtr task) {
234 mTasks.push(MakePair(name, task));
235 return *this;
236 }
237
245 connection.pushTo(*this);
246 return *this;
247 }
248
254 inline void loop() {
255 auto startMs = millis();
256 mTasks.begin();
257 while (!mTasks.isEnd()) {
258 const auto &task = mTasks.current();
259 task.second->loop();
260
261 // Remove anonymous tasks only if they are detached (finished)
262 if (!task.first && !task.second->isAttached()) {
263 // auto wasSize = mTasks.calcSize();
264 mTasks.deleteCurrent();
265 // auto newSize = mTasks.calcSize();
266 // UNIOT_LOG_DEBUG("anonymous task removed, size: %d -> %d", wasSize, newSize);
267 } else {
268 mTasks.next();
269 }
270
271 yield();
272 }
273 mTotalElapsedMs += millis() - startMs;
274 }
275
281 void exportTasksInfo(TaskInfoCallback callback) const {
282 if (!callback) {
283 return;
284 }
285
286 uint64_t totalAnonymousElapsedMs = 0;
287 uint8_t anonymousTaskCount = 0;
288
289 mTasks.forEach([&](const Pair<const char *, TaskPtr> &task) {
290 if (task.first) {
291 callback(task.first, task.second->isAttached(), task.second->getTotalElapsedMs());
292 } else {
293 totalAnonymousElapsedMs += task.second->getTotalElapsedMs();
294 anonymousTaskCount++;
295 }
296 });
297
298 if (anonymousTaskCount > 0) {
299 constexpr size_t BUFFER_SIZE = 20;
300 static char anonymousTaskName[BUFFER_SIZE];
301 snprintf(anonymousTaskName, BUFFER_SIZE, "__anonymous[%d]", anonymousTaskCount);
302 callback(anonymousTaskName, true, totalAnonymousElapsedMs);
303 }
304 }
305
311 uint64_t getTotalElapsedMs() const {
312 return mTotalElapsedMs;
313 }
314
315 private:
316 uint64_t mTotalElapsedMs;
319};
320
321} // namespace uniot
ESP32-specific task implementation for the Uniot Core.
Definition IterableQueue.h:36
Definition ESP32Task.h:41
Definition ESP8266Task.h:48
void attach(uint32_t ms, bool repeat, TaskCallback callback)
Attach a simple callback to run periodically.
Definition ESP8266Task.h:86
void detach()
Stop and detach the timer.
Definition ESP8266Task.h:107
Interface for executing tasks in the scheduler system.
Definition IExecutor.h:31
virtual void execute(short times)=0
Execute the implementation's functionality.
Interface for connecting components to the TaskScheduler.
Definition ISchedulerConnectionKit.h:35
virtual void pushTo(TaskScheduler &scheduler)=0
Register this component with the given scheduler.
uint64_t getTotalElapsedMs() const
Get the total execution time of this task in milliseconds.
Definition TaskScheduler.h:163
SchedulerTask(SchedulerTaskCallback callback)
Constructor with custom callback function.
Definition TaskScheduler.h:95
SchedulerTask(IExecutor &executor)
Constructor that wraps an IExecutor implementation.
Definition TaskScheduler.h:87
SharedPointer< SchedulerTaskCallback > spSchedulerTaskCallback
Shared pointer type for task callbacks.
Definition TaskScheduler.h:80
void loop()
Main execution loop for the task.
Definition TaskScheduler.h:145
std::function< void(SchedulerTask &, short)> SchedulerTaskCallback
Callback function signature for scheduled tasks.
Definition TaskScheduler.h:75
void once(uint32_t ms)
Schedule the task to run once after the specified delay.
Definition TaskScheduler.h:116
void attach(uint32_t ms, short times=0)
Attach the task to run on a specified interval.
Definition TaskScheduler.h:106
void trigger()
Run the task once on the scheduler's next pass.
Definition TaskScheduler.h:135
auto MakePair(Args &&...args) -> decltype(std::make_pair(std::forward< Args >(args)...))
Creates a pair instance, alias for std::make_pair.
Definition Common.h:337
std::shared_ptr< T > SharedPointer
Type alias for std::shared_ptr with cleaner syntax.
Definition Common.h:313
std::pair< T_First, T_Second > Pair
Type alias for std::pair with cleaner syntax.
Definition Common.h:322
SharedPointer< SchedulerTask > TaskPtr
Shared pointer type for scheduler tasks.
Definition TaskScheduler.h:190
std::function< void(const char *, bool, uint64_t)> TaskInfoCallback
Callback signature for task status reporting.
Definition TaskScheduler.h:199
void exportTasksInfo(TaskInfoCallback callback) const
Report information about all registered tasks.
Definition TaskScheduler.h:281
TaskScheduler()
Constructor.
Definition TaskScheduler.h:204
static TaskPtr make(SchedulerTask::SchedulerTaskCallback callback)
Static factory method to create a task with a callback.
Definition TaskScheduler.h:212
static TaskPtr make(IExecutor &executor)
Static factory method to create a task from an IExecutor.
Definition TaskScheduler.h:222
TaskScheduler & push(const char *name, TaskPtr task)
Add a named task to the scheduler.
Definition TaskScheduler.h:233
uint64_t getTotalElapsedMs() const
Get the total execution time of the scheduler in milliseconds.
Definition TaskScheduler.h:311
TaskScheduler & push(ISchedulerConnectionKit &connection)
Add connection kit components to the scheduler.
Definition TaskScheduler.h:244
void loop()
Main execution loop for the scheduler.
Definition TaskScheduler.h:254
Contains all classes and functions related to the Uniot Core.
ESP8266Task Task
Definition TaskScheduler.h:52