\chapter{State of the Art}
\glsresetall

As the prevalence of diabetes mellitus continues to rise, advancements in technology are being directed toward improving the treatment of the disease. \gls{cgm} systems allow diabetic patients to continuously monitor their blood glucose levels. In combination with an insulin pump, a closed-loop system can be created. Such a system can autonomously control patients' blood glucose levels. Today's closed-loop systems are not fully autonomous yet and require patients to manually inject correcting insulin doses. The systems are referred to as hybrid closed-loop. There are multiple hybrid closed-loop systems available for diabetic patients, including certified (e.g.,\gls{fda} approved) \parencite{minimed} and \gls{diy} devices \parencite{openaps}\parencite{aaps}\parencite{loop}. Before a device can be made commercially available, it must obtain approval from a governing body (e.g., \gls{fda}). During the approval, clinical studies are conducted to assess the security and safety of the device. Simulation can be used in the clinical studies \parencite{dmmsr}. SmartCGMS provides a framework to create \gls{cgm} system or hybrid closed-loop software that can be tested in a simulation and without any modifications deployed to a real device \parencite{scgms_dmmsr}. However, its support for low-power devices is limited. This chapter summarizes the current state of popular available hybrid closed-loop systems, describes a recently-emerging way of bringing \gls{wasm} to \gls{iot} as a way to create portable software, and details technologies used for the realization of this project.

\section{Diabetes Mellitus}

Diabetes mellitus is a chronic metabolic disorder characterized by high blood glucose levels (hyperglycemia) resulting from insufficient insulin production or the body's inability to use insulin effectively. Failing to keep blood glucose levels in the optimal range can result in various health complications for the patients (e.g., kidney damage, nerve damage, and cardiovascular diseases). The blood glucose levels can be regulated by injecting insulin into the patient's bloodstream. However, an excessive insulin dose can result in a too-low blood glucose level (hypoglycemia). To avoid hyperglycemia and hypoglycemia, diabetic patients must closely monitor and control their blood glucose levels.

\subsection{Insulin Therapy}

Some diabetic patients require insulin therapy. The patients inject synthetic insulin into the fat layer under their skin, where it is absorbed into the bloodstream. Two types of insulin are used: long-acting and short-acting. The long-acting insulin provides a steady supply of insulin. It helps regulate blood glucose levels throughout the night and between meals. The short-acting insulin is injected before eating a meal to help process the consumed carbohydrates or as a correction when the blood glucose level is too high. It is referred to as a bolus dose.

Insulin pumps can be used for insulin therapy as an alternative to insulin injections. An insulin pump continuously injects insulin under the patient's skin. It only uses short-acting insulin to regulate blood glucose levels. The short-acting insulin is injected continuously in small doses to mimic the body's background level of insulin production. This constant stream of short-acting insulin is referred to as basal rate. Before a meal, the user can inject a higher bolus insulin dose to keep blood glucose levels in the desired range.

\section{Continuous Glucose Monitoring}

To determine the required insulin dose, diabetic patients may measure their blood glucose levels using a blood glucose meter. A blood glucose meter (glucometer) is a device that measures blood glucose levels from a drop of blood. The blood is usually extracted from the patient's fingertip. Even diabetic patients without insulin therapy are required to measure their blood glucose levels to help manage their medications and evaluate the results of ongoing therapy (e.g., diet and exercise).

\gls{cgm} system can be used instead of a glucometer. A \gls{cgm} system is a device that estimates a patient's blood glucose level by using a sensor located under their skin. It provides a real-time estimated value of the blood glucose levels. It consists of three parts: a blood glucose sensor, a transmitter, and a receiver. The sensor measures an electric current produced by a glucose-triggered electrochemical reaction. The measured current is denoised and transformed into a blood glucose level estimate. Then, these estimates are transmitted to the receiver. The receiver can be a smartphone, an insulin pump, or a separate device that displays or further processes the measured data.

