.
[phd-thesis.git] / top / 4iot.tex
1 \documentclass[../thesis.tex]{subfiles}
2
3 \input{subfilepreamble}
4
5 \setcounter{chapter}{2}
6
7 \begin{document}
8 \input{subfileprefix}
9 \chapter{\texorpdfstring{\Glsxtrlong{TOP} for the \glsxtrlong{IOT}}{Task-oriented programming for the internet of things}}%
10 \label{chp:top4iot}
11 \begin{chapterabstract}
12 \noindent This chapter introduces the monograph. It compares traditional edge device programming to \gls{TOP} by:
13 \begin{itemize}
14 \item introducing edge device programming;
15 \item showing how to create the \emph{Hello World!} application for microcontrollers using \gls{ARDUINO} and \gls{MTASK};
16 \item extending the idea to cooperative multitasking, uncovering problems using \gls{ARDUINO};
17 \item demonstrating that upgrading to a multi-tasking variant is straightforward using \gls{MTASK};
18 \item elaborating on integrating an edge device program with a server;
19 \item and providing a reading guide for the rest of the monograph.
20 \end{itemize}
21 \end{chapterabstract}
22
23 The edge layer of \gls{IOT} systems predominantly consists of microcontrollers.
24 Microcontrollers are tiny computers designed specifically for embedded applications that differ much from regular computers in all aspects.
25 They are much smaller; only have a fraction of the memory and processor speed; and run on different architectures.
26 However, they have much more energy-efficient sleep modes, and support connecting and interfacing with peripherals such as sensors and actuators.
27 \Cref{tbl:mcu_laptop} compares the hardware properties of a typical laptop with two very popular microcontrollers.
28 Usually, programming microcontrollers requires an elaborate multi-step toolchain of compilation, linkage, binary image creation, and burning this image onto the flash memory of the microcontroller in order to run a program.
29 The programs are usually cyclic executives instead of tasks running in an \gls{OS}, i.e.\ there is only a single all-encompassing task that continuously runs on the bare metal.
30 Hence, all tasks must be manually combined into a single program.
31
32 \begin{table}
33 \caption{Hardware characteristics of typical microcontrollers and a laptop.}%
34 \label{tbl:mcu_laptop}
35 \centering
36 \begin{tabular}{llll}
37 \toprule
38 & Laptop & Atmega328P & ESP8266\\
39 \midrule
40 CPU speed & \qtyrange{2}{4}{\giga\hertz} & \qty{16}{\mega\hertz} & \qty{80}{\mega\hertz} or \qty{160}{\mega\hertz}\\
41 \textnumero{} cores & \numrange{4}{8} & 1 & 1\\
42 Storage & \qty{1}{\tebi\byte} & \qty{32}{\kibi\byte} & \qtyrange{0.5}{4}{\mebi\byte}\\
43 \Gls{RAM} & \qtyrange{4}{16}{\gibi\byte} & \qty{2}{\kibi\byte} & \qty{160}{\kibi\byte}\\
44 Power & \qtyrange{50}{100}{\watt} & \qtyrange{0.13}{250}{\milli\watt} & \qtyrange{0.1}{350}{\milli\watt}\\
45 Size & $\pm$\qty{1060}{\cubic\cm} & $\pm$\qty{7.5}{\cubic\cm} & $\pm$\qty{1.1}{\cubic\cm}\\
46 Display & \numproduct{1920x1080x24} & \numproduct{1x1x1} & \numproduct{1x1x1}\\ %chktex 29
47 Price & \euro{1500} & \euro{3} & \euro{4}\\
48 \bottomrule
49 \end{tabular}
50 \end{table}
51
52 Different models of microcontrollers require their own vendor-provided drivers, hardware abstraction layer, compilers and \glspl{RTS}.
53 To structure this jungle of tools, platforms exist that provide abstraction layers over the low-level toolchains such as \gls{ARDUINO}\footnote{\refurl{https://www.arduino.cc}{\formatdate{19}{12}{2022}}}.
54 It is specifically designed for education and prototyping and hence used here to illustrate traditional microcontroller programming.
55 The popular \gls{ARDUINO} \ccpp{} dialect and accompanying libraries provide an abstraction layer for common microcontroller behaviour allowing the programmer to program multiple types of microcontrollers using a single language.
56 Originally it was designed for the in-house developed open-source hardware with the same name but the setup allows porting to many architectures by vendor-provided \emph{cores}.
57 It provides an \gls{IDE} and toolchain automation to perform all steps of the toolchain with a single command.
58
59 \section{\texorpdfstring{\Glsxtrshort{TOP} for the \glsxtrshort{IOT}}{TOP for the IoT}}
60 \Gls{TOP} is a programming paradigm that allows multi-tier interactive systems to be generated from a single declarative source (see \cref{sec:back_top}).
61 An example of a \gls{TOP} system is \gls{ITASK}, a general-purpose \gls{TOP} language for programming interactive distributed web applications.
62 Interactive distributed web applications often form the core of the top two layers of \gls{IOT} applications.
63 Furthermore, \gls{IOT} edge devices are typically programmed with similar workflow-like programs for which \gls{TOP} is very suitable.
64 Directly incorporating the perception layer in \gls{ITASK} however is not straightforward.
65 \Gls{ITASK} targets relatively fast and hence energy-hungry systems with large amounts of \gls{RAM} and a speedy connection.
66 Edge devices in \gls{IOT} systems are typically slow but energy efficient and do not have the memory to run the naturally heap-heavy feature-packed functional programs that \gls{ITASK} programs are.
67 The \gls{MTASK} system bridges this gap by providing a \gls{TOP} \gls{DSL} for \gls{IOT} edge devices.
68 Domain-specific knowledge is embedded in the language and execution platform; and unnecessary features for edge devices are removed to drastically lowere the hardware requirements.\todo{beter?}
69
70 \section{Hello world!}
71 Traditionally, the first program that one writes when trying a new language is the so-called \emph{Hello World!} program.
72 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.
73 Microcontrollers usually do not come with screens in the traditional sense.
74 Nevertheless, almost always there is a built-in 1 pixel screen with a \qty{1}{\bit} color depth, namely the on-board \gls{LED}.
75 The \emph{Hello World!} equivalent on microcontrollers blinks this \gls{LED}.
76
77 Using \gls{ARDUINO}'s \ccpp{} dialect to create the blink program results in the code seen in \cref{lst:arduinoBlink}.
78 \Gls{ARDUINO} programs are implemented as cyclic executives and hence, each program defines a \arduinoinline{setup} and a \arduinoinline{loop} function.
79 The \arduinoinline{setup} function is executed only once on boot, the \arduinoinline{loop} function is continuously called afterwards and contains the event loop.
80 In the blink example, the \arduinoinline{setup} function only contains code for setting the \gls{GPIO} pin to the correct mode.
81 The \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.
82 In between, it waits \qty{500}{\ms} so that the blinking is actually visible for the human eye.
83
84 \begin{lstArduino}[caption={Blinking an \gls{LED}.},label={lst:arduinoBlink}]
85 void setup() {
86 pinMode(D2, OUTPUT);
87 }
88
89 void loop() {
90 digitalWrite(D2, HIGH);
91 delay(500);
92 digitalWrite(D2, LOW);
93 delay(500);
94 }\end{lstArduino}
95
96 \subsection{Blinking the \texorpdfstring{\glsxtrshort{LED}}{LED} in \texorpdfstring{\gls{MTASK}}{mTask}.}
97 Naively translating the traditional blink program to \gls{MTASK} can be done by simply substituting some syntax as seen in \cref{lst:blinkImp}.
98 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.
99 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.
100 To simulate a loop, the \cleaninline{rpeat} task combinator can be used as this task combinator executes the argument task and, when stable, reinstates it.
101 The body of the \cleaninline{rpeat} contains similarly named tasks to write to the pins and to wait in between.
102 The tasks are connected using the sequential \cleaninline{>>|.} combinator that for all current intents and purposes executes the tasks after each other.
103
104 \begin{lstClean}[caption={Blinking the \gls{LED} using the \cleaninline{rpeat} combinator.},label={lst:blinkImp}]
105 blinkTask :: Main (MTask v ()) | mtask v
106 blinkTask = declarePin D2 PMOutput \ledPin->
107 {main = rpeat (
108 writeD ledPin true
109 >>|. delay (lit 500)
110 >>|. writeD ledPin false
111 >>|. delay (lit 500))
112 }
113 \end{lstClean}
114
115 However, as \gls{MTASK} is hosted in a full fledged functional language, it is also possible to define the blinking behaviour as a function.
116 \Cref{lst:blinkFun} shows this more natural translation.
117 The \cleaninline{main} expression is just a call to the \cleaninline{blink} function parametrised with the state.
118 The \cleaninline{blink} function first writes the current state to the \gls{LED}, waits for the specific time and calls itself recursively with the inverse of the state, resulting in the same behaviour.
119 Creating recursive functions like this is not possible in the \gls{ARDUINO} language because the program would run out of stack quickly and combining multiple tasks defined this would be very difficult.
120
121 \begin{lstClean}[caption={Blinking the \gls{LED} using a function.},label={lst:blinkFun}]
122 blinkTask :: Main (MTask v ()) | mtask v
123 blinkTask = declarePin D2 PMOutput \ledPin->
124 fun \blink=(\st->
125 writeD ledPin st
126 >>|. delay (lit 500)
127 >>|. blink (Not st))
128 In {main = blink true}
129 \end{lstClean}
130
131 \section{Multi tasking}
132 Now say that we want to blink multiple blinking patterns on different \glspl{LED} concurrently.
133 For example, blink three \glspl{LED} connected to \gls{GPIO} pins $1,2$ and $3$ at intervals of \qtylist{500;300;800}{\ms}.
134 Intuitively you would want to lift the blinking behaviour to a function and call this function three times with different parameters as shown in \cref{lst:blinkthreadno}.
135
136 \begin{lstArduino}[caption={Naive approach to multiple blinking patterns.},label={lst:blinkthreadno}]
137 void setup () { ... }
138
139 void blink (int pin, int wait) {
140 digitalWrite(pin, HIGH);
141 delay(wait);
142 digitalWrite(pin, LOW);
143 delay(wait);
144 }
145
146 void loop() {
147 blink (D1, 500);
148 blink (D2, 300);
149 blink (D3, 800);
150 }\end{lstArduino}
151
152 Unfortunately, this does not work because the \arduinoinline{delay} function blocks all further execution.
153 The resulting program blinks the \glspl{LED} after each other instead of at the same time.
154 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}.
155 \Cref{lst:blinkthread} shows how three different blinking patterns could be implemented in \gls{ARDUINO} using the slicing method.
156 If we want the blink function to be a separate parametrisable function we need to explicitly provide all references to the required global state.
157 Furthermore, the \arduinoinline{delay} function can not be used and polling \arduinoinline{millis} is required.
158 The \arduinoinline{millis} function returns the number of milliseconds that have passed since the boot of the microcontroller.
159 If the delay is long enough, it may also be possible to put the processor in sleep mode, reducing the power consumption drastically.
160 Hence, using \arduinoinline{millis} potentially affects power consumption since the processor is basically busy looping all the time.
161 Manually combining tasks into a single program is very error prone, requires a lot of pointer juggling, and generally results into spaghetti code.
162 Furthermore, it is very difficult to represent dependencies between threads, often state machines have to be explicitly programmed by hand to achieve this.
163 In the simple case of blinking three \glspl{LED} according to fixed intervals, it is possible to calculate the delays in advance using static analysis and generate the appropriate \arduinoinline{delay} calls.
164 Unfortunately, this is very hard when for example the blinking patterns are determined at runtime.
165
166 \begin{lstArduino}[label={lst:blinkthread},caption={Threading three blinking patterns.}]
167 long led1 = 0, led2 = 0, led3 = 0;
168 bool st1 = false, st2 = false, st3 = false;
169
170 void setup () { ... }
171
172 void blink(int pin, int interval, long *lastrun, bool *st) {
173 if (millis() - *lastrun > interval) {
174 digitalWrite(pin, *st = !*st);
175 *lastrun += interval;
176 }
177 }
178
179 void loop() {
180 blink(D1, 500, &led1, &st1);
181 blink(D2, 300, &led2, &st1);
182 blink(D3, 800, &led3, &st1);
183 }\end{lstArduino}
184
185 \subsection{Multi tasking in \texorpdfstring{\gls{MTASK}}{mTask}}
186 In contrast to the \arduinoinline{delay} function in \gls{ARDUINO}, \gls{MTASK}'s \cleaninline{delay} \emph{task} does not block the execution.
187 It has no observable value until the target waiting time has passed, and thence is \emph{stable}.
188 To make code reuse possible and make the implementation more intuitive, the blinking behaviour is lifted to a recursive function instead of using the imperatively looking \cleaninline{rpeat} task combinator.
189 There is no global state, the function is parametrized with the current status, the pin to blink and the waiting time.
190 With a parallel combinator, tasks are executed in an interleaved fashion.
191 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}.
192
193 % VimTeX: SynIgnore on
194 \begin{lstClean}[label={lst:blinkthreadmtask},caption={Threading three blinking patterns.}]
195 blinktask :: MTask v () | mtask v
196 blinktask = declarePin D1 PMOutput \d1->
197 declarePin D2 PMOutput \d2->
198 declarePin D3 PMOutput \d3->
199 fun \blink=(\(st, pin, wait)->
200 delay wait
201 >>|. writeD d13 st
202 >>|. blink (Not st, pin, wait))
203 In {main = blink (true, d1, lit 500)
204 .||. blink (true, d2, lit 300)
205 .||. blink (true, d3, lit 800)
206 }
207 \end{lstClean}
208 % VimTeX: SynIgnore off
209
210 \section{Conclusion and reading guide}
211 The edge layer of \gls{IOT} systems is powered by microcontrollers.
212 Microcontrollers have significantly different characteristics to regular computers.
213 Programming them happens through compiled firmwares using low-level imperative programming languages.
214 Due to the lack of an \gls{OS}, writing applications that perform multiple tasks at the same time is error prone, and complex; and requires a lot of boilerplate and manual scheduling code.
215 With the \gls{MTASK} system, a \gls{TOP} programming language for \gls{IOT} edge devices, this limitation can be overcome.
216 As much domain-specific knowledge is built into the language and the \gls{RTS}, the hardware requirements can be kept relatively low while maintaining a high abstraction level.
217 Furthermore, the programs are automatically integrated with \gls{ITASK}, allowing for data sharing, task coordination, and dynamic construction of tasks.
218
219 The following chapters thoroughly introduce all aspects of the \gls{MTASK} system.
220 First the language setup and interface is shown in \cref{chp:mtask_dsl}.
221 Then the interface for integrating \gls{MTASK} with \gls{ITASK} is provided in \cref{chp:integration_with_itask}.
222 \Cref{chp:implementation} provides the implementation of the \gls{DSL}, the compilation schemes, instruction set and details on the interpreter.
223 \Cref{chp:green_computing_mtask} explains all the green computing aspects of \gls{MTASK}, i.e.\ task scheduling and processor interrupts.
224 Finally, \cref{chp:finale} concludes, and shows related work together with a short history of \gls{MTASK}.
225
226 \input{subfilepostamble}
227 \end{document}