more updates, slight restructure
[phd-thesis.git] / mtask / mtask.tex
index 7e54b3f..46aaeff 100644 (file)
@@ -5,10 +5,12 @@
        \pagenumbering{arabic}
 }{}
 
-\chapter{\Gls{TOP} for the \gls{IOT}}
+\mychapter{chp:top4iot}{Introduction to \gls{IOT} programming}
+\todo{betere chapter naam}
 \begin{chapterabstract}
        This chapter introduces \gls{MTASK} and puts it into perspective compared to traditional microprocessor programming.
 \end{chapterabstract}
+
 Traditionally, the first program that one writes when trying a new language is the so called \emph{Hello World!} program.
 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.
 On microprocessors, there often is no screen for displaying text.
@@ -23,13 +25,13 @@ In between it waits for 500 milliseconds so that the blinking is actually visibl
 Compiling this results in a binary firmware that needs to be flashed onto the program memory.
 
 Translating the traditional blink program to \gls{MTASK} can almost be done by simply substituting some syntax as seen in \cref{lst:blinkImp}.
-E.g.\ \cleaninline{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.
+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.
 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.
 To simulate a loop, the \cleaninline{rpeat} task can be used, this task executes the argument task and, when stable, reinstates it.
 The body of the \cleaninline{rpeat} contains similarly named tasks to write to the pins and to wait in between.
 The tasks are connected using the sequential \cleaninline{>>|.} combinator that for all current intents and purposes executes the tasks after each other.
 
-\begin{figure}[!ht]
+\begin{figure}[ht]
        \begin{subfigure}[b]{.5\linewidth}
                \begin{lstArduino}[caption={Blink program.},label={lst:arduinoBlink}]
 void setup() {
@@ -48,23 +50,100 @@ void loop() {
 
 blink :: Main (MTask v ()) | mtask v
 blink =
-       declarePin D4 PMOutput \d4->
+       declarePin D2 PMOutput \d2->
        {main = rpeat (
-                    writeD d4 true
+                    writeD d2 true
                >>|. delay (lit 500)
-               >>|. writeD d4 false
+               >>|. writeD d2 false
                >>|. delay (lit 500)
        )}\end{lstClean}
        \end{subfigure}
 \end{figure}
 
-\chapter{The \gls{MTASK} \gls{DSL}}
+\section{Threaded blinking}
+Now say that we want to blink multiple blinking patterns on different \glspl{LED} concurrently.
+For example, blink three \glspl{LED} connected to \gls{GPIO} pins $1,2$ and $3$ at intervals of $500,300$ and $800$ milliseconds.
+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}
+
+\begin{lstArduino}[caption={Naive approach to multiple blinking patterns.},label={lst:blinkthreadno}]
+void setup () { ... }
+
+void blink (int pin, int wait) {
+       digitalWrite(pin, HIGH);
+       delay(wait);
+       digitalWrite(pin, LOW);
+       delay(wait);
+}
+
+void loop() {
+       blink (1, 500);
+       blink (2, 300);
+       blink (3, 800);
+}\end{lstArduino}
+
+Unfortunately, this does not work because the \arduinoinline{delay} function blocks all further execution.
+The resulting program will blink the \glspl{LED} after each other instead of at the same time.
+To overcome this, it is necessary to slice up the blinking behaviour in very small fragments so it can be manually interleaved~\cite{feijs_multi-tasking_2013}.
+Listing~\ref{lst:blinkthread} shows how three different blinking patterns might be achieved in \gls{ARDUINO} using the slicing method.
+If we want the blink function to be a separate parametrizable function we need to explicitly provide all references to the required state.
+Furthermore, the \arduinoinline{delay} function can not be used and polling \arduinoinline{millis} is required.
+The \arduinoinline{millis} function returns the number of milliseconds that have passed since the boot of the microprocessor.
+Some devices use very little energy when in \arduinoinline{delay} or sleep state.
+Resulting in \arduinoinline{millis} potentially affects power consumption since the processor is basically busy looping all the time.
+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.
+Unfortunately, this is very hard when for example the blinking patterns are determined at runtime.
+
+\begin{lstArduino}[label={lst:blinkthread},caption={Threading three blinking patterns.}]
+long led1 = 0, led2 = 0, led3 = 0;
+bool st1 = false, st2 = false, st3 = false;
+
+void blink(int pin, int delay, long *lastrun, bool *st) {
+       if (millis() - *lastrun > delay) {
+               digitalWrite(pin, *st = !*st);
+               *lastrun += delay;
+       }
+}
+
+void loop() {
+       blink(1, 500, &led1, &st1);
+       blink(2, 300, &led2, &st1);
+       blink(3, 800, &led3, &st1);
+}\end{lstArduino}
+
+This method is very error prone, requires a lot of pointer juggling and generally results into spaghetti code.
+Furthermore, it is very difficult to represent dependencies between threads, often state machines have to be explicitly programmed by hand to achieve this.
+
+\section{Blinking in \gls{MTASK}}
+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.
+In contrast, the \cleaninline{delay} \emph{function} on the \gls{ARDUINO} is blocking which prohibits interleaving.
+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.
+The function is parametrized with the current state, the pin to blink and the waiting time.
+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.
+With a parallel combinator, tasks can be executed in an interleaved fashion.
+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}.
+
+\begin{lstClean}[label={lst:blinkthreadmtask},caption={Threaded blinking.}]
+blinktask :: MTask v () | mtask v
+blinktask =
+       declarePin D1 PMOutput \d1->
+       declarePin D2 PMOutput \d2->
+       declarePin D3 PMOutput \d3->
+       fun \blink=(\(st, pin, wait)->
+                    delay wait
+               >>|. writeD d13 st
+               >>|. blink (Not st, pin, wait)) In
+       {main =  blink (true, d1, lit 500)
+               .||. blink (true, d2, lit 300)
+               .||. blink (true, d3, lit 800)
+       }\end{lstClean}
+
+\mychapter{chp:mtask_dsl}{The \gls{MTASK} \gls{DSL}}
 \begin{chapterabstract}
 This chapter serves as a complete guide to the \gls{MTASK} language, from an \gls{MTASK} programmer's perspective.
 \end{chapterabstract}
 
 The \gls{MTASK} system is a \gls{TOP} programming environment for programming microprocessors.
-It is implemented as an \gls{EDSL} in \gls{CLEAN} using class-based---or tagless-final---embedding (See~\cref{ssec:tagless}).
+It is implemented as an \gls{EDSL} in \gls{CLEAN} using class-based---or tagless-final---embedding (See \cref{ssec:tagless}).
 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.
 
 \begin{itemize}
@@ -101,7 +180,7 @@ The class constraints for values in \gls{MTASK} are omnipresent in all functions
                \cleaninline{Int}              & \cinline{int16_t} & 16\\
                \cleaninline{:: Long}          & \cinline{int32_t} & 32\\
                \cleaninline{Real}             & \cinline{float}   & 32\\
-               \cleaninline{:: T = A | B | C} & \cinline{enum}    & 16\\
+               \cleaninline{:: T = A \| B \| C} & \cinline{enum}    & 16\\
                \bottomrule
        \end{tabular}
        \caption{Mapping from \gls{CLEAN}/\gls{MTASK} data types to \gls{CPP} datatypes.}%
@@ -121,29 +200,31 @@ class basicType t | type t where ...
 class mtask v | expr, ..., int, real, long v
 
 someExpr :: v Int | mtask v
-tempTask :: MTask v Bool | mtask, dht v
+someExpr = ...
+
+someTask :: MTask v Int | mtask v
+someTask =
+       sensor1 config1 \sns1->
+       sensor2 config2 \sns2->
+          fun \fun1= ( ... )
+       In fun \fun2= ( ... )
+       In {main=mainexpr}
 \end{lstClean}
 
 \section{Expressions}
-\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}), to do basic arithmetics and conditional execution.
+\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.
 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.
 
 \begin{lstClean}[caption={The \gls{MTASK} class for expressions},label={lst:expressions}]
 class expr v where
        lit :: t -> v t | type t
        (+.) infixl 6 :: (v t) (v t) -> v t | basicType, +, zero t
