% !TeX root = main.tex
\iffalse
This should include background theory, justification for the design choices and any assumptions made. 
These should relate to each IoT layer under consideration.
Block diagrams, schematic diagrams and flowcharts are excellent illustration tools.
This section should not include screenshots nor detailed “how-to” operations 
(these should appear in an Appendix if necessary)

* Have you identified the problem you are addressing?
* Have you provided an overview of how you are addressing this problem?
* Have you provided detailed steps of what you did in a logical order?
* Have you described the methods you used to solve the problem and their purpose?
* Have you identified the parameters for designing your system?
* Have you identified the metrics for evaluating the performance of your system?
* Have you used illustrations to give the reader a visual interpretation of your system?
\fi

\newpage
\section{Design Methodology and Implementation}

\subsection{The Problem}


\subsection{Background Theory}

\subsubsection{IoT Stack}

% explain the IoT stack and each layer

	\begin{figure}[H]
		\centering
		\begin{subfigure}[b]{0.45\textwidth}
			\centering
			\includegraphics[scale=0.55]{graphics/iot_model1.eps}
			\caption{Model 1}
			\label{fig:iot_model1}
		\end{subfigure}
		\begin{subfigure}[b]{0.45\textwidth}
			\centering
			\includegraphics[scale=0.55]{graphics/iot_model2.eps}
			\caption{Model 2}
			\label{fig:iot_model2}
		\end{subfigure}
		\caption{IoT conceptual models}\label{fig:iot_models}
	\end{figure}

	\textbf{{\small Model 1}}
	
	\textbf{{\small Model 2}}

	% talk about which model was chosen for the project

	\textbf{{\small Chosen Model}}

\subsubsection{Characteristics of Sensors}
	
	\textbf{{\small Range}}
	
	Maximum and minimum value range over which a sensor works well. Sensors may work well outside this range, but require additional calibration. e.g. the output may no longer be linear. \\
	
	\textbf{{\small Accuracy}}
	
	How well the sensor measures the environment in an absolute sense, i.e. how good the data is when compared with a recognized standard. e.g. a temperature sensor accurate to 0.001oC is expected to agree within 0.001oC with a known temperature standard. This is what you want to compare results with other observations. \\
	
	\textbf{{\small Resolution}}
	
	The ability of a sensor to see small differences in readings. e.g. a temperature sensor may have a resolution of $\mbox{0.000,01}^{o}\mbox{C}$, but only be accurate to $\mbox{0.001}^{o}\mbox{C}$. Can detect relatively small changes in temperature, smaller than the accuracy of the sensor. Resolution in often controlled by the quantisation in digitising the signal so is not a function of the sensor itself, but of the sampling process. \\
	
	\textbf{{\small Repeatability}}
	
	This is the ability of a sensor to repeat a measurement when put back in the same environment. It is often directly related to accuracy, but a sensor can be inaccurate, yet be repeatable in making observations. \\
	
	\textbf{{\small Drift/Stability}}
	
	This is the low frequency change in a sensor with time, i.e., with a given input you always get the same output. It is often associated with electronic aging of components or reference standards in the sensor. \\
	
	\textbf{{\small Response time}}
	
	A simple estimate of the frequency response of a sensor assuming a change in the measurement. \\
	
	\textbf{{\small Output}}
	
	What output is given for a change in the parameter being measured. For example, a voltage range e.g. 0 to 5 volts for an input range of 0 to $\mbox{30}^{o}\mbox{C}$. \\ 
	
	\textbf{{\small Power Consumption}}
	
	What is needed to power the sensor, quite often specified as the current draw. \\
	
	\textbf{{\small Setting Time}}
	
	After being switched on, how long before a valid measurement is ready. \\
	
	\textbf{{\small Sampling time required}}
	
	How often do we need to repeat measurements to get an accurate picture of the phenomenon being measured. \\

\subsubsection{Communication Protocol for sensor data}

	% Give a small general introduction to the topic
	
	\textbf{SPI}
	
	% SPI - image
	
	\textbf{$\mbox{I}^{2}\mbox{C}$}
	
	% I2C - image

\subsubsection{Methods for accessing external devices}

	% Polling
	
	\textbf{{\small Polling}}
	
	% Interrupts
	
	\textbf{{\small Interrupts}}

\subsubsection{Low Power Mode}

