2020-02-06 07:39:21 -08:00
|
|
|
#pragma once
|
|
|
|
|
|
2020-07-06 00:54:30 +02:00
|
|
|
#include "PeriodicScheduler.h"
|
|
|
|
|
#include "../time.h"
|
2020-03-15 19:27:42 -07:00
|
|
|
|
2020-07-06 00:54:30 +02:00
|
|
|
namespace concurrency {
|
2020-02-06 07:39:21 -08:00
|
|
|
|
2020-02-21 08:41:36 -08:00
|
|
|
/**
|
|
|
|
|
* A base class for tasks that want their doTask() method invoked periodically
|
2020-03-15 19:27:42 -07:00
|
|
|
*
|
2020-02-21 08:41:36 -08:00
|
|
|
* FIXME: currently just syntatic sugar for polling in loop (you must call .loop), but eventually
|
|
|
|
|
* generalize with the freertos scheduler so we can save lots of power by having everything either in
|
|
|
|
|
* something like this or triggered off of an irq.
|
|
|
|
|
*/
|
2020-02-06 07:39:21 -08:00
|
|
|
class PeriodicTask
|
|
|
|
|
{
|
2020-04-25 10:59:40 -07:00
|
|
|
friend class PeriodicScheduler;
|
|
|
|
|
|
2020-02-21 08:41:36 -08:00
|
|
|
uint32_t lastMsec = 0;
|
|
|
|
|
uint32_t period = 1; // call soon after creation
|
2020-02-06 07:39:21 -08:00
|
|
|
|
2020-03-15 19:27:42 -07:00
|
|
|
public:
|
2020-04-25 10:59:40 -07:00
|
|
|
virtual ~PeriodicTask() { periodicScheduler.unschedule(this); }
|
2020-02-06 07:39:21 -08:00
|
|
|
|
2020-04-25 10:59:40 -07:00
|
|
|
/**
|
|
|
|
|
* Constructor (will schedule with the global PeriodicScheduler)
|
|
|
|
|
*/
|
2020-02-21 08:41:36 -08:00
|
|
|
PeriodicTask(uint32_t initialPeriod = 1);
|
2020-02-06 07:39:21 -08:00
|
|
|
|
2020-04-25 10:59:40 -07:00
|
|
|
/** MUST be be called once at startup (but after threading is running - i.e. not from a constructor)
|
|
|
|
|
*/
|
|
|
|
|
void setup();
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Set a new period in msecs (can be called from doTask or elsewhere and the scheduler will cope)
|
|
|
|
|
* While zero this task is disabled and will not run
|
|
|
|
|
*/
|
2020-05-25 07:48:36 -07:00
|
|
|
void setPeriod(uint32_t p)
|
|
|
|
|
{
|
2020-07-06 00:54:30 +02:00
|
|
|
lastMsec = time::millis(); // reset starting from now
|
2020-05-25 07:48:36 -07:00
|
|
|
period = p;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
uint32_t getPeriod() const { return period; }
|
2020-02-06 07:39:21 -08:00
|
|
|
|
2020-04-25 10:59:40 -07:00
|
|
|
/**
|
|
|
|
|
* Syntatic sugar for suspending tasks
|
|
|
|
|
*/
|
|
|
|
|
void disable() { setPeriod(0); }
|
2020-02-21 10:20:47 -08:00
|
|
|
|
2020-03-15 19:27:42 -07:00
|
|
|
protected:
|
2020-02-21 10:20:47 -08:00
|
|
|
virtual void doTask() = 0;
|
2020-02-06 07:39:21 -08:00
|
|
|
};
|
2020-07-06 00:54:30 +02:00
|
|
|
|
|
|
|
|
} // namespace concurrency
|