\documentclass[10pt, draftclsnofoot,onecolumn, compsoc]{IEEEtran}

\def\changemargin#1#2{\list{}{\rightmargin#2\leftmargin#1}\item[]}
\let\endchangemargin=\endlist

\usepackage{textcomp}
\usepackage{todonotes}
\usepackage{caption}
\usepackage{pgfgantt}
\usepackage{setspace}
\linespread{1}

\def \CapstoneTeamName{Automated Fenceless Grazing}
\def \CapstoneTeamNumber{CS3}
\def \GroupMemberOne{Ryan Alder}
\def \GroupMemberTwo{Danila Fedorin}
\def \GroupMemberThree{Matthew Sessions}
\def \CapstoneProjectName{Automated Fenceless Grazing}
\def \CapstoneSponsorCompany{Oregon State University}
\def \CapstoneSponsorPerson{Bechir Hamdaoui}
\def \DocType{Design Document}

\newcommand{\NameSigPair}[1]{\par
\makebox[2.75in][r]{#1} \hfil 	\makebox[3.25in]{\makebox[2.25in]{\hrulefill} \hfill		\makebox[.75in]{\hrulefill}}
\par\vspace{-12pt} \textit{\tiny\noindent
\makebox[2.75in]{} \hfil		\makebox[3.25in]{\makebox[2.25in][r]{Signature} \hfill	\makebox[.75in][r]{Date}}}}

\begin{document}

\begin{titlepage}
    \pagenumbering{gobble}
    \begin{singlespace}
        % 4. If you have a logo, use this includegraphics command to put it on the coversheet.
        %\includegraphics[height=4cm]{CompanyLogo}   
        \par\vspace{.2in}
        \centering
        \scshape{
            \huge CS Capstone \DocType \par
            {\large\today}\par
            \vspace{.5in}
            \textbf{\Huge\CapstoneProjectName}\par
            \vfill
            {\large Prepared for}\par
            \Huge \CapstoneSponsorCompany\par
            \vspace{5pt}
            {\Large\NameSigPair{\CapstoneSponsorPerson}\par}
            {\large Prepared by }\par
            Group\CapstoneTeamNumber\par
            % 5. comment out the line below this one if you do not wish to name your team
            \CapstoneTeamName\par 
            \vspace{5pt}
            {\Large
                \NameSigPair{\GroupMemberOne}\par
                \NameSigPair{\GroupMemberTwo}\par
                \NameSigPair{\GroupMemberThree}\par
            }
            \vspace{20pt}
        }
        \begin{abstract}
            The Fenceless Grazing Collar system aims to reduce the amount of work
            needed by farmers to keep herds of grazing animals. The project
            will be implemented using the LoRa wireless communication protocol to allow
            for long-range interaction between animal-worn collars and a gateway device.
            The gateway device will also provide an HTTP-based JSON API to apply configuration
            changes to collars through an application built for Android mobile devices.
            The MariaDB SQL database management system will be used to store the data
            received from the collar for viewing and analysis.
        \end{abstract}     
    \end{singlespace}
\end{titlepage}

\pagebreak
\tableofcontents

\pagebreak

\section{Introduction}
The Fenceless Grazing Collar system is designed to reduce the amount of manual
labor performed by farmers owning herds of livestock. By automating
the herding of animals such as cattle, farmers may be able to save a significant
amount of time and money.

The Fenceless Grazing Collar system consists of a smart application,
a "gateway", and individual collars to be placed onto animals.

% Collars are attached to live animals that emit an auditory or electrical stimulus when the animal
% leaves its designated area, preventing it from traveling further outside
% the established grazing boundaries.
% TODO this is bad; improve later.

\section{Glossary}
\begin{itemize}
    \item \emph{LoRa:} A radio-based protocol for \textbf{Lo}ng\textbf{Ra}nge communication.
    \item \emph{HTTP:} HyperText Transfer Protocol, which is currently the most popular standard
        for web servers and APIs.
    \item \emph{JSON:} JavaScript Object Notation, a language for encodings structured data.
\end{itemize}

\section{Design Stakeholders and Concerns}
The primary stakeholders for this project are farmers who may replace their
manual herding of animals with the automated Fencless Grazing Collar system.

The design concerns for this group are as follows:
\begin{itemize}
    \item \emph{Support for large areas:} Grazing can take place over large plots
        of land, and thus, it is important that the Fenceless Grazing Collar system can
        reliably function over large distances.
    \item \emph{Support for large herds:} The majority of farmers have many animals
        that need herding. The Fenceless Grazing Collar system must be able to
        support such configurations.
    \item \emph{Long battery life:} Since the purpose of the Fenceless Grazing Collar System
        is to avoid manual labor in animal herding, it must not require frequent
        maintenance. A long battery life will prevent the need for frequent battery
        replacements.
    \item \emph{Reliability:} Animals must consistently remain within
        prescribed boundaries to prevent livestock loss. It is therefore
        crucial that the system reliably works at all times.
    \item \emph{Accessibility:} The system must support simple configuration
        and management without requiring significant technical skill.
\end{itemize}

\section{Design Viewpoints}
This section provides an overview of the design viewpoints used in this document.

\begin{itemize}
    \item \emph{Context viewpoint:} This viewpoint will define the actors (external active elements
        interacting with the Fenceless Grazing Collar system), and the
        use cases of the system.
    \item \emph{Composition viewpoint:} This viewpoint will define the systems, subsystems, frameworks,
        and other components of the Fenceless Grazing Collar system, as well as how they fit together and
        interact.
    \item \emph{Dependency viewpoint:} This viewpoint will define the dependencies of the systems and subsystems
        of the Fenceless Grazing Collar system.
    \item \emph{Information viewpoint:} This viewpoint will define the types of data items stored in the
        system, as well as the access mechanisms to these data items.
    \item \emph{Interface viewpoint:} This viewpoint will provide an explanation of how to correctly
        use the services provided by the Fenceless Grazing Collar system.
    \item \emph{Structure viewpoint:} This viewpoint will define the physical structure of the system
        in terms of its components.
    \item \emph{Interaction viewpoint:} This viewpoint will define the interactions between the various
        components of the system.
    \item \emph{State dynamics viewpoint:} This viewpoint will describe the internal states of the 
        Fenceless Grazing Collar system, as well as how the system transitions between them.
\end{itemize}

\section{Design Views}
\subsection{Context View}
This section describes the actors that will interact with the Fenceless Grazing Collar
system, as well as the services (interactions) between these actors and the system.

\subsubsection{Livestock}
The Fenceless Grazing Collars will be placed on live animals, and be used to track their
behavior. The interactions between the collars and the animals are as follows:
\begin{itemize}
    \item \emph{Movement:} Animals will move haphazardly when not acted upon
        by the collars. Because the collar is attached to the animal, its position
        will change as the animal moves.
    \item \emph{Auditory Stimulus:} If the animal leaves a prescribed area,
        the collar will emit an unpleasant sound, intended to prevent the animal
        from going further outside the defined grazing boundaries. 
    \item \emph{Electrical Stimulus:} If the animal continues to move away
        from the prescribed grazing area, the collar will transition from
        using an audotiry simulus to applying a mild shock to the animal.
\end{itemize}

\subsubsection{Users}
The Fencelss Grazing Collars will be configured and monitored by farmers.
The following interactions between the system and the users are possible:
\begin{itemize}
    \item \emph{Adjustment of Boundaries:} Users will be able to adjust
        the prescribed grazing areas, altering the boundaries at which
        various stimuli are invoked. This will be possible through
        a \emph{smart application}, as well as directly through the
        \emph{LoRa gateway}.
    \item \emph{Request for Data:} Users may query the system for the
        locations of the animals, instances of the use of auditory or electrical
        stimuli, or the battery levels of the collars.
    \item \emph{Maintenance:} Users will perform maintenance on the Fenceless
        Grazing Collar devices. The most common instance of maintenance is
        the replacement of the batteries on a collar.
\end{itemize}

\subsection{Composition View}
This section describes the systems and subsystems of the Fenceless Grazing Collar
system, as well as how they fit together. The system is made up of three primary
components: the smart application, the LoRa gateway, and the individual collars.
See the Interaction view to see how these components behave together.

\subsubsection{Smart Application}
The smart application will consist of the following libraries, frameworks, and subsystems:

\begin{itemize}
    \item \emph{Android Platform:} The application will be implemented using
        the Android mobile operating system, as well as its set of supporting
        software and libraries. The Android platform was chosen for its
        ubiquity and ease of use.
    \item \emph{Kotlin Programming Language:} The Kotlin programming languages,
        created by IntelliJ, will be used to implement the Android application.
        Kotlin's "standard library" (the set of methods and procedures
        available to the programmer by default), as well as Kotlin-specific
        Android libraries such as Anko will be used as part of the smart application.
