95a01c2d313fb056d17c12060786e5fb37e6481e
[phd-thesis.git] / top / mtask.tex
1 \documentclass[../thesis.tex]{subfiles}
2
3 \begin{document}
4 \ifSubfilesClassLoaded{
5 \pagenumbering{arabic}
6 }{}
7
8 \chapter{Introduction to \texorpdfstring{\gls{IOT}}{IoT} programming}%
9 \label{chp:top4iot}
10 \todo{betere chapter naam}
11 \begin{chapterabstract}
12 This chapter introduces \gls{MTASK} and puts it into perspective compared to traditional microprocessor programming.
13 \end{chapterabstract}
14
15 Traditionally, the first program that one writes when trying a new language is the so called \emph{Hello World!} program.
16 This program has the single task of printing the text \emph{Hello World!} to the screen and exiting again, useful to become familiarised with the syntax and verify that the toolchain and runtime environment is working.
17 On microprocessors, there often is no screen for displaying text.
18 Nevertheless, almost always there is a monochrome $1\times1$ pixel screen, namely an---often builtin---\gls{LED}.
19 The \emph{Hello World!} equivalent on microprocessors blinks this \gls{LED}.
20
21 \Cref{lst:arduinoBlink} shows how the logic of a blink program might look when using \gls{ARDUINO}'s \gls{CPP} dialect.
22 Every \gls{ARDUINO} program contains a \arduinoinline{setup} and a \arduinoinline{loop} function.
23 The \arduinoinline{setup} function is executed only once on boot, the \arduinoinline{loop} function is continuously called afterwards and contains the event loop.
24 After setting the \gls{GPIO} pin to the correct mode, blink's \arduinoinline{loop} function alternates the state of the pin representing the \gls{LED} between \arduinoinline{HIGH} and \arduinoinline{LOW}, turning the \gls{LED} off and on respectively.
25 In between it waits for 500 milliseconds so that the blinking is actually visible for the human eye.
26 Compiling this results in a binary firmware that needs to be flashed onto the program memory.
27
28 Translating the traditional blink program to \gls{MTASK} can almost be done by simply substituting some syntax as seen in \cref{lst:blinkImp}.
29 E.g.\ \arduinoinline{digitalWrite} becomes \cleaninline{writeD}, literals are prefixed with \cleaninline{lit} and the pin to blink is changed to represent the actual pin for the builtin \gls{LED} of the device used in the exercises.
30 In contrast to the imperative \gls{CPP} dialect, \gls{MTASK} is a \gls{TOP} language and therefore there is no such thing as a loop, only task combinators to combine tasks.
31 To simulate a loop, the \cleaninline{rpeat} task can be used, this task executes the argument task and, when stable, reinstates it.
32 The body of the \cleaninline{rpeat} contains similarly named tasks to write to the pins and to wait in between.
33 The tasks are connected using the sequential \cleaninline{>>|.} combinator that for all current intents and purposes executes the tasks after each other.
34
35 \begin{figure}[ht]
36 \begin{subfigure}[b]{.5\linewidth}
37 \begin{lstArduino}[caption={Blink program.},label={lst:arduinoBlink}]
38 void setup() {
39 pinMode(D2, OUTPUT);
40 }
41
42 void loop() {
43 digitalWrite(D2, HIGH);
44 delay(500);
45 digitalWrite(D2, LOW);
46 delay(500);
47 }\end{lstArduino}
48 \end{subfigure}%
49 \begin{subfigure}[b]{.5\linewidth}
50 \begin{lstClean}[caption={Blink program.},label={lst:blinkImp}]
51 blink :: Main (MTask v ()) | mtask v
52 blink =
53 declarePin D2 PMOutput \d2->
54 {main = rpeat (
55 writeD d2 true
56 >>|. delay (lit 500)
57 >>|. writeD d2 false
58 >>|. delay (lit 500)
59 )
60 }\end{lstClean}
61 \end{subfigure}
62 \end{figure}
63
64 \section{Threaded blinking}
65 Now say that we want to blink multiple blinking patterns on different \glspl{LED} concurrently.
66 For example, blink three \glspl{LED} connected to \gls{GPIO} pins $1,2$ and $3$ at intervals of $500,300$ and $800$ milliseconds.
67 Intuitively you want to lift the blinking behaviour to a function and call this function three times with different parameters as done in \cref{lst:blinkthreadno}
68
69 \begin{lstArduino}[caption={Naive approach to multiple blinking patterns.},label={lst:blinkthreadno}]
70 void setup () { ... }
71
72 void blink (int pin, int wait) {
73 digitalWrite(pin, HIGH);
74 delay(wait);
75 digitalWrite(pin, LOW);
76 delay(wait);
77 }
78
79 void loop() {
80 blink (D1, 500);
81 blink (D2, 300);
82 blink (D3, 800);
83 }\end{lstArduino}
84
85 Unfortunately, this does not work because the \arduinoinline{delay} function blocks all further execution.
86 The resulting program will blink the \glspl{LED} after each other instead of at the same time.
87 To overcome this, it is necessary to slice up the blinking behaviour in very small fragments so it can be manually interleaved~\citep{feijs_multi-tasking_2013}.
88 \Cref{lst:blinkthread} shows how three different blinking patterns might be achieved in \gls{ARDUINO} using the slicing method.
89 If we want the blink function to be a separate parametrizable function we need to explicitly provide all references to the required state.
90 Furthermore, the \arduinoinline{delay} function can not be used and polling \arduinoinline{millis} is required.
91 The \arduinoinline{millis} function returns the number of milliseconds that have passed since the boot of the microprocessor.
92 Some devices use very little energy when in \arduinoinline{delay} or sleep state.
93 Resulting in \arduinoinline{millis} potentially affects power consumption since the processor is basically busy looping all the time.
94 In the simple case of blinking three \glspl{LED} on fixed intervals, it might be possible to calculate the delays in advance using static analysis and generate the appropriate \arduinoinline{delay} code.
95 Unfortunately, this is very hard when for example the blinking patterns are determined at runtime.
96
97 \begin{lstArduino}[label={lst:blinkthread},caption={Threading three blinking patterns.}]
98 long led1 = 0, led2 = 0, led3 = 0;
99 bool st1 = false, st2 = false, st3 = false;
100
101 void blink(int pin, int dlay, long *lastrun, bool *st) {
102 if (millis() - *lastrun > dlay) {
103 digitalWrite(pin, *st = !*st);
104 *lastrun += dlay;
105 }
106 }
107
108 void loop() {
109 blink(D1, 500, &led1, &st1);
110 blink(D2, 300, &led2, &st1);
111 blink(D3, 800, &led3, &st1);
112 }\end{lstArduino}
113
114 This method is very error prone, requires a lot of pointer juggling and generally results into spaghetti code.
115 Furthermore, it is very difficult to represent dependencies between threads, often state machines have to be explicitly programmed by hand to achieve this.
116
117 \section{Blinking in \texorpdfstring{\gls{MTASK}}{mTask}}
118 The \cleaninline{delay} \emph{task} does not block the execution but \emph{just} emits no value when the target waiting time has not yet passed and emits a stable value when the time is met.
119 In contrast, the \arduinoinline{delay()} \emph{function} on the \gls{ARDUINO} is blocking which prohibits interleaving.
120 To make code reuse possible and make the implementation more intuitive, the blinking behaviour is lifted to a recursive function instead of using the imperative \cleaninline{rpeat} construct.
121 The function is parametrized with the current state, the pin to blink and the waiting time.
122 Creating recursive functions like this is not possible in the \gls{ARDUINO} language because the program would run out of stack in an instant and nothing can be interleaved.
123 With a parallel combinator, tasks can be executed in an interleaved fashion.
124 Therefore, blinking three different blinking patterns is as simple as combining the three calls to the \cleaninline{blink} function with their arguments as seen in \cref{lst:blinkthreadmtask}.
125
126 % VimTeX: SynIgnore on
127 \begin{lstClean}[label={lst:blinkthreadmtask},caption={Threaded blinking.}]
128 blinktask :: MTask v () | mtask v
129 blinktask =
130 declarePin D1 PMOutput \d1->
131 declarePin D2 PMOutput \d2->
132 declarePin D3 PMOutput \d3->
133 fun \blink=(\(st, pin, wait)->
134 delay wait
135 >>|. writeD d13 st
136 >>|. blink (Not st, pin, wait)) In
137 {main = blink (true, d1, lit 500)
138 .||. blink (true, d2, lit 300)
139 .||. blink (true, d3, lit 800)
140 }\end{lstClean}
141 % VimTeX: SynIgnore off
142
143 \chapter{The \texorpdfstring{\gls{MTASK}}{mTask} \texorpdfstring{\gls{DSL}}{DSL}}%
144 \label{chp:mtask_dsl}
145 \begin{chapterabstract}
146 This chapter serves as a complete guide to the \gls{MTASK} language, from an \gls{MTASK} programmer's perspective.
147 \end{chapterabstract}
148
149 The \gls{MTASK} system is a \gls{TOP} programming environment for programming microprocessors.
150 It is implemented as an\gls{EDSL} in \gls{CLEAN} using class-based---or tagless-final---embedding (See \cref{ssec:tagless}).
151 Due to the nature of the embedding technique, it is possible to have multiple interpretations of---or views on---programs written in the \gls{MTASK} language.
152 The following interpretations are available for \gls{MTASK}.
153
154 \begin{itemize}
155 \item Pretty printer
156
157 This interpretation converts the expression to a string representation.
158 \item Simulator
159
160 The simulator converts the expression to a ready-for-work \gls{ITASK} simulation in which the user can inspect and control the simulated peripherals and see the internal state of the tasks.
161 \item Compiler
162
163 The compiler compiles the \gls{MTASK} program at runtime to a specialised bytecode.
164 Using a handful of integration functions and tasks, \gls{MTASK} tasks can be executed on microprocessors and integrated in \gls{ITASK} as if they were regular \gls{ITASK} tasks.
165 Furthermore, with special language constructs, \glspl{SDS} can be shared between \gls{MTASK} and \gls{ITASK} programs.
166 \end{itemize}
167
168 When using the compiler interpretation in conjunction with the \gls{ITASK} integration, \gls{MTASK} is a heterogeneous \gls{DSL}.
169 I.e.\ some components---e.g.\ the \gls{RTS} on the microprocessor---is largely unaware of the other components in the system.
170 Furthermore, it is executed on a completely different architecture.
171 The \gls{MTASK} language consists of a host language---a simply-typed $\lambda$-calculua with support for some basic types, function definition and data types (see \cref{sec:expressions})---enriched with a task language (see \cref{sec:top}).
172
173 \section{Types}
174 To leverage the type checker of the host language, types in the \gls{MTASK} language are expressed as types in the host language, to make the language type safe.
175 However, not all types in the host language are suitable for microprocessors that may only have \qty{2}{\kibi\byte} of \gls{RAM} so class constraints are therefore added to the \gls{DSL} functions.
176 The most used class constraint is the \cleaninline{type} class collection containing functions for serialization, printing, \gls{ITASK} constraints \etc.
177 Many of these functions can be derived using generic programming.
178 An even stronger restriction on types is defined for types that have a stack representation.
179 This \cleaninline{basicType} class has instances for many \gls{CLEAN} basic types such as \cleaninline{Int}, \cleaninline{Real} and \cleaninline{Bool}.
180 The class constraints for values in \gls{MTASK} are omnipresent in all functions and therefore often omitted throughout throughout the chapters for brevity and clarity.
181
182 \begin{table}[ht]
183 \centering
184 \begin{tabular}{lll}
185 \toprule
186 \gls{CLEAN}/\gls{MTASK} & \gls{CPP} type & \textnumero{}bits\\
187 \midrule
188 \cleaninline{Bool} & \cinline{bool} & 16\\
189 \cleaninline{Char} & \cinline{char} & 16\\
190 \cleaninline{Int} & \cinline{int16_t} & 16\\
191 \cleaninline{:: Long} & \cinline{int32_t} & 32\\
192 \cleaninline{Real} & \cinline{float} & 32\\
193 \cleaninline{:: T = A \| B \| C} & \cinline{enum} & 16\\
194 \bottomrule
195 \end{tabular}
196 \caption{Mapping from \gls{CLEAN}/\gls{MTASK} data types to \gls{CPP} datatypes.}%
197 \label{tbl:mtask-c-datatypes}
198 \end{table}
199
200 The \gls{MTASK} language consists of a core collection of type classes bundled in the type class \cleaninline{class mtask}.
201 Every interpretation implements the type classes in the \cleaninline{mtask} class
202 There are also \gls{MTASK} extensions that not every interpretation implements such as peripherals and integration with \gls{ITASK}.
203
204 \Cref{lst:constraints} contains the definitions for the type constraints and shows some example type signatures for typical \gls{MTASK} expressions and tasks.
205 \todo{uitleggen}
206
207 \begin{lstClean}[caption={Classes and class collections for the \gls{MTASK} language.},label={lst:constraints}]
208 :: Main a = { main :: a }
209 :: In a b = (In) infix 0 a b
210
211 class type t | iTask, ... ,fromByteCode, toByteCode t
212 class basicType t | type t where ...
213
214 class mtask v | expr, ..., int, real, long v
215
216 someExpr :: v Int | mtask v
217 someExpr = ...
218
219 someTask :: MTask v Int | mtask v
220 someTask =
221 sensor1 config1 \sns1->
222 sensor2 config2 \sns2->
223 fun \fun1= ( ... )
224 In fun \fun2= ( ... )
225 In {main=mainexpr}
226 \end{lstClean}
227
228 \section{Expressions}\label{sec:expressions}
229 \Cref{lst:expressions} shows the \cleaninline{expr} class containing the functionality to lift values from the host language to the \gls{MTASK} language (\cleaninline{lit}); perform number and boolean arithmetics; do comparisons; and conditional execution.
230 For every common arithmetic operator in the host language, an \gls{MTASK} variant is present, suffixed by a period to not clash with \gls{CLEAN}'s builtin operators.
231
232 \begin{lstClean}[caption={The \gls{MTASK} class for expressions},label={lst:expressions}]
233 class expr v where
234 lit :: t -> v t | type t
235 (+.) infixl 6 :: (v t) (v t) -> v t | basicType, +, zero t
236 ...
237 (&.) infixr 3 :: (v Bool) (v Bool) -> v Bool
238 (|.) infixr 2 :: (v Bool) (v Bool) -> v Bool
239 Not :: (v Bool) -> v Bool
240 (==.) infix 4 :: (v a) (v a) -> v Bool | Eq, basicType a
241 ...
242 If :: (v Bool) (v t) (v t) -> v t | type t
243 \end{lstClean}
244
245 Conversion to-and-fro data types is available through the overloaded functions \cleaninline{int}, \cleaninline{long} and \cleaninline{real}.
246
247 \begin{lstClean}[caption={Type conversion functions in \gls{MTASK}.}]
248 class int v a :: (v a) -> v Int
249 class real v a :: (v a) -> v Real
250 class long v a :: (v a) -> v Long
251 \end{lstClean}
252
253 Finally, values from the host language must be explicitly lifted to the \gls{MTASK} language using the \cleaninline{lit} function.
254 For convenience, there are many lower-cased macro definitions for often used constants such as \cleaninline{true :== lit True}, \cleaninline{false :== lit False}, \etc.
255
256 \Cref{lst:example_exprs} shows some examples of these expressions.
257 \cleaninline{e0} defines the literal $42$, \cleaninline{e1} calculates the literal $42.0$ using real numbers.
258 \cleaninline{e2} compares \cleaninline{e0} and \cleaninline{e1} as integers and if they are equal it returns the \cleaninline{e2}$/2$ and \cleaninline{e0} otherwise.
259 \cleaninline{approxEqual} performs an approximate equality---albeit not taking into account all floating point pecularities---and demonstrates that \gls{CLEAN} can be used as a macro language, i.e.\ maximise linguistic reuse \citep{krishnamurthi_linguistic_2001}.
260 \todo{uitzoeken waar dit handig is}
261 When calling \cleaninline{approxEqual} in an \gls{MTASK} function, the resulting code is inlined.
262
263 \begin{lstClean}[label={lst:example_exprs},caption={Example \gls{MTASK} expressions.}]
264 e0 :: v Int | expr v
265 e0 = lit 42
266
267 e1 :: v Real | expr v
268 e1 = lit 38.0 + real (lit 4)
269
270 e2 :: v Int | expr v
271 e2 = if' (e0 ==. int e1)
272 (int e1 /. lit 2) e0
273
274 approxEqual :: (v Real) (v Real) (v Real) -> v Real | expr v
275 approxEqual x y eps = if' (x == y) true
276 ( if' (x > y)
277 (y -. x < eps)
278 (x -. y < eps)
279 )
280 \end{lstClean}
281
282 \subsection{Data Types}
283 Most of \gls{CLEAN}'s basic types have been mapped on \gls{MTASK} types.
284 However, it can be useful to have access to compound types as well.
285 All types in \gls{MTASK} must have a fixed size representation on the stack so sum types are not (yet) supported.
286 While it is possible to lift types using the \cleaninline{lit} function, you cannot do anything with the types besides passing them around but they are being produced by some parallel task combinators (see \cref{sssec:combinators_parallel}).
287 To be able to use types as first class citizens, constructors and field selectors are required.
288 \Cref{lst:tuple_exprs} shows the scaffolding for supporting tuples in \gls{MTASK}.
289 Besides the constructors and field selectors, there is also a helper function available that transforms a function from a tuple of \gls{MTASK} expressions to an \gls{MTASK} expression of a tuple.
290
291 \begin{lstClean}[label={lst:tuple_exprs},caption={Tuple constructor and field selectors in \gls{MTASK}.}]
292 class tupl v where
293 tupl :: (v a) (v b) -> v (a, b) | type a & type b
294 first :: (v (a, b)) -> v a | type a & type b
295 second :: (v (a, b)) -> v b | type a & type b
296
297 tupopen f :== \v->f (first v, second v)
298 \end{lstClean}
299
300 \subsection{Functions}
301 Adding functions to the language is achieved by one multi-parameter class to the \gls{DSL}.
302 By using \gls{HOAS}, both the function definition and the calls to the function can be controlled by the \gls{DSL}~\citep{pfenning_higher-order_1988,chlipala_parametric_2008}.
303 As \gls{MTASK} only supports first-order functions and does not allow partial function application.
304 Using a type class of this form, this restriction can be enforced on the type level.
305 Instead of providing one instance for all functions, a single instance per function arity is defined.
306 Also, \gls{MTASK} only supports top-level functions which is enforced by the \cleaninline{Main} box.
307 The definition of the type class and the instances for an example interpretation are as follows:
308 \todo{uitbreiden}
309
310 \begin{lstClean}[caption={Functions in \gls{MTASK}.}]
311 class fun a v :: ((a -> v s) -> In (a -> v s) (Main (MTask v u)))
312 -> Main (MTask v u)
313
314 instance fun () Inter where ...
315 instance fun (Inter a) Inter | type a where ...
316 instance fun (Inter a, Inter b) Inter | type a where ...
317 instance fun (Inter a, Inter b, Inter c) Inter | type a where ...
318 ...
319 \end{lstClean}
320
321 Deriving how to define and use functions from the type is quite the challenge even though the resulting syntax is made easier using the infix type \cleaninline{In}.
322 \Cref{lst:function_examples} show the factorial function, a tail-call optimised factorial function and a function with zero arguments to demonstrate the syntax.
323 Splitting out the function definition for each single arity means that that for every function arity and combination of arguments, a separate class constraint must be created.
324 Many of the often used functions are already bundled in the \cleaninline{mtask} class constraint collection.
325 \cleaninline{factorialtail} shows a manually added class constraint.
326 Definiting zero arity functions is shown in the \cleaninline{zeroarity} expression.
327 Finally, \cleaninline{swapTuple} shows an example of a tuple being swapped.
328
329 % VimTeX: SynIgnore on
330 \begin{lstClean}[label={lst:function_examples},caption={Function examples in \gls{MTASK}.}]
331 factorial :: Main (v Int) | mtask v
332 factorial =
333 fun \fac=(\i->if' (i <. lit 1)
334 (lit 1)
335 (i *. fac (i -. lit 1)))
336 In {main = fac (lit 5) }
337
338 factorialtail :: Main (v Int) | mtask v & fun (v Int, v Int) v
339 factorialtail =
340 fun \facacc=(\(acc, i)->if' (i <. lit 1)
341 acc
342 (fac (acc *. i, i -. lit 1)))
343 In fun \fac=(\i->facacc (lit 1, i))
344 In {main = fac (lit 5) }
345
346 zeroarity :: Main (v Int) | mtask v
347 zeroarity =
348 fun \fourtytwo=(\()->lit 42)
349 In fun \add=(\(x, y)->x +. y)
350 In {main = add (fourtytwo (), lit 9)}
351
352 swapTuple :: Main (v (Int, Bool)) | mtask v
353 swapTuple =
354 fun \swap=(tupopen \(x, y)->tupl y x)
355 In {main = swap (tupl true (lit 42)) }
356 \end{lstClean}
357 % VimTeX: SynIgnore off
358
359 \section{Tasks}\label{sec:top}
360 \Gls{MTASK}'s task language can be divided into three categories, namely
361 \begin{enumerate*}
362 \item Basic tasks, in most \gls{TOP} systems, the basic tasks are called editors, modelling the interactivity with the user.
363 In \gls{MTASK}, there are no \emph{editors} in that sense but there is interaction with the outside world through microprocessor peripherals such as sensors and actuators.
364 \item Task combinators provide a way of describing the workflow.
365 They combine one or more tasks into a compound task.
366 \item \glspl{SDS} in \gls{MTASK} can be seen as references to data that can be shared using many-to-many communication and are only accessible from within the task language to ensure atomicity.
367 \end{enumerate*}
368
369 As \gls{MTASK} is integrated with \gls{ITASK}, the same stability distinction is made for task values.
370 A task in \gls{MTASK} is denoted by the \gls{DSL} type synonym shown in \cref{lst:task_type}.
371
372 \begin{lstClean}[label={lst:task_type},caption={Task type in \gls{MTASK}.}]
373 :: MTask v a :== v (TaskValue a)
374 :: TaskValue a
375 = NoValue
376 | Value a Bool
377 \end{lstClean}
378
379 \subsection{Basic tasks}
380 The most rudimentary basic tasks are the \cleaninline{rtrn} and \cleaninline{unstable} tasks.
381 They lift the value from the \gls{MTASK} expression language to the task domain either as a stable value or an unstable value.
382 There is also a special type of basic task for delaying execution.
383 The \cleaninline{delay} task---given a number of milliseconds---yields an unstable value while the time has not passed.
384 Once the specified time has passed, the time it overshot the planned time is yielded as a stable task value.
385
386 \begin{lstClean}[label={lst:basic_tasks},caption={Function examples in \gls{MTASK}.}]
387 class rtrn v :: (v t) -> MTask v t
388 class unstable v :: (v t) -> MTask v t
389 class delay v :: (v n) -> MTask v n | long v n
390 \end{lstClean}
391
392 \subsubsection{Peripherals}\label{sssec:peripherals}
393 For every sensor or actuator, basic tasks are available that allow interaction with the specific peripheral.
394 The type classes for these tasks are not included in the \cleaninline{mtask} class collection as not all devices nor all language interpretations have such peripherals connected.
395 \todo{Historically, peripheral support has been added \emph{by need}.}
396
397 \Cref{lst:dht} and \cref{lst:gpio} show the type classes for \glspl{DHT} sensors and \gls{GPIO} access.
398 Other peripherals have similar interfaces, they are available in the \cref{sec:aux_peripherals}.
399 For the \gls{DHT} sensor there are two basic tasks, \cleaninline{temperature} and \cleaninline{humidity}, that---will given a \cleaninline{DHT} object---produce a task that yields the observed temperature in \unit{\celcius} or relative humidity as a percentage as an unstable value.
400 Currently, two different types of \gls{DHT} sensors are supported, the \emph{DHT} family of sensors connect through $1$-wire protocol and the \emph{SHT} family of sensors connected using \gls{I2C} protocol.
401 Creating such a \cleaninline{DHT} object is very similar to creating functions in \gls{MTASK} and uses \gls{HOAS} to make it type safe.
402
403 \begin{lstClean}[label={lst:dht},caption{The \gls{MTASK} interface for \glspl{DHT} sensors.}]
404 :: DHT //abstract
405 :: DHTInfo
406 = DHT_DHT Pin DHTtype
407 | DHT_SHT I2CAddr
408 :: DHTtype = DHT11 | DHT21 | DHT22
409 class dht v where
410 DHT :: DHTInfo ((v DHT) -> Main (v b)) -> Main (v b) | type b
411 temperature :: (v DHT) -> MTask v Real
412 humidity :: (v DHT) -> MTask v Real
413
414 measureTemp :: Main (MTask v Real) | mtask v & dht v
415 measureTemp = DHT (DHT_SHT (i2c 0x36)) \dht->
416 {main=temperature dht}
417 \end{lstClean}
418
419 \Gls{GPIO} access is divided into three classes: analog, digital and pin modes.
420 For all pins and pin modes an \gls{ADT} is available that enumerates the pins.
421 The analog \gls{GPIO} pins of a microprocessor are connected to an \gls{ADC} that translates the voltage to an integer.
422 Analog \gls{GPIO} pins can be either read or written to.
423 Digital \gls{GPIO} pins only report a high or a low value.
424 The type class definition is a bit more complex since analog \gls{GPIO} pins can be used as digital \gls{GPIO} pins as well.
425 Therefore, if the \cleaninline{p} type implements the \cleaninline{pin} class---i.e.\ either \cleaninline{APin} or \cleaninline{DPin}---the \cleaninline{dio} class can be used.
426 \Gls{GPIO} pins usually operate according to a certain pin mode that states whether the pin acts as an input pin, an input with an internal pull-up resistor or an output pin.
427 This setting can be applied using the \cleaninline{pinMode} class by hand or by using the \cleaninline{declarePin} \gls{GPIO} pin constructor.
428 Setting the pin mode is a task that immediately finisheds and fields a stable unit value.
429 Writing to a pin is also a task that immediately finishes but yields the written value instead.
430 Reading a pin is a task that yields an unstable value---i.e.\ the value read from the actual pin.
431
432 \begin{lstClean}[label={lst:gpio},caption{The \gls{MTASK} interface for \gls{GPIO} access.}]
433 :: APin = A0 | A1 | A2 | A3 | A4 | A5
434 :: DPin = D0 | D1 | D2 | D3 | D4 | D5 | D6 | D7 | D8 | D9 | D10 | D11 | D12 | D13
435 :: PinMode = PMInput | PMOutput | PMInputPullup
436 :: Pin = AnalogPin APin | DigitalPin DPin
437 class pin p :: p -> Pin
438
439 class aio v where
440 writeA :: (v APin) (v Int) -> MTask v Int
441 readA :: (v APin) -> MTask v Int
442
443 class dio p v | pin p where
444 writeD :: (v p) (v Bool) -> MTask v Bool
445 readD :: (v p) -> MTask v Bool | pin p
446
447 class pinMode v where
448 pinMode :: (v PinMode) (v p) -> MTask v () | pin p
449 declarePin :: p PinMode ((v p) -> Main (v a)) -> Main (v a) | pin p
450 \end{lstClean}
451
452 \subsection{Task combinators}
453 Task combinators are used to combine multiple tasks into one to describe workflows.
454 There are three main types of task combinators, namely:
455 \begin{enumerate*}
456 \item Sequential combinators that execute tasks one after the other, possibly using the result of the left hand side.
457 \item Parallel combinators that execute tasks at the same time combining the result.
458 \item Miscellaneous combinators that change the semantics of a task---e.g.\ repeat it or delay execution.
459 \end{enumerate*}
460
461 \subsubsection{Sequential}
462 Sequential task combination allows the right-hand side task to observe the left-hand side task value.
463 All seqential task combinators are expressed in the \cleaninline{expr} class and can be---and are by default---derived from the Swiss army knife step combinator \cleaninline{>>*.}.
464 This combinator has a single task on the left-hand side and a list of \emph{task continuations} on the right-hand side.
465 The list of task continuations is checked every rewrite step and if one of the predicates matches, the task continues with the result of this combination.
466 \cleaninline{>>=.} is a shorthand for the bind operation, if the left-hand side is stable, the right-hand side function is called to produce a new task.
467 \cleaninline{>>|.} is a shorthand for the sequence operation, if the left-hand side is stable, it continues with the right-hand side task.
468 The \cleaninline{>>~.} and \cleaninline{>>..} combinators are variants of the ones above that ignore the stability and continue on an unstable value as well.
469
470 \begin{lstClean}[label={lst:mtask_sequential},caption={Sequential task combinators in \gls{MTASK}.}]
471 class step v | expr v where
472 (>>*.) infixl 1 :: (MTask v t) [Step v t u] -> MTask v u
473 (>>=.) infixl 0 :: (MTask v t) ((v t) -> MTask v u) -> MTask v u
474 (>>|.) infixl 0 :: (MTask v t) (MTask v u) -> MTask v u
475 (>>~.) infixl 0 :: (MTask v t) ((v t) -> MTask v u) -> MTask v u
476 (>>..) infixl 0 :: (MTask v t) (MTask v u) -> MTask v u
477
478 :: Step v t u
479 = IfValue ((v t) -> v Bool) ((v t) -> MTask v u)
480 | IfStable ((v t) -> v Bool) ((v t) -> MTask v u)
481 | IfUnstable ((v t) -> v Bool) ((v t) -> MTask v u)
482 | Always (MTask v u)
483 \end{lstClean}
484
485 \todo{more examples step?}
486
487 The following listing shows an example of a step in action.
488 The \cleaninline{readPinBin} function produces an \gls{MTASK} task that classifies the value of an analogue pin into four bins.
489 It also shows that the nature of embedding allows the host language to be used as a macro language.
490 Furthermore
491
492 \begin{lstClean}[label={lst:mtask_readpinbin},caption={Read an analog pin and bin the value in \gls{MTASK}.}]
493 readPinBin :: Int -> Main (MTask v Int) | mtask v
494 readPinBin lim = declarePin PMInput A2 \a2->
495 { main = readA a2 >>*.
496 [ IfValue (\x->x <. lim) (\_->rtrn (lit bin))
497 \\ lim <-[64,128,192,256]
498 & bin <- [0..]]}
499 \end{lstClean}
500
501 \subsubsection{Parallel}\label{sssec:combinators_parallel}
502 The result of a parallel task combination is a compound that actually executes the tasks at the same time.
503
504 There are two types of parallel task combinators (see \cref{lst:mtask_parallel}).
505 The conjunction combinator (\cleaninline{.&&.}) combines the result by putting the values from both sides in a tuple.
506 The stability of the task depends on the stability of both children.
507 If both children are stable, the result is stable, otherwise the result is unstable.
508 The disjunction combinator (\cleaninline{.\|\|.}) combines the results by picking the leftmost, most stable task.
509 The semantics are easily described using \gls{CLEAN} functions shown in \cref{lst:semantics_con,lst:semantics_dis}.
510
511 \begin{figure}[ht]
512 \centering
513 \begin{subfigure}[t]{.5\textwidth}
514 \begin{lstClean}[caption={Semantics of the\\conjunction combinator.},label={lst:semantics_con}]
515 con :: (TaskValue a) (TaskValue b)
516 -> TaskValue (a, b)
517 con NoValue r = NoValue
518 con l NoValue = NoValue
519 con (Value l ls) (Value r rs)
520 = Value (l, r) (ls && rs)
521
522 \end{lstClean}
523 \end{subfigure}%
524 \begin{subfigure}[t]{.5\textwidth}
525 \begin{lstClean}[caption={Semantics of the\\disjunction combinator.},label={lst:semantics_dis}]
526 dis :: (TaskValue a) (TaskValue a)
527 -> TaskValue a
528 dis NoValue r = r
529 dis l NoValue = l
530 dis (Value l ls) (Value r rs)
531 | rs = Value r True
532 | otherwise = Value l ls
533 \end{lstClean}
534 \end{subfigure}
535 \end{figure}
536
537 \begin{lstClean}[label={lst:mtask_parallel},caption={Parallel task combinators in \gls{MTASK}.}]
538 class (.&&.) infixr 4 v :: (MTask v a) (MTask v b) -> MTask v (a, b)
539 class (.||.) infixr 3 v :: (MTask v a) (MTask v a) -> MTask v a
540 \end{lstClean}
541
542 \Cref{lst:mtask_parallel_example} gives an example of the parallel task combinator.
543 This program will read two pins at the same time, returning when one of the pins becomes \arduinoinline{HIGH}.
544 If the combinator was the \cleaninline{.&&.} instead, the type would be \cleaninline{MTask v (Bool, Bool)} and the task would only return when both pins have been \arduinoinline{HIGH} but not necessarily at the same time.
545
546 \begin{lstClean}[label={lst:mtask_parallel_example},caption={Parallel task combinator example in \gls{MTASK}.}]
547 task :: MTask v Bool
548 task =
549 declarePin D0 PMInput \d0->
550 declarePin D1 PMInput \d1->
551 let monitor pin = readD pin >>*. [IfValue (\x->x) \x->rtrn x]
552 In {main = monitor d0 .||. monitor d1}
553 \end{lstClean}
554
555 \subsubsection{Repeat}
556 The \cleaninline{rpeat} combinator executes the child task.
557 If a stable value is observed, the task is reinstated.
558 The functionality of \cleaninline{rpeat} can also be simulated by using functions and sequential task combinators and even made to be stateful as can be seen in \cref{lst:blinkthreadmtask}.
559
560 \begin{lstClean}[label={lst:mtask_repeat},caption={Repeat task combinators in \gls{MTASK}.}]
561 class rpeat v where
562 rpeat :: (MTask v a) -> MTask v a
563 \end{lstClean}
564
565 To demonstrate the combinator, \cref{lst:mtask_repeat_example} show \cleaninline{rpeat} in use.
566 This task will mirror the value read from analog \gls{GPIO} pin \cleaninline{A1} to pin \cleaninline{A2} by constantly reading the pin and writing the result.
567
568 \begin{lstClean}[label={lst:mtask_repeat_example},caption={Exemplatory repeat task in \gls{MTASK}.}]
569 task :: MTask v Int | mtask v
570 task =
571 declarePin A1 PMInput \a1->
572 declarePin A2 PMOutput \a2->
573 {main = rpeat (readA a1 >>~. writeA a2)}
574 \end{lstClean}
575
576 \subsection{\texorpdfstring{\Acrlongpl{SDS}}{Shared data sources}}
577 \Glspl{SDS} in \gls{MTASK} are by default references to shared memory.
578 Similar to peripherals (see \cref{sssec:peripherals}), they are constructed at the top level and are accessed through interaction tasks.
579 The \cleaninline{getSds} task yields the current value of the \gls{SDS} as an unstable value.
580 This behaviour is similar to the \cleaninline{watch} task in \gls{ITASK}.
581 Writing a new value to an \gls{SDS} is done using \cleaninline{setSds}.
582 This task yields the written value as a stable result after it is done writing.
583 Getting and immediately after setting an \gls{SDS} is not an \emph{atomic} operation.
584 It is possible that another task accesses the \gls{SDS} in between.
585 To circumvent this issue, \cleaninline{updSds} is created, this task atomically updates the value of the \gls{SDS}.
586
587 \begin{lstClean}[label={lst:mtask_sds},caption={\Glspl{SDS} in \gls{MTASK}.}]
588 :: Sds a // abstract
589 class sds v where
590 sds :: ((v (Sds t)) -> In t (Main (MTask v u))) -> Main (MTask v u)
591 getSds :: (v (Sds t)) -> MTask v t
592 setSds :: (v (Sds t)) (v t) -> MTask v t
593 updSds :: (v (Sds t)) ((v t) -> v t) -> MTask v t
594 \end{lstClean}
595
596 \todo{examples sdss}
597
598 \chapter{Green computing with \texorpdfstring{\gls{MTASK}}{mTask}}%
599 \label{chp:green_computing_mtask}
600
601 \chapter{Integration with \texorpdfstring{\gls{ITASK}}{iTask}}%
602 \label{chp:integration_with_itask}
603 The \gls{MTASK} language is a multi-view \gls{DSL}, i.e.\ there are multiple interpretations possible for a single \gls{MTASK} term.
604 Using the byte code compiler (\cleaninline{BCInterpret}) \gls{DSL} interpretation, \gls{MTASK} tasks are fully integrated in \gls{ITASK} and executed as if they were regular \gls{ITASK} tasks and communicate using \gls{ITASK} \glspl{SDS}.
605 \Gls{MTASK} devices contain a domain-specific \gls{OS} (\gls{RTS}) and are little \gls{TOP} servers in their own respect, being able to execute tasks.
606 \Cref{fig:mtask_integration} shows the architectural layout of a typical \gls{IOT} system created with \gls{ITASK} and \gls{MTASK}.
607 The entire system is written as a single \gls{CLEAN} specification where multiple tasks are executed at the same time.
608 Tasks can access \glspl{SDS} according to many-to-many communication and multiple clients can work on the same task.
609 Devices are integrated into the system using the \cleaninline{widthDevice} function (see \cref{sec:withdevice}).
610 Using \cleaninline{liftmTask}, \gls{MTASK} tasks are lifted to a device (see \cref{sec:liftmtask}).
611 \Gls{ITASK} \glspl{SDS} are lifted to the \gls{MTASK} device using \cleaninline{liftsds} (see \cref{sec:liftmtask}).
612
613 \begin{figure}[ht]
614 \centering
615 \includestandalone{mtask_integration}
616 \caption{\Gls{MTASK}'s integration with \gls{ITASK}.}%
617 \label{fig:mtask_integration}
618 \end{figure}
619
620 \section{Devices}\label{sec:withdevice}
621 \Gls{MTASK} tasks in the byte code compiler view are always executed on a certain device.
622 All communication with this device happens through a so-called \emph{channels} \gls{SDS}.
623 The channels contain three fields, a queue of messages that are received, a queue of messages to send and a stop flag.
624 Every communication method that implements the \cleaninline{channelSync} class can provide the communication with an \gls{MTASK} device.
625 As of now, serial port communication, direct \gls{TCP} communication and \gls{MQTT} over \gls{TCP} are supported as communication providers.
626 The \cleaninline{withDevice} function transforms a communication provider and a task that does something with this device to an \gls{ITASK} task.
627 This task sets up the communication, exchanges specifications, handles errors and cleans up after closing.
628 \Cref{lst:mtask_device} shows the types and interface to connecting devices.
629
630 \begin{lstClean}[label={lst:mtask_device},caption={Device communication interface in \gls{MTASK}.}]
631 :: MTDevice //abstract
632 :: Channels :== ([MTMessageFro], [MTMessageTo], Bool)
633
634 class channelSync a :: a (sds () Channels Channels) -> Task () | RWShared sds
635
636 withDevice :: (a (MTDevice -> Task b) -> Task b) | iTask b & channelSync, iTask a
637 \end{lstClean}
638
639 \section{Lifting tasks}\label{sec:liftmtask}
640 Once the connection with the device is established, \ldots
641 \begin{lstClean}
642 liftmTask :: (Main (BCInterpret (TaskValue u))) MTDevice -> Task u | iTask u
643 \end{lstClean}
644
645 \section{Lifting \texorpdfstring{\acrlongpl{SDS}}{shared data sources}}\label{sec:liftsds}
646 \begin{lstClean}[label={lst:mtask_itasksds},caption={Lifted \gls{ITASK} \glspl{SDS} in \gls{MTASK}.}]
647 class liftsds v where
648 liftsds :: ((v (Sds t))->In (Shared sds t) (Main (MTask v u)))
649 -> Main (MTask v u) | RWShared sds
650 \end{lstClean}
651
652 \chapter{Implementation}%
653 \label{chp:implementation}
654 IFL19 paper, bytecode instructieset~\cref{chp:bytecode_instruction_set}
655
656 \section{Integration with \texorpdfstring{\gls{ITASK}}{iTask}}
657 IFL18 paper stukken
658
659 \chapter{\texorpdfstring{\gls{MTASK}}{mTask} history}
660 \section{Generating \texorpdfstring{\gls{C}/\gls{CPP}}{C/C++} code}
661 A first throw at a class-based shallowly \gls{EDSL} for microprocessors was made by \citet{plasmeijer_shallow_2016}.
662 The language was called \gls{ARDSL} and offered a type safe interface to \gls{ARDUINO} \gls{CPP} dialect.
663 A \gls{CPP} code generation backend was available together with an \gls{ITASK} simulation backend.
664 There was no support for tasks or even functions.
665 Some time later in the 2015 \gls{CEFP} summer school, an extended version was created that allowed the creation of imperative tasks, \glspl{SDS} and the usage of functions~\citep{koopman_type-safe_2019}.
666 The name then changed from \gls{ARDSL} to \gls{MTASK}.
667
668 \section{Integration with \texorpdfstring{\gls{ITASK}}{iTask}}
669 Mart Lubbers extended this in his Master's Thesis by adding integration with \gls{ITASK} and a bytecode compiler to the language~\citep{lubbers_task_2017}.
670 \Gls{SDS} in \gls{MTASK} could be accessed on the \gls{ITASK} server.
671 In this way, entire \gls{IOT} systems could be programmed from a single source.
672 However, this version used a simplified version of \gls{MTASK} without functions.
673 This was later improved upon by creating a simplified interface where \glspl{SDS} from \gls{ITASK} could be used in \gls{MTASK} and the other way around~\citep{lubbers_task_2018}.
674 It was shown by Matheus Amazonas Cabral de Andrade that it was possible to build real-life \gls{IOT} systems with this integration~\citep{amazonas_cabral_de_andrade_developing_2018}.
675 Moreover, a course on the \gls{MTASK} simulator was provided at the 2018 \gls{CEFP}/\gls{3COWS} winter school in Ko\v{s}ice, Slovakia~\citep{koopman_simulation_2018}.
676
677 \section{Transition to \texorpdfstring{\gls{TOP}}{TOP}}
678 The \gls{MTASK} language as it is now was introduced in 2018~\citep{koopman_task-based_2018}.
679 This paper updated the language to support functions, tasks and \glspl{SDS} but still compiled to \gls{CPP} \gls{ARDUINO} code.
680 Later the bytecode compiler and \gls{ITASK} integration was added to the language~\citep{lubbers_interpreting_2019}.
681 Moreover, it was shown that it is very intuitive to write \gls{MCU} applications in a \gls{TOP} language~\citep{lubbers_multitasking_2019}.
682 One reason for this is that a lot of design patterns that are difficult using standard means are for free in \gls{TOP} (e.g.\ multithreading).
683 In 2019, the \gls{CEFP} summer school in Budapest, Hungary hosted a course on developing \gls{IOT} applications with \gls{MTASK} as well~\citep{lubbers_writing_2019}.
684
685 \section{\texorpdfstring{\gls{TOP}}{TOP}}
686 In 2022, the SusTrainable summer school in Rijeka, Croatia hosted a course on developing greener \gls{IOT} applications using \gls{MTASK} as well (the lecture notes are to be written).
687 Several students worked on extending \gls{MTASK} with many useful features:
688 Erin van der Veen did preliminary work on a green computer analysis, built a simulator and explored the possibilities for adding bounded datatypes~\citep{veen_van_der_mutable_2020}; Michel de Boer investigated the possibilities for secure communication channels~\citep{boer_de_secure_2020}; and Sjoerd Crooijmans added abstractions for low-power operation to \gls{MTASK} such as hardware interrupts and power efficient scheduling~\citep{crooijmans_reducing_2021}.
689 Elina Antonova defined a preliminary formal semantics for a subset of \gls{MTASK}~\citep{antonova_MTASK_2022}.
690 Moreover, plans for student projects and improvements include exploring integrating \gls{TINYML} into \gls{MTASK}; and adding intermittent computing support to \gls{MTASK}.
691
692 In 2023, the SusTrainable summer school in Coimbra, Portugal will host a course on \gls{MTASK} as well.
693
694 \section{\texorpdfstring{\gls{MTASK}}{mTask} in practise}
695 Funded by the Radboud-Glasgow Collaboration Fund, collaborative work was executed with Phil Trinder, Jeremy Singer and Adrian Ravi Kishore Ramsingh.
696 An existing smart campus application was developed using \gls{MTASK} and quantitively and qualitatively compared to the original application that was developed using a traditional \gls{IOT} stack~\citep{lubbers_tiered_2020}.
697 The collaboration is still ongoing and a journal article is under review comparing four approaches for the edge layer: \gls{PYTHON}, \gls{MICROPYTHON}, \gls{ITASK} and \gls{MTASK}.
698 Furthermore, power efficiency behaviour of traditional versus \gls{TOP} \gls{IOT} stacks is being compared as well adding a \gls{FREERTOS} implementation to the mix as well
699
700 \input{subfilepostamble}
701 \end{document}