<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">%====================================================================
\section{Properties of Helm Behaviors}
%====================================================================
\wikisec{grp=moosivp,file=HelmBehaviors,short=Behavior Properties}
\label{sec_bhv_props}

The objective of this section is to describe properties common to all
IvP Helm behaviors, describe how to overload standard functions for
3rd party behaviors, and to provide a detailed simple example of a
behavior.  It builds on the discussion from Section
\ref{sec_ivphelm_autonomy}. The focus in this section is an expansion
of detail of Step 3 in Figure \ref{helm_iterate}.

%===================================================================
\subsection{Brief Overview}

Behaviors are implemented as C++ classes with the helm having one or
more instances at runtime, each with a unique descriptor. The
properties and implemented functions of a particular behavior are
partly derived from the \var{IvPBehavior} superclass, shown in Figure
\ref{bhv_overview}. The is-a relationship of a derived class provides
a form of code re-use as well as a common interface for constructing
mission files with behaviors.

\vspace{0.2in}

\begin{figure}[H]
  \centering 
  \includegraphics[width=0.90\textwidth]{figs_helm/bhv-inherit.png}
  \caption{{\bf Behavior inheritance}: Behaviors are derived from the
    \var{IvPBehavior} superclass. The native behaviors are the
    behaviors distributed with the helm. New behaviors also need to be
    a subclass of the IvPBehavior class to work with the helm. Certain
    virtual functions invoked by the helm may be optionally but
    typically overloaded in all new behaviors. Other private functions
    may be invoked within a behavior function as a way of facilitating
    common tasks involved in implementing a behavior.}
\label{bhv_overview}
\end{figure}

\vspace{0.15in}
\noindent
The \var{IvPBehavior} class provides five virtual functions which are
typically overloaded in a particular behavior implementation:

\begin{packed_itemize}[2]
\index{IvP Behavior Functions!The \var{setParam()} Function}
\item The \func{setParam()} function: parameter-value pairs are
  handled to configure a behavior's unique properties distinct from
  its superclass.

\index{IvP Behavior Functions!The \var{onRunState()} Function}
\item The \func{onRunState()} function: the meat of a behavior
  implementation, performed when the behavior has met its conditions
  for running, with the output being an objective function and a
  possibly empty set of variable-value pairs for posting to the
  \app{MOOSDB}.

\index{IvP Behavior Functions!The \var{onIdleState()} Function}
\item The \func{onIdleState()} function: what the behavior does when
  it has not met its run conditions. It may involve updating internal
  state history, generation of variable-value pairs for posting to the
  \app{MOOSDB}, or absolutely nothing at all.

\index{IvP Behavior Functions!The \var{onIdleToRunState()} Function}
\item The \func{onIdleToRunState()} function: invoked once by the helm
  upon transitioning from the idle to running state (compared to the
  \func{onRunState()} function which is invoked on {\em each} helm
  iteration where the behavior has met its conditions).

\index{IvP Behavior Functions!The \var{onRunToIdleState()} Function}
\item The \func{onRunToIdleState()} function: invoked once by the helm
  upon transitioning from the running to idle state (compared to the
  \func{onIdleState()} function which is invoked on {\em each} helm
    iteration where the behavior has not met its conditions).
\end{packed_itemize}


This section discusses the properties of the \var{IvPBehavior}
superclass that an author of a third-party behavior needs to be aware
of in implementing new behaviors. It is also relevant material for
users of the native behaviors as it details general properties.

%===================================================================
\subsection{Parameters Common to All IvP Behaviors}
\label{sec_bhv_common_params}
\index{IvP Behavior Parameters}

A behavior has a standard set of parameters defined at the
\var{IvPBehavior} level as well as unique parameters defined at the
subclass level. By configuring a behavior during mission planning, the
setting of parameters is the primary venue for affecting the overall
autonomy behavior in a vehicle. Parameters are set in the behavior
file, but can also be dynamically altered once the mission has
commenced. A parameter is set with a single line of the form:

\prevbhv
\begin{verbatim}
    parameter = value
\end{verbatim}
\postverb

The left-hand side, the parameter component, is case insensitive,
while the value component is typically case sensitive.  This was
discussed in depth in Section \ref{bhv_params}.  In this section, the
parameters defined at the superclass level and available to all
behaviors are exhaustively listed and discussed. Each behavior
typically augments these parameters with new ones unique to the
behavior, and in the next section the issue of implementing new
parameters by overloading the \func{setParam()} function is addressed.

%---------------------------------------------------------------------
\subsubsection{A Summary of the Full Set of General Behavior Parameters}
\label{bhv_common_params}

The following parameters are defined for all behaviors at the
superclass level. They are listed here for reference - certain
related aspects are discussed in further detail in other sections.

\index{IvP Behavior Parameters!\var{name}} 