\end{itemize}

\subsubsection{LoRa Gateway}
The LoRa gateway will consist of the following libraries, frameworks, and subsystems:
\begin{itemize}
    \item \emph{Raspberry Pi:} The LoRa gateway's primary subcomponent will be
        the Raspberry Pi, a single-board Linux computer. The Raspberry Pi
        is capable of interfacing with hardware components such as the LoRa
        shield. It also supports the execution of arbitrary programs, such
        as the API server and database management software.
    \item \emph{LoRa Interface:} The LoRa interface will be used as part of the
        LoRa gateway to allow communication between the gateway and the collars
        in the field. The LoRa interface will be invoked from the API server
        software.
    \item \emph{API Server Software:} The LoRa gateway will execute an API
        server, which will be responsible for the communication between
        the smart application and the gateway itself. The API server software
        will use the LoRa interface and receive and send data to deployed collars.
    \item \emph{Database Management Software:} The LoRa gateway will host
        the SQL-based database subsystem. For details on data storage, see
        the Information view.
\end{itemize}

\subsubsection{Collar}
The collar component is the physical device that will be placed onto grazing
livestock. Conceptually, it made up of the driver and the system logic.

\begin{itemize}
    \item \emph{Driver:} The driver component is the software responsible for
        the interaction of the various components of the collar. As described
        in the structure viewpoint, the collar will be made of several
        physical devices, such as an AVR Atmega128 microcontroller, a
        LoRa shield, and hardware for emitting sound. The driver
        component is the low-level software (likely written in AVR
        assembly) for interfacing with these components.
    \item \emph{System Logic:} Implemented using C, this code will
        implement the core state machine (see State View), and will
        issue commands to hardware through the driver.
