+
+The \CI{deviceResource} component of the record must implement the
+\CI{MTaskDuplex} interface that provides a function that launches a \gls{Task}
+used for synchronizing the channels. The \CI{deviceTask} stores the
+\gls{Task}-id for this \gls{Task} when active so that it can be checked upon.
+This top-level task has the duty to report exceptions and errors as they are
+thrown by setting the \CI{deviceError} field. All communication goes via these
+channels. If the system wants to send a message to the device, it just puts it
+in the channels. Messages sent from the client to the server are also placed
+in there. In the case of the \gls{TCP} device type, the \gls{Task} is just a
+simple wrapper around the existing \CI{tcpconnect} function in \gls{iTasks}. In
+case of a device connected by a serial connection, it uses the newly developed
+serial port library of \gls{Clean}\footnote{\url{%
+https://gitlab.science.ru.nl/mlubbers/CleanSerial}}.
+
+Besides all the communication information, the record also keeps track of the
+\glspl{Task} currently on the device, the compiler state (see
+Section~\ref{sec:compiler}) and the according \glspl{SDS}. Finally, it stores
+the specification of the device that is received when connecting. All of this
+is given in Listing~\ref{lst:mtaskdevice}. The definitions of the message
+format are explained in the following section.
+
+\subsection{Integration}
+When the system starts up, the devices from the previous execution still
+residing in the \gls{SDS} must be cleaned up. It might be the case that they
+contain \glspl{Task}, \glspl{SDS} or errors that are no longer applicable in
+this run. A user or programmer can later choose to reconnect to some devices.
+
+\begin{lstlisting}[caption={Starting up the devices},%
+ label={lst:startupdevs}]
+startupDevices :: Task [MTaskDevice]
+startupDevices = upd (map reset) deviceStoreNP
+ where reset d = {d & deviceTask=Nothing, deviceTasks=[], deviceError=Nothing}
+\end{lstlisting}
+
+The system's management is done through the interface of a single \gls{Task}
+called \CI{mTaskManager}. To manage the system, a couple of different
+functionalities are needed and are launched. An image of the management
+interface is shown in Figure~\ref{lst:manage}. The left sidebar of the
+interface shows the list of example \glspl{Task} that are present in the
+system. When clicking a \gls{Task}, a dialog opens in which you can select the
+device to send the \gls{Task} to. The dialog might contain user specified
+variables. All example \glspl{mTask} are of the type
+\CI{Task (Main (ByteCode () Stmt))} and can thus ask for user input first if
+needed for parameterized \glspl{mTask}. The bottom panel shows the device
+information. In this panel, the devices can be created and modified. Moreover,
+this panel allows the user to reconnect with a device after a restart of the
+server application.
+
+\todo{redo this image}
+\begin{figure}[H]
+ \centering
+ \includegraphics[width=\linewidth]{manage}
+ \caption{The device management interface}\label{lst:manage}
+\end{figure}
+
+\subsection{Shares}
+The architecture of the system keeps track of the \glspl{SDS} stored on
+the client in the big devices \gls{SDS}. Client-\glspl{SDS} can be stored on
+one device at the same time. This means that if a \gls{SDS} updates, everyone
+watching it will be notified. This would result in to a lot of notifications
+that are not meant for the listener. Moreover, when a client updates the
+\gls{SDS} this is processed by the connection handler and results in an update
+of the real \gls{SDS}. Finally, the \gls{SDS} of a client must be synchronized
+with the actual device. Thus, when an \gls{iTasks}-\gls{Task} writes the
+client-\gls{SDS}, it must be propagated to the real device. There are several
+ways of tackling this problem each with their own pros and cons and their own
+level of abstraction.
+
+First an actual \gls{iTasks}-\gls{SDS} for every \gls{SDS} used in a client can
+be instantiated with one \gls{iTasks}-\gls{Task} listening to the \gls{SDS} and
+synchronizing it with the device when an update occured. This approach is very
+expensive as it requires a lot of listening \glspl{Task}.
+
+Improved on this, a single \gls{iTasks}-\gls{SDS} can be created for every
+devices that stores the respective \glspl{SDS}. Using the \CI{mapReadWrite}
+functions, a single \gls{SDS} per device can be created as a lens that allows
+mapping on a single client-\gls{SDS}. However, This approach still requires
+\glspl{Task} listening to the \gls{SDS} and when a \gls{SDS} is written,
+everyone is notified, even if the \gls{Task} wanted to only watch a single
+different \gls{SDS}.
+
+Ultimately, the current approach --- a single \gls{SDS} for the entire system
+--- was explored. To create \glspl{SDS} per device or per client-\glspl{SDS} a
+\CI{mapReadWrite} can be used but it suffers the same problem as mentioned
+before. Moreover, a \gls{Task} still has to watch the \gls{SDS} and communicate
+the client-\gls{SDS} updates to the actual device. Both of these problems can
+be solved using a tailor made share heavily depending on parametric lenses. The
+type signature of the share then is as listed in Listing~\ref{lst:actualdev}.
+
+\begin{lstlisting}[label={lst:actualdev},%
+ caption={Device \gls{SDS}}]
+deviceStore :: Shared [MTaskDevice]
+\end{lstlisting}
+
+\subsection{Parametric Lenses}
+The type of the parametric lens is \CI{Maybe (MTaskDevice, Int)}. The \gls{SDS}
+can be responsible for the entire list of devices, from now on global.
+Moreover, the \gls{SDS} can focus on a single device, from now on local. A
+local \gls{SDS} can also specifically focus on a single \gls{SDS} on a single
+device, from now on called local-share.
+
+\paragraph{Global \glspl{SDS}: }
+Accessing the global \gls{SDS} is just a matter of focussing the
+\CI{deviceStore} with the \CI{Nothing} parameter. The signature for
+\CI{deviceStore} was given in Chapter~\ref{chp:arch}. The actual implementation
+is as in Listing~\ref{lst:global}
+
+\begin{lstlisting}[label={lst:shareimpl},%
+ caption={Base share implementation}]
+deviceStoreNP :: RWShared (Maybe (MTaskDevice, Int)) [MTaskDevice] [MTaskDevice]
+deviceStoreNP = sdsFocus Nothing deviceStore
+\end{lstlisting}
+
+
+
+
+\paragraph{Local \glspl{SDS}: }
+\paragraph{Local-share specific \glspl{SDS}: }
+
+The implementation for the share is shown in Listing~\ref{lst:shareimpl}. The
+\CI{realDeviceStore} \gls{SDS} is not exported through the header files. This
+\gls{SDS} contains the actual \gls{SDS} that writes to disk or memory.
+\CI{Int} is the identifier of the \gls{SDS}. The \gls{iTasks} way of applying
+lenses is through the \CI{sdsFocus} function and through the \CI{sdsLens}
+functions. \CI{sdsFocus} allows the programmer to fix the parameter.
+\CI{sdsLens} is basically a \CI{mapReadWrite} that has access to the parameter.
+This allows the programmer to create filters and lenses. Both of the methods
+are not good enough for the device \gls{SDS} because they do not achieve the
+writing to the actual device. Writing to a device requires being able to write
+to \glspl{SDS}. To solve this problem, a real base \gls{SDS} is created. All
+the details are visible in Listing~\ref{lst:shareimpl}.
+
+\section{Communication}
+The communication from the server to the client and vice versa is just a
+character stream containing encoded \gls{mTask} messages. The specific encoding
+is visible in Appendix~\ref{app:communication-protocol}. The type holding the
+messages in Listing~\ref{lst:avmsg}. Detailed explanation about the message
+types will be given in the following subsections.
+
+\begin{lstlisting}[label={lst:avmsg},caption={Available messages}]
+:: MTaskId :== Int
+:: MSDSId :== Int
+:: MTaskFreeBytes :== Int
+:: MTaskMSGRecv
+ = MTTaskAck MTaskId MTaskFreeBytes | MTTaskDelAck MTaskId
+ | MTSDSAck MSDSId | MTSDSDelAck MSDSId
+ | MTPub MSDSId BCValue | MTMessage String
+ | MTDevSpec MTaskDeviceSpec | MTEmpty
+
+:: MTaskMSGSend
+ = MTTask MTaskInterval String | MTTaskDel MTaskId
+ | MTShutdown | MTSds MSDSId BCValue
+ | MTUpd MSDSId BCValue | MTSpec
+
+:: MTaskInterval = OneShot | OnInterval Int | OnInterrupt Int
+\end{lstlisting}
+
+\subsection{Add a device}
+A device can be added by filling in the \CI{MTaskDevice} record as much as
+possible and running the \CI{connectDevice} function. This function grabs the
+channels, starts the synchronization \gls{Task}, makes sure the errors are
+handled when needed and runs a processing function in parallel to react on the
+incoming messages. Moreover, it sends a specification request to the device in
+question to determine the details of the device and updates the record to
+contain the top-level \gls{Task}-id. All the device functionality heavily
+depends on the specific \CI{deviceShare} function that applies a function a device in
+the \gls{SDS} when they are equal. Device equality is defined as equality on
+their channels. This allows you to give an old device record to the function
+and still update the latest instance. Listing~\ref{lst:connectDevice} shows the
+connection function.
+
+\begin{lstlisting}[label={lst:connectDevice},%
+ caption={Connect a device}]
+withDevices :: MTaskDevice (MTaskDevice -> MTaskDevice) -> Task [MTaskDevice]
+
+connectDevice :: (MTaskDevice (Shared Channels) -> Task ()) MTaskDevice -> Task Channels
+connectDevice procFun device = let ch = channels device
+ in appendTopLevelTask 'DM'.newMap True
+ (procFun device ch -||- catchAll (getSynFun d.deviceData ch) errHdl)
+ >>= \tid->withDevices device (\d->{d&deviceTask=Just tid,deviceError=Nothing})
+ >>| upd (\(r,s,ss)->(r,s++[MTSpec],ss)) ch
+ where
+ errHdl e = withDevices device (\d->{d & deviceTask=Nothing, deviceError=Just e}) @! ()
+\end{lstlisting}
+
+Figure~\ref{fig:handshake} shows the connection diagram. The client responds to
+the server with their device specification. This is detected by the processing
+function and the record is updated accordingly.
+
+\begin{figure}[H]
+ \centering
+ \begin{sequencediagram}
+ \newthread{s}{Server}
+ \newinst[4]{c}{Client}
+ \begin{call}{s}{MTSpec}{c}{MTDevSpec}
+ \end{call}
+ \end{sequencediagram}
+ \caption{Connect a device}\label{fig:handshake}
+\end{figure}
+
+\subsection{\glspl{Task} \& \glspl{SDS}}
+When a \gls{Task} is sent to the device it is added to the device record
+without an identifier. The actual identifier is added to the record when the
+acknowledgement of the \gls{Task} by the device is received. The connection
+diagram is shown in Figure~\ref{fig:tasksend}.
+
+\begin{figure}[H]
+ \centering
+ \begin{sequencediagram}
+ \newthread{s}{Server}
+ \newinst[4]{c}{Client}
+ \begin{call}{s}{MTSDS}{c}{MTSDSAck}
+ \end{call}
+ \begin{call}{s}{MTTask}{c}{MTTaskAck}
+ \end{call}
+ \end{sequencediagram}
+ \caption{Sending a \gls{Task} to a device}\label{fig:tasksend}
+\end{figure}
+
+The function for sending a \gls{Task} to the device is shown in
+Listing~\ref{lst:sendtask}. First the \gls{Task} is compiled into messages. The
+details of the compilation process are given in Section~\ref{sec:compiler}.
+The new \glspl{SDS} that were made during compilation are added to the
+deviceshares that were made during the compilation are merged with the existing
+shares on the device. Furthermore the messages are placed in the channel share
+of the device. This will result in sending the actual \gls{SDS} specification
+and \gls{Task} specifications to the device. A \gls{Task} record is created
+with the identifier $-1$ to denote a \gls{Task} not yet acknowledged. Finally
+the device itself is updated with the new state and with the new \gls{Task}.
+When the device returns an acknowledgement the \gls{Task} is updated
+accordingly.
+
+\begin{lstlisting}[label={lst:sendtask},%
+ caption={Sending a \gls{Task} to a device}]
+makeTask :: String Int -> Task MTaskTask
+makeTask name ident = get currentDateTime @ \dt->{MTaskTask | name=name, ident=ident, dateAdded=dt}
+
+makeShare :: String Int BCValue -> MTaskShare
+makeShare withTask identifier value = {MTaskShare | withTask=[withTask], identifier=identifier, value=value}
+
+sendTaskToDevice :: String (Main (ByteCode a Stmt)) (MTaskDevice, MTaskInterval) -> Task [MTaskDevice]
+sendTaskToDevice wta mTask (device, timeout)
+# (msgs, newState) = toMessages timeout mTask device.deviceState
+# shares = [makeShare wta sdsi sdsval\\{sdsi,sdsval}<-newState.sdss, (MTSds sdsi` _)<-msgs | sdsi == sdsi`]
+= updateShares device ((++) shares)
+ >>| sendMessages msgs device
+ >>| makeTask wta -1
+ >>= withDevices device o addTaskUpState newState
+ where
+ addTaskUpState :: BCState MTaskTask MTaskDevice -> MTaskDevice
+ addTaskUpState st task device = {MTaskDevice | device &
+ deviceState=st, deviceTasks=[task:device.deviceTasks]}
+\end{lstlisting}
+
+\subsection{Miscellaneous Messages}
+There exists one special type of message that is sent to the device only when
+it needs to reboot. When the server wants to stop the bond with the device it
+sends the \CI{MTShutdown} message. The device will then clear his memory, thus
+losing all the \glspl{SDS} and \glspl{Task} that were stored and reset itself.
+Shortly after the shutdown message a new server can connect to the device
+because the device is back in listening mode.
+
+\section{Lifting mTask to iTasks}
+\todo{task lifting}
+
+\section{Examples}
+\todo{example program (demo)}