\vspace{0.15in}
\begin{listing}{Configuration Parameters Common to All Behaviors}
\label{lst_ufsb_params}
\renewcommand{\arraystretch}{1.1}
\begin{longtable}{rp{0.75\textwidth}} 

  \bvar{name}: &amp; The name of the behavior - should be unique between
  all behaviors.  Due to the implementation of behavior templating,
  spawned behavior take on a new name by concatenating on the end of a
  base name. For this reason all configured behavior names could be
  regarded as base names. The check for uniqueness includes
  hypothetical extension. Thus the names \var{loiter} and
  \var{loiter\_two} are not regarded as safe since the first could
  potentially grow into the latter with the contcatenation of
  \var{\_two}.  Logging and output sent to the helm console during
  operation will organize information by the behavior name. \\

  \bvar{priority}: &amp; The priority weight of the produced objective
  function. The default value is 100. A behavior may also be
  implemented to determine its own priority weight depending on
  information about the world. \\

  \bvar{duration}: &amp; The time in seconds that the behavior will remain
  running before declaring completion. If no duration value is
  provided, the behavior will never time-out.  The clock starts
  ticking once the behavior satisfies its run conditions (becoming
  non-idle) the first time. {\em Should the behavior switch between
    running and idle states, the clock keeps ticking even during the
    idle periods.}  See Section \ref{sec_duration} for more detail. \\

  \bvar{duration\_status}: &amp; If the \bvar{duration} parameter is set,
  the remaining duration time, in seconds, can be posted by naming a
  \bvar{duration\_status} variable. This variable will be
  update/posted only when the behavior is in the running state. See
  Section \ref{sec_duration} for more detail. \\

  \bvar{duration\_reset}: &amp; This parameter takes a variable-pair such
  as \psvar{MY\_RESET=true}.  If the \bvar{duration} parameter is set,
  the duration clock is reset when the variable is posted to the
  \app{MOOSDB} with the specified value.  Each time such a post is
  noted, the duration clock is reset.  See Section \ref{sec_duration}
  for more detail. \\

  \bvar{post\_mapping}: &amp; This parameter takes a comma-separated pair
  such as \msvar{WPT\_STAT, WAYPT\_STATUS} where the left-hand value
  is a variable normally posted by the behavior, and the right-hand
  value is an alternative variable name to be used. There is no
  error-checking to ensure that the left-hand value names a variable
  actually posted by the behavior. Transitive relationships are not
  respected. For example, if the two re-mappings are declared,
  \bsvar{FOO,BAR}, and \bsvar{BAR,CAR}, \msvar{FOO} will be posted as
  \msvar{BAR}, not \msvar{CAR}.  To disable the normal posting of a
  variable \msvar{FOO}, use \bvar{post\_mapping} \bsvar{=
    FOO,SILENT}. \\

  \bvar{duration\_idle\_decay}: &amp; If this parameter is false the
  duration clock is paused when the vehicle is in the {\em idle}
  state. The default value is true. See Section
  \ref{sec_duration} for more detail. \\

  \bvar{condition}: &amp; This parameter specifies a condition that must
  be met for the behavior to be active. Conditions are checked for
  each behavior at the beginning of each control loop iteration.
  Conditions are based on current MOOS variables, such as \var{STATE =
    normal} or \var{(K &lt; 4)}.  More than one condition may be
  provided, as a convenience, treated collectively as a single
  conjunctive condition.  The helm automatically subscribes for any
  condition variables.  See Section \ref{sec_runconditions} for more
  detail on run conditions. \\

  \bvar{runflag}: &amp; This parameter specifies a variable and a value to
  be posted when the behavior has met all its conditions for being in
  the {\em running} state. It is only posted if the behavior, on the
  previous helm iteration, was not in the {\em running} state. It is
  an equal-separated pair such as \bsvar{TRANSITING=true}.  More than
  one flag may be provided.  These can be used to satisfy or block the
  conditions of other behaviors.  \\

  \bvar{idleflag}: &amp; This parameter specifies a variable and a value
  to be posted when the behavior is in the {\em idle} state.  See the
  Section \ref{sec_run_states} for more on run states.  It is only
  posted if the behavior, on the previous helm iteration, was not in
  the {\em idle} state. It is an equal-separated pair such as
  \bsvar{WAITING=true}.  More than one flag may be provided.  These
  can be used to satisfy or block the conditions of other behaviors. \\

  \bvar{activeflag}: &amp; This parameter specifies a variable and a value
  to be posted when the behavior is in the {\em active} state.  See
  the Section \ref{sec_run_states} for more on run states.  It is only
  posted if the behavior, on the previous helm iteration, was not in
  the {\em avtive} state.  It is an equal-separated pair such as
  \bsvar{TRANSITING=true}.  More than one flag may be provided.  These
  can be used to satisfy or block the conditions of other behaviors. \\

  \bvar{inactiveflag}: &amp; This parameter specifies a variable and a
  value to be posted when the behavior is {\em not} in the {\em
    active} state.  See the Section \ref{sec_run_states} for more on
  run states.  It is only posted if the behavior, on the previous helm
  iteration, was in the {\em active} state. It is a equal-separated
  pair such as \bsvar{OUT\_OF\_RANGE=true}.  More than one flag may be
  specified by the user in the behavior configuration.  These can be
  used to satisfy or block the conditions of other behaviors.  \\

  \bvar{endflag}: &amp; This parameter specifies a variable and a value to
  be posted when the behavior has set the completed state
  variable to be true.  The circumstances causing completion are
  unique to the individual behavior.  However, if the behavior has a
  \bvar{duration} specified, the completed flag is set to true
  when the duration is exceeded.  The value of this parameter is a
  equal-separated pair such as \bsvar{ARRIVED\_HOME=true}. Once the
  completed flag is set to true for a behavior, it remains inactive
  thereafter, regardless of future events, barring a complete helm
  restart. \\

  \bvar{updates}: &amp; This parameter specifies a variable from which
  updates to behavior configuration parameters are read from after the
  behavior has been initially instantiated and configured at the helm
  startup time.  Any parameter and value pair that would have been
  legal at startup time is legal at runtime. The syntax for this
  string is a \#-separated list of parameter-value pairs:
  \var{"param=value \# param=value \# ...  \# param=value"}.  This is
  one of the primary hooks to the helm for mission control - the other
  being the behavior conditions described above. See Section
  \ref{sec_updates} for more detail. \\

  \bvar{nostarve}: &amp; The \bvar{nostarve} parameter allows a behavior
  to assert a maximum staleness for one or more MOOS variables, i.e.,
  the time since the variable was last updated. The syntax for this
  parameter is a comma-separated pair \var{"variable, ..., variable,
    value"}, where last component in the list is the time value given
  in seconds. See Section \ref{sec_stalevars} for more detail. \\

  \bvar{perpetual}: &amp; Setting the \bvar{perpetual} parameter to
  true allows the behavior to continue to run even after it has
  completed and posted its end flags. The parameter value is not case
  sensitive and the only two legal values are true and
  false.  See Section \ref{sec_perpetual} for more detail. \\

  \bvar{templating}: &amp; The \bvar{templating} parameter may be used to
  turn a behavior specification into a template for spawning new
  behaviors dynamically after the helm has been
  launched. Instantiation requests are received via the \bvar{updates}
  parameter described in Section \ref{sec_bhv_templates}. \\

\end{longtable}
\end{listing}

%---------------------------------------------------------------------
\subsubsection{The \bvar{name} Parameter}
\label{sec_bhv_name}
\index{IvP Behavior Parameters!\var{name}}

The \bvar{name} parameter is a mandatory parameter with no default
value that assigns a name to the behavior instance. The name must be
unique. The behavior name is case sensitive, so having the names
\var{"return\_home"} and \var{"Return\_Home"} is acceptable (although
not advisable).

\pskip

Due to the capability of {\em behavior templating} (Section
\ref{sec_bhv_templates}) the policy of behavior uniqueness was
expanded to include pairs of names where one name matches the
beginning component of another. For example \var{"return"} and
\var{"return\_home"} are not allowed.  This is due to way template
spawning is implemented. The spawning process begins by setting the
name of the newly spawned behavior. This is achieved by appending to
the {\em base name} declared for the behavior template.  By allowing,
for example, \var{"return"} and \var{"return\_home"}, it leaves open
the possiblity that the first behavior may spawn an instance with a
name clash if it were spawned with a suffix directive of
\var{"\_home".}

\pskip

Behavior names have no relation to the behavior class name. For
example an instance of the \var{Waypoint} behavior may be called
\var{"station-keep"} (although not advisable). Furthermore, multiple
instances of the same behavior may certainly co-exist so long as each
instance has a unique name. If the helm is configured with one or more
behaviors with non-unique names, the helm will come up in the
\var{"MALCONFIG"} state. The terminal or appcasting output would look
something like:

\vspace{0.1in}
\begin{consoleverb}
===================================================================
pHelmIvP alpha                                             1/0(411)
===================================================================
Configuration Warnings: 1
 [1 of 1]: Duplicate behavior name found: waypt_return

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   !!                                             !!
   !!  The helm is in the MALCONFIG state due to  !!
   !!  unresolved configuration warnings.         !!
   !!                                             !!
   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
\end{consoleverb}



%---------------------------------------------------------------------
\subsubsection{The \bvar{priority} Parameter}
\label{sec_bhv_priority}
\index{IvP Behavior Parameters!\var{priority}}

The \bvar{priority} parameter is a optional parameter with a default
value of 100. It assigns a priority weight to be applied to an
objective function produced by the behavior. Many behaviors interpret
this priority to establish a range of priorities depending on the 
further evaluation of the situation by the behavior. For example, the 
collision avoidance behavior will treat the configured priority to be
the maximum priority (when a contact is close) and will degrade the 
priority accordingly as the contact range is greater.

\pskip
The range of acceptable values is from zero to infinity. If a negative
value is given for a behavior the helm will come up in the
\var{"MALCONFIG"} state. The terminal or appcasting output would look
something like:

\vspace{0.1in}
\begin{consoleverb}
===================================================================
pHelmIvP alpha                                             1/0(21)
===================================================================
Configuration Warnings: 1
 [1 of 1]: alpha.bhv: Line 61: pwt   = -1

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   !!                                             !!
   !!  The helm is in the MALCONFIG state due to  !!
   !!  unresolved configuration warnings.         !!
   !!                                             !!
   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
\end{consoleverb}


%---------------------------------------------------------------------
\subsubsection{The \bvar{post\_mapping} Parameter}
\label{sec_bhv_postmap}
\index{IvP Behavior Parameters!\var{post\_mapping}}

The \bvar{post\_mapping} parameter is a optional parameter with no
default value. It allows the user to configure a behavior to change
the name of the variables otherwise posted by the behavior. For
example, the Waypoint behavior by default publishes a variable
\mvar{WPT\_INDEX} indicating the index of the next point on its
path. If there are multiple waypoint behaviors, or if you just don't
like this variable, it may be change for example to \msvar{SURVEY\_INDEX}
with the following configuration:

\vspace{0.1in}
\bvar{post\_mapping=WPT\_INDEX,SURVEY\_INDEX}
\vspace{0.1in}


%---------------------------------------------------------------------
\subsubsection{Altering Parameters Dynamically with the \bvar{updates} Parameter}
\label{sec_updates}
\index{IvP Behavior Parameters!\var{updates}}
\index{IvP Behaviors!Dynamic Configuration}

The parameters of a behavior can be made to allow dynamic
modifications - after the helm has been launched and executing the
initial mission in the behavior file.  The modifications come in a
single MOOS variable specified by the parameter
\bvar{updates}. For example, consider the simple waypoint behavior 
configuration below in Listing \ref{updates_example}. The return point
is the (0,0) point in local coordinates, and return speed is 2.0
meters/second. When the conditions are met, this is what will be
executed.

\vspace{0.1in}
\begin{listing}{An example behavior configuration using the \bvar{updates} parameter}
\label{updates_example}
\footnotesize
\begin{verbatim}
 1  Behavior = BHV_Waypoint
 2  {
 3    name      = WAYPT_RETURN
 4    priority  = 100
 5    speed     = 2.0
 6    radius    = 8.0
 7    points    = 0,0
 8    updates   = RETURN_UPDATES
 9    condition = RETURN = true
10    condition = DEPLOY = true
11  }
\end{verbatim}
\end{listing}
\normalsize
\vspace{0.1in}

If, during the course of events, a different return point or speed is
desired, this behavior can be altered dynamically by writing to the
variable specified by the \bvar{updates} parameter, in this case the
variable \mvar{RETURN\_UPDATES} (line 8 in Listing
\ref{updates_example}).  The syntax for this variable is of the form:

\prevblue
\begin{verbatim}
    parameter = value # parameter = value # ... # parameter = value
\end{verbatim}
\postverb

\noindent
White space is ignored. The '\#' character is treated as special for
parsing the line into separate parameter-value pairs. It cannot be
part of a parameter component or value component.  For example, the
return point and speed for this behavior could be altered by any other
MOOS process that writes to the MOOS variable:

\prevgreen
\begin{verbatim}
    RETURN_UPDATES = "points=50,50 # speed = 1.5"
\end{verbatim}
\postverb

Each parameter-value pair is passed to the same parameter setting routines
used by the behavior on initialization. The only difference is that an 
erroneous parameter-value pair will simply be ignored as opposed to 
halting the helm as done on startup. If a faulty parameter-value pair is
encountered, a warning will be written to the variable \mvar{BHV\_WARNING}. 
For example:

\prevgreen
\begin{verbatim}
  BHV_WARNING = "Faulty update for behavior: WAYPT_RETURN. Bad parameter(s): speed."
\end{verbatim}
\postverb

\noindent
Note that a check for parameter updates is made at the outset of helm
iteration loop for a behavior (Figure \ref{bhv_overview}) with the
call \func{checkUpdates()}. Any updates received by the helm on the
current iteration will be applied prior to behavior execution and in
effect for the current iteration.

%---------------------------------------------------------------------
\subsubsection{Limiting Behavior Duration with the \bvar{duration} Parameter}
\label{sec_duration}
\index{IvP Behavior Parameters!\var{duration}}

The \bvar{duration} parameter specifies a time period in seconds
before a behavior times out and permanently enters the completed state
(Figure \ref{helm_calls}). If left unspecified, there is no time limit
to the behavior. By default, the duration clock begins ticking as soon
as the helm is in drive.  The duration clock remains ticking when or
if the behavior subsequently enters the idle state. It even remains
ticking if the helm temporarily parks.  When a timeout occurs, end
flags are posted. The behavior can be configured to post the time
remaining before a timeout with the \bvar{duration\_status} parameter.
The forms for each are:

\prevbhv
\begin{verbatim}
   duration        =  value (positive numerical)
   duration_status =  value (variable name)
\end{verbatim}
\postverb

\vspace{0.1in}
\noindent
Note that the duration status variable will only be published/updated
when the behavior is in the running state. The duration status is
rounded to the nearest integer until less than ten seconds remain,
after which the time is posted out to two decimal places. The behavior
can be configured to have the duration clock pause when it is in the
idle state with the following:

\prevbhv
\begin{verbatim}
   duration_idle_decay = false   // The default is true 
\end{verbatim}
\postverb

\noindent
Configured in the above manner, a behavior's duration clock will
remain paused until it's conditions are met.  The behavior may also be
configured to allow for the duration clock to be reset upon the
writing of a MOOS variable with a particular value.  For example:

\prevbhv
\begin{verbatim}
   duration_reset = BRAVO_TIMER_RESET=true
\end{verbatim}
\postverb

\noindent
The behavior checks for and notes that the variable-value pair holds
true and the duration clock is then reset to the original duration
value. The behavior also marks the time at which the variable-value
pair was noted to have held true. Thus there is no need to "un-set"
the variable-value pair, e.g., setting
\msvar{BRAVO\_TIMER\_RESET=false}, to allow the duration clock to resume
its count-down.

%---------------------------------------------------------------------
\subsubsection{The \bvar{perpetual} Parameter}
\label{sec_perpetual}
\index{IvP Behavior Parameters!\var{perpetual}}

When a behavior enters the {\em completed} state, it by default
remains in that state with no chance to change. When the
\bvar{perpetual} parameter is set to true, a behavior that is
declared to be complete does not actually enter the complete state but
performs all the other activity normally associated with completion,
such as the posting of end flags.  See Section \ref{sec_flags} for
more detail on posting flags to the \app{MOOSDB} from the helm.  The
default value for \bvar{perpetual} is false.  The form for this
parameter is:

\prevbhv
\begin{verbatim}
   perpetual  =  value
\end{verbatim}
\postverb

\noindent
The value component is case insensitive, and the only legal values are
either true or false. A behavior using the \bvar{duration}
parameter with \bvar{perpetual} set to true will post its end
flags upon time out, but will reset its clock and begin the count-down
once more the next time its run conditions are met, i.e., enters the
running state. Typically when a behavior is used in this way, it also
posts an endflag that would put itself in the idle state, waiting for
an external event.


%---------------------------------------------------------------------
\subsubsection{The \bvar{post\_mapping} Parameter}
\label{sec_bhv_post_mapping}
\index{IvP Behavior Parameters!\var{post\_mapping}}

This parameter takes a comma-separated pair where the left-hand value
is a variable normally posted by the behavior, and the right-hand
value is an alternative variable name to be used. For example, the
Waypoint behavior normally posts the variable \mvar{WPT\_STAT} when it
is running. This can be changed with:

\prevbhv
\begin{verbatim}
 post_mapping = WPT_STAT, WAYPT_STATUS 
\end{verbatim}
\postverb


Note there is no error-checking to ensure that the left-hand value
names a variable actually posted by the behavior. Transitive
relationships are not respected. For example, if the two re-mappings
are declared, \bsvar{FOO,BAR}, and \bsvar{BAR,CAR}, \msvar{FOO} will
be posted as \msvar{BAR}, not \msvar{CAR}.  To disable the normal
posting of a variable \msvar{FOO}, use:

\prevbhv
\begin{verbatim}
 post_mapping = FOO, SILENT
\end{verbatim}
\postverb

%---------------------------------------------------------------------
\subsubsection{Detection of Stale Variables with the \bvar{nostarve} Parameter}
\label{sec_stalevars}
\index{IvP Behavior Parameters!\var{nostarve}}

A behavior utilizing a variable generated by a MOOS process outside
the helm, may require the variable to be sufficiently up-to-date. The
staleness of a variable is the time since it was last written to by
any process. The \bvar{nostarve} parameter allows the mission writer to
set a staleness threshold. The form for this parameters is:

\prevbhv
\begin{verbatim}
   nostarve  =  variable_1, ..., variable_n, duration
\end{verbatim}
\postverb

\noindent
The value of this parameter is a comma-separated list such as
\bvar{nostarve} \bsvar{= NAV\_X, NAV\_Y, 5.0}.  The variable
components name MOOS variables and the duration component, the last
entry in the list, represents the tolerated staleness in seconds.  If
staleness is detected, a behavior failure condition is triggered which
will trigger the helm to post all-stop values and relinquish to manual
control.

%===================================================================
\subsection{Overloading the \func{setParam()} Function in New Behaviors}
\label{sec_bhv_setparam}
\index{IvP Behavior Functions!The \var{setParam()} Function}

The \func{setParam()} function is a virtual function defined in the
\var{IvPBehavior} class, with parameters implemented in the superclass
(Section \ref{sec_bhv_common_params}) handled in the superclass
version of this function:

\vspace{0.1in}
\small
\begin{verbatim}
    bool IvPBehavior::setParam(string parameter, string value);
\end{verbatim}
\normalsize
\vspace{0.1in}

\noindent
The \func{setParam()} function should return true if the
parameter is recognized and the value is in an acceptable form. In the
rare case that a new behavior has no additional parameters, leaving
this function undefined in the subclass is appropriate.  The example
below in Listing \ref{lst_set_param} gives an example for a fictional
behavior \var{BHV\_YourBehavior} having a single parameter
\psvar{period}.

\vspace{0.25in}
\begin{listing}{Example \func{setParam()} implementation for fictional BHV\_YourBehavior}
\label{lst_set_param}
\footnotesize
\begin{verbatim}
  1  bool BHV_YourBehavior::setParam(string param, string value) 
  2  {
  3    if(param == "period") {
  4      double time_value = atof(value.c_str());
  5      if((time_value &lt; 0) || (!isNumber(value)))
  6        return(false);
  7      m_period = time_value;
  8      return(true);
  9    }
 10    return(false);
 11  }
\end{verbatim}
\end{listing}
\normalsize

\noindent
Since the \bsvar{period} parameter refers to a time period, a check is
made on line 4 that the value component indeed is not a negative
number. The \func{atof()} function on line 6, which converts an ASCII
string to a floating point value, returns zero when passed a
non-numerical string, therefore the \func{isNumber()} function is also
used to ensure the string represented by \var{value} represents a
numerical value.  The \func{isNumber()} function is part of the
IvP utility library. A behavior implementation of this function
without sufficient syntax or semantic checking simply runs the risk
that faulty parameters are not detected at the time of helm launch, or
during dynamic updates. Solid checking in this function will reduce
debugging headaches down the road.


%The helm treats each behavior in a standard way on each iteration. It
%is oblivious to what a behavior may be trying to accomplish, or what
%combinations of behaviors are in play. In a nutshell it is interested
%in receiving the following from each behavior - an objective function
%defined over a subset of the helm's decision space, and a list of new
%variables with values. Those variables and values are then posted to
%the MOOSDB at the end of the iteration along with the standard helm
%output which includes a decision for each component in its decision
%space.  

%===================================================================
\subsection{Behavior Functions Invoked by the Helm}
\label{sec_helm_overview}
\index{IvP Behavior Functions!Helm-Invoked Functions}

The \var{IvPBehavior} superclass implements a number of functions
invoked by the helm on each iteration. Two of these functions are
overloadable as described previously - the \func{onRunState()} and
\func{onIdleState()} functions. The basic flow of calls to a behavior
from the helm are shown in Figure \ref{helm_calls}.  These are
discussed in more detail later in the section, but the idea is to
execute certain behavior functions based on the {\em activity state},
which may be one of the four states depicted.

\vspace{0.15in}
\begin{figure}[H]
  \centering 
  \includegraphics[width=0.96\textwidth]{figs_helm/helm-bhv-flow.png}
  \caption{{\bf Behavior function-calls by the helm}: The helm invokes
    a sequence of functions on each behavior on each iteration of the
    helm.  The sequence of calls is dependent on what the behavior
    returns, and reflects the behaviors activity state. Certain
    functions are immutable and can not be overloaded by a behavior
    author. Two key functions, \func{onRunState()} and \func{onIdleState()}
    can be indeed overloaded as the usual hook for an author to provide
    the implementation of a behavior. The \func{postFlags()} function is
    also immutable, but the parameters (flags) are provided in the helm
    configuration (\var{*.bhv}) file.}
 \label{helm_calls}
\end{figure}
 \vspace{0.15in}

An {\em idle} behavior is one that has not met its conditions for
running. A {\em completed} behavior is one that has reached its
objectives or exceeded its duration. A {\em running} behavior is one
that has not yet completed, has met its run conditions, but may still
opt not to produce any output. An {\em active} behavior is one that is
running and is producing output in the form of an objective function.

The types of functions defined at the superclass level fall into one
of the three categories below, only the first two of which are
shown in Figure \ref{helm_calls}:

\begin{packed_itemize}[3]
\item Helm-invoked immutable functions - functions invoked by the helm
  on each iteration that the author of a new behavior may not
  re-implement.

\item Helm-invoked overloadable functions - functions invoked by the
  helm that an author of a new behavior typically re-implements of
  overloads.

\item User-invoked functions - functions invoked within a behavior
  implementation.
\end{packed_itemize}

The user-invoked functions are utilities for common operations
typically invoked within the implementation of the \func{onRunState()} and
\func{onIdleState()} functions written by the behavior author.

%---------------------------------------------------------------------
\subsubsection{Helm-Invoked Immutable Functions}
\index{IvP Behavior Functions!Helm-Invoked Immutable Functions}

These functions, implemented in the \var{IvPBehavior} superclass, are
called by the helm but are {\em not} defined as virtual functions
which means that attempts to overload them in a new behavior
implementation will be ignored. See Figure \ref{helm_calls} regarding
the sequence of these function calls.

\begin{itemize}

\index{IvP Behavior Functions!The \var{checkUpdates()} Function}

 \item \func{void checkUpdates()}: This function is called first on
   each iteration to handle requested dynamic changes in the behavior
   configuration. This needs to be the very first function applied to
   a behavior on the helm iteration so any requested changes to the
   behavior parameters may be applied on the present iteration. See
   Section \ref{sec_updates} for more on dynamic behavior
   configuration with the \bvar{updates} parameter.

\index{IvP Behavior Functions!The \var{isComplete()} Function}
 \item \func{bool isComplete()}: This function simply returns a
   Boolean indicating whether the behavior was put into the {\em
     complete} state during a prior iteration.

\index{IvP Behavior Functions!The \var{isRunnable()} Function}
 \item \func{bool isRunnable()}: Determines if a behavior is in the
   {\em running} state or not. Within this function call four things
   are checked: (a) if the \bvar{duration} is set, the duration time
   remaining is checked for timeout, (b) variables that are monitored
   for staleness are checked against (Section \ref{sec_stalevars}).
   (c) the run conditions must be met.  (d) the behavior's decision
   domain (IvP domain) is a proper subset of the helm's configured IvP
   domain.  See Section \ref{sec_runconditions} for more detail on run
   conditions.

\index{IvP Behavior Functions!The \var{postFlags()} Function}
 \item \func{void postFlags(string flag\_type)}: This function will
   post flags depending on whether the value of \var{flag\_type} is
   set to \var{"idleflags"}, \var{"runflags"}, \var{"activeflags"},
   \var{"inactiveflags"}, or \var{"endflags"}. Although this function
   is immutable, not overloadable by subclass implementations, its
   effect is indeed mutable since the flags are specified in the
   mission configuration \var{*.bhv} file. See Section \ref{sec_flags}
   for more detail on posting flags to the \app{MOOSDB} from the helm.

\end{itemize}

%---------------------------------------------------------------------
\subsubsection{Helm-Invoked Overloaded Functions}
\label{sec_overload}
\index{IvP Behavior Functions!Helm-Invoked Overloadable Functions}

These are functions called by the helm. They are defined as virtual
functions so that a behavior author may overload them. Typically the
bulk of writing a new behavior resides in implementing these three
functions.

\index{IvP Behavior Functions!The \var{onRunState()} Function}

\begin{itemize}
 \item \func{IvPFunction* onRunState()}: This function is called by the
   helm when deemed to be in the {\em running} state (Figure
   \ref{helm_calls}).  The bulk of the work in implementing a new
   behavior is in this function implementation, and is the subject of
   Section \ref{sec_bhv_onstate}.

\index{IvP Behavior Functions!The \var{onIdleState()} Function}

 \item \func{void onIdleState()}: This function is called by the helm
   when deemed to be in the {\em idle} state (Figure
   \ref{helm_calls}). Many behaviors are implemented with this
   function left undefined, but it is a useful hook to have in many
   cases.

\index{IvP Behavior Functions!The \var{setParam()} Function}

 \item \func{bool setParam(string, string)}: This function is called
   by the helm when the behavior is first instantiated with the set of
   parameter and parameter values provided in the behavior file. It is
   also called by the helm within the \func{checkUpdates()} function
   to apply parameter updates dynamically.
\end{itemize}

%===================================================================
\subsection{Local Behavior Utility Functions}
\index{IvP Behavior Functions!Implementor-Invoked Functions}

The bulk of the work done in implementing a new behavior is in the
implementation of the \func{onIdleState()} and \func{onRunState()}
functions. The utility functions described below are designed to aid
in that implementation and are generally "protected" functions, that
is callable only from within the code of another function in the
behavior, such as the \func{onRunState()} and \func{onIdleState()}
functions, and not invoked by the helm.

%---------------------------------------------------------------------
\subsubsection{Summary of Implementor-Invoked Utility Functions}
\label{sec_bhv_util_funcs}

The following is summary of utility functions implemented at the 
\var{IvPBehavior} superclass level.

\begin{itemize}

 \index{IvP Behavior Functions!The \var{setComplete()} Function}
 \item \func{void setComplete()}: The notion of what it means for a
   behavior to be "complete" is largely an issue specific to an
   individual behavior.  When or if this state is reached, a call to
   \func{setComplete()} can be made and end flags will be posted, and
   the behavior will be permanently put into the {\em completed} state
   unless the \bvar{perpetual} parameter is set to true. See
   Section \ref{sec_run_states} for more on behavior run states.

 \index{IvP Behavior Functions!The \var{addInfoVars()} Function}
 \item \func{void addInfoVars(string var\_names)}: The helm will
   register for variables from the \app{MOOSDB} on a need-only basis,
   and a behavior is obligated to inform the helm that certain
   variables are needed on its behalf. A call to the
   \func{addInfoVars()} function can be made from anywhere with a
   behavior implementation to declare needed variables. This can be
   one call per variable, or the string argument can be a
   comma-separated list of variables. The most common point of
   invoking this function is within a behavior's constructor since
   needed variables are typically known at the point of
   instantiation. More on this issue in Section \ref{sec_ibuff_reg}.

 \index{IvP Behavior Functions!The \var{getBuffer*()} Functions}
 \item \func{double getBufferDoubleVal(string varname, bool\&amp;
   result)}: Query the \var{info\_buffer} for the latest (double)
   value for a given variable named by the string argument. The bool
   argument indicates whether the queried variable was found in the
   buffer. More on this in Section \ref{sec_ibuff}.

 \index{IvP Behavior Functions!The \var{getBuffer*()} Functions}
 \item \func{double getBufferStringVal(string varname, bool\&amp;
   result)}: Query the \var{info\_buffer} for the latest (string)
   value for a given variable named by the string argument. The bool
   argument indicates whether the queried variable was found in the
   buffer. More on this in Section \ref{sec_ibuff}.

 \index{IvP Behavior Functions!The \var{getBufferCurrTime()} Function}
 \item \func{double getBufferCurrTime()}: Query the \var{info\_buffer}
   for the current buffer local time, equivalent to the duration in
   seconds since the helm was launched. More on this in Section
   \ref{sec_ibuff}.

 \index{IvP Behavior Functions!The \var{getBuffer*()} Functions}
 \item \func{vector&lt;double&gt; getBufferDoubleVector(string var, bool\&amp;
   result)}: Query the \var{info\_buffer} for all changes to the
   variable (of type double) named by the string argument, since the
   last iteration. The bool argument indicates whether the queried
   variable was found in the buffer. More on this in Section
   \ref{sec_ibuff}.

 \index{IvP Behavior Functions!The \var{getBuffer*()} Functions}
 \item \func{vector&lt;string&gt; getBufferStringVector(string var, bool\&amp;
   result)}: Query the \var{info\_buffer} for all changes to the
   variable (of type string) named by the string argument, since the
   last iteration. The bool argument indicates whether the queried
   variable was found in the buffer. More on this in Section
   \ref{sec_ibuff}.

\index{IvP Behavior Functions!The \var{post*Message()} Functions}
 \item \func{void postMessage(string varname, string value, string
   key)}: The helm can post messages (variable-value pairs) to the
   \app{MOOSDB} at the end of the helm iteration. Behaviors can
   request such postings via a call to the \func{postMessage()}
   function where the first argument is the variable name, and the
   second is the variable value. The optional {\em key} parameter is
   used in conjunction with the duplication filter and by default is
   the empty string. See Section \ref{auto_filter} for more on the
   duplication filter.

 \index{IvP Behavior Functions!The \var{post*Message()} Functions}
 \item \func{void postMessage(string varname, double value, string
   key)}: Same as above except used when the posted variable is of
   type \var{double} rather than \var{string}. The optional {\em key}
   parameter is used in conjunction with the duplication filter and by
   default is the empty string. See Section \ref{auto_filter} for
   more on the duplication filter.

 \index{IvP Behavior Functions!The \var{post*Message()} Functions}
 \item \func{void postBoolMessage(string varname, bool value, string
   key)}: Same as above, except used when the posted variable is a
   \var{bool} rather than \var{string}. The optional {\em key}
   parameter is used in conjunction with the duplication filter and by
   default is the empty string. See Section \ref{auto_filter} for more
   on the duplication filter.

 \index{IvP Behavior Functions!The \var{post*Message()} Functions}
 \item \func{void postIntMessage(string varname, double value, string
   key)}: Same as \func{postMessage(string, double)} above except the
   numerical output is rounded to the nearest integer. This, combined
   with the helm's use of the {\em duplication filter}, can reduce the
   number of posts to the \app{MOOSDB}. The optional {\em key}
   parameter is used in conjunction with the duplication filter and by
   default is the empty string.  See Section \ref{auto_filter} for
   more on the duplication filter.

 \index{IvP Behavior Functions!The \var{post*Message()} Functions}
 \item \func{void postWMessage(string warning\_msg)}: Identical to the
   \func{postMessage()} function except the variable name is
   automatically set to \mvar{BHV\_WARNING}. Provided as a matter of
   convenience to the caller and for uniformity in monitoring
   warnings.

 \index{IvP Behavior Functions!The \var{post*Message()} Functions}
 \item \func{void postEMessage(string error\_msg)}: Similar to the
   \func{postWMessage()} function except the variable name is
   \mvar{BHV\_ERROR}. This call is for more serious problems noted by
   the behavior. It also results in an internal \var{state\_ok} bit
   being flipped which results in the helm posting all-stop values to
   the actuators.

 \index{IvP Behavior Functions!The \var{post*Message()} Functions}
 \item \func{void postRepeatableMessage(string varname, string
   value)}: A convenience function. A posting of
   \var{postRepeatableMessage("FOO", "bar")} is equivalent to
   \var{postMessage("FOO", "bar", "repeatable")}.

 \index{IvP Behavior Functions!The \var{post*Message()} Functions}
 \item \func{void postRepeatableMessage(string varname, double
   value)}: A convenience function. A posting of
   \var{postRepeatableMessage("FOO", 100)} is equivalent to
   \var{postMessage("FOO", 100, "repeatable")}.

\end{itemize}

%---------------------------------------------------------------------
\subsubsection{The Information Buffer}
\label{sec_ibuff}
\index{IvP Behaviors!The Information Buffer}

Behaviors do not have direct access to the \app{MOOSDB} - they don't read
mail, and they don't post changes directly, but rather through the
helm as an intermediary.  The information buffer, or
\var{info\_buffer}, is a data structure maintained by the helm to
reflect a subset of the information in the \app{MOOSDB} and made available
to each behavior.  This topic is hidden from a user configuring
existing behaviors and can be safely skipped, but is an important
issue for a behavior author implementing a new behavior. The
\var{info\_buffer} is a data structure shared by all behaviors, each
behavior having an pointer to a single instance of the
\var{InfoBuffer} class. This data structure is maintained by the helm,
primarily by reading mail from the \app{MOOSDB} and reflecting the change
onto the buffer on each helm iteration, before the helm requests input
from each behavior. Each behavior therefore has the exact same
snapshot of a subset of the \app{MOOSDB}. A behavior author needs to know
two things - how to ensure that certain variables show up in the
buffer, and how to access that information from within the
behavior. These two issues are discussed next.

%---------------------------------------------------------------------
\subsubsection{Requesting the Inclusion of a Variable in the Information Buffer}
\label{sec_ibuff_reg}
\index{IvP Behavior Functions!The \var{addInfoVars()} Function}

A variable can be specifically requested for inclusion in the
\var{info\_buffer} by invoking the following function:

\small
\begin{verbatim}
   void  IvPBehavior::addInfoVars(string varnames)
\end{verbatim}
\normalsize

\noindent 
The string argument is either a single MOOS variable or a
comma-separated list of variables. Duplicate requests are simply
ignored. Typically such calls are invoked in a behavior's constructor,
but may be done dynamically at any point after the helm is running.
The helm will simply register with the \app{MOOSDB} for the requested
variable at the end of the current iteration. Certain variables are
registered for automatically on behalf of the behavior. All variables
referenced in run conditions will be registered and accessible in the
buffer. Variables named in the \bvar{updates} and \bvar{nostarve}
parameters will also be automatically registered.

%---------------------------------------------------------------------
\subsubsection{Accessing Variable Information from the Information Buffer}
\label{sec_ibuff_pull}
\index{IvP Behavior Functions!The \var{getBuffer*()} Functions}

A variable value can be queried from the buffer with one of the following
two function calls, depending on whether the variable is of type
double or string.

\small
\begin{verbatim}
   string  IvPBehavior::getBufferStringVal(string varname, bool&amp; result)
   double  IvPBehavior::getBufferDoubleVal(string varname, bool&amp; result)
\end{verbatim}
\normalsize

\noindent
The first string argument is the variable name, and the second
argument is a reference to a Boolean variable which, upon the function
return, will indicate whether the queried variable was found in the
buffer. A duration value indicating the elapsed time since the
variable was last changed in the buffer can be obtained from the
following function call:

\small
\begin{verbatim}
   double  IvPBehavior::getBufferTimeVal(string varname);
\end{verbatim}
\normalsize

\noindent
The string argument is the variable name. The returned value should be
exactly zero if this variable was updated by new mail received by the
helm at the beginning of the current iteration.  If the variable name
is not found in the buffer, the return value is -1. The ``current''
buffer time, equivalent to the cumulative time in seconds since the
helm was launched, can be retrieved with the following function call:

\small
\begin{verbatim}
   double  IvPBehavior::getBufferCurrTime()
\end{verbatim}
\normalsize

\noindent
The buffer time is a local variable of the \var{info\_buffer} data
structure. It is updated once at the beginning of the helm
\func{OnNewMail()} loop prior to processing all new updates to the
buffer from the MOOS mail stack, or at the beginning of the
\func{Iterate()} loop if no mail is processed on the current iteration.
Thus the time-stamp returned by the above call should be exactly the
same for successive calls by all behaviors within a helm iteration.

\pskip

The values returned by \func{getBufferStringVal()} and
\func{getBufferDoubleVal()} represent the latest value of the variable 
in the \app{MOOSDB} at the point in time when the helm began its iteration
and processed its mail stack. The value may have changed several times
in the \app{MOOSDB} between iterations, and this information may be of use
to a behavior. This is particularly true when a variable is being
posted in pieces, or a sequence of delta changes to a data structure.
In any event, this information can be recovered with the following two
function calls: 

\small
\begin{verbatim}
   vector&lt;string&gt;  IvPBehavior::getBufferStringVector(string varname, bool&amp; result)
   vector&lt;double&gt;  IvPBehavior::getBufferDoubleVector(string varname, bool&amp; result)
\end{verbatim}
\normalsize

\noindent
They return all values updated to the buffer for a given variable
since the last iteration in a vector of strings or doubles
respectively. The latest change is located at the highest index of the
vector. An empty vector is returned if no changes were received at the
outset of the current iteration.

%===================================================================
\subsection{Overloading the onRunState() and onIdleState() Functions}
\label{sec_bhv_onstate}
\index{IvP Behavior Functions!The \var{onIdleState()} Function}
\index{IvP Behavior Functions!The \var{onRunState()} Function}

The \func{onRunState()} function is declared as a virtual function in
the \var{IvPBehavior} superclass intended to be overloaded by the
behavior author to accomplish the primary work of the behavior.  The
primary behavior output is the objective function.  This is what
drives the vehicle. The objective function is an instance of the class
\var{IvPFunction}, and a behavior generates an instance and returns a
pointer to the object in the following function:

\small
\begin{verbatim}
   IvPFunction* onRunState()
\end{verbatim}
\normalsize

\noindent
This function is called automatically by the helm on the current
iteration if the behavior is deemed to be in the {\em running} state,
as depicted in Figure \ref{helm_calls}. The invocation of
\func{onRunState()} does not necessarily mean an objective function is
returned. The behavior may opt not to for whatever reason, in which
case it returns a null pointer. However, if it does generate a
function, the behavior is said to be in the {\em active} state. The
steps comprising the typical implementation of the \func{onRunState()}
implementation can be summarized as follows:

\begin{packed_itemize}[3]
\item Get information from the \var{info\_buffer}, and update any
  internal behavior state.
\item Generate any messages to be posted to the \app{MOOSDB}.
\item Produce an objective function if warranted.
\item Return.
\end{packed_itemize}

The same steps hold for the \func{onIdleState()} function except for
producing an objective function.  The first two steps have been
discussed in detail. Accessing the \var{info\_buffer} was described in
Sections \ref{sec_ibuff} - \ref{sec_ibuff_pull}. The functions for
posting messages to the \app{MOOSDB} from within a behavior were
discussed in Section \ref{sec_bhv_util_funcs}.  Further issues
regarding the posting of messages were covered in Section
\ref{sec_flags} The remaining issue to discuss is how objective
functions are generated. This is covered in the IvPBuild Toolbox
documentation.





%===================================================================
\subsection{Dynamic Behavior Spawning}
\label{sec_bhv_templates}
\index{Dynamic Behavior Spawning}

In certain scenarios it may not be practical or possible to know in
advance all the behaviors needed to accomplish mission objectives.
For example, if the helm uses a certain kind of behavior to deal with
another vehicle in its operation area, for collision avoidance or
trailing etc., the identities or number of such vehicles may not be
known when the mission planner is configuring the helm's behavior
file. One way to circumvent this problem is to design a collision
avoidance behavior, for example, to handle all known contacts.
However, this has a couple drawbacks. It would entail a degree of
multi-objective optimization be implemented within the behavior to
produce an objective function that was comprehensive across all
contacts. This would likely be much more computationally expensive
than simply generating an objective function for each contact. It also
may be advantageous to have different types of collision avoidance
behaviors for different contact types or collision avoidance
protocols. In any event, the helm support for dynamic behavior
spawning gives behavior architects and mission planners another
potentially powerful option for implementing an autonomy system.

%---------------------------------------------------------------------
\subsubsection{Behavior Specifications Viewed as Templates}

The \bvar{templating} parameter may be used to turn an otherwise static
behavior specification into a template for spawning new behaviors
dynamically after the helm has been launched. Instantiation requests
are received via the \bvar{updates} parameter described in Section
\ref{sec_updates}. Updates received through this variable are
normally used to change behavior parameters dynamically, but they can
be further used to request the spawning of a new behavior by including
the following component:

\prevblue
\begin{verbatim}
   name = &lt;new-behavior-name&gt;
\end{verbatim}
\postverb

\noindent
If the \var{&lt;new-behavior-name&gt;} is not the name of the behavior given
in the behavior specification, and if it is not the name of a behavior
already presently instantiated by the helm, the helm interprets this
as a request to spawn a new behavior, if templating is enabled.
Templating is enabled by including the following component in the
behavior specification:

\prevblue
\begin{verbatim}
   templating = &lt;templating-mode&gt;
\end{verbatim}
\postverb

\noindent
The \var{&lt;templating-mode&gt;} may be set to either \var{"disallowed"}
(the default), \var{"clone"}, or \var{"spawn"}. In the \var{"clone"}
mode, the helm will instantiate a behavior immediately upon helm
startup.  In the \var{"spawn"} mode, the helm will not instantiate a
behavior until it receives a request to do so via the \bvar{updates}
parameter as described above. An example of a behavior configured to
allow dynamic spawning is given in Listing \ref{lst_berta_one}, taken
from the Berta example mission.

\pskip 

For a behavior configured with templating enabled in the \var{"spawn"}
mode, the helm will {\em not} spawn a behavior at the helm startup
time. However, internally it will indeed spawn such a behavior, check
that it can be found and built as configured, and then destroy it
immediately. This means that the behavior configuration found in the
\var{.bhv} configuration file must not have an invalid
configuration. It is preferable to know at helm launch time that a
behavior is misconfigured, rather than waiting for the spawning event
to occur perhaps hours into a mission and being surprised that a
critical behavior, such as collision avoidance, failed to be spawned.

%---------------------------------------------------------------------
\subsubsection{Behavior Completion and Removal from the Helm}

All behaviors, whether statically spawned upon helm startup, or
dynamically spawned during the mission, are capable of dying and being
removed from the helm. Death and removal are part of the consequences
of a behavior entering the \var{completed} state. Behavior run states
were discussed in Section \ref{sec_run_states}. A completed behavior
configured with \bvar{perpetual}\bsvar{=true} will not die upon
completion. Once a behavior dies, its name is removed from the helm's
internal registry of currently-spawned behaviors and a new behavior by
the same name may be spawned at a future time.


%---------------------------------------------------------------------
\subsubsection{Example Missions with Dynamic Behavior Spawning}

Two example missions are provided that demonstrate the workings of
dynamic behavior spawning, The Echo mission in Section
\ref{exmissions_s5}, and the Berta mission in Section
\ref{exmissions_m2}. The Echo mission involves a single vehicle with
its helm configured to spawn dynamic behaviors of the type
\var{BHV\_BearingLine}. These behaviors do nothing more than post a
viewable line segment to the \app{MOOSDB} between ownship and a point
in the operation area. The interesting thing about this example is
that the mission is configured with an event script (via
\app{uTimerScript}) to automatically cue the spawning of 5000
behaviors over about one hour. Each behavior has a random duration of
less than a minute, so behaviors are spawning and dying quite rapidly
with visual confirmation via the viewable line segments.

\index{uTimerScript!Example Usage}
\pskip

The second example mission, the Berta mission, involves two vehicles
that are loitering near one another. Periodically their loiter
assignments are randomly altered (again through \app{uTimerScript}).
The change in loiter locations repeatedly puts them on an
unpredictable and random near-collision course and each vehicle needs
to spawn a collision avoidance behavior.  The interesting thing about
this scenario is that the behavior, the \var{BHV\_AvoidCollision}
behavior, is an actual behavior of common use, unlike the
\var{BHV\_BearingLine} behavior used in the Echo mission. This example
also uses the \app{pBasicContactMgr} to coordinate the receiving of 
contact reports with helm behavior spawning.

%---------------------------------------------------------------------
\subsubsection{Examining the Helm's Life Event History}
\index{Life Events}

Behavior spawning, and behavior completion and removal from the helm,
are two types of {\em life events} the helm takes note of and posts in
the MOOS variable \mvar{IVPHELM\_LIFE\_EVENT}. A third type of life
event occurs when a behavior spawning is aborted due to either a
syntax error or a name collision. Monitoring life events at run time
is possible by scoping on the variable \mvar{IVPHELM\_LIFE\_EVENT}
with either \app{uXMS} or \app{uMS}. A better method is available via
the \app{uHelmScope} application. It automatically registers for the
\mvar{IVPHELM\_LIFE\_EVENT} variable and will generate a formatted
report like that shown in Listing \ref{lst_life_events}. In the
post-mission analysis phase, the \app{aloghelm} application may be
used to examine the life event history and will generate the same
formatted report from a given alog file.

\vspace{0.25in}
\begin{listing}{A Life Event History generated with either the uHelmScope or aloghelm utilities}
\label{lst_life_events}
\footnotesize
\begin{verbatim}

 1        ***************************************************
 2        *        Summary of Behavior Life Events          *
 3        ***************************************************
 4  
 5  Time    Iter  Event  Behavior      Behavior Type       Spawning Seed             
 6  ------  ----  -----  ------------  ------------------  ----------------------------
 7   47.84     1  spawn  loiter        BHV_Loiter          helm startup                
 8   47.84     1  spawn  waypt_return  BHV_Waypoint        helm startup                
 9   47.84     1  spawn  station-keep  BHV_StationKeep     helm startup                
10  101.79   218  spawn  avd_henry     BHV_AvoidCollision  name=avd_henry#contact=henry
11  161.20   423  death  avd_henry     BHV_AvoidCollision                              
12  297.07   969  spawn  avd_henry     BHV_AvoidCollision  name=avd_henry#contact=henry
13  351.80  1159  death  avd_henry     BHV_AvoidCollision                              
14  461.37  1599  spawn  avd_henry     BHV_AvoidCollision  name=avd_henry#contact=henry
15  516.51  1795  death  avd_henry     BHV_AvoidCollision                              
16  644.94  2311  spawn  avd_henry     BHV_AvoidCollision  name=avd_henry#contact=henry
17  704.31  2517  death  avd_henry     BHV_AvoidCollision                              
18  730.02  2620  abort                BHV_AvoidCollision  name=avd_henry#foo=bar  
19  825.17  3002  spawn  avd_henry     BHV_AvoidCollision  name=avd_henry#contact=henry
\end{verbatim}
\end{listing}
\normalsize

\index{uHelmScope}
\index{uHelmScope!Life Event History}
\vspace{0.15in}

The life event history shown in Listing \ref{lst_life_events} was
taken from the Berta example mission, the "gilda" vehicle, described
in Section \ref{exmissions_m2}. The time-stamp reported in column one
is the elapsed time between the event and the time of the helm's
startup.  The first three events, in lines 6-8, reflect the three
static behaviors spawned when the helm was launched, in first
iteration of the helm. The collision avoidance behavior was spawned
each time (lines 9, 11, 13 etc.) the vehicle "henry" came within
sufficiently close range. Each time the "henry" vehicle passed and
opened range to a sufficient amount, the collision avoidance behavior
completed and died (lines 10, 12, 14, etc.). Line 17 shows an example
of an aborted spawning. This was brought about purposely by poking the
\app{MOOSDB} with the Spawning Seed shown for that line. Since the collision
avoidance parameter does not have a parameter "foo", the spawning
failed.

\pskip

Accessing the life event history via \app{uHelmScope} may be done
by launching the scope with the vehicle's mission file, and hitting
the \var{'L'} key to toggle into the life event history mode. Or
one may launch the scope directly into this mode via:

\vspace{0.1in}
\begin{consoleverb}
 uHelmScope --life targ_gilda.moos}
\end{consoleverb}
\vspace{0.1in}

\noindent
The same summary may also be accessed after mission completion via the
log files:

\vspace{0.1in}
\begin{consoleverb}
 aloghelm --life gilda.alog
\end{consoleverb}
\vspace{0.1in}

\noindent
Note that perhaps not all life events will be displayed when using
\app{uHelmScope}, depending on when it is launched relative to
\app{pHelmIvP}. When \app{uHelmScope} connects to the \app{MOOSDB} it
will only receive the latest and all following posts to the variable
\mvar{IVPHELM\_LIFE\_EVENT}. If \app{uHelmScope} connects after
\app{pHelmIvP} is launched and put into drive, it may have missed
older postings. The initial spawning events do not occur in the helm
until the helm enters the \var{DRIVE} state. (See Section
\ref{sec_helm_state} about helm state). In the example in Listing
\ref{lst_life_events}, the helm apparently was in the \var{PARK} state
for about 48 seconds before it was put into drive and began to execute
its first iteration. The full event history should always be
accessible via the log file however.

</pre></body></html>