\end{itemize}

\subsection{Dependency View}
The dependencies of each of the components in the Fenceless Grazing Collar
system are as follows:

\begin{itemize}
    \item \emph{Smart Application:} The smart application depends on the LoRa
        gateway to provide information from the collars via an HTTP API.
    \item \emph{LoRa Gateway:} The LoRa gateway depends on the deployed
        collar devices to provide data such as their location, battery level,
        and state.
    \item \emph{Collar System Logic:} The collar system logic will dispatch
        commands to hardware components using the driver software. Thus,
        it depends on said driver software to interact with the external
        world.
        % TODO More thorough?
\end{itemize}

\subsection{Information View}
\subsubsection{Data Items}
The following data items will be stored by the Fenceless Grazing Collar system:
\begin{itemize}
    \item \emph{Device Data Point:} Every 15 (fifteen) seconds, each collar device
        will report its status. The status consists of the collar identifier,
        the GPS coordinates of the device, the battery level, the current date
        and time, as well as whether
        or not the device is currently outside of the prescribed area bounds.
    \item \emph{Stimulus Activation Report:} If a collar uses an auditory or electrical
        stimulus to attempt to influence the behavior of its host animal, the conditions
        of this event will be stored. This data item consists of the GPS location at the
        time of the event, the current date and time, the level of stimulus used (volume of sound or voltage),
        as well as the identifier of the collar.
    \item \emph{Account Data:} User account data needs to be stored on the server
        to implement authentication in the HTTP API. Only the minimal information
        necessary will be stored in the database, namely username/hashed password
        pairs. The password will be hashed using the BCrypt algorithm.
