2ba1ffd7784597c28210d8ab8d1951ebc14afada
[phd-thesis.git] / top / green.tex
1 \documentclass[../thesis.tex]{subfiles}
2
3 \input{subfilepreamble}
4
5 \begin{document}
6 \input{subfileprefix}
7 \chapter{Green computing with \texorpdfstring{\gls{MTASK}}{mTask}}%
8 \label{chp:green_computing_mtask}
9 \begin{chapterabstract}
10 \noindent This chapter demonstrate the energy saving features of \gls{MTASK} by
11 \begin{itemize}
12 \item giving an overview of general green computing measures for edge devices;
13 \item explaining \gls{MTASK}'s task scheduling, and it is shown how to customise it so suit the applications and energy needs;
14 \item showing how to use interrupts in \gls{MTASK} to reduce the need for polling.
15 \end{itemize}
16 \end{chapterabstract}
17
18 The edge layer of the \gls{IOT} contains small devices that sense and interact with the world and it is crucial to lower their energy consumption.
19 While individual devices consume little energy, the sheer number of devices in total amounts to a lot.
20 Furthermore, many \gls{IOT} devices operate on batteries and higher energy consumption increases the amount of e-waste as \gls{IOT} edge devices are often hard to reach and consequently hard to replace \citep{nizetic_internet_2020}.
21
22 To reduce the power consumption of an \gls{IOT} device, the specialized low-power sleep modes of the microprocessors can be leveraged.
23 Different sleep modes achieve different power reductions because of their different run time characteristics.
24 These specifics range from disabling or suspending WiFi; stopping powering (parts) of the \gls{RAM}; disabling peripherals; or even turning off the processor completely, requiring an external signal to wake up again.
25 Determining when exactly and for how long it is possible to sleep is expensive in the general case and often requires annotations in the source code, a real-time operating system or a handcrafted scheduler.
26
27 \begin{table}
28 \centering
29 \caption{Current use in \unit{\milli\ampere} of two microprocessor boards in various sleep modes.}%
30 \label{tbl:top_sleep}
31 \small
32 \begin{tabular}{ccccccccc}
33 \toprule
34 & \multicolumn{4}{c}{Wemos D1 mini} & \multicolumn{4}{c}{Adafruit Feather M0 Wifi} \\
35 \midrule
36 & active & modem & light & deep & active & modem & light & deep \\
37 & & sleep & sleep & sleep & & sleep & sleep & sleep \\
38 \midrule
39 WiFi & on & off & off & off & on & off & off & off \\
40 CPU & on & on & pending & off & on & on & idle & idle \\
41 \gls{RAM} & on & on & on & off & on & on & on & on\\%low power \\
42 \midrule
43 current & 100--240 & 15 & 0.5 & 0.002 & 90--300 & 5 & 2 & 0.005\\
44 \bottomrule
45 \end{tabular}
46 \end{table}
47
48 \Cref{tbl:top_sleep} shows the properties and current consumption of two commonly used microcontrollers.
49 It shows that switching the WiFi radio off yields the biggest energy savings.
50 In most \gls{IOT} applications, we need WiFi for communications.
51 It is fine to switch it off, but after switching it on, the WiFi protocol needs to transmit a number of messages to re-establish the connection.
52 This implies that it is only worthwhile to switch the radio off when this can be done for some time.
53 The details vary per system and situation.
54 As a rule of thumb, it is only worthwhile to switch the WiFi off when it is not needed for at least some tens of seconds.
55
56 \section{Green \texorpdfstring{\glsxtrshort{IOT}}{IoT} computing}
57 The data in \cref{tbl:top_sleep} shows that it is worthwhile to put the system in some sleep mode when there is temporarily no work to be done.
58 A deeper sleep mode saves more energy, but also requires more work to restore the software to its working state.
59 A processor like the ESP8266 driving the Wemos D1 mini loses the content of its \gls{RAM} in deep sleep mode.
60 As a result, after waking up, the program itself is preserved, since it is stored in flash memory, but the program state is lost.
61 When there is a program state to be preserved, we must either store it elsewhere, limit us to light sleep, or use a microcontroller that keeps the \gls{RAM} intact during deep sleep.
62
63 For \gls{IOT} nodes executing a single task, explicit sleeping to save energy can be achieved without too much hassle.
64 This becomes much more challenging as soon as multiple independent tasks run on the same node.
65 Sleeping of the entire node induced by one task prevents progress of all tasks.
66 This is especially annoying when the other tasks are executing time critical parts, like communication protocols.
67 Such protocols control the communication with sensors and actuators.
68 Without the help of an \gls{OS}, the programmer is forced to combine all subtasks into one big system that decides if it is safe to sleep for all subtasks.
69
70 \Gls{MTASK} offers abstractions for edge layer-specific details such as the heterogeneity of architectures, platforms and frameworks; peripheral access; and multitasking but also for energy consumption and scheduling.
71 In \gls{MTASK}, tasks are implemented as a rewrite system, where the work is automatically segmented in small atomic bits and stored as a task tree.
72 Each cycle, a single rewrite step is performed on all task trees, during rewriting, tasks do a bit of their work and progress steadily, allowing interleaved and seemingly parallel operation.
73 After a loop, the \gls{RTS} knows which task is waiting on which triggers and is thus able to determine the next execution time for each task automatically.
74 Utilising this information, the \gls{RTS} can determine when it is possible and safe to sleep and choose the optimal sleep mode according to the sleeping time.
75 For example, the \gls{RTS} never attempts to sleep during an \gls{I2C} communication because \gls{IO} is always contained \emph{within} a rewrite step.
76
77 An \gls{MTASK} program is dynamically transformed to byte code.
78 This byte code and the initial \gls{MTASK} expression are shipped to \gls{MTASK} \gls{IOT} node.
79 The \gls{MTASK} rewrite engine rewrites the current expression just a single rewrite step at a time.
80 When subtasks are composed in parallel, all subtasks are rewritten unless the result of the first rewrite step makes the result of the other tasks superfluous.
81 The task design ensures such that all time critical communication with peripherals is within a single rewrite step.
82 This is very convenient, since the system can inspect the current state of all \gls{MTASK} expressions after a rewrite and decide if sleeping and how long is possible.
83 %As a consequence, we cannot have fair multitasking.
84 %When a single rewrite step would take forever due to an infinite sequence of function calls, this would block the entire IoT node.
85 Even infinite sequences rewrite steps, as in the \cleaninline{blink} example, are perfectly fine.
86 The \gls{MTASK} system does proper tail-call optimizations to facilitate this.
87
88 \section{Rewrite interval}
89 Some \gls{MTASK} examples contain one or more explicit \cleaninline{delay} primitives, offering a natural place for the node executing it to pause.
90 However, there are many \gls{MTASK} programs that just specify a repeated set of primitives.
91 A typical example is the program that reads the temperature for a sensor and sets the system \gls{LED} if the reading is below some given \cleaninline{goal}.
92
93 \begin{lstClean}[caption={A basic thermostat task.},label={lst:thermostat}]
94 thermostat :: Main (MTask v Bool) | mtask v
95 thermostat = DHT I2Caddr \dht->
96 {main = rpeat (temperature dht >>~. \temp.
97 writeD builtInLED (goal <. temp))}
98 \end{lstClean}
99
100 This program repeatedly reads the \gls{DHT} sensor and sets the on-board \gls{LED} based on the comparison with the \cleaninline{goal} as fast as possible on the \gls{MTASK} node.
101 This is a perfect solution as long as we ignore the power consumption.
102 The \gls{MTASK} machinery ensures that if there are other tasks running on the node, they will make progress.
103 However, this solution is far from perfect when we take power consumption into account.
104 In most applications, it is very unlikely that the temperature will change significantly within one minute, let alone within some milliseconds.
105 Hence, it is sufficient to repeat the measurement with an appropriate interval.
106
107 There are various ways to improve this program.
108 The simplest solution is to add an explicit delay to the body of the repeat loop.
109 A slightly more sophisticated option is to add a repetition period to the \cleaninline{rpeat} combinator.
110 The combinator implementing this is called \cleaninline{rpeatEvery}.
111 Both solutions rely on an explicit action of the programmer.
112
113 Fortunately, \gls{MTASK} also contains machinery to do this automatically.
114 The key of this solution is to associate dynamically an evaluation interval with each task.
115 The interval $\rewriterate{low}{high}$ indicates that the evaluation can be safely delayed by any number of milliseconds within that range.
116 Such an interval is just a hint for the \gls{RTS}.
117 It is not a guarantee that the evaluation takes place in the given interval.
118 Other parts of the task expression can force an earlier evaluation of this part of the task.
119 When the system is very busy with other work, the task might even be executed after the upper bound of the interval.
120 The system calculates the rewrite rates from the current task expression.
121 This has the advantage that the programmer does not have to deal with them and that they are available in each and every \gls{MTASK} program.
122
123 \subsection{Basic tasks}
124
125 We start by assigning default rewrite rates to basic tasks.
126 These rewrite rates reflect the expected change rates of sensors and other inputs.
127 Basic tasks to one-shot set a value of a sensor or actuator usually have a rate of $\rewriterate{0}{0}$, this is never delayed, e.g.\ writing to a \gls{GPIO} pin.
128 Basic tasks that continuously read a value or otherwise interact with a peripheral have default rewrite rates that fit standard usage of the sensor.
129 \Cref{tbl:rewrite} shows the default values for the basic tasks.
130 I.e.\ reading \glspl{SDS} and fast sensors such as sound or light aim for a rewrite every \qty{100}{\ms}, medium slow sensors such as gesture sensors every \qty{1000}{\ms} and slow sensors such as temperature or air quality every \qty{2000}{\ms}.
131
132 \begin{table}
133 \centering
134 \caption{Default rewrite rates of basic tasks.}%
135 \label{tbl:rewrite}
136 \begin{tabular}{ll}
137 \toprule
138 task & default interval\\
139 \midrule
140 reading \pgls{SDS} & $\rewriterate{0}{2000}$\\
141 slow sensor & $\rewriterate{0}{2000}$\\
142 medium sensor & $\rewriterate{0}{1000}$\\
143 fast sensor & $\rewriterate{0}{100}$\\
144 \bottomrule
145 \end{tabular}
146 \end{table}
147
148 \subsection{Deriving rewrite rates}\label{sec:deriving_rewrite_rates}
149 Based on these default rewrite rates, the system automatically derives rewrite rates for composed \gls{MTASK} expressions using the function $\mathcal{R}$ as shown in \cref{equ:r}.
150
151 \begin{equ}
152 \begin{align}
153 \mathcal{R} :: (\mathit{MTask}~v~a) & \shortrightarrow \rewriterate{\mathit{Int}}{\mathit{Int}} \notag \\
154 \mathcal{R} (t_1~{.||.}~t_2) & = \mathcal{R}(t_1) \cap_{\textit{safe}} \mathcal{R}(t_2) \label{R:or} \\
155 \mathcal{R}(t_1~{.\&\&.}~t_2) & = \mathcal{R}(t_1) \cap_{\textit{safe}} \mathcal{R}(t_2) \label{R:and}\\
156 \mathcal{R}(t~{>\!\!>\!\!*.}~[a_1 \ldots a_n]) & = \mathcal{R}(t) \label{R:step} \\
157 \mathcal{R}(\mathit{rpeat}~t~\mathit{start}) & =
158 \left\{\begin{array}{ll}
159 \mathcal{R}(t) & \text{if $t$ is unstable}\\
160 \rewriterate{r_1-\mathit{start}}{r_2-\mathit{start}} & \text{otherwise}\\
161 \end{array}\right.\\
162 \mathcal{R} (\mathit{waitUntil}~d) & = \rewriterate{e-\mathit{time}}{e-\mathit{time}}\label{R:delay}\\
163 \mathcal{R} (t) & =
164 \left\{%
165 \begin{array}{ll}
166 \rewriterate{\infty}{\infty}~& \text{if}~t~\text{is Stable} \\
167 \rewriterate{r_l}{r_u} & \text{otherwise}
168 \end{array}
169 \right.\label{R:other}
170 \end{align}
171 \caption{Function $\mathcal{R}$ for deriving refresh rates.}%
172 \label{equ:r}
173 \end{equ}
174
175 \subsubsection{Parallel combinators}
176 For parallel combinators, the \emph{or}-combinator (\cleaninline{.\|\|.}) in \cref{R:or} and the \emph{and}-combinator (\cleaninline{.&&.}) in \cref{R:and}, the safe intersection (see \cref{equ:safe_intersect}) of the rewrite rates is taken to determine the rewrite rate of the complete task.
177 The conventional intersection does not suffice here because it yields an empty intersection when the intervals do not overlap.
178 In that case, the safe intersection behaves will return the range with the lowest numbers.
179 The rationale is that subtasks should not be delayed longer than their rewrite range.
180 Evaluating a task earlier should not change its result but just consumes more energy.
181
182 \begin{equ}
183 \[
184 X \cap_{\textit{safe}} Y = \left\{%
185 \begin{array}{ll}
186 X\cap Y & X\cap Y \neq \emptyset\\
187 Y & Y_2 < X_1\\
188 X & \text{otherwise}\\
189 \end{array}
190 \right.
191 \]
192 \caption{Safe intersection operator}\label{equ:safe_intersect}
193 \end{equ}
194
195 \subsubsection{Sequential combinators}
196 For the step combinator (\cref{R:step})---and all other derived sequential combinators---the refresh rate of the left-hand side task is taken since that is the only task that is rewritten.
197 Only after stepping, the combinator rewrites to the right-hand side.
198
199 \subsubsection{Repeating combinators}
200 The repeat combinators repeats their argument indefinitely.
201 As the \cleaninline{rpeat} task tree node already includes a rewrite rate (set to $\rewriterate{0}{0}$ for a default \cleaninline{rpeat}), both \cleaninline{rpeat} and \cleaninline{rpeatEvery} use the same task tree node and thus only one entry is required here.
202 The derived refresh rate of the repeat combinator is the refresh rate of the child if it is unstable.
203 Otherwise, the refresh rate is the embedded rate time minus the start time.
204 In case of the \cleaninline{rpeat} task, the default refresh rate is $\rewriterate{0}{0}$ so the task immediately refreshes and starts the task again.
205 \todo{netter opschrijven}
206
207 \subsubsection{Delay combinators}
208 Upon installation, a \cleaninline{delay} task is stored as a \cleaninline{waitUntil} task tree containing the time of installation added to the specified time to wait.
209 Execution wise, it waits until the current time exceeds the time is greater than the argument time.
210
211 \subsubsection{Other tasks}
212 All other tasks are captured by \cref{R:other}.
213 If the task is stable, rewriting can be delayed indefinitely since the value will not change anyway.
214 In all other cases, the values from \cref{tbl:rewrite} apply where $r_l$ and $r_u$ represent the lower and upper bound of this rate.
215
216 The rewrite intervals associated with various steps of the thermostat program from \cref{lst:thermostat} are given in \cref{tbl:intervals}.
217 Those rewrite steps and intervals are circular, after step 2 we continue with step 0 again.
218 Only the actual reading of the sensor with \cleaninline{temperature dht} offers the possibility for a non-zero delay.
219
220 \subsection{Example}
221 %%\begin{table}[tb]
222 \begin{table}
223 \centering
224 \caption{Rewrite steps of the thermostat from \cref{lst:thermostat} and associated intervals.}%
225 \label{tbl:intervals}
226 \begin{tabular}{cp{20em}c}
227 \toprule
228 Step & Expression & Interval \\
229 \midrule
230 0 &
231 \begin{lstClean}[aboveskip=-2ex,belowskip=-2ex,frame=]
232 rpeat ( temperature dht >>~. \temp.
233 writeD builtInLED (goal <. temp)
234 )\end{lstClean}
235 &
236 $\rewriterate{0}{0}$ \\
237 %\hline
238 1 &
239 \begin{lstClean}[aboveskip=-2ex,belowskip=-2ex,frame=]
240 temperature dht >>~. \temp.
241 writeD builtInLED (goal <. temp) >>|.
242 rpeat ( temperature dht >>~. \temp.
243 writeD builtInLED (goal <. temp)
244 )\end{lstClean}
245 & $\rewriterate{0}{2000}$ \\
246 %\hline
247 2 &
248 \begin{lstClean}[aboveskip=-2ex,belowskip=-2ex,frame=]
249 writeD builtInLED false >>|.
250 rpeat ( temperature dht >>~. \temp.
251 writeD builtInLED (goal <. temp)
252 )\end{lstClean}
253 & $\rewriterate{0}{0}$ \\
254 \bottomrule
255 \end{tabular}
256 \end{table}
257
258 \subsection{Tweaking rewrite rates}
259 A tailor-made \gls{ADT} (see \cref{lst:interval}) determines the timing intervals for which the value is determined at runtime but the constructor is known at compile time.
260 During compilation, the constructor of the \gls{ADT} is checked and code is generated accordingly.
261 If it is \cleaninline{Default}, no extra code is generated.
262 In the other cases, code is generated to wrap the task tree node in a \emph{tune rate} node.
263 In the case that there is a lower bound, i.e.\ the task must not be executed before this lower bound, an extra \emph{rate limit} task tree node is generated that performs a no-op rewrite if the lower bound has not passed but caches the task value.
264
265 \begin{lstClean}[caption={The \gls{ADT} for timing intervals in \gls{MTASK}.},label={lst:interval}]
266 :: TimingInterval v = Default
267 | BeforeMs (v Int) // yields [+$\rewriterate{0}{x}$+]
268 | BeforeS (v Int) // yields [+$\rewriterate{0}{x \times 1000}$+]
269 | ExactMs (v Int) // yields [+$\rewriterate{x}{x}$+]
270 | ExactS (v Int) // yields [+$\rewriterate{0}{x \times 1000}$+]
271 | RangeMs (v Int) (v Int) // yields [+$\rewriterate{x}{y}$+]
272 | RangeS (v Int) (v Int) // yields [+$\rewriterate{x \times 1000}{y \times 1000}$+]
273 \end{lstClean}
274
275 \subsubsection{Sensors and \texorpdfstring{\glspl{SDS}}{shared data sources}}
276 In some applications, it is necessary to read sensors or \glspl{SDS} at a different rate than the default rate given in \cref{tbl:rewrite}, i.e.\ to customise the rewrite rate.
277 This is achieved by calling the access functions with a custom rewrite rate as an additional argument (suffixed with the backtick (\cleaninline{`}))
278 The adaptions to other classes are similar and omitted for brevity.
279 \Cref{lst:dht_ext} shows the extended \cleaninline{dht} and \cleaninline{dio} class definition with functions for custom rewrite rates.
280
281 \begin{lstClean}[caption={Auxiliary definitions to \cref{lst:gpio,lst:dht} for \gls{DHT} sensors and digital \gls{GPIO} with custom timing intervals.},label={lst:dht_ext}]
282 class dht v where
283 ...
284 temperature` :: (TimingInterval v) (v DHT) -> MTask v Real
285 temperature :: (v DHT) -> MTask v Real
286 humidity` :: (TimingInterval v) (v DHT) -> MTask v Real
287 humidity :: (v DHT) -> MTask v Real
288
289 class dio p v | pin p where
290 ...
291 readD` :: (TimingInterval v) (v p) -> MTask v Bool | pin p
292 readD :: (v p) -> MTask v Bool | pin p
293 \end{lstClean}
294
295 As example, we define an \gls{MTASK} that updates the \gls{SDS} \cleaninline{tempSds} in \gls{ITASK} in a tight loop.
296 The \cleaninline{temperature`} reading requires that this happens at least once per minute.
297 Without other tasks on the \gls{IOT} node, the temperature \gls{SDS} is updated once per minute.
298 Other tasks can cause a slightly more frequent update.
299
300 \begin{lstClean}[caption={Updating \pgls{SDS} in \gls{ITASK} at least once per minute.},label={lst:updatesds2}]
301 delayTime :: TimingInterval v | mtask v
302 delayTime = BeforeS (lit 60) // 1 minute in seconds
303
304 devTask :: Main (MTask v Real) | mtask, dht, liftsds v
305 devTask =
306 DHT (DHT_DHT pin DHT11) \dht =
307 liftsds \localSds = tempSds
308 In {main = rpeat (temperature` delayTime dht >>~. setSds localSds)}
309 \end{lstClean}
310
311 \subsubsection{Repeating tasks}
312 The task combinator \cleaninline{rpeat} restarts the child task in the evaluation if the previous produced a stable result.
313 However, in some cases it is desirable to postpone the restart of the child.
314 For this, the \cleaninline{rpeatEvery} task is introduced which receives an extra argument, the rewrite rate, as shown in \cref{lst:rpeatevery}.
315 Instead of immediately restarting the child once it yields a stable value, it checks whether the lower bound of the provided timing interval has passed since the start of the task\footnotemark.
316 \footnotetext{In reality, it also compensates for time drift by taking into account the upper bound of the timing interval.
317 If the task takes longer to stabilise than the upper bound of the timing interval, this upper bound is taken as the start of the task instead of the actual start.}
318
319 \begin{lstClean}[caption={Repeat task combinator with a timing interval.},label={lst:rpeatevery}]
320 class rpeat v where
321 rpeat :: (MTask v t) -> MTask v t
322 rpeatEvery v :: (TimingInterval v) (MTask v t) -> MTask v t
323 \end{lstClean}
324
325 \Cref{lst:rpeateveryex} shows an example of an \gls{MTASK} task utilising the \cleaninline{rpeatEvery} combinator that would be impossible to create with the regular \cleaninline{rpeat}.
326 The \cleaninline{timedPulse} function creates a task that sends a \qty{50}{\ms} pulse to the \gls{GPIO} pin 0 every second.
327 The task created by the \cleaninline{timedPulseNaive} functions emulates the behaviour by using \cleaninline{rpeat} and \cleaninline{delay}.
328 However, this results in a time drift because rewriting tasks trees takes some time and the time it takes can not always be reliably predicted due to external factors.
329 E.g.\ writing to \gls{GPIO} pins takes some time, interrupts may slow down the program (see \cref{lst:interrupts}), or communication may occur in between task evaluations.
330
331 \begin{lstClean}[caption={Example program for the repeat task combinator with a timing interval.},label={lst:rpeateveryex}]
332 timedPulse :: Main (MTask v Bool) | mtask v
333 timedPulse = declarePin D0 PMOutput \d0->
334 in {main = rpeatEvery (ExactSec (lit 1)) (
335 writeD d0 true
336 >>|. delay (lit 50)
337 >>|. writeD d0 false
338 )
339 }
340
341 timedPulseNaive :: Main (MTask v Bool) | mtask v
342 timedPulseNaive = declarePin D0 PMOutput \d0->
343 {main = rpeat (
344 writeD d0 true
345 >>|. delay (lit 50)
346 >>|. writeD d0 false
347 >>|. delay (lit 950))
348 }
349 \end{lstClean}
350
351 \section{Task scheduling in the \texorpdfstring{\gls{MTASK}}{mTask} engine}
352 The rewrite rates from the previous section only tell us how much the next evaluation of the task can be delayed.
353 An \gls{IOT} edge devices executes multiple tasks may run interleaved.
354 In addition, it has to communicate with a server to collect new tasks and updates of \glspl{SDS}.
355 Hence, the rewrite intervals cannot be used directly to let the microcontroller sleep.
356 Our scheduler has the following objectives.
357 \begin{itemize}
358 \item
359 Meet the deadline whenever possible, i.e.\ the system tries to execute every task before the end of its rewrite interval.
360 Only too much work on the device might cause an overflow of the deadline.
361 \item
362 Achieve long sleep times. Waking up from sleep consumes some energy and takes some time.
363 Hence, we prefer a single long sleep over splitting this interval into several smaller pieces.
364 \item
365 The scheduler tries to avoid unnecessary evaluations of tasks as much as possible.
366 A task should not be evaluated now when its execution can also be delayed until the next time that the device is active.
367 That is, a task should preferably not be executed before the start of its rewrite interval.
368 Whenever possible, task execution should even be delayed when we are inside the rewrite interval as long as we can execute the task before the end of the interval.
369 \item
370 The optimal power state should be selected.
371 Although a system uses less power in a deep sleep mode, it also takes more time and energy to wake up from deep sleep.
372 When the system knows that it can sleep only a short time it is better to go to light sleep mode since waking up from light sleep is faster and consumes less energy.
373 \end{itemize}
374
375 The algorithm $\mathcal{R}$ from \cref{sec:deriving_rewrite_rates} computes the evaluation rate of the current tasks.
376 For the scheduler, we transform this interval to an absolute evaluation interval; the lower and upper bound of the start time of that task measured in the time of the \gls{IOT} edge device.
377 We obtain those bounds by adding the current system time to the bounds of the computed rewrite interval by algorithm $\mathcal{R}$.
378
379 For the implementation, it is important to note that the evaluation of a task takes time.
380 Some tasks are extremely fast, but other tasks require long computations and time-consuming communication with peripherals as well as with the server.
381 These execution times can yield a considerable and noticeable time drift in \gls{MTASK} programs.
382 For instance, a task like \cleaninline{rpeatEvery (ExactMs 1) t} should repeat \cleaninline{t} every millisecond.
383 The programmer might expect that \cleaninline{t} will be executed for the ${(N+1)}^{th}$ time after $N$ milliseconds.
384 Uncompensated time drift might make this considerably later.
385 \Gls{MTASK} does not pretend to be a hard real-time \gls{OS}, and cannot give firm guarantees with respect to evaluation time.
386 Nevertheless, we try to make time handling as reliable as possible.
387 This is achieved by adding the start time of this round of task evaluations rather than the current time to compute absolute execution intervals.
388
389 \subsection{Scheduling Tasks}
390 Apart from the task to execute, the \gls{IOT} device has to maintain the connection with the server and check there for new tasks and updates of \gls{SDS}.
391 When the microcontroller is active, it checks the connection and updates from the server and executes the task if it is in its execution window.
392 Next, the microcontroller goes to light sleep for the minimum of a predefined interval and the task delay.
393
394 In general, the microcontroller node executes multiple \gls{MTASK} tasks at the same time.
395 \Gls{MTASK} nodes repeatedly check for inputs from servers and execute all tasks that cannot be delayed to the next evaluation round one step.
396 The tasks are stored in a priority queue to check efficiently which of them need to be stepped.
397 The \gls{MTASK} tasks are ordered at their absolute latest start time in this queue; the earliest deadline first.
398 We use the earliest deadline to order tasks with equal latest deadline.
399
400 It is very complicated to make an optimal scheduling algorithm for tasks to minimize the energy consumption.
401 We use a simple heuristic to evaluate tasks and determine sleep time rather than wasting energy on a fancy evaluation algorithm.
402 \Cref{lst:evalutionRound} gives this algorithm in pseudo code.
403 First the \gls{MTASK} node checks for new tasks and updates of \glspl{SDS}.
404 This communication adds any task to the queue.
405 The \cleaninline{stepped} set contains all tasks evaluated in this evaluation round.
406 Next, we evaluate tasks from the queue until we encounter a task that has an evaluation interval that is not started.
407 This might evaluate tasks earlier than required, but maximizes the opportunities to sleep after this evaluation round.
408 %Using the \prog{stepped} set ensures that we evaluate each task at most once during an evaluation round.
409 Executed tasks are temporarily stored in the \cleaninline{stepped} set instead of inserted directly into the queue to ensure that they are evaluated at most once in a evaluation round to ensure that there is frequent communication with the server.
410 A task that produces a stable value is completed and is not queued again.
411
412 \begin{algorithm}
413 %\DontPrintSemicolon
414 \SetKwProg{Repeatt}{repeat}{}{end}
415 \KwData{queue = []\;}
416 \Begin{
417 \Repeatt{}{
418 time = currentTime()\;
419 queue += communicateWithServer()\;
420 stepped = []\tcp*{tasks stepped in this round}
421 \While{$\neg$empty(queue) $\wedge$ earliestDeadline(top(queue)) $\leq$ time}{
422 (task, queue) = pop(queue)\;
423 task2 = step(task)\tcp*{computes new execution interval}
424 \If(\tcp*[f]{not finished after step}){$\neg$ isStable(task2)}{
425 stepped += task2\;
426 }
427 }
428 queue = merge(queue, stepped)\;
429 sleep(queue)\;
430 }
431 }
432 \caption{Pseudo code for the evaluation round of tasks in the queue.}
433 \label{lst:evalutionRound}
434 \end{algorithm}
435
436 The \cleaninline{sleep} function determines the maximum sleep time based on the top of the queue.
437 The computed sleep time and the characteristics of the microprocessor determine the length and depth of the sleep.
438 For very short sleep times it might not be worthwhile to sleep.
439 In the current \gls{MTASK} \gls{RTS}, the thresholds are determined by experimentation but can be tuned by the programmer.
440 On systems that lose the content of their \gls{RAM} it is not possible to go to deep sleep mode.
441
442 \section{Interrupts}\label{lst:interrupts}
443 Most microcontrollers have built-in support for processor interrupts.
444 These interrupts are hard-wired signals that can interrupt the normal flow of the program to execute a small piece of code, the \gls{ISR}.
445 While the \glspl{ISR} look like regular functions, they do come with some limitations.
446 For example, they must be very short, in order not to miss future interrupts; can only do very limited \gls{IO}; cannot reliably check the clock; and they operate in their own stack, and thus communication must happen via global variables.
447 After the execution of the \gls{ISR}, the normal program flow is resumed.
448 Interrupts are heavily used internally in the \gls{RTS} of the microcontrollers to perform timing critical operations such as WiFi, \gls{I2C}, or \gls{SPI} communication; completed \gls{ADC} conversions, software timers; exception handling; \etc.
449
450 Interrupts offer two substantial benefits: fewer missed events and better energy usage.
451 Sometimes an external event such as a button press only occurs for a very small duration, making it possible to miss it due to it happening right between two polls.
452 Using interrupts is not a fool-proof way of never missing an event.
453 Events may still be missed if they occur during the execution of an \gls{ISR} or while the microcontroller is still in the process of waking up from a triggered interrupt.
454 There are also some sensors, such as the CCS811 air quality sensor, with support for triggering interrupts when a value exceeds a critical limit.
455
456 There are several different types of interrupts possible.
457 \begin{table}
458 \centering
459 \caption{Overview of \gls{GPIO} interrupt types.}%
460 \label{tbl:gpio_interrupts}
461 \begin{tabular}{ll}
462 \toprule
463 type & triggers\\
464 \midrule
465 change & input changes\\
466 falling & input becomes low\\
467 rising & input becomes high\\
468 low & input is low\\
469 high & input is high\\
470 \bottomrule
471 \end{tabular}
472 \end{table}
473
474 \subsection{\Gls{ARDUINO} platform}
475 \Cref{lst:arduino_interrupt} shows an exemplatory program utilising interrupts written in \gls{ARDUINO}'s \gls{CPP} dialect.
476 The example shows a debounced light switch for the built-in \gls{LED} connected to \gls{GPIO} pin 13.
477 When the user presses the button connected to \gls{GPIO} pin 11, the state of the \gls{LED} changes.
478 As buttons sometimes induce noise shortly after pressing, events within \qty{30}{\ms} after pressing are ignored.
479 In between the button presses, the device goes into deep sleep using the \arduinoinline{LowPower} library.
480
481 \Crefrange{lst:arduino_interrupt:defs_fro}{lst:arduino_interrupt:defs_to} defines the pin and debounce constants.
482 \Cref{lst:arduino_interrupt:state} defines the current state of the \gls{LED}, it is declared \arduinoinline{volatile} to exempt it from compiler optimisations because it is accessed in the interrupt handler.
483 \Cref{lst:arduino_interrupt:cooldown} flags whether the program is in debounce state, i.e.\ events should be ignored for a short period of time.
484
485 In the \arduinoinline{setup} function (\crefrange{lst:arduino_interrupt:setup_fro}{lst:arduino_interrupt:setup_to}), the pinmode of the \gls{LED} and interrupt pins are set.
486 Furthermore, the microcontroller is instructed to wake up from sleep mode when a \emph{rising} interrupt occurs on the interrupt pin and to call the \gls{ISR} at \crefrange{lst:arduino_interrupt:isr_fro}{lst:arduino_interrupt:isr_to}.
487 This \gls{ISR} checks if the program is in cooldown state.
488 If this is not the case, the state of the \gls{LED} is toggled.
489 In any case, the program goes into cooldown state afterwards.
490
491 In the \arduinoinline{loop} function, the microcontroller goes to low-power sleep immediately and indefinitely.
492 Only when an interrupt triggers, the program continues, writes the state to the \gls{LED}, waits for the debounce time, and finally disables the \arduinoinline{cooldown} state.
493
494 \begin{lstArduino}[numbers=left,label={lst:arduino_interrupt},caption={Light switch using interrupts.}]
495 #define LEDPIN 13[+\label{lst:arduino_interrupt:defs_fro}+]
496 #define INTERRUPTPIN 11
497 #define DEBOUNCE 30[+\label{lst:arduino_interrupt:defs_to}+]
498
499 volatile int state = LOW;[+\label{lst:arduino_interrupt:state}+]
500 volatile bool cooldown = true;[+\label{lst:arduino_interrupt:cooldown}+]
501
502 void setup() {[+\label{lst:arduino_interrupt:setup_fro}+]
503 pinMode(LEDPIN, OUTPUT);
504 pinMode(INTERRUPTPIN, INPUT);
505 LowPower.attachInterruptWakeup(INTERRUPTPIN, buttonPressed, RISING);
506 }[+\label{lst:arduino_interrupt:setup_to}+]
507
508 void loop() {[+\label{lst:arduino_interrupt:loop_fro}+]
509 LowPower.sleep();
510 digitalWrite(LEDPIN, state);
511 delay(DEBOUNCE);
512 cooldown = false;
513 }[+\label{lst:arduino_interrupt:loop_to}+]
514
515 void buttonPressed() {[+\label{lst:arduino_interrupt:isr_fro}+]
516 if (!cooldown)
517 state = !state;
518 cooldown = true;
519 }[+\label{lst:arduino_interrupt:isr_to}+]
520 \end{lstArduino}
521
522 \subsection{\texorpdfstring{\Gls{MTASK}}{MTask} language}
523 \Cref{lst:mtask_interrupts} shows the interrupt interface in \gls{MTASK}.
524 The \cleaninline{interrupt} class contains a single function that, given an interrupt mode and a \gls{GPIO} pin, produces a task that represents this interrupt.
525 Lowercase variants of the various interrupt modes such as \cleaninline{change :== lit Change} are available as convenience macros (see \cref{sec:expressions}).
526
527 \begin{lstClean}[label={lst:mtask_interrupts},caption={The interrupt interface in \gls{MTASK}.}]
528 class interrupt v where
529 interrupt :: (v InterruptMode) (v p) -> MTask v Bool | pin p
530
531 :: InterruptMode = Change | Rising | Falling | Low | High
532 \end{lstClean}
533
534 When the \gls{MTASK} device executes this task, it installs an \gls{ISR} and sets the rewrite rate of the task to infinity, $\rewriterate{\infty}{\infty}$.
535 The interrupt handler is set up in such a way that the rewrite rate is changed to $\rewriterate{0}{0}$ once the interrupt triggers.
536 As a consequence, the task is executed on the next execution cycle.
537
538 The \cleaninline{pirSwitch} function in \cref{lst:pirSwitch} creates, given an interval in \unit{\ms}, a task that reacts to motion detection by a \gls{PIR} sensor (connected to \gls{GPIO} pin 0) by lighting the \gls{LED} connected to \gls{GPIO} pin 13 for the given interval.
539 The system lightens the \gls{LED} again when there is still motion detected after this interval.
540 By changing the interrupt mode in this program text from \cleaninline{High} to \cleaninline{Rising} the system lights the \gls{LED} only one interval when it detects motion no matter how long this signal is present at the \gls{PIR} pin.
541
542 \begin{lstClean}[caption={Example of a toggle light switch using interrupts.},label={lst:pirSwitch}]
543 pirSwitch :: Int -> Main (MTask v Bool) | mtask v
544 pirSwitch =
545 declarePin D13 PMOutput \ledpin->
546 declarePin D0 PMInput \pirpin->
547 {main = rpeat ( interrupt high pirpin
548 >>|. writeD ledpin false
549 >>|. delay (lit interval)
550 >>|. writeD ledpin true) }
551 \end{lstClean}
552
553 \subsection{\texorpdfstring{\Gls{MTASK}}{MTask} engine}
554
555 While interrupt tasks have their own node type in the task tree, they differ slightly from other node types because they require a more elaborate setup and teardown.
556 Enabling and disabling interrupts is done in a general way in which tasks register themselves after creation and deregister after deletion.
557 Interrupts should be disabled when there are no tasks waiting for that kind of interrupt because unused interrupts can lead to unwanted wake ups, and only one kind of interrupt can be attached to a pin.
558
559 \subsubsection{Event registration}
560 The \gls{MTASK} \gls{RTS} contains an event administration to register which task is waiting on which event.
561 During the setup of an interrupt task, the event administration in the \gls{MTASK} \gls{RTS} is checked to determine whether a new \gls{ISR} for the particular pin needs to be registered.
562 Furthermore, this registration allows for a quick lookup in the \gls{ISR} to find the tasks listening to the events.
563 Conversely, during the teardown, the \gls{ISR} is disabled again when the last interrupt task of that kind is deleted.
564 The registration is light-weight and consists only of an event identifier and task identifier.
565 This event registration is stored as a linked list of task tree nodes so that the garbage collector can clean them up when they become unused.
566
567 Registering and deregistering interrupts is a device specific procedure, although most supported devices use the \gls{ARDUINO} \gls{API} for this.
568 Which pins support which interrupt differs greatly from device to device but this information is known at compile time.
569 At the time of registration, the \gls{RTS} checks whether the interrupt is valid and throws an \gls{MTASK} exception if it is not.
570 Moreover, an exception is thrown if multiple types of interrupts are registered on the same pin.
571
572 \subsubsection{Triggering interrupts}
573 Once an interrupt fires, tasks registered to that interrupt are not immediately evaluated because it is usually not safe to do.
574 For example, the interrupt could fire in the middle of a garbage collection process, resulting in incorrect pointers.
575 Furthermore, as the \gls{ISR} is supposed to be be very short, just a flag in the event administration is set.
576 Interrupt event flags are processed at the beginning of the event loop, before tasks are executed.
577 For each subscribed task, the task tree is searched for nodes listening for the particular interrupt.
578 When found, the node is flagged and the pin status is written.
579 Afterwards, the evaluation interval of the task is set to $\rewriterate{0}{0}$ and the task is reinsterted at the front of the scheduling queue to ensure rapid evaluation of the task.
580 Finally, the event is removed from the registration and the interrupt is disabled.
581 The interrupt can be disabled as all tasks waiting for the interrupt become stable after firing.
582 More occurrences of the interrupts do not change the value of the task as stable tasks keep the same value forever.
583 Therefore, it is no longer necessary to keep the interrupt enabled, and it is relatively cheap to enable it again if needed in the future.
584 Evaluating interrupt task node in the task tree is trivial because all of the work was already done when the interrupt was triggered.
585 The task emits the status of the pin as a stable value if the information in the task shows that it was triggered.
586 Otherwise, no value is emitted.
587
588 \input{subfilepostamble}
589 \end{document}