errata
[phd-thesis.git] / top / int.tex
1 %chktex-file 17
2 \documentclass[../thesis.tex]{subfiles}
3
4 \input{subfilepreamble}
5
6 \setcounter{chapter}{6}
7
8 \begin{document}
9 \input{subfileprefix}
10 \chapter{The integration of mTask and iTask}%
11 \label{chp:integration_with_itask}
12 \begin{chapterabstract}
13 This chapter shows the integration of \gls{MTASK} and \gls{ITASK} by discussing:
14 \begin{itemize}
15 \item an architectural overview of \gls{MTASK} applications;
16 \item the interface for connecting devices;
17 \item the interface for lifting \gls{MTASK} tasks to \gls{ITASK} tasks;
18 \item the interface for lowering \gls{ITASK} \glspl{SDS} to \gls{MTASK} \glspl{SDS};
19 \item and a non-trivial home automation example application using all integration mechanisms;
20 \end{itemize}
21 \end{chapterabstract}
22
23 The \gls{MTASK} system is a \gls{TOP} \gls{DSL} for edge devices.
24 It is a multi-view \gls{DSL}, there are multiple interpretations possible for a single \gls{MTASK} term.
25 The main interpretation of \gls{MTASK} terms is the byte code compiler, \cleaninline{:: BCInterpret a}.
26 When using this interpretation and a few integration functions, \gls{MTASK} tasks are fully integrated in \gls{ITASK}.
27 They execute as regular \gls{ITASK} tasks and they can access \glspl{SDS} from \gls{ITASK}.
28 Devices in the \gls{MTASK} system are set up with a domain-specific \gls{OS} and become little \gls{TOP} engines in their own respect, being able to execute tasks.
29
30 \Cref{fig:mtask_integration} shows the architectural layout of a typical \gls{IOT} system created with \gls{ITASK} and \gls{MTASK}.
31 The entire system is written as a single \gls{CLEAN} specification where multiple tasks are executed at the same time.
32 Tasks can access \glspl{SDS} following the many-to-many communication pattern and multiple clients can work on the same task.
33 The diagram contains three labelled arrows that denote the integration functions between \gls{ITASK} and \gls{MTASK}.
34 Devices are connected to the system using the \cleaninline{withDevice} function (see \cref{sec:withdevice}).
35 There can be multiple devices connected to a single \gls{ITASK} host at the same time.
36 Using \cleaninline{liftmTask}, \gls{MTASK} tasks are lifted to a device (see \cref{sec:liftmtask}).
37 It is possible to execute multiple tasks on a single device.
38 \glspl{SDS} from \gls{ITASK} are lowered to the \gls{MTASK} device using \cleaninline{lowerSds} (see \cref{sec:liftsds}).
39
40 \begin{figure}
41 \centering
42 \includestandalone{mtask_integration}
43 \caption{An architectural overview of an \imtask{} application.}%
44 \label{fig:mtask_integration}
45 \end{figure}
46
47 \section{Connecting edge devices}\label{sec:withdevice}
48 Edge devices in an \gls{MTASK} application are always coordinated by a server.
49 This means that they wait for a server to take initiative, set up a connection, and send the work.
50 The heavy lifting of connecting an \gls{MTASK} device to an \gls{ITASK} server is done with the \cleaninline{withDevice} \gls{ITASK} function.
51 This function has two parameters, a communication specification, and a function using a device handle.
52 The device handle is required to interact with \gls{MTASK} devices, e.g.\ lift tasks.
53 By using \gls{HOAS} like this, setting up and tearing down the connection to the device is fully controlled.
54
55 All communication with a device happens through a so-called \emph{channels} \gls{SDS}.
56 The channels contain three fields, a queue of messages that are received, a queue of messages to send, and a stop flag.
57 Every communication method that implements the \cleaninline{channelSync} class can provide the communication with an \gls{MTASK} device.
58 At the time of writing, serial port, direct \gls{TCP}, and \gls{MQTT} over \gls{TCP} are supported communication methods (see \cref{lst:connection_types}).
59 Internally, the \cleaninline{withDevice} task sets up the communication, exchanges specifications with the device, executes the inner task while handling errors, and finally cleans up after closing.
60 \Cref{lst:mtask_device} shows the types and interface for connecting devices.
61
62 \begin{lstClean}[label={lst:mtask_device},caption={Device communication interface in \gls{MTASK}.}]
63 :: MTDevice //abstract
64 :: Channels :== ([MTMessageFro], [MTMessageTo], Bool)
65 class channelSync a :: a (Shared sds Channels) -> Task () | RWShared sds
66 withDevice :: a (MTDevice -> Task b)
67 -> Task b | iTask b & channelSync, iTask a
68 \end{lstClean}
69
70 \subsection{Implementation}
71 \Cref{lst:pseudo_withdevice} shows a pseudocode implementation of the \cleaninline{withDevice} function.
72 The \cleaninline{MTDevice} abstract type is internally represented as three \gls{ITASK} \gls{SDS} that contain all the current information about the tasks.
73 The first \gls{SDS} is the information about the \gls{RTS} of the device, i.e.\ metadata on the tasks that are executing, the hardware specification and capabilities, and a list of fresh task identifiers.
74 The second \gls{SDS} is a map storing downstream \gls{SDS} updates.
75 When a lowered \gls{SDS} is updated on the device, a message is sent to the server.
76 This message is initially queued in the map in order to properly handle multiple updates asynchronously.
77 Finally, the \cleaninline{MTDevices} type contains the communication channels.
78
79 The \cleaninline{withDevice} task itself first constructs the \glspl{SDS} using the \gls{ITASK} function \cleaninline{withShared}.
80 Then, it performs the following four tasks in parallel to monitor the edge device.
81 \begin{enumerate}
82 \item The channels are synchronised using the overloaded \cleaninline{channelSync} function.
83 Errors that occur here are converted to the proper \gls{MTASK} or \gls{ITASK} exception.
84 \item The shutdown flag of the channels is watched.
85 If the connection is lost with the device unexpectedly, an \gls{MTASK} exception is thrown.
86 \item The received messages in the channels are watched and processed.
87 Depending on the type of message, either the device information \gls{SDS} is updated, or the \gls{SDS} update is added to the lowered \gls{SDS} updates \gls{SDS}.
88 \item A request for a specification is sent.
89 Once the specification is received, the device task is run.
90 The task value of this device task is then used as the task value of the \cleaninline{withDevice} task.
91 \end{enumerate}
92
93 \begin{lstClean}[caption={Pseudocode for the \texttt{withDevice} function in \gls{MTASK}.},label={lst:pseudo_withdevice}]
94 withDevice :: a (MTDevice -> Task b) -> Task b | ...
95 withDevice spec deviceTask =
96 withShared default \dev->
97 withShared newMap \sdsupdates->
98 withShared ([], [MTTSpecRequest], False) \channels->
99 parallel
100 [ channelSync spec channels
101 , watchForShutdown channels
102 , watchChannelMessages dev channels
103 , waitForSpecification
104 >>| deviceTask (MTDevice dev sdsupdates channels)
105 >>* [OnValue $ ifStable $ \_->issueShutdown]
106 ]
107 \end{lstClean}
108
109 If at any stage an unrecoverable device error occurs, an \gls{ITASK} exception is thrown in the \cleaninline{withDevice} task.
110 This exception can be caught in order to devise fail-safe mechanisms.
111 For example, if a device fails, the task can be sent to another device as can be seen in \cref{lst:failover}.
112 This function executes an \gls{MTASK} task on a pool of devices connected through \gls{TCP}.
113 If a device error occurs during execution, the next device in the pool is tried until the pool is exhausted.
114 If another type of error occurs, it is re-thrown for a parent task to catch.
115
116 \begin{lstClean}[caption={An \gls{MTASK} failover combinator.},label={lst:failover}]
117 failover :: [TCPSettings] (Main (MTask BCInterpret a)) -> Task a
118 failover [] _ = throw "Exhausted device pool"
119 failover [d:ds] mtask = try (withDevice d (liftmTask mtask)) except
120 where except MTEUnexpectedDisconnect = failover ds mtask
121 except e = throw e
122 \end{lstClean}
123
124 \section{Lifting mTask tasks}\label{sec:liftmtask}
125 Once the connection with the device is established, \gls{MTASK} tasks are lifted to \gls{ITASK} tasks using the \cleaninline{liftmTask} function (see \cref{lst:liftmtask}).
126 Given an \gls{MTASK} task in the \cleaninline{BCInterpret} view and a device handle obtained from \cleaninline{withDevice}, an \gls{ITASK} task is returned.
127 This \gls{ITASK} task proxies the \gls{MTASK} task that is executed on the microcontroller.
128 So, when another task observes the task value, the actual task value from the microcontroller is observed.
129
130 \begin{lstClean}[label={lst:liftmtask},caption={The interface for lifting \gls{MTASK} tasks to \gls{ITASK} tasks.}]
131 liftmTask :: (Main (MTask BCInterpret a)) MTDevice -> Task a | iTask a
132 \end{lstClean}
133
134 \subsection{Implementation}
135 \Cref{lst:liftmTask_pseudo} shows the pseudocode for the \cleaninline{liftmTask} implementation
136 The first argument is the task and the second argument is the device which is an \gls{ADT} containing the \glspl{SDS} referring to the device information, the \gls{SDS} update queue, and the channels.
137 First a fresh identifier for the task is generated using the device state.
138 With this identifier, the cleanup hook can be installed.
139 This is done to assure the task is removed from the edge device if the \gls{ITASK} task coordinating it is destroyed.
140 Tasks in \gls{ITASK} are destroyed when for example they are executed in parallel with another task and the parallel combinator terminates, or when the condition to step holds in a sequential task combination.
141 Then the \gls{MTASK} compiler is invoked, its only argument besides the task is a function doing something with the results of the compilation, i.e.\ the lowered \glspl{SDS} and the messages containing the compiled and serialised task.
142 With the result of the compilation, the task can be executed.
143 First the messages are put in the channels, sending them to the device.
144 Then, in parallel:
145 \begin{enumerate}
146 \item the value is watched by looking in the device state \gls{SDS}, this task also determines the task value of the whole task;
147 \item the downstream \glspl{SDS} are monitored, i.e.\ the \cleaninline{sdsupdates} \gls{SDS} is monitored and updates from the device are applied to the associated \gls{ITASK} \gls{SDS};
148 \item the upstream \glspl{SDS} are monitored by spawning tasks that watch these \glspl{SDS}, if one is updated, the novel value is sent to the edge device.
149 \end{enumerate}
150
151 \begin{lstClean}[float=,label={lst:liftmTask_pseudo},caption={Pseudocode implementation for \texttt{liftmTask}.}]
152 liftmTask :: (Main (MTask BCInterpret a)) MTDevice -> Task a | iTask a
153 liftmTask task (MTDevice dev sdsupdates channels)
154 = freshTaskId dev
155 >>= \tid->withCleanupHook (sendmessage [MTTTaskDel tid] channels) (
156 compile task \mrefs msgs->
157 sendMessage msgs channels
158 >>| waitForReturnAndValue tid dev
159 -|| watchSharesDownstream mrefs tid sdsupdates
160 -|| watchSharesUpstream mrefs channels tid)
161 \end{lstClean}
162
163 Sending the complete byte code to the device is not always a suitable option.
164 For example, when the device is connected through an unstable or slow connection, sending the entire byte code induces a lot of delay.
165 To mitigate this problem, \gls{MTASK} tasks can be preloaded on a device.
166 Preloading means that the task is compiled and integrated into the device firmware.
167 On receiving a \cleaninline{TaskPrep}, a hashed value of the task to be sent is included.
168 The device then checks the preloaded task registry and uses the local preloaded version if the hash matches.
169 Of course this only works for tasks that are not tailor-made for the current work specification and not depend on run time information.
170 The interface for task preloading can be found in \cref{lst:preload}.
171 Given an \gls{MTASK} task, a header file is created that should be placed in the source code directory of the \gls{RTS} before building to include it in the firmware.
172
173 \begin{lstClean}[label={lst:preload},caption={Preloading tasks in \gls{MTASK}.}]
174 preloadTask :: (Main (MTask BCInterpret a)) -> Task String
175 \end{lstClean}
176
177 \section{Lowering iTask shared data sources}\label{sec:liftsds}
178 Lowering \gls{ITASK} \glspl{SDS} to \gls{MTASK} \glspl{SDS} is something that mostly happens at the \gls{DSL} level using the \cleaninline{lowerSds} function (see \cref{lst:mtask_itasksds}).
179 Lowering \pgls{SDS} proxies the \gls{ITASK} \gls{SDS} for use in \gls{MTASK}.
180 \Glspl{SDS} in \gls{MTASK} always have an initial value.
181 For regular \gls{SDS} this value is given in the source code, for lowered \gls{ITASK} \glspl{SDS} this value is obtained by reading the values once just before sending the task to the edge device.
182 On the device, there is just one difference between lowered \glspl{SDS} and regular \glspl{SDS}: after changing a lowered \gls{SDS}, a message is sent to the server containing this new value.
183 The \cleaninline{withDevice} task (see \cref{sec:withdevice}) receives and processes this message by writing to the \gls{ITASK} \gls{SDS}.
184 Tasks watching this \gls{SDS} get notified then through the normal notification mechanism of \gls{ITASK}.
185 \Cref{lst:imp_sds} shows the implementation of this type class for the byte code compiler.
186
187 \begin{lstClean}[label={lst:mtask_itasksds},caption={Lowered \gls{ITASK} \glspl{SDS} in \gls{MTASK}.}]
188 class lowerSds v where
189 lowerSds :: ((v (Sds t)) -> In (Shared sds t) (Main (MTask v u)))
190 -> Main (MTask v u) | RWShared sds
191 \end{lstClean}
192
193 As an example, \cref{lst:mtask_liftsds_ex} shows a light switch function producing an \imtask{} task when given a device handle.
194 First an \gls{ITASK} \gls{SDS} of the type boolean is created.
195 This boolean represents the state of the light.
196 The \gls{MTASK} task uses this \gls{SDS} to turn on or off the light.
197 The \gls{ITASK} task that runs in parallel allows interactive updating of this state.
198
199 \begin{lstClean}[label={lst:mtask_liftsds_ex},caption={Interactive light switch program in \gls{MTASK}.}]
200 lightswitch :: MTDevice -> Task Bool
201 lightswitch dev = withShared False \sh->
202 liftmTask (mtask sh) dev
203 -|| updateSharedInformation [] sh
204 <<@ Hint "Light switch"
205 where
206 mtask :: (Shared sds Bool) -> Main (MTask v Bool)
207 | mtask, lowerSds v & RWShared sds
208 mtask sh =
209 declarePin D13 PMOutput \ledPin->
210 lowerSds \ls=sh
211 In fun \f=(\st->
212 getSds ls
213 >>*. [IfValue (\v->v !=. st) (writeD ledPin)]
214 >>=. f)
215 In {main=getSds ls >>~. f}
216 \end{lstClean}
217
218 \section{Conclusion}
219 This chapter explained the integration of \gls{MTASK} programs with \gls{ITASK}.
220 Using just three \gls{ITASK} functions, \gls{MTASK} devices are integrated in \gls{ITASK} seamlessly.
221 Devices, using any supported type of connection, are integrated in \gls{ITASK} using the \cleaninline{withDevice} function.
222 Once connected, \gls{MTASK} tasks are sent to the device for execution using \cleaninline{liftmTask}, lifting them to full-fledged \gls{ITASK} tasks.
223 To lower the bandwidth, tasks can also be preloaded.
224 Furthermore, the \gls{MTASK} tasks interact with \gls{ITASK} \glspl{SDS} using the \cleaninline{lowerSds} construct.
225 All of this together allows programming all layers of an \gls{IOT} system from a single source and in a single paradigm.
226 All details regarding interoperation are automatically taken care of.
227 The following section contains an elaborate example using all integration functions that has deliberately been placed after the conclusion for formatting reasons.
228
229 \newpage
230 \vspace*{\fill}
231 \hfill
232 \begin{center}
233 \cleaninline[basewidth=0pt,columns=flexible,basicstyle=\tt\footnotesize]{let p = [['This page would be intentionally blank if I were not telling you that ']:p] in p} % chktex 10
234 \end{center}
235 \vspace{\fill}
236 \newpage
237
238 \section{Home automation}%
239 \label{sec:home_automation}
240 This section presents an interactive home automation program (\cref{lst:example_home_automation}) to illustrate the dynamic integration of the \gls{MTASK} language and the \gls{ITASK} system.
241 All layers of \gls{IOT} systems are used in this application.
242 The presentation layer consists of an automatically generated web interface for the user to control which tasks are sent to a device for execution.
243 The application layer is the \gls{ITASK} server, the coordinator of the tasks in the system that also stores the data.
244 The perception layer is populated by two devices: an \gls{ARDUINO} UNO, and an ESP8266 based prototyping board called {NodeMCU}.
245 \Crefrange{lst:example:spec1}{lst:example:spec2} show the specification for the devices.
246 The UNO is connected via serial using the UNIX filepath \path{/dev/ttyACM0} and the default serial port settings.
247 The NodeMCU is connected via \gls{TCP} over \gls{WIFI} and hence the \cleaninline{TCPSettings} record is used.
248
249 The code is split up into an \gls{ITASK} part and several \gls{MTASK} parts.
250 \Crefrange{lst:example:task1}{lst:example:task2} contains the \gls{ITASK} task that coordinates the \gls{IOT} application.
251 First the devices are connected (\crefrange{lst:example:conn1}{lst:example:conn2}) followed by launching a \cleaninline{parallel} task, visualised as a tabbed window, and a shutdown button to terminate the program (\crefrange{lst:example:par1}{lst:example:par2}).
252 This parallel task is the controller of the tasks that run on the edge devices.
253 It contains one task that allows adding new tasks (using \cleaninline{appendTask}) and all other tasks in the process list will be \gls{MTASK} tasks once they are added by the user.
254 The controller task, \cleaninline{chooseTask} as shown in \crefrange{lst:example:ct1}{lst:example:ct2}, allows the user to pick a task, and sending it to the specified device.
255 Tasks are picked by index from the \cleaninline{tasks} list (\crefrange{lst:example:tasks1}{lst:example:tasks2}) using \cleaninline{enterChoice}.
256 The interface that is generated for this is seen in \cref{fig:example_screenshots1}.
257 After selecting the task, a device is selected (see \cref{fig:example_screenshots2,lst:example:selectdev}).
258 When both a task and a device are selected, an \gls{ITASK} task is added to the process list using \cleaninline{appendTask}.
259 Using the helper function \cleaninline{mkTask}, the actual task is selected from the \cleaninline{tasks} list and executed by providing it the device argument.
260
261 The \cleaninline{tasks} list contains named \gls{MTASK} tasks that can be sent to the device.
262 When selecting the \cleaninline{temperature} task, the current temperature is shown to the user (\cref{fig:example_screenshots3}).
263 This task just sends a simple temperature monitoring task to the device using \cleaninline{liftmTask} and provides a view on its task value using the \cleaninline{>\&>} \gls{ITASK} combinator.
264 This combinator allows the observation of the left-hand side task's value through \pgls{SDS}.
265 The light switch task at \crefrange{lst:example:ls1}{lst:example:ls2} is a task that has bidirectional interaction using the definition of \cleaninline{lightswitch} shown in \cref{lst:mtask_liftsds_ex}.
266 Using \cleaninline{lowerSds}, the server-side status of the light switch is synchronised with the actual light attached to the \gls{GPIO} pin.
267 Finally, some tasks contain significant \gls{ITASK} portions as well.
268 The remote computation task first queries the user for a number and then constructs a tailor-made task to send to the device to perform a computation, i.e.\ it calculates the factorial for the given number.
269
270 \begin{figure}[p]
271 \centering
272 \begin{subfigure}{.33\linewidth}
273 \includegraphics[width=.9\linewidth]{home_auto1}
274 \caption{Select task.}%
275 \label{fig:example_screenshots1}
276 \end{subfigure}%
277 \begin{subfigure}{.33\linewidth}
278 \includegraphics[width=.9\linewidth]{home_auto2}
279 \caption{Select device.}%
280 \label{fig:example_screenshots2}
281 \end{subfigure}%
282 \begin{subfigure}{.33\linewidth}
283 \includegraphics[width=.9\linewidth]{home_auto3}
284 \caption{View result.}%
285 \label{fig:example_screenshots3}
286 \end{subfigure}
287 \caption{Screenshots of the home automation example program in action.}%
288 \label{fig:example_screenshots}
289 \end{figure}
290
291 \begin{figure}[p]
292 \cleaninputlisting[firstline=12,lastline=49,numbers=left,belowskip=0pt,basicstyle=\tt\footnotesize]{lst/example.icl}
293 \begin{lstClean}[numbers=left,firstnumber=39,aboveskip=0pt,basicstyle=\tt\footnotesize,caption={An example of a home automation program.},label={lst:example_home_automation}]
294 , ...][+\label{lst:example:tasks2}+]\end{lstClean}
295 \end{figure}
296
297 \input{subfilepostamble}
298 \end{document}