\end{itemize}

\subsubsection{Data Stores}
The MariaDB database management software will be used on the LoRa gateway to store each data
item. Each type of data item will be stored in a corresponding table in an SQL database.
Because the data does not have a complex structure, no normalization is necessary, and
the database schema corresponding to each type of data item is exactly as defined above.

\subsubsection{Access Mechamisms}
In the LoRa gateway, SQL queries will be used to store and retrieve data from the MariaDB
database. To facilitate the formulation of complex queries, and to improve code clarity,
the SQLAclehmy Object Relational Model (ORM) will be used. This library maps data presented
in a relational model to objects, thereby allowing for an object-oriented style of interaction
with the database.

In the smart application, data access will be performed through interaction with the LoRa gateway's
HTTP API. In this design, the smart application itself will not store data, but rather make
requests for the data from the gateway, which will, in turn, access the data as described above.
This alows for the abstraction of the details of database storage from the smart application
and potential future user-facing components.

Similarly, the Fenceless Grazing Collars will not directly read or write data from the database.
Rather, they will interact with the LoRa gateway using the LoRa (Long Range) communication
protocol, and broadcasting updates regarding their status. The LoRa gateway will then store
these updates in the database as described above.

\subsection{Interface View}
The Fenceless Grazing Collar system will provide two methods of using its services,
namely the HTTP API and the smart application.

\subsubsection{HTTP API}
The HTTP API, provided by the LoRa gateway's software, defines a programmatic way of
accessing the information in the system, as well as configuring the behavior
of the component collars. The HTTP API will use JSON Web Token (JWT) technology
for authenticating clients (users of the interface), and plain JSON as the data
interchange format used for communicating information between the Fenceless Grazing Collar
system and the cliens. The HTTP API defines the following HTTP routes:

\begin{itemize}
    \item \textbf{/auth/login:} This route receives, in a JSON HTTP request, the username
        and password of the account which is to be authenticated. If the username and password
        match the information in the database, it will return a JWT token containing
        the user's unique identifier. This token will then be used for further interactions
        with the API.
    \item \textbf{/auth/\textless token\textgreater/logout:} This route receives a JWT token as a URL
        parameter. If the token is valid, this route will invalidate it, thereby logging
        out the application that received this token during its authentication.
    \item \textbf{/data/\textless token\textgreater/current:} This route, when supplied with a valid authentication
        JWT token, will return a JSON object containing the most recent device data points
        for each of the active collars in the system.
    \item \textbf{/data/\textless token\textgreater/collar/\textless id\textgreater} This route, when supplied with
        a valid authentication JWT token and a valid collar identifier, will return
        some number of the latest device data points associated with the collar.
        The precise number of points to be returned will be configured with a URL
        parameter. Device data points will be returned in the same format as the \textbf{current} route.
    \item \textbf{/control/\textless token\textgreater/adjust} This route, when supplied with a
        valid authentication JWT token and a JSON-encoded sequence of coordinates representing
        vertices of the new valid grazing area, will apply this configuration to the collars
        in the field.
\end{itemize}

An example interaction is shown in Figure \ref{fig:sequence}. The user first performs
a login operation to retrive a JSON API token, then uses that token to perform another
API request.