-       (-.) infixl 6 :: (v t) (v t) -> v t | basicType, -, zero t
-       (*.) infixl 7 :: (v t) (v t) -> v t | basicType, *, zero, one t
-       (/.) infixl 7 :: (v t) (v t) -> v t | basicType, /, zero t
+       ...
        (&.) infixr 3 :: (v Bool) (v Bool) -> v Bool
        (|.) infixr 2 :: (v Bool) (v Bool) -> v Bool
        Not           :: (v Bool) -> v Bool
        (==.) infix 4 :: (v a) (v a) -> v Bool | Eq, basicType a
-       (!=.) infix 4 :: (v a) (v a) -> v Bool | Eq, basicType a
-       (<.)  infix 4 :: (v a) (v a) -> v Bool | Ord, basicType a
-       (>.)  infix 4 :: (v a) (v a) -> v Bool | Ord, basicType a
-       (<=.) infix 4 :: (v a) (v a) -> v Bool | Ord, basicType a
-       (>=.) infix 4 :: (v a) (v a) -> v Bool | Ord, basicType a
+       ...
        If :: (v Bool) (v t) (v t) -> v t | type t
 \end{lstClean}
 
@@ -165,6 +246,7 @@ false :== lit False
 \end{lstClean}
 
 \subsection{Functions}
