Bluenet  5.7.0
Bluenet, firmware for nRF52 smart home devices
Loading...
Searching...
No Matches
cs_Coroutine.h
Go to the documentation of this file.
1/*
2 * Author: Crownstone Team
3 * Copyright: Crownstone (https://crownstone.rocks)
4 * Date: May 11, 2020
5 * License: LGPLv3+, Apache License 2.0, and/or MIT (triple-licensed)
6 */
7#pragma once
8
9#include <drivers/cs_RTC.h>
10#include <drivers/cs_Timer.h>
11
12#include <functional>
13
14// coroutines
15// note: coroutine is currently built upon the event buss tickrate
16// which is set to about 10 ticks/s. (wishlist: use SystemTime instead.)
17
40class Coroutine {
41private:
42 uint32_t nextCallTickcount = 0;
43
44public:
45 typedef std::function<uint32_t(void)> Action;
46
47 // void function that returns the amount of tick events before it should be called again.
49
50 Coroutine() = default;
52
56 void onTick(uint32_t currentTickCount) {
57 // TODO: not doing roll-over checks here yet..
58 if (currentTickCount >= nextCallTickcount && action) {
59 auto ticksToWait = action();
60 nextCallTickcount = currentTickCount + ticksToWait;
61 }
62 }
63
69 bool handleEvent(event_t& evt) {
70 if (evt.type == CS_TYPE::EVT_TICK) {
71 this->onTick(*reinterpret_cast<TYPIFY(EVT_TICK)*>(evt.data));
72 return true;
73 }
74 return false;
75 }
76
77 uint32_t getNextCallTickCount() const { return nextCallTickcount; }
78
79 static uint32_t delayMs(uint32_t ms) { return ms / TICK_INTERVAL_MS; }
80
81 static uint32_t delayS(uint32_t s) { return delayMs(s * 1000); }
82};
A coroutine essentially is a throttling mechanism: it takes in a tick-event or tick count and execute...
Definition: cs_Coroutine.h:40
static uint32_t delayS(uint32_t s)
Definition: cs_Coroutine.h:81
bool handleEvent(event_t &evt)
Convenience function replacing onTick().
Definition: cs_Coroutine.h:69
static uint32_t delayMs(uint32_t ms)
Definition: cs_Coroutine.h:79
uint32_t getNextCallTickCount() const
Definition: cs_Coroutine.h:77
Coroutine()=default
uint32_t nextCallTickcount
Definition: cs_Coroutine.h:42
Action action
Definition: cs_Coroutine.h:48
Coroutine(Action a)
Definition: cs_Coroutine.h:51
std::function< uint32_t(void)> Action
Definition: cs_Coroutine.h:45
void onTick(uint32_t currentTickCount)
To be called on tick event.
Definition: cs_Coroutine.h:56
Author: Crownstone Team Copyright: Crownstone (https://crownstone.rocks) Date: Oct 9,...
Definition: cs_Event.h:26
void * data
Definition: cs_Event.h:45
CS_TYPE type
Definition: cs_Event.h:42
#define TICK_INTERVAL_MS
Interval in milliseconds at which tick events are dispatched.
Definition: cs_Config.h:277
#define TYPIFY(NAME)
Definition: cs_Types.h:476