\begin{figure}[h]
    \centering
    \includegraphics[width=0.5\textwidth]{sequence.png}
    \caption{Sequence Diagram for Interaction using HTTP API}
    \label{fig:sequence}
\end{figure}

\subsubsection{Smart Application}
The smart application is another interface used to interact with the services provided
by the Fenceless Grazing Collar system. It provides a Graphical User Interface (GUI)
for the HTTP API, allowing users to request data from the sysem and update its configuration
without directly invoking HTTP. This is primarily motivated by the \emph{Accessiblity} design concern.

The smart application interface will be split into three "tabs". Only one tab will be visible
at a time, and the user will be able to switch between tabs at any time. The tabs will be as follows:

\begin{itemize}
    \item \emph{Collar map:} This tab will contain a map of the configured grazing area. On the map,
        the application will also display the location of each animal. Using color and a visual icon,
        it will indicate the battery level of each collar. The application will update
        the map every 15 (fifteen) seconds, a time period which corresponds to the delay between
        device data points being received by the LoRa gateway.

    \item \emph{Collar list:} This tab will provide a textual representation of the device
        data points of each individual collar. In this tab, the application will display a list
        of every active collar, together with its location and battery level.

    \item \emph{Report list:} This tab will provide a textual representation of the stimulus
        activation reports as described in the Information section.

    \item \emph{Adjustment map:} This tab will contain another map. Through this map, it will
        be possible to adjust the boundaries of the grazing area. This will be done by creating,
        moving, and deleting vertices of a polygon, the inside of which represents the valid
        grazing area.
\end{itemize}

\subsection{Structure View}
The LoRa gateway will be constructed using a Raspberry Pi 2b and the corresponding LoRa shield.
The Raspberry Pi and the LoRa shield have compatible pinouts, allowing one to be stacked on top
of the other without the using of soldering equipment or other, more invasive techniques.
This construction also allows for the simple disassembly of the entire system.

The Raspberry Pi component of the LoRa gateway will be connected to the internet using an
Ethernet cable. It will also use a 32 Gigabyte SD card for the storage of the Linux (Raspbian)
operating system, as well as the MariaDB database.

The each individual Fenceless Grazing Collar will consist of a PCB board containing an Atmega328
microprocessor, a 9 volt battery pack, and a LoRa receiver / transmitter module. Additionally,
the PCB will contain a speaker used to produce the auditory stimulus, and a GPS module to
track the location of the collar. These component will
be soldered onto the PCB to improve structural integrity. The entire PCB assembly will be housed
within a 3D-printed casing, used to prevent exposure to moisture and other environmental effects.

% TODO how electric shock?

\subsection{Interaction View}
In the Fenceless Grazing Collar system, the LoRa gateway serves as the mediator between
the smart application and the deployed collars, due to the absence of LoRa receivers
and transmitters on standard Android mobile devices. Therefore, both the smart application
and the individual collars need to interact with the LoRa gateway.

The smart application interacts with the LoRa gateway through the use of the HTTP API, as specified
in the Interface view. Each action performed by the user in the application (such as listing
all collar locations, listing all stimulus activiation reports, or viewing the map) corresponds
to an API request made by the application to the LoRa gateway over internet.

The collars interact with the LoRa gateway using the LoRa protocol. As described in the Information view,
the collars will broadcast their device state every 15 (fifteen) seconds.
Furthermore, the collars will broadcast information in the event of a use of an auditory
or electical stimulus. These broadcasts will be received by the LoRa gateway, and added to
the database as appropriate.

The interaction between the smart application and the Fenceless Grazing Collars is transitive, and
goes through the LoRa gateway: the application updates the grazing boundaries of deployed devices
by using the HTTP API to contact the LoRa gateway, which, in turns, broadcasts the update command
to the collars. Similarly, the collars deliver location information and stimulus reports
by sending them to the LoRa gateway, from which they are retreived by the application.