An insulin pump can be connected to a \gls{cgm} system to create a closed-loop or a hybrid closed-loop system. Such a system automatically adjusts the patient's insulin dosage based on the measurements from the \gls{cgm}. A closed-loop system is fully autonomous. A hybrid closed-loop system requires users to input their meals into the system.

\subsection{OpenAPS}

OpenAPS is an example of a hybrid closed-loop system. It is a \gls{diy} solution for diabetic patients. It is distributed as an open-source software with thorough documentation on how to set it up. The OpenAPS solution uses a certified \gls{cgm} system to collect the data but in a non-certified manner. It processes the data and then adjusts the injected insulin dosage of a remotely connected certified insulin pump. It works only with specific \gls{cgm} systems and insulin pumps. For compatibility reasons, it sometimes uses legacy technology. As a result, the \gls{diy} solutions like OpenAPS are not certified by any authority.

OpenAPS uses an algorithm called \texttt{oref0}. It is a heuristic-based algorithm. OpenAPS argues that an algorithm with decision-making that can be understood by the user is beneficial. For safety reasons, the \textit{oref0} algorithm only adjusts the basal rate of the insulin pump. The basal insulin rate's maximum is low enough not to overdose the patient. OpenAPS offers an improved version of the original \texttt{oref0} algorithm referred to as \texttt{oref1}. A study conducted by Petruzelkova et al. \parencite{petruzelkova} concluded that the OpenAPS \texttt{oref0} algorithm is a safe alternative to the \gls{fda} approved algorithm developed by Medtronic. Further studies showed that the OpenAPS solution can improve the patient's blood glucose levels \parencite{openapsgood}. However, K{\"u}nzler et al. \parencite{openapsreliability} showed the limitations of \gls{diy} hybrid closed-loop systems, in their study users of OpenAPS encountered malfunctions that rendered the system unusable for 23\% of the total measured time.

It should be strongly noted that Petruzelkova et al. did not investigate the hardware and software design of the OpenAPS solution, and they did not evaluate any fault-tolerant or fail-safe aspect of the system. By examining its source code, particularly the recent git commit \texttt{da7015c} \parencite{openapsgithub}, it can be seen that the software does not meet fail-safe nor fault-tolerant requirements. This is in accordance with study \cite{openapsreliability}. Therefore, we conclude that improvement of the patient medical condition could have been achieved rather by increased self-monitoring of the blood glucose level and more frequent patient interventions (bolus, meal, physical activity, stress relief, etc.), thus being the \texttt{oref}-benefit a self-bias affected. This is in accordance, e.g., with study \cite{melmer2019glycaemic} that states "OpenAPS shows similar results to more rigorously developed and tested AP technology in a highly selective, motivated and technology-adept population of individuals with type 1 diabetes" [sic!]. Another study \cite{cybersecuritycgm}, is concerned about the cybersecurity of DIY solutions, explicitly naming OpenAPS, whereas the cybersecurity comes from the hardware and software design of the system.


When building an OpenAPS system, a \gls{cgm} system, an insulin pump, and additional hardware that runs OpenAPS are required. OpenAPS recommends, for example, the Raspberry Pi Zero WH. If using the Raspberry Pi, the OpenAPS application runs on the Raspberry Pi OS Lite operating system. This allows the application to be updated without rebuilding the whole system. \parencite{openaps}

\subsection{AndroidAPS}

\gls{aaps} is another \gls{diy} hybrid closed-loop system. It is an Android application based on the \texttt{oref0} and \texttt{oref1} algorithms from OpenAPS. The \gls{aaps} system uses an \gls{aaps} application to control the insulin rate and another application to communicate with the \gls{cgm} system. Some pumps might require an additional device to be able to communicate with the phone - a RileyLink compatible device. RileyLink is a protocol defined for communication with insulin pumps. The data is collected using Bluetooth. \gls{aaps} is compatible with more insulin pumps and \gls{cgm} systems than the OpenAPS solution. \parencite{aaps}

\subsection{Loop}

Loop is also a \gls{diy} hybrid closed-loop system. It is an application for iPhones. It uses its own algorithm to determine the optimal insulin bolus and basal rate. Unlike OpenAPS's \texttt{oref0} algorithm, which only computes the basal rate. Loop does not issue insulin bolus commands by default. It only suggests a recommended dose. The Loop system also requires a RileyLink compatible device to communicate with certain insulin pumps. \parencite{loop}

\subsection{Medtronic MiniMed 670G}

Medtronic MiniMed 670G is the first \gls{fda} approved hybrid closed-loop system, but more hybrid closed-loop systems have been approved since its approval in 2016. The MiniMed 670G comprises a \gls{cgm} system and an insulin pump. The insulin basal rates are computed using a SmartGuard algorithm developed by Medtronic. The MiniMed system offers two modes: auto mode and manual mode. In auto mode, the basal insulin dosage is automatically adjusted based on data from the CGM system. In manual mode, users have control over setting the basal rate themselves. Numerous studies, such as  \parencite{medtronic-horowitz} and \parencite{medtronic-saunders}, have shown that the device in auto mode - acting as a hybrid closed-loop - has a positive effect on a patient's blood glucose levels. \parencite{medtronicmini}\parencite{minimed}

\subsection{SmartCGMS}
\label{subs:scgms}

SmartCGMS is an open-source software architecture framework for continuous glucose monitoring. SmartCGMS is based on the idea of co-simulation and \gls{hla} standard. \gls{hla} is a standard that allows the combination of multiple real and simulated devices in a distributed simulation \parencite{hla}. In the SmartCGMS framework, such a device can be, for example, a glucose sensor, insulin pump, or a predictor of glucose level. The SmartCGMS framework defines filters that represent individual parts of the system. The concept of co-simulation allows developers to perform optimization and development on simulated devices and then switch the simulated device to a real one when the program code is ready. An example of how SmartCGMS can be used has been shown in \parencite{scgms_dmmsr}. In this study, SmartCGMS has been used to evaluate the \texttt{oref} algorithm using an \gls{fda} approved virtual diabetic patients simulator DMMS.R \parencite{dmmsr}. By taking advantage of SmartCGMS co-simulation support, the original \texttt{oref} code could have been directly used in the experimental setup \parencite{scgms_dmmsr}. \parencite{scgms}

\section{Current Efforts to Execute SmartCGMS on Low-Power Devices}

SmartCGMS officially supports these platforms:

\begin{itemize}
    \item Win64
    \item MacOS 64
    \item Debian 64
    \item Android arm64-v8a
    \item Android armeabi-v7a
\end{itemize}


In a study by Otta \parencite{otta} an approach was proposed to execute SmartCGMS on the ESP32 system on a chip. In the proposal, Otta suggests using \gls{espidf} as the underlying software system. The \gls{espidf} is based on FreeRTOS and provides multiple software components (e.g., peripheral drivers and network stack). Using a \gls{rtos} ensures the system's critical tasks are executed in time. In the proposed system, several tasks run on top of FreeRTOS to manage applications, remote communication, and updates. 

The proposal defines features - applications that can be remotely installed (e.g., SmartCGMS). Each feature is a \gls{wasm} module run by a lightweight virtual machine. There are already multiple supported \gls{wasm} runtimes for \gls{espidf} \parencite{wamr}\parencite{wasm3}. The features can then be updated during runtime.

\subsection{WebAssembly}
\label{subsection:wasm_general}

\gls{wasm} is a binary format defined by The World Wide Web Consortium \parencite{wasmcore}. The definition includes a set of virtual instructions. The instructions are executed by a virtual stack machine. The code is distributed in \gls{wasm} binary files called \gls{wasm} modules. Initially, \gls{wasm} was meant for web browsers, but the virtual instructions set can be implemented in a standalone runtime. Some of these standalone runtimes also support embedded devices (e.g., the ESP32) \parencite{wamr} \parencite{wasm3}.

\gls{wasm} was designed to be safe, fast, and portable \parencite{wasm}. The binary files are called modules. The modules define functions, globals, tables, and memories. Definitions can be both imported and exported. All imports must be resolved when instantiating the module. A module is the static representation of the program. The dynamic representation is called an instance. Instances hold the runtime state of the \gls{wasm} module, allowing execution and interaction with the host environment. Functions represent an executable block of code. Exported functions can be called from the host environment directly, or they can be called by other \gls{wasm} functions, even recursively. Globals are global variables defined in the module. Tables are arrays of references to objects. The memory of a \gls{wasm} module is a large array of bytes (referred to as linear memory). The unit of size for \gls{wasm} module memory is 64 KB. Each module can only have one memory, but it is possible to grow the module's memory in increments of 64 KB. The memory is separate from the code space and execution stack. This makes executing \gls{wasm} modules safe, as they cannot corrupt their execution environment. The module's memory can, however, be accessed by the execution environment. This makes it possible to make a shared memory region between the module and the execution environment. \parencite{wasm} \parencite{wasmcore}

Several papers have been published on the usability of \gls{wasm} in low-power devices, mainly with a focus on the \gls{iot}, such as \parencite{iotuptospeedwithwasm} and \parencite{liquidiot}. Its low overhead, safety, and portability make it a good candidate for \gls{iot} applications \parencite{wasmiotoverview}. The main appeal of \gls{wasm} for SmartCGMS is the ability to update the application dynamically as suggested by \parencite{otta} and \parencite{liquidiot} and evaluated by \parencite{opswi}. Compiling SmartCGMS for low-power devices as a native application using an \gls{rtos} (e.g., FreeRTOS) would require flashing the whole firmware when introducing new functionality or fixing issues. 
 

\section{Building Blocks of Proposed SmartCGMS Concept}

This paper proposes and evaluates another approach for executing SmartCGMS on low-power devices. The project's requirements are to define and implement a real-time SmartCGMS concept based on FreeRTOS. The concept should maintain compatibility with the x86-64 \gls{isa}. The concept will also be compiled into the \gls{wasm} format to test the feasibility of Otta's suggested solution \parencite{otta}. The following sections describe the technologies used to implement the proposed system. First, the SmartCGMS framework and its relevant parts are described. The next section describes FreeRTOS, and the last section is dedicated to \gls{wasm} tools.

\subsection{SmartCGMS}
\label{subsection-scgms}
\glsresetall

The general description of SmartCGMS and the description of what it can be used for is in section \ref{subs:scgms}. This section details the project-relevant SmartCGMS internals. 

\subsubsection{SmartCGMS Architecture}
\label{sec:scgms_arch}

SmartCGMS uses a fall-through architecture for signal processing. The steps of the processing are represented by filters, which together form a filter chain. A signal is processed as a series of messages called device events that linearly pass through the filter chain. Typically, at the beginning of the filter chain, there is a filter representing a source of device events. This filter can either simulate a device (e.g., by generating events from a predefined dataset) or read data from a real device. The device event is then sent to the next filter. Each filter can decide to destroy, modify, or pass the event through. It can also generate a new event. At the end of the filter chain, an output filter can represent, for example, an insulin pump or a filter visualizing the data from the events. An example of a filter chain can be seen in figure \ref{fig:filter_chain}. \parencite{diabetes_zcu}


\begin{figure}[htpb]
  \centering
  \includegraphics[width=1\textwidth]{figures/filter_chain.PNG}
  \caption{Example of a SmartCGMS filter chain \parencite{diabetes_zcu}.} \label{fig:filter_chain}
\end{figure}

SmartCGMS also defines other entities (e.g., models and signals). Each entity is compiled into a dynamic library. A SmartCGMS application is a set of dynamic libraries. The main SmartCGMS components are  SmartCGMS core and SmartCGMS common. The common library defines interfaces for SmartCGMS entities based on the Component Object Model, and it provides base implementations for SmartCGMS classes, functions, and utilities. The SmartCGMS core library manages the resources of a SmartCGMS application (e.g., builds the filter chain and creates events). A typical SmartCGMS application includes the core and common SmartCGMS dynamic libraries and then a dynamic library for each entity that is used in the application. The SmartCGMS project currently offers precompiled binaries for Windows, MacOS, Debian, and Android operating systems. \parencite{diabetes_zcu}


\subsubsection{Device Event}

The device event represents a message in the SmartCGMS filter chain. It is a structure that holds a device \gls{guid} that identifies each event originator, signal \gls{guid} that identifies the signal carried by the event, device and logical time, and segment ID (specifying a time segment the event belongs to). The data carried by the event is stored in a union containing a level (signal level value), parameters (array of parameters), and info (a string). The type of event is distinguished by event code. There are fifteen different event codes. \parencite{diabetes_zcu}

There are four event codes relevant to this project:
\begin{itemize}
    \item Shut\_Down - signals to a filter that it should terminate and release its resources
    \item Level - holds a signal value
    \item Information - holds an information string
    \item Error - reports an error, holds the error string

\end{itemize}


\subsubsection{SmartCGMS Filter}

Each SmartCGMS filter is managed as a dynamic library. It is loaded by the SmartCGMS framework and managed by calling exported functions: \texttt{do\_create\_filter} and \texttt{do\_get\_filter\_descriptors}. A filter is described by its descriptor \newline(\texttt{scgms::TFilter\_Descriptor}). It is a structure that holds the filter's \gls{guid}, name, description, parameter information, and flags. Each descriptor member provides necessary information about the filter to the SmartCGMS framework or the developer. The filter must export the \texttt{do\_get\_filter\_descriptors} function, which returns its descriptors in a continuous array. \parencite{diabetes_zcu}

To create the filter object, SmartCGMS uses the other exported function \newline\texttt{do\_create\_filter}. This function takes the filter \gls{guid} as a parameter. If the \gls{guid} matches the \gls{guid} of the filter, it creates the filter and returns a reference to it. \parencite{diabetes_zcu}

Once a filter is created, it has to be configured before it can process events. The filter life cycle can be seen in figure \ref{fig:filter_life}. Each SmartCGMS filter must implement an interface defined by the SmartCGMS framework called \texttt{scgms::IFilter}. This interface is an abstract class with two pure virtual functions: \texttt{Configure} and \texttt{Execute}. A pure virtual function in C++ is a function that is not defined in the base class. This forces its classes to implement the function. \parencite{diabetes_zcu}

The \texttt{Configure} function provides the filter parameters (loaded from the filter chain configuration) to the filter. It configures the filter and puts it in the operational state. When the filter is in the operational state, it can process events. The events are processed by calling the \texttt{Execute} function. When the \texttt{Execute} function is called, an event is passed to the filter. The filter can read and modify the event values. After the filter processes the event, it can then either pass it to the next filter or deallocate the event memory. The event processing is synchronous. Each \texttt{Execute} recursively calls the next \texttt{Execute} functions until the event is deallocated by a filter or the event reaches the end of the filter chain (where it is deallocated by a terminal filter). Then the \texttt{Execute} function call returns. The filter chain execution is protected by a recursive mutex. In the case of multiple threads calling \texttt{Execute} simultaneously, SmartCGMS only allows a single call to the \texttt{Execute} function and blocks the other threads. \parencite{diabetes_zcu}

The filter is terminated when it receives a \texttt{Shut\_Down} event. \parencite{diabetes_zcu}


\begin{figure}[htpb]
  \centering
  \includegraphics[width=0.8\textwidth]{figures/filter_life.PNG}
  \caption{Life cycle of a SmartCGMS filter \parencite{diabetes_zcu}.} \label{fig:signal_generator}
\end{figure}

\subsubsection{SmartCGMS Discrete Model}

The SmartCGMS discrete model is an entity that can represent, for example, a physiological model of a diabetic patient (e.g., The Bergman Minimal Model \parencite{bergman}). The discrete model is implemented as a derived class from the \texttt{scgms::IFilter} interface. It implements two additional functions: \texttt{Step} and \texttt{Initialize}. The discrete model has a state. It has to be initialized prior to operation. The discrete model then performs discrete steps to advance its state. The discrete model is managed by a signal generator filter. Its operation can be seen in figure \ref{fig:signal_generator}. The model parameters are specified under the signal generator filter parameters in the configuration file.


\begin{figure}[htpb]
  \centering
  \includegraphics[width=0.8\textwidth]{figures/signal_generator.PNG}
  \caption{Operation of the SmartCGMS signal generation filter and a discrete model \parencite{diabetes_zcu}.} \label{fig:filter_life}
\end{figure}

\subsubsection{SmartCGMS Configuration}

The SmartCGMS configuration is stored in an INI file. It defines the order of the filters in the filter chain and contains their parameters. The configuration can be generated by the SmartCGMS GUI application or by using a text editor. It is designed to be human-readable. A single filter can be configured, for example, as follows:
\begin{lstlisting}
[Filter_001_{8FAB525C-5E86-AB81-12CB-D95B1588530A}]
Buffer_Size = 100
Log_File = Log.txt
\end{lstlisting}
The three-digit number after 'Filter\_' denotes the filter's position in the filter chain, the curly brackets hold its \gls{guid}, and then follow the filter's parameters (specified in the filter descriptor). \parencite{diabetes_zcu}

\subsubsection{SmartCGMS Portability}

SmartCGMS has been developed with portability in mind. The source code is written in C++ (C++17 standard) to make SmartCGMS portable, minimize its memory footprint, and maximize its computational performance \parencite{scgms-older}. As mentioned in section \ref{sec:scgms_arch}, SmartCGMS is available on Windows, MacOS, Debian, and Android. All of these platforms have a file system and support dynamic libraries. These features might not be available on embedded devices running a \gls{rtos}, and thus, the support for such devices would require modifications to the SmartCGMS code base. SmartCGMS has been compiled for Raspberry Pi, but it is not officially supported and documented.


\subsection{FreeRTOS}
\label{substection-freertos}

To achieve predictability and reliability, a \gls{rtos} can be used to manage complex programs in a real-time system. Safety-critical real-time systems (e.g., medical embedded systems) require the highest level of predictability and reliability. This can be achieved by using a certified \gls{rtos} \parencite{hard_rtos}. FreeRTOS is a free, widespread \gls{rtos} that offers a pre-certified version (SAFERTOS) with official instructions on how to port an existing application from FreeRTOS to SAFERTOS \parencite{safertos}\parencite{freertos}. However, SAFERTOS does not use the same codebase as FreeRTOS. It is only based on its functional model \parencite{safertos}. If certified software is not required for a solution, FreeRTOS is very well supported by its community and also offers official technical support under the project OpenRTOS. The codebase of FreeRTOS and OpenRTOS is shared. Therefore, applications written for FreeRTOS can be ported to OpenRTOS without any modifications \parencite{openrtos}.

As many other \glspl{rtos}, FreeRTOS has low processing and memory overhead (typically around 6 to 12 KB). The core functionality of the kernel is located in only 3 files, which makes it simple to use and understand. Its documentation is extensive, and it offers official support for many architectures \parencite{freertos}. Additionally, many community ports are available online. FreeRTOS is also supported as a component in \gls{espidf} \parencite{espidf}. 

FreeRTOS was selected as a base operating system for the approach of bringing SmartCGMS to a smartwatch proposed by \parencite{otta}. It is also specified as a required \gls{rtos} for this project.

\subsubsection{Tasks}

Tasks are the threads of a \gls{rtos}. A task in FreeRTOS is a function that executes as an endless loop or must delete itself after finishing its execution. FreeRTOS scheduler manages the execution of tasks and guarantees that only one task runs at a given time. The tasks are executed according to their priority, which is set during the task creation. Other parameters can also be configured during the creation. These are the task's code, its name, stack depth, parameters, priority, and a task handle that refers to the created task. FreeRTOS additionally offers support for creating tasks statically. In this case, the task is not allocated from the FreeRTOS heap, but the memory needs to be provided at the task creation. This solution is slightly more complex. There are two extra parameters: the task's stack buffer (used for the task's stack) and the task buffer (used for storing runtime information about the task). However, the task's memory can be allocated at compile time. \parencite{freertos}

\subsubsection{FreeRTOS-Plus-POSIX}

FreeRTOS-Plus-POSIX is a FreeRTOS extension that implements a subset of the POSIX threading \gls{api} \parencite{pthreads}. This extension wraps the FreeRTOS tasks \gls{api} with \glspl{pthread} \gls{api}, thus allowing usage of \glspl{pthread} \gls{api} to control the execution of FreeRTOS tasks. Only 20\% of the \glspl{pthread} \gls{api} is implemented. Therefore, libraries written using \glspl{pthread} can not be ported directly to FreeRTOS using only this extension. \parencite{freertos-posix}


\subsection{WebAssembly}
\label{subsection-wasm}


The goal of this project is to create a real-time concept of SmartCGMS that could be compiled for embedded platforms (e.g., ESP32, Raspberry Pi Zero W) and general-purpose computers (e.g., an x86-64 machine running Windows) with minimal differences in the source code. A typical scenario of using the concept might look like this: generate a configuration using the SmartCGMS GUI, optimize its parameters on a general-purpose computer with higher computing power, and then upload the code to an embedded device receiving data from a \gls{cgm} system and controlling an insulin pump.


There are multiple ways to create portable software. One of them is CMake. CMake is a software to manage build systems. It can support multiple platforms, but it usually requires slight modifications to the source code for each platform (e.g., in the form of C/C++ preprocessor directives). \gls{wasm}, on the other hand, is a portable binary format for a virtual stack machine \parencite{wasm}. It is, therefore, possible to run the same compiled binary on any machine implementing the \gls{wasm} virtual instruction set. It was originally intended for web browsers, but the virtual instruction set has also been implemented in non-web environments \parencite{wasi}. These standalone runtimes also support some embedded devices (e.g., the ESP32) \parencite{wamr} \parencite{wasm3}. \gls{wasm} supports the compilation of programs written in different programming languages (e.g., C, C++, Rust, C\#) \parencite{wasm_online}. This makes it a good candidate for developing a multi-platform prototype of SmartCGMS, as suggested by Otta \parencite{otta}. The \gls{wasm} format is described in section \ref{subsection:wasm_general}. This section describes \gls{wasm} tools and toolchains used in this project.


\subsubsection{Emscripten}

Emscripten is a complete compiler toolchain for \gls{wasm}. It supports C and C++ and other languages that support \gls{llvm} to \gls{wasm} compilation. Emscripten targets mainly the web and Node.js \gls{wasm} runtimes. Alongside the compiled \gls{wasm} binary, it produces JavaScript glue code that ensures the \gls{wasm} module can run (e.g., it imports required functions). Emscripten provides its own implementation of the standard C and C++ library. In addition to exporting functions from the compiled C/C++ code, Emscripten provides ways for the C/C++ code to execute JavaScript. All functions exported from the \gls{wasm} module must be declared as C functions (using \texttt{Extern "C"} to prevent C++ name mangling). \parencite{emcc_online} \parencite{emcc_old}

\subsubsection{WebAssembly System Interface}
\label{sub:wasi}
As \gls{wasm} gained popularity outside of browsers, there is a need for standardization of the system interface. This is what \gls{wasi} aims to resolve. \gls{wasm} requires access to system resources (e.g., system calls) to utilize the full potential of the environment it is running in. \gls{wasi} is a system interface between the \gls{wasm} module and the host system. It provides a standardized \gls{api} to the \gls{wasm} module that can be used to access the system resources. It is up to each \gls{wasm} environment to implement this interface.

\subsubsection{WASI Software Development Kit}

\gls{wasi} \gls{sdk} is a toolchain that combines \gls{wasi} C library implementation, Clang and \gls{llvm} to one \gls{sdk}. It is used to compile C and C++ into \gls{wasm}.
It offers a Docker image for a portable way to build \gls{wasm} modules. The \gls{wasi} \gls{sdk} supports most of C and C++ functionality. However, C++ exceptions are not yet supported, and threads are still an experimental feature without long-term stability. Regardless, \gls{wasi} is in constant development, and more features are planned to be supported in the future. \parencite{wasi} \parencite{wasi-sdk}


\subsubsection{Standalone WebAssembly Runtime}

When running \gls{wasm} outside of the browser environment, a standalone \gls{wasm} runtime is required. Standalone \gls{wasm} runtime is an application or a library that implements the \gls{wasm} virtual stack machine. Such a runtime can then be embedded into an existing application outside of the web browser. There are multiple standalone \gls{wasm} runtimes available. The most popular (based on GitHub stars) standalone \gls{wasm} runtimes at the time of writing this project are:

\begin{itemize}
    \item Wasmer \parencite{wasmer}
    \item Wasmtime \parencite{wasmtime}
    \item \gls{wamr} \parencite{wamr}
    \item Wasm3 \parencite{wasm3}
    \item wazero \parencite{wazero}
    \item WasmEdge \parencite{wasmedge}
\end{itemize}

Of these runtimes, only two officially support real-time devices: \gls{wamr} and Wasm3. The other runtimes are targeted at systems running GNU/Linux, Microsoft Windows, or MacOS operating systems. Both \gls{wamr} and Wasm3 support Xtensa, ARM, and x86-64 \glspl{isa}, and both support \gls{wasi}. Wasm3 is currently in a phase of minimal maintenance. Therefore, \gls{wamr} has been selected as the standalone \gls{wasm} runtime for this project.

\subsubsection{WebAssembly Micro Runtime}

\gls{wamr} is a standalone \gls{wasm} runtime. It has a small memory footprint, high performance, and many configurable features \parencite{wamr}. Features that are relevant for this project are \gls{wasi} threads support, \gls{pthread} \gls{api}, and out-of-the-box support for Xtensa (\gls{espidf}) and x86-64 with prepared examples. It supports three modes to execute a \gls{wasm} module:

\begin{itemize}
    \item \gls{aot} compilation mode
    \item Interpreter mode
    \item \gls{jit} compilation mode
\end{itemize}

When using the \gls{aot} mode, the \gls{wasm} module is compiled into native machine code ahead of deployment to \gls{wamr}. The \gls{wasm} module is compiled using \texttt{wamrc} compiler. It needs to be compiled separately for each different platform. Its advantage is nearly native execution speed and very quick startup. It also has a very small memory footprint. \parencite{wamr_modes}

The interpreter mode is the slowest of the three modes. It has a small memory footprint. The \gls{wasm} instructions are interpreted by \gls{wamr} during runtime. \gls{wamr} offers two interprets: classic and fast. The fast interpreter is 2 times faster but consumes more memory. The classic interpreter supports source code debugging. \parencite{wamr_modes}

\gls{jit} mode offers the same execution speed as \gls{aot} and is platform-agnostic. The disadvantage is a long startup time as the \gls{wasm} module is compiled during execution. \parencite{wamr_modes}