\subsection{System Design}

	This section describes overall design of our Internet of Things (IoT) device.
	The IoT core component is \texttt{Feather HUZZAH ESP8266} module containing \texttt{ESP8266} microcontroller
	with built-in Wi-Fi. This module also has built-in Lithium Polymer (LiPo) battery charging circuit,
	USB connectivity with serial converter to charge and program microcontroller; linear converter to
	supply 3.3V rail. Air Quality \texttt{SGP30} and temperature-humidity \texttt{BME280} sensor modules are connected via $I^2C$ bus. An additional \texttt{IO16} pin is connected to reset pin enabling deep-sleep mode wakeup timer. Circuit diagram is shown in \autoref{fig:thing_diagram}.

	\begin{figure}[H]
		\centering
		\includegraphics[scale=0.55]{graphics/thing_diagram.eps}
		\caption{Circuit of IoT device.}
		\label{fig:thing_diagram}
	\end{figure}

	With this configuration, even in deep-sleep mode both sensor modules are still powered as 3.3V bus is not affected. This is intentional as both sensors have low-power modes. \texttt{BME280} sensor that include temperature, humidity and pressure readings has three of such modes, sleep which does no operation and is at the lowest power; forced which perform one mesurement, store results and return to sleep; and normal mode for perpetual cycling of measurements. Additional oversampling and IIR filter settings can be set. Weather monitoring configuration recommended by datasheet was used which uses forced mode with one sample per minute without oversampling and IIR filter. This achieves reasonable noise and performance with average current consumption of $160nA$.
	
	\texttt{SGP30} sensor is equiped to measure Carbon Dioxide (from 400 ppm), Total Volatile Organic Compounds (in ppb range), relative $H_2$ and Ethanol values. After power up, sensor low power sleep mode is activated and high current measurement mode is only actived when microprocessor sends a measurement request. Sensor internally takes samples at 1Hz in order to calculate baseline. During experimentation it was discovered that it takes around 16 seconds from power up to reading an accurate value. This lead to decision to not disconnect power from this sensor during sleep. In addition, this sensor features on-chip humidity compensation calculation, however it requires absolute humidity value to be provided by microprocessor. This value is calculated from \texttt{BME280} sensor readings with \autoref{eq:ah}:
	
	\begin{equation}\label{eq:ah}
	AH = 216.7 \times \frac{\frac{RH}{100} \times 6.112^{\frac{17.62t}{243.12+t}}}{273.15+t}
	\end{equation}
	Where AH is absolute humidity in $g/m^3$, RH is relative humidity in percent, and t is temperature in $^{\circ} C$.
	
	\begin{figure}[h]
		\centering
		\includegraphics[width=\linewidth]{graphics/program.eps}
		\caption{Functional diagram of IoT device program.}
		\label{fig:program}
	\end{figure}
	
	\autoref{fig:program} show a function diagram of implemented software in IoT device. It starts at enabling WiFi monitor mode which executes an interrupt routine on every time microcontroller's WiFi module has observed a WiFi packet. This packet is processed and WiFi packet counter in increased. The main routine then follows serial and sensor initialisation, if either of sensors do not respond, a error flag is set high for that sensor. Main routine then sleeps for one second in order for WiFi monitor routine to gather enough packets. Main routine then gathers sensor readings, composes a payload message with CRC32 checksum. Then a WiFi mode is changed to connect to Access Point, and further connect to server. Upon a new TCP socket server sends a cryptographic nonce which microcontroller uses to encrypt payload and send it to server. Afterwards server and WiFi connections are gradually disconnected and timer in deep sleep mode is set upon which program is reset. 
	
	
	\begin{center}
	\begin{tabular}{r@{}l@{}ll}
	  	&& \textbf{Content Name} & \textbf{Size and type} \\
	  	\hline
	  	&& Device ID & 8bits \\
	 		&& Payload length* & 8bit unsigned integer\\
		\multirow{13}{2cm}{Encrypted Payload \textbf{24-bytes}} & \ldelim\{{13}{*} &
		Temperature Reading& 32bit float \\
		&& Humidity Reading& 32bit float \\
		&& Pressure Reading& 32bit float \\
		&& WiFi Managed packets & 16bit unsigned integer \\
		&& WiFi Control packets & 16bit unsigned integer \\
		&& WiFi Data packets & 16bit unsigned integer \\
		&& $CO_2$ Reading& 16bit unsigned integer \\
		&& $H_2$ Reading& 16bit unsigned integer \\
		&& TVOC Reading& 16bit unsigned integer \\
		&& Ethanol Reading& 16bit unsigned integer \\
		&& Status Flags& 8bits \\
		&& \textit{reserved.} & 8bits \\
		&& CRC32 Checksum & 32bits \\

	\end{tabular}
	\captionof{table}{List of message content sent from IoT device to server via TCP socket. \textbf{*} Payload length is represented in multiples of 12bits, value of 2 in this case.}
	\label{tab:message_content}
	\end{center}

	Message content sent to server is shown in \autoref{tab:message_content}. Sending data in raw binary was chosen as suppose to encoded with data interchange format such as JSON or XML due to bandwidth efficiency, computation time and simplicity of implementation with C. Checksum was required to ensure that all values sent are correct as there is no way to ensure that raw values were not corrupted. ChaCha20 cipher was used for encryption with 12 byte nonce. This nonce size requires payload to be in multiples of 12 bytes blocks which is the reason for having "reserved" byte in payload. Message authentication code (such as Poly1305) was not used due to simplcity reasons. Instead Device ID is not encrypted and used by server to lookup symmetric key to decrypt the payload.
	
	\begin{figure}[H]
		\centering
		\includegraphics[scale=0.4]{graphics/cloud.eps}
		\caption{General flow diagram of whole system connectivity.}
		\label{fig:cloud}	
	\end{figure}
	


\subsubsection{Layer 1 approach}

\subsubsection{Layer 2 approach}

\subsubsection{Layer 3 approach}