+Functions in \gls{MTASK} are defined 
 
 \section{Tasks}
 \subsection{Basic tasks}
@@ -175,18 +257,59 @@ false :== lit False
 \subsubsection{Miscellaneous}
 \subsection{\glspl{SDS}}
 
-\chapter{Green computing with \gls{MTASK}}
+\mychapter{chp:green_computing_mtask}{Green computing with \gls{MTASK}}
 
-\chapter{Integration with \gls{ITASK}}
+\mychapter{chp:integration_with_itask}{Integration with \gls{ITASK}}
 \section{Devices}
 \section{Lift tasks}
 \section{Lift \glspl{SDS}}
 
-\chapter{Implementation}
+\mychapter{chp:implementation}{Implementation}
 IFL19 paper, bytecode instructieset~\cref{chp:bytecode_instruction_set}
 
 \section{Integration with \gls{ITASK}}
 IFL18 paper stukken
 
+\chapter{\gls{MTASK} history}
+\section{Generating \glsentrytext{C}/\glsentrytext{CPP} code}
+A first throw at a class-based shallowly \gls{EDSL} for microprocessors was made by Pieter Koopman and Rinus Plasmijer in 2016~\cite{plasmeijer_shallow_2016}.
+The language was called \gls{ARDSL} and offered a type safe interface to \gls{ARDUINO} \gls{CPP} dialect.
+A \gls{CPP} code generation backend was available together with an \gls{ITASK} simulation backend.
+There was no support for tasks or even functions.
+Some time later in the 2015 CEFP summer school, an extended version was created that allowed the creation of imperative tasks, \glspl{SDS} and the usage of functions~\cite{koopman_type-safe_2019}.
+The name then changed from \gls{ARDSL} to \gls{MTASK}.
+
+\section{Integration with \glsentrytext{ITASK}}
+Mart Lubbers extended this in his Master's Thesis by adding integration with \gls{ITASK} and a bytecode compiler to the language~\cite{lubbers_task_2017}.
+\Gls{SDS} in \gls{MTASK} could be accessed on the \gls{ITASK} server.
+In this way, entire \gls{IOT} systems could be programmed from a single source.
+However, this version used a simplified version of \gls{MTASK} without functions.
+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~\cite{lubbers_task_2018}.
+It was shown by Matheus Amazonas Cabral de Andrade that it was possible to build real-life \gls{IOT} systems with this integration~\cite{amazonas_cabral_de_andrade_developing_2018}.
+Moreover, a course on the \gls{MTASK} simulator was provided at the 2018 CEFP/3COWS winter school in Ko\v{s}ice, Slovakia~\cite{koopman_simulation_2018}.
+
+\section{Transition to \glsentrytext{TOP}}
+The \gls{MTASK} language as it is now was introduced in 2018~\cite{koopman_task-based_2018}.
+This paper updated the language to support functions, tasks and \glspl{SDS} but still compiled to \gls{CPP} \gls{ARDUINO} code.
+Later the bytecode compiler and \gls{ITASK} integration was added to the language~\cite{lubbers_interpreting_2019}.
+Moreover, it was shown that it is very intuitive to write \gls{MCU} applications in a \gls{TOP} language~\cite{lubbers_multitasking_2019}.
+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).
+In 2019, the CEFP summer school in Budapest, Hungary hosted a course on developing \gls{IOT} applications with \gls{MTASK} as well~\cite{lubbers_writing_2019}.
+
+\section{\glsentrytext{TOP}}
+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).
+Several students worked on extending \gls{MTASK} with many useful features:
+Erin van der Veen did preliminary work on a green computer analysis, built a simulator and explored the possibilities for adding bounded datatypes~\cite{veen_van_der_mutable_2020}; Michel de Boer investigated the possibilities for secure communication channels~\cite{boer_de_secure_2020}; and Sjoerd Crooijmans added abstractions for low-power operation to \gls{MTASK} such as hardware interrupts and power efficient scheduling~\cite{crooijmans_reducing_2021}.
+Elina Antonova defined a preliminary formal semantics for a subset of \gls{MTASK}~\cite{antonova_MTASK_2022}.
+Moreover, plans for student projects and improvements include exploring integrating \gls{TINYML} into \gls{MTASK}; and adding intermittent computing support to \gls{MTASK}.
+
+In 2023, the SusTrainable summer school in Coimbra, Portugal will host a course on \gls{MTASK} as well.
+
+\section{\glsentrytext{MTASK} in practise}
+Funded by the Radboud-Glasgow Collaboration Fund, collaborative work was executed with Phil Trinder, Jeremy Singer and Adrian Ravi Kishore Ramsingh.
+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~\cite{lubbers_tiered_2020}.
+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}.
+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
+
 \input{subfilepostamble}
 \end{document}