\subsection{State Dynamics View}
Each Fenceless Grazing Collar is a state machine. The states are described as follows:
\begin{itemize}
    \item \emph{Sleep:} This will be the most common state for the collar. As per the
        \emph{Long battery life} design concern, it's necessary that the collars remain functional
        for long periods of time without maintenance. By putting the hardware of the collar
        into sleep, the system will lower power consumption, and thus improve battery life.
    \item \emph{Awake; quiet} The device will be in this state when it is gathering and trasmitting
        GPS data to the LoRa gateway, while the host animal is within the prescribed grazing area.
        No sound or other stimulus is necessary in this state.
    \item \emph{Awake; loud} The device will be in the state when the host animal is within
        a small distance outside the prescribed grazing area, and had not spent a long
        period of time there. In this state, the auditory stimulus will be active with the
        intention of preventing the animal from further negative action.
    \item \emph{Awake; shocking} The device will be in this state when the host animal has
        traveled far outside the prescribed grazing area, or has remained within
        a small distance of the area for a long time. The electrical stimulus component is active
        in this state.
\end{itemize}

The transitions between the states are as follows:
\begin{itemize}
    \item Every 15 seconds, if the device is in the \emph{Sleep} state, it will transition
        into the \emph{Awake; quiet} state.
    \item In the \emph{Awake; quiet} state, if the GPS coordinates are within the prescribed grazing area,
        the device will return into the \emph{Sleep} state.
    \item In the \emph{Awake; quiet} state, if the GPS coordinates are within a 10ft distance
        outside the prescribed grazing area, the device will transmit a stimulus activation report,
        and transition into the \emph{Awake; loud} state.
    \item In the \emph{Awake; loud} state, if the GPS coordinates are within the prescribed grazing
        area, the device will transition into the \emph{Sleep} state.
    \item in the \emph{Awake; loud} state, if the device has spent 30 seconds outside, but in
        close proximity to, the prescribed grazing area, it will transmit a stimulus activation
        report, and transition into the \emph{Awake; shocking} state.
    \item in the \emph{Awake; loud} state, if the device is further than 10ft outside the grazing
        area, it will transmit a stimulus activation report, and transition into the
        \emph{Awake; shocking} state.
    \item in the \emph{Awake; shocking} state, if the device is within a 10ft distance 
        outside the prescribed grazing area, it will transition into the \emph{Awake; loud} state.
\end{itemize}

This is summarized in Figure \ref{fig:state}.

\begin{figure}[h]
    \centering
    \includegraphics[width=0.75\textwidth]{state.png}
    \caption{State Diagram for Fenceless Grazing System}
    \label{fig:state}
\end{figure}

\section{Design Rationale}
The LoRa communication protocol was used specifically to address the \emph{Support for large areas}
design concern: LoRa works over \textbf{Lo}ng \textbf{Ra}nge, and is bidirectional. These properties
make it ideal for the Fenceless Grazing Collar system.

The LoRa gateway's API was chosen to be HTTP-based, rather than Bluetooth-based, to allow for
both remote communication and alternative clients (such as web interfaces). This necessitates
the use of a public-facing server (and likely a domain name to allow for DNS resolution).

Kotlin was chosen over Java due to its superior type system, which helps mitigate the Million Dollar
Mistake [citation needed], as well as because of its capacity to reduce boilerplate. This is
an acceptable decision due to Google's official support of the Kotlin language.

\section{Conclusion}
The Fenceless Grazing Collar system provides reliable, accessible, and scalable solution for replacing
manual labor in livestock herding. Through the use of physical collars attached to live animals,
providing auditory and electric stimuli, the system encourages animals to stay within prescribed
grazing boundaries without the need of direct human involvement. LoRa communication is used
to manage the collar devices spread out in the field, and both an HTTP JSON-based API
and a smart application are provided to expose the configuration and data collection functionality
of the collars to the user.

\end{document}
