

\documentclass[a4paper,10pt]{article}
\usepackage{listings,color,qtree,epsfig,amsmath}
\definecolor{codecolor}{rgb}{0.99,0.97,0.94} % color values Red, Green, Blue
\definecolor{commentcolor}{rgb}{0.1,0.5,0.1} % color values Red, Green, Blue
\definecolor{stringcolor}{rgb}{0.3,0.1,0.1} % color values Red, Green, Blue
\newcommand{\Code}[1]{\texttt{#1} }
\newcommand{\code}[1]{\Code{#1} }
\newcommand{\DB}   {\code{{MOOSDB}}}
\newcommand{\MA}   {\code{{MOOSApp}}}
\newcommand{\Ignore}[1]   {}




\lstset{ frame = shadowbox,
 %language=[Visual]{c++},
 rulesepcolor=\color{black},
 basicstyle=\small } \lstset{
backgroundcolor=\color{codecolor},
keywordstyle=\color{blue}\bfseries,
commentstyle=\color{commentcolor},
stringstyle=\color{stringcolor}\ttfamily, linewidth =
1.2\linewidth,
breaklines=true} %

\lstset{language=C++}
% Title Page
\title{Introduction to Programming with MOOS}
\author{Paul Newman}



\begin{document}
\maketitle

\begin{center}
\epsfig{file=images/moose6.eps,width = 0.2\linewidth}
\end{center}

\begin{abstract}
This document is intended to bootstrap the process of using the
MOOS communications libraries. It is aimed at programmers who are
competent in C++. All the code in this document is supplied
in full in the ``code'' sibling directory of this document.
\end{abstract}
\newpage
\tableofcontents
\newpage
\section{Building a New Application using MOOS}

We shall get straight to the matter in hand --- how to use the
MOOS/Core directory to build a new application which takes
advantage of the MOOS communications layer. To do this, it makes
sense to quickly introduce an important class provided by the MOOS
Communications libraries, namely \code{CMOOSApp}.


\subsection{Derivation from \code{CMOOSApp}}
MOOS provides a class called \textit{CMOOSApp} which makes writing
a program using MOOS a simple affair. Beneath the hood of the
\code{CMOOSApp} class is a loop which repetitively calls a
function called \code{Iterate()} which by default does nothing.
One of our jobs as writers of a new MOOS-enabled application is to
flesh this function out with the code that makes the application
do what we want\footnote{Don't write a forever loop in
\code{Iterate()} - allow CMOOSApp to call this function for you
time and time again.}. Behind the scenes this uber-loop in
\code{CMOOSApp}\footnote{You can find the loop in the
\code{CMOOSApp::Run} method.} is also checking to see if new data
has been delivered to the application. If it has, another virtual
function, \code{OnNewMail}, is called --- this is the spot to write
code to process the newly delivered data. 

We'll cover this in more detail later, but for now it makes sense
to get stuck into an example. But before we do, look at Figure
\ref{Fig:MOOSAppRun} which summarises graphically the basic flow
of execution in an application which makes use of the \code{CMOOSApp}
class (by deriving a new class from it) and has just called the
\code{CMOOSApp::Run} method.


\section{A First Worked Example}

So let us use \code{CMOOSApp} to build an new application. Perhaps
the simplest procedure  is as follows:

\begin{enumerate}
\item Make a new "main.cpp".
\item Make a new class derived  class from \textit{CMOOSApp}.
\item In main() make an instance of this class.
\item Call ::Run() on this object.
\item As needs dictate overload the following virtual functions:
    \begin{description}
    \item[\Code{::Iterate()}] a function in which the application will do its main processing; see Section \ref{Sec:Iterate}.
    \item[\Code{::OnNewMail()}] a function called when  new mail (data) has arrived; see Section \ref{Sec:OnNewMail}
    \item[\Code{::OnConnectToServer()}] called when a connection has been made to the MOOS database; see Section \ref{Sec:OnConnectToServer}
    \item[\Code{::OnStartup()}] called when the application starts up; see Section \ref{Sec:OnStartUp}
    \end{description}
\end{enumerate}

\begin{figure}[h!]
\centering \epsfig{figure=./images/MOOSAppRun.eps,
width=0.9\linewidth} \caption{The flow of execution once
\code{::Run} has been called on a class derived from
\code{CMOOSApp}. The ``scrolls'' indicate where we (as users of
the functionality of \code{CMOOSApp}) will be writing new code
that implements whatever it is we want our application (program)
to do. }\label{Fig:MOOSAppRun}
\end{figure}


Listings \ref{Code:Ex1:Main}, \ref{Code:Ex1:SimpleApp.h} and
\ref{Code:Ex1:SimpleApp.cpp} show the most skinny of conceivable
MOOS applications using the functionality of \code{CMOOSApp} as a
base class to a newly derived class \code{CSimpleApp}. My advice
to you is to not proceed beyond this point until you can get this
code to compile and link. See the document on Building and Linking
 for more details on building MOOS projects.


\subsection{First Example Code Listing}


\lstinputlisting[ caption = {Simplest Application -
main.cpp},label = {Code:Ex1:Main} ]{../code/Ex1/main.cpp}


\lstinputlisting[basicstyle=\footnotesize, caption = {Simplest
Application - main.cpp},label = {Code:Ex1:SimpleApp.h}
]{../code/Ex1/SimpleApp.h}

\lstinputlisting[basicstyle=\footnotesize, caption = {Simplest
Application - main.cpp},label = {Code:Ex1:SimpleApp.cpp}
]{../code/Ex1/SimpleApp.cpp}


\section{The Important CMOOSApp Virtual Functions}\label{Sec:MOOSAppVirtuals}

\code{CMOOSApp} itself contains a few important virtual functions
which can (should) be overridden in derived classes. These
functions are called by the base class at the suitable time.

\subsection{Iterate}\label{Sec:Iterate}
By overriding the \code{CMOOSApp::Iterate} function in a new
derived class, the author creates a function from which he or she
can orchestrate the work that the application is tasked with
doing. As an example, and without prejudice, imagine the new
application was designed to control a marine vehicle. The iterate
function is automatically called by the base class periodically
and so it makes sense to execute one cycle of the controller code
from this ``\code{Iterate}'' function. Some things to note here:
\begin{itemize}
\item Don't enter into an infinite loop waiting on data in this code - it won't break anything (the thread that handles the communications with other processes will still be running and responsive to you posting or checking for mail) but it is rather orthogonal to the intended use of \code{CMOOSApp}.
\item You can configure the rate at which \code{Iterate} is called by the \code{SetAppFreq()} method or by specifying the ``AppTick'' parameter in a mission file (see Section \ref{Sec:App:Configuration} for more on configuring an application from a file).
\item Note that the parameter passed to \code{SetAppFreq()} specifies the maximum frequency at which \code{Iterate} will be called - it does not guarantee that it will be called then - for example if you write code in iterate that takes 1s to complete there is no way that iterate can be called at more than 1Hz.
\item If you want to call iterate as fast as is possible simply call  \code{SetAppFreq(0)} --- but ask yourself why you need such a greedy application, are you being polite?
\item Although MOOSApp doesn't enter into a contract with you about exactly when \code{Iterate} will be called, it does allow you to know when it is being called. The function \code{MOOSTime} returns unix time in floating point seconds.
\end{itemize}


\subsection{OnNewMail}\label{Sec:OnNewMail}

This function is called from within \code{CMOOSApp::Run()} if and
when some other process has posted data that you (``you'' being
the application here) have previously declared an interest in (see
Section \ref{Sec:Registering}). The mail arrives in the form
of a \code{std::list<CMOOSMsg>} --- a list of \code{CMOOSMsg}
objects (see Section \ref{Sec:CMOOSMsg}). The programmer is free to
iterate over this collection examining who sent the data, what it
pertains to, how old it is, whether or not it is string or
numerical data and to act / process the data accordingly.

\subsection{OnConnectToServer}\label{Sec:OnConnectToServer}

Unlike \code{Iterate} and \code{OnNewMail} this function is not
called directly from \code{CMOOSApp::Run()}. It is actually a
callback from a thread in the \code{m\_Comms} object (a instance
\code{CMOOSCommsObject}) possessed by \code{CMOOSApp} that handles
all the IPC communications \footnote{Indeed you could think of
\code{CMOOSApp} as a fancy wrapper for this object.}. The callback
occurs whenever contact has been made with the \code{MOOSDB}
server which sits at the heart of the MOOS topology (see Section on ``Topology'' in the CommsArchitecture document.)
This is one of two places where  the
programmer is advised to call \code{m\_Comms.Register} to tell the
\code{MOOSDB} that we want to be sent mail if any other process
posts data relating to a particular variable. See the example code
and the sibling ``CommsArchitecture'' document and this will become
blindingly obvious. Just remember that code executed in this
callback is not in thread 0.

\subsection{OnDisconnectFromServer}\label{Sec:OnDisconnectFromServer}
This is the counter part of \code{OnConnectToServer}. It is called
when contact has been lost with the \code{MOOSDB} - generally, if
this happens something terrible has happened. It is here for
completeness. If there is nothing special you want to do when
comms has been lost, don't bother adding this function to your
\code{CMOOSApp}-derived class.


\subsection{OnStartUp}\label{Sec:OnStartUp}

This function is called by \code{CMOOSApp::Run} just before it
enters into its own ``forever-loop''. This is the spot that you
would populate with initialisation code, and in particular use the
functionality provided by the \code{m\_MissionReader} member
object to read configuration parameters (including those that
modify the default behaviour of the  \code{CMOOSApp} base class)
from file. See Section \ref{Sec:App:Configuration} for more
details on configuration from file.


\section{A Second Worked Example - Handling Mail}

At present our application really doesn't do much - it just
connects to the DB and sits there (behind the scenes the
application is in regular contact with the DB but you wouldn't
know it at the moment). So we'll now modify the Example 1 code
and fill in the functions described in Section
\ref{Sec:MOOSAppVirtuals}. The code in Main.cpp remains unchanged \footnote{Apart from the fact that the MOOSApp is told to register as ``Ex2'' rather than ``Ex1''.}
so we won't replicate it here, but Listings
\ref{Code:Ex2:SimpleApp.h} and \ref{Code:Ex2:SimpleApp.cpp} show
the updated code for our own \code{MOOSApp}.

We shall pretend we are building some process running on a
vehicle\footnote{That's just because I work on mobile robotics -
there is nothing about the MOOS Comms API that is specific to
autonomous vehicles.} --- perhaps some kind of navigation process.
Anyway, assume that this process needs to know about the status of
the vehicle and its heading. We assume that some other processes
(written by someone who has already read this document...) are
publishing this data via the MOOS infrastructure. The question is,
how do we get hold of this data? The first thing to do is
``register'' for mail and then write code in the \code{OnNewMail}
function to parse the mail. We'll cover these topics in Sections
\ref{Sec:Registering} and \ref{Sec:MailParsing}.

\lstinputlisting[basicstyle=\footnotesize, caption = {Simplest
Application - main.cpp},label = {Code:Ex2:SimpleApp.h}
]{../code/Ex2/SimpleApp.h}

\lstinputlisting[basicstyle=\footnotesize, caption = {Simplest
Application - main.cpp},label = {Code:Ex2:SimpleApp.cpp}
]{../code/Ex2/SimpleApp.cpp}


\subsection{Registering for Mail}\label{Sec:Registering}

An instance of \code{MOOSApp} comes with an \code{CMOOSCommClient}
object called \code{m\_Comms} --- this is the guy that allows us
to register for mail with a call to \code{m\_Comms.Register()}. In
Listing \ref{Code:Ex2:SimpleApp.cpp} two such calls are made in a
function called \code{DoRegistrations} where we register for
messages (mail) about ``Heading'' and ``VehicleStatus''. Note that
the former will be delivered at  a maximum of 4Hz (irrespective of
how often some unknown external process is writing the data
\footnote{This is a good thing - it stops some over-zealous
process (which you didn't write) causing copious amounts of mail
to your door.}) while ``VehicleStatus'' messages will be delivered
to us every time someone writes ``VehicleStatus''.

\subsubsection{Where and When Should the Registrations Occur?}

I advise folk to register for mail in two places. Once at the end
of \code{OnStartup()} and once in \code{OnConnectToServer()}. The
reasons for this are as follows.
\begin{itemize}
\item It is usual to execute code in \code{OnStartUp} which
determines what mail we want to register for (e.g. as a result of
parsing the mission file which should happen in
\code{OnStartUp}--- see later for more on Mission Files.)
\item Connection to the DB is asynchronous (it depends on what
else is going on in the network). Accordingly
\code{OnConnectToServer} might be called before or after
\code{OnStartUp()} so in the former case we'd want to perform
registrations at the end of \code{OnStartUp} and in the latter
case in \code{OnConnectToServer}. \footnote{Hmmm, upon reflection
maybe there is a case to be made for having persistent
registrations so the CommsClient remembers all the registrations
you ever ask for and makes sure that these are preserved across DB
connections/disconnections...I would welcome a view on this...}
\end{itemize}


\subsection{Parsing Messages}\label{Sec:MailParsing}

Perhaps the most important thing to focus on in Listing
\ref{Code:Ex2:SimpleApp.cpp} is the \code{OnNewMail} method. Here
you can see how (in this example) the list of \code{CMOOSMsgs}
that have been delivered to us (in response to earlier calls to
\code{m\_Comms.Register} - see section \ref{Sec:Registering}) are
cracked and execution is routed as a function of the variable name
which each message pertains to. Pretty simple.

So, having marshalled execution to regions of code dedicated to
handling \code{CMOOSMsgs} pertaining to particular named data
(like heading of vehicle status in our rather contrived example)
we need to extract the data itself. \code{CMOOSMsgs} can contain
double-data (\code{Msg.GetDouble()}) or string-data
(\code{Msg.GetString()}). In this case we were promised by other
developers that ``VehicleStatus'' will be a string-variable and
``Heading'' will be a double-variable. You can see this contract
being checked in the two message cracking methods in Listing
\ref{Code:Ex2:SimpleApp.cpp}. Extracting the double precision data
from the heading messages is trivial, however extracting data from
the string of vehicle status is more interesting and is a common
problem in MOOSApplications. As you might expect, there are a whole
load of tools ready and waiting to help you with this task (many
of them are found in the header file
\code{MOOSGenLibGlobalHelper.h} --- see Section
\ref{Sec:MOOSGenLib}). We'll talk about string manipulation in the
context of Parsing \code{CMOOSMsgs} in Section
\ref{Sec:StringParsing}.

\subsection{Using \code{::PeekMail} for Sorting Mail}
The example code in Listing \ref{Code:Ex2:SimpleApp.cpp} used a bunch of ``if'' statements inside an interation overall message to marshall the incoming message to the correct handler. It is possible to do away with writing  \code{for} loop by using the
\code{CMOOSCommsClient::PeekMail} function \footnote{i.e you would call \code{m\_Comms.PeekMail(...)}}. This function is passed a reference to the whole list of incoming messages and extracts a particular message according to the name of the variable we are interested in. \textbf{Importantly} this method can extract the most recent message of a given name. Why is this useful? Well, imagine you've requested to receive notifications about \textit{every} write to a named variable. It is quite possible that some other client published data about that particular variable many times since our application last received mail. Hence we will receive multiple messages pertaining to the same variable in our \code{MOOSMSG\_LIST} when \code{OnNewMail} is called. We can imagine that it would be pretty useful at times to only act on the most uptodate (recent) message. A call to \code{PeekMail} can also remove (rather than copy) the message from the \code{MOOSMSG\_LIST}. Look at Listing \ref{Code:Ex2:PeekMail} for a coded example.

\subsection{Checking for Stale Messages}
When a process starts up and registers for mail, it has no knowledge about the state of variables stored in the DB. If at the time an application registers for notifications about a particular variable that variable already exists in the \code{MOOSDB} it will be sent a message about that variable which will appear in the mail on the first time \code{OnNewMail} is invoked. This might mean that an application receives a message from the DB about a posting which is days old. An obvious approach  would be to check the time field of each message and only process messages that are ``recent''. The method \code{CMOOSMsg::IsSkewed} is an easy way to check this - behind the scenes it simply makes sure the message in question has a time field within a few seconds of the current time. Of course one may want better precision on what counts as stale mail and want to write your own method to do so. However \code{IsSkewed} is ofen useful to make the first cut. Look at Listing \ref{Code:Ex2:PeekMail} for a coded example.


\lstinputlisting[basicstyle=\footnotesize, caption = {An alternative way of handling mail. This time using \code{PeekMail} and also checking for stale messages.},label = {Code:Ex2:PeekMail}
]{../code/Ex2/AlternativeNewMail.cpp}


\subsection{Parsing Strings} \label{Sec:StringParsing}

The developer is in no way obligated to use the string parsing
methods provided by the MOOS Core libraries. But they are there to
be used and by doing so the developer is more likely to adopt
string structures/formats used by the multitude of MOOS processes
already in existence.

The good thing about sending string data is that multiple fields
can be sent at the same time. Typically a string is sent as a
comma separated list of parameter=value pairs where value is
itself a string, double or string representation of a matrix. For
example, the developer of a process which publishes ``VehicleStatus''
messages told us that the data would use the string field of
MOOSMsgs and would contain the following fields:
\begin{description}
\item [Status] one of ``good'', ``bad'' or ``sunk'' (the latter
presumably being a special case of ``bad'')
\item [BatteryVoltage]  a double value
\item [Bilge] a string, one of ``On'' or ``Off'.
\end{description}


The data corresponding to each of these tokens can be extracted
from the string of the \code{CMOOSMsg} (or any string for that
matter) by using the \code{::MOOSValFromString} family of functions
found in MOOSGenLib --- see Section \ref{Sec:MOOSGenLib}. The
reader's attention is also drawn to the way in which chunks of
numerical (\code{std::vector<double>)} data can be sent and
extracted from strings.

\subsection{Testing The New Application}

So we've built our new application --- how do we test it? Well, usually you'd run it in the system in which it was designed to reside, but this is a fictitious system and no processes that write ``VehicleStatus' and or ``Heading'' exist. So we could either write new processes that do, or  use a preexisting tool to write data to the \code{MOOSDB} and see our application respond appropriately. The former is described in Section \ref{Sec:VehicleSimulator} and the latter in Section \ref{Sec:UsinguMS}.

\subsubsection{Testing with \code{uMS}} \label{Sec:UsinguMS}

The simplest way to test our example is to launch the graphical tool \code{uMS}\footnote{Again, it is assumed that you have already built the MOOS distribution which includes \code{uMS} which uses the FLTK library. See the sibling document on Graphical tools for more information on \code{uMS}.}. The steps are as follows:

\begin{enumerate}
\item Start an instance of \code{MOOSDB} (either double click in Windows or type MOOSDB \&  from a terminal in linux).
\item Start an instance of \code{uMS}. Press the connect button (the default is to connect to a MOOSDB using the MOOSDB defaults settings). You should see \code{uMS} come to life.
\item Start an instance of your new application. In this case it is called Ex2. You should see its existence being detected by both the \code{MOOSDB} and \code{uMS}.
\item Pick a blank line in \code{uMS} and ctrl-left click in the left most column. From here you can ``Poke the MOOS'' with new data (indeed clicking on an existing variable allows you to change that variable).
\item Start by poking ``Heading'' into the system as a double. You should see your application (Ex2) print to the screen that it has received heading data.
\end{enumerate}

Figure \ref{Fig:UsinguMS} shows a screen shot of this process taken from my machine (which today happens to be a linux box).\footnote{ The screen shot isn't brilliant  - you may have to zoom in or look at the raw image (UsinguMS.eps) if you want real detail.}

\begin{figure}\label{Fig:UsinguMS}
\centering
\epsfig{figure = ./images/UsinguMS.eps, width = 1.0\linewidth}
\caption{Using uMS to poke data into the \code{MOOSDB} to test a new application.}
\end{figure}

\subsection{Testing Ex2 with Another Application}\label{Sec:VehicleSimulator}

A more interesting way of testing our new application is to write another new process which writes ``VehicleStatus'' and ``Heading''\footnote{We could write two - one for Heading and one for VehicleStatus but there is nothing new to be learned there.}. The code for such a process can be found in the Ex3 directory. The main thing to notice is that the \code{::Iterate()} function is now populated with code which publishes data using the \code{Notify} method of the \code{m\_Comms} member. The guts of the new application (simulator) is given in Listing \ref{Code:Simulator.cpp}. Of course the details of how the simulator works are irrelevant (I'd hardly call it a simulator); the code is provided here just to show how data is posted to the DB. Note that the third field to the Notify method is optional - if you don't supply a time, MOOSTime() is called behind the scenes for you \footnote{It is common practice when sending string data to send the time field in the string as well, but it is not a requirement of course -- you can send what you want in strings.}.

\lstinputlisting[basicstyle=\footnotesize, caption = {Code for a ``heading and status'' simulator},label = {Code:Simulator.cpp}
]{../code/Ex3/Simulator.cpp}

So after building Ex3  you can start it up and see Ex2 respond to the messages being posted. You should also get warm fuzzies about seeing the two applications in action via \code{uMS}. Figure \ref{Fig:UsingSim} is a screen shot of uMS running when Ex3 (which registers with the DB as Simulator) and Ex2 are running.

\begin{figure}\label{Fig:UsingSim}
\centering
\epsfig{figure = ./images/UsingSim.eps, width = 1.0\linewidth}
\caption{Spying on Ex2 and the crude simulator (Ex3) in action}
\end{figure}


\section{Message Content --- \code{CMOOSMsg} } \label{Sec:CMOOSMsg}
The communications API in MOOS allows data to be transmitted
between \DB and a client. The meaning of that data is dependent on
the role of the client. However the form of that data is
constrained by MOOS. Somewhat unusually, MOOS only allows for data
to be sent in string or double form. Data is packed into messages
(CMOOSMsg class) which contain other salient information as shown in
Table \ref{tab:MOOSMsg}.
\begin{table*}
\centering
\begin{tabular}{l|l}\hline
  % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
  {\textbf{Variable}} & {\textbf{Meaning}} \\ \hline
  Name  & The name of the data \\
  String Val & Data in string format \\
  Double Val & Numeric double float data \\
  Source & Name of client that sent this data to the \DB \\
  Time & Time at which the data was written \\
  Data Type & Type of data (STRING or DOUBLE)  \\
  Message Type & Type of Message (usually NOTIFICATION) \\
  Source Community & The community to which the source process
belongs --- see the Section on ``MOOS Communities'' in the CommunicationArchitecture document\\\hline
\end{tabular}\vspace{7mm}
  \caption{Contents of MOOS Message}\label{tab:MOOSMsg}
\end{table*}
The fact that data is commonly sent in string format is often seen
as a strange and inefficient aspect of MOOS. For example, the
string \verb"Type=EST,Name=AUV,Pos=[3x1]{3.4,6.3,-0.23}" might
describe the position estimate of a vehicle called ``AUV'' as a
3x1 column vector\footnote{Typically string data in MOOS is a
concatenation of comma separated "name = value" pairs.}. It is
true that using custom binary data formats does decrease the
number of bytes sent. However, binary data is unreadable to humans
and requires structure declarations to decode it, and header file
dependencies are to be avoided where possible. The communications
efficiency argument is not as compelling as one may initially
think. The CPU cost invoked in sending a TCP/IP packet is largely
independent of size up to about one thousand bytes. So it is as
costly to send two bytes as it is one thousand. In this light
there is basically no penalty in using strings. There is however a
additional cost incurred in parsing string data, which is far in
excess of that incurred when simply casting binary data.
Irrespective of this, experience has shown that the benefits of
using strings far outweigh the difficulties. In particular:
\begin{itemize}
\item Strings are human-readable -- debugging is trivial, especially
using a tool like MOOSScope. (see the document on Graphical tools for more information.)
\item All data becomes the same type.
\item Logging files are human-readable (they can be compressed for
storage).
\item Replaying a log file is simply a case of reading strings from
a file and ``throwing'' them back at the \DB in time order.
\item The contents and internal order of strings transmitted by an application can be changed
without the need to recompile consumers (subscribers to that data)
-- users simply would not understand new data fields but they would
not crash.
\end{itemize}
Of course, scalar data need not be transmitted in string format --
for example the depth of a sub-sea vehicle. In this case the data
would be sent while setting the data type to  \verb"MOOS_DOUBLE"
and writing the numeric value in the double data field of the
message.


\section{Important \code{CMOOSApp} Methods}


\subsection{Reading Configurations From File}\label{Sec:App:Configuration}

Every MOOS process can read configuration parameters from a
``Mission file'' which by convention has a ``.moos'' extension.
For example, the default mission file mentioned in the example code
given in Appendix A is {\it{Mission.moos}}. Traditionally MOOS
processes share  the same mission file to the maximum extent
possible. For example, it is usual for there to be one common
mission file for all MOOS processes running on a given machine.
Every MOOS process has information contained in a configuration
block within a *.moos file. The block begins with the statement
\begin{center}
\code{ProcessConfig} = \code{ProcessName}
\end{center}
where {\code{ProcessName}} is the unique name the application will
use when connecting to the \DB. The configuration block is
delimited by braces. Within the braces there is a collection of
parameter statements -- one per line.

Each statement is written as
\begin{center}
\code{ParameterName = Value}
\end{center}
where \code{Value} can be any string or numeric value. All
applications deriving from \code{CMOOSApp} and
\code{CMOOSInstrument} inherit several important configuration
options. The most important options for \code{CMOOSApp} derived applications
are  \code{CommTick} and \code{AppTick}. The latter configures how often the
communications thread talks to the \code{MOOSDB} and the former how often (approximately)
iterate will be called.


\begin{figure}\label{fig:ProcConfig}
\caption{A typical configuration block for a MOOS application. A
process called ``iDepth'' will search a mission file until a block
like this is found. It will then parse our configuration
parameters.}
\begin{lstlisting}[language = {matlab}]{}
/////////////////////////////
// depth sensor configuration
ProcessConfig = iDepth
{
    AppTick = 8
    CommsTick   = 4
    Port        = com1
    BaudRate    = 9600
    Streaming   = false
    Type        = ParaSci
    Resolution  = 0.1
}
\end{lstlisting}
\end{figure}
Figure \ref{fig:ProcConfig} gives an example of a typical
configuration block, in this case for a depth sensor. The
parameters \code{Type} and \code{Resolution} are specific to the
class defining the methods of a ``DepthSensor''. All the other
parameters are handled by its base classes
--- in this case (\code{CMOOSInstrument} and \code{CMOOSApp}).

\subsection{Parsing Configuration Blocks}

The library MOOSGenLin (see section \ref{Sec:MOOSGenLib}) contains many functions and classes
designed to help with parsing mission files. In particular the \code{CMOOSApp} class comes equipped with its own
\code{CMOOSProcessConfiguration} object called \code{m\_MissionReader}. By the time OnStartup is called, this object is already configured for use (i.e. it already knows which block it should be reading in the config file) and can be queried at will.
Listing \ref{Code:Ex4:Simulator.cpp} shows a modified version of our simulator (found in the ``Ex4'' directory). Note the new code appearing in \code{OnStartup} which looks for parameters in the mission file by making calls on the ProcessConfig reader object. You might also want to refer back to Sections \ref{Sec:StringParsing} and  \ref{Sec:MOOSGenLib}  to review the methods available for string passing.

\lstinputlisting[basicstyle=\footnotesize, caption = {A modified simulator application which reads configuration information from its mission file.},label = {Code:Ex4:Simulator.cpp}
]{../code/Ex4/Simulator.cpp}

We can now run up the simulator (which compiles using the CMake files supplied to ``Ex4'') and pass it a mission file as a parameter. But first we must create a suitable mission file --- for example ``Ex4.moos'' which is reproduced in Listing \ref{Listing:Ex4.moos}.

\lstinputlisting[basicstyle=\footnotesize, caption = {A simple mission file for Ex4},label = {Listing:Ex4.moos}
]{../code/Ex4/Ex4.moos}

In Figure \ref{Fig:RunningEx4} you can see a screen shot of what you should see happening when you launch \code{Ex4} and point it at \code{Ex4.moos} (don't forget to launch a \code{MOOSDB} first\footnote{I tend to always have one running on my machine.}.

\begin{figure}
\begin{center}
\epsfig{figure = images/RunningEx4.eps, width = 1.0\linewidth}
\end{center}
\caption{A screen shot of \code{Ex4} being run. Note how it was launched and has picked up the configuration parameters from Ex4.moos (see Listing \ref{Listing:Ex4.moos})}\label{Fig:RunningEx4}.
\end{figure}


\subsection{The Role of \code{AppTick} and \code{CommsTick }}

Every configuration block can set the \code{AppTick} and \code{CommsTick} properties of a \code{CMOOSApp} derived application --- see for example Figure \ref{fig:ProcConfig}. The former specifies the target rate (in Hz and can be less that 1.0 ) that \code{::Iterate} will be called at. Setting \code{AppTick} to zero is a special case and causes Iterate to be called as fast as possible (in other words the \code{::Run} method of CMOOSApp loops without any ``sleep'' period) --- use this with caution and good manners. The \code{CommsTick} variable dictates how often the \code{m\_Comms} object owned by every \code{CMOOSApp} contacts the DB in a never-ending quest to collect and post data from and to the DB. High values will lead to snappy response times if combined with high \code{AppTick}. If your application needs to call Iterate to do work often but you don't expect or require fast communication with other processes, then a high AppTick and a low CommsTick will suffice.


\section{Using the \code{CMOOSVariables} with \code{CMOOSApp}} \label{Sec:CMOOSVariable}

There is one other functionality provided by \code{CMOOSApp} which can prove very useful and that is the ability to create and manage runtime variables. You may well find that your application needs to maintain a representation of system state using a whole set of variables which are set according to the contents of incoming mail. To be concrete (and perhaps a bit naive) one can imagine a navigation application possessing variables for heading, speed, fuel, engine speed, headwind, current, depth. Each of these variables would appear in the mail processing switch yard (where they are updated to the values contained in individual MOOS messages) and each variable would have to be persistent --- in a object-oriented outlook this would mean a whole list of member variables. For a few such variables this is no big deal but in applications that have requested notifications on large numbers of variables, the mail processing function becomes long and tedious and the class itself becomes peppered with simple member variables.

\code{CMOOSApp} offers a way to soothe this frustration with the following functions (taken from \code{MOOSApp.h}).

\begin{lstlisting}

    ////////////////////////////////////////////////
    //  DYNAMIC VARIABLES  - AN OPTIONAL GARNISH
    ////////////////////////////////////////////////

    /** Add a dynamic (run time) variable
        @param sName name of the variable
        @param sSubscribeName if you call RegisterMOOSVariables() the variable will be updated with mailcalled <sSubscribeName> if and when you call UpdateMOOSVariables()
        @param sPublishName  if you call PublishFreshMOOSVariables() (and you've written to the dynamic variable since the last call) the variable will be published under this name.
        @param CommsTime - if sSubscribeName is not empty this is the minimum time between updates which you are interested in knowing about, so if CommsTime=0.1 then the maximum update rate you will see on the variable from the DB is 10HZ.  */
    bool AddMOOSVariable(std::string sName,std::string sSubscribeName,std::string sPublishName,double dfCommsTime);

    /** return a pointer to a named variable */
    CMOOSVariable * GetMOOSVar(std::string sName);

    /** Register with the DB to be mailed about any changes to any dynamic variables which were created with non-empty sSubscribeName fields */
    bool RegisterMOOSVariables();
	
    /** Pass mail (usually collected in OnNewMail) to the set of dynamic variables. If they are interested (mail name matches their subscribe name) they will update themselves automatically */
    bool UpdateMOOSVariables(MOOSMSG_LIST & NewMail);

    /** Set  value in a dynamic variable if the variable is of type double (type is set on first write )*/
    bool SetMOOSVar(const std::string & sName,const std::string & sVal,double dfTime);

    /** Set  value in a dynamic variable if the variable is of type string (type is set on first write ) */
    bool SetMOOSVar(const std::string & sVarName,double dfVal,double dfTime);

  /** Send any variables (under their sPublishName see AddMOOSVariable)  which been written to since the last call of PublishFreshMOOSVariables()*/
    bool PublishFreshMOOSVariables();
\end{lstlisting}


The idea is that with a call to \code{AddMOOSVariable} one can dynamically create a named variable (which behind the scenes is of type \code{CMOOSVariable}). As you do so, you specify the name of the messages (the string returned by calls to \code{CMOOSMsg.GetKey()}) which should be used to update this variable and also the name under which you wish to publish this data should you wish to undertake a notification. 
A concrete case may clarify things. Consider the case of a GPS sensor application, calling \code{AddMOOSVariable("X","","GPS\_X",0)} will create a dynamic variable called "X". I can set the value of this variable, presumably after successful parsing of a string read from a serial port) via \code{SetMOOSVar("X",...)} and, should I desire, retrieve it via \code{GetMOOSVar("X",...)}. I don't need to have a \code{m\_dfGPSX} variable explicitly declared in any class - it is made at run time. Now a role of this hypothetical application is to inform the MOOS community about the vehicle location --- we need to do a ``notify'' on ``GPS\_X''. This is easily achieved by calling \code{PublishFreshMOOSVariables} which calls a ``notify'' on any dynamic variable which has been written to since the last invocation (so in this case if no new GPS data had been received from the sensor no new data would be published to the MOOSDB). Imagine now you have ten things you might like to post to the database as and when occasion dictates --- a single call to \code{PublishFreshMOOSVariables} handles the whole thing for you.

Finally, consider the symmetrical case where instead of pushing data out we want to read data in. In this case we would do something like \code{AddMOOSVariable("Temp","ENGINE\_TEMP","",0)}. Here we are making a local MOOSVariable called \code{Temp} and telling the application (which is a \code{MOOSApp}) that it is a mirror of the \code{MOOSDB} code variable called \code{ENGINE\_TEMP}. So instead of having a \code{if} statement like
\begin{lstlisting}
if(Msg.Key()=="ENGINE\_TEMP")
{
}
\end{lstlisting}
 in the \code{OnNewMail} we can simply call \code{UpdateMOOSVariables(NewMail)} and if within the list of \code{MOOSMsg} there is a message pertaining to \code{ENGINE\_TEMP} it will be automatically used to update the \code{Temp} variable. Note you do need to make a call \code{to RegisterMOOSVariables()} to make sure that your application does all the registrations for all your MOOSvariables for you.





\section{Getting By Without \code{MOOSApp}}


There may be times when a developer does not wish to write an application from scratch using \code{CMOOSApp}, preferring to add the MOOS communications functionality to an existing application. This is an easy thing to achieve; a typical plan is laid out in the following five steps:

\begin{enumerate}
\item Instantiate a persistent instance of \code{CMOOSCommClient} -- perhaps as class member or even as a global singleton.
\item If required, use the \code{CMOOSCommClient::SetOnConnectCallBack} and \code{CMOOSCommClient::SetOnDisConnectCallBack} methods to tell the communications object what functions to call when a connection is made (or lost) with the \code{MOOSDB}. Note that these callbacks will happen in a separate thread. The latter of these callback registration functions is rarely used but symmetry is attractive.
\item Call the non-blocking \code{CMOOSCommClient::Run} passing the name (or IP address) of the machine hosting the DB, the port on which it is listening (usually 9000 but that can be configured) and the rate at which you want the communications thread to run in Hz (the default is 5Hz).
\item As soon as calls to \code{CMOOSCommClient::IsConnected} start returning true, you are free to start registering for notifications and posting your own data, as described in earlier sections. It is a good plan to put your registration code in the connection callback.
\item In your existing code periodically (perhaps via a timer in a gui application) call \code{CMOOSCommClient::Fetch} to retrieve whatever mail has been delivered to your application since the last invocation of \code{CMOOSCommClient::Fetch} (the comms object will have been having regular chats with the \code{MOOSDB} in the background while your own code has been doing its thing).
\end{enumerate}






\section{Other Bells and Whistles}

In releases post 7.0.1 several new methods are available via \code{CMOOSApp}.

\subsection{Process Status Summaries}

Every few seconds \code{CMOOSApp} publishes a status string. If the MOOS name of a process is XYZ then a status string is published under the name \code{XYZ\_STATUS}. By default the status string is formatted by the virtual member function \code{std::string CMOOSApp::MakeStatusString() } which formats a string containing:
\begin{itemize}
\item process uptime
\item names of all messages published so far
\item names of messages currently subscribed to.
\end{itemize}

By overloading \code{std::string CMOOSApp::MakeStatusString() } you can append or replace the status string with whatever you choose --- \code{CMOOSApp} will call your version in preference to its own.

\subsection{Automatic Handling of \code{<PROCESSNAME>\_CMD} Messages}

It is commonplace to want to have processes monitoring variables which contain instructions on how to behave or which request certain actions --- one could invoke the umbrella term ``command messages''. Post release 7.0.1,  \code{CMOOSApp} contains some plumbing to manage the handling of such messages. By extending the API it also helps best practice of using a common message naming policy for all such messages.
By calling \code{CMOOSApp::EnableCommandMessageFiltering(true)} (for example in \code{OnStartup}) CMOOSApp will, behind the scenes, peruse incoming mail for messages called \code{XYZ\_CMD} where the XYZ is a {\textbf{capitalised}} MOOS Community name of process (the  name with which process registers itself with the DB). If any such messages are found, the virtual function \code{CMOOSApp::OnCommandMsg(CMOOSMsg Msg)} is called. The default implementation does nothing --- overload this function to perform your own customised processing.

The command message filtering facility can also be turned on in any process's  configuration block by adding the line \code{CatchCommandMessages = true}. By default command message filtering is off.

\subsection{Running a \code{CMOOSApp} in a Separate Thread}

Some folk choose to create and run a \code{CMOOSApp} derived class from a secondary thread. This is of course completely fine but you may find you need to terminate this thread at run time and require \code{CMOOSApp::Run} to return. This can be achieved by calling the \code{CMOOSApp::RequestQuit()} method.


\section{MOOSGenLib Functions}\label{Sec:MOOSGenLib}

The library MOOSGenLib provides a plethora of functions that tend
to be useful for programs using MOOS. They are quite self
explanatory and are best perused by looking at the
\code{MOOSGenLibGlobalHelper.h} header file which is included here
for your delectation. \lstinputlisting[basicstyle=\footnotesize,
caption = {MOOSGenLibGlobalHelper.h - many goodies live
here},label = {Code:MOOSGenLibGlobalHelper.h}
]{../../../Core/MOOSGenLib/MOOSGenLibGlobalHelper.h}


\end{document}




