**HET Flight Software**

Design Notes and User's Guide

T. Nolan

December 27, 2004

# How to Use This Document

This document has two purposes. First, it serves as a reference for the
HET and SIT flight software systems. In this regard, the document sets
forth the general architecture of the flight software and describes the
major subsystems -- command and telemetry -- in detail. The reference
material is designed to help the HET and SIT science teams understand
the information delivered by the instruments. Second, this document
describes the components of the flight software and shows how they fit
together. This information is designed to assist in the maintenance of
the flight software, from editing the code to rebuilding the binary
images.

Those seeking a general description of the flight software should
consult Sections 3 (Architecture), 4 (Commanding) and 5 (Telemetry).
Section 6 (Status Indicators) describes the telemetry items created in
the flight software (as opposed to items read from hardware or computed
according to external specifications).

Those seeking to modify or rebuild the flight software should review
Section 2 (Hardware Description) and consult Sections 3-5 to aid in
understanding the flight code. In addition, the listing file created by
the assembler (\*\*\*.lst) contains absolute addresses in RAM that may
be important in testing and debugging, even in flight (via the "peekw"
and "modw" commands). Section 7 lists the source files that contain the
various flight software components and gives the procedures for
assembling them and creating the flight software images. Several custom
tools are used in this process, which are also described in Section 7.

# Hardware Description

This section describes the hardware environment in which the flight
software operates. The flight microprocessor is the GSFC customized
CPU-24 version of the P24 processor. This processor is implemented in a
gate array, which also contains glue logic and timing for the flight
digital electronics. The CPU has a 24-bit word length, 32 arithmetic and
logic instructions, and 32 input/output instructions.

The CPU has local RAM. However, it has no permanent program storage. At
power-on, the CPU begins executing a small hardware-based boot routine,
which receives program code over the serial port. The program code is
stored in sequential words in RAM. After the program download is
complete, the CPU transfers control to the start of the program at
address 1.

The program code for HET and SIT is stored in EEPROM in SEP Central.
After power-on, SEP Central sends the entire program load, including
code and initialized data, to the CPU using the serial boot protocol.

The CPU has three major interfaces: a bidirectional serial port for
commanding, a unidirectional serial port for telemetry, and a customized
interface to the detector digital electronics for event handling. The
two serial ports are connected to SEP Central. HET and SIT are expected
to be ready to receive commands at any time. However, transmissions from
HET or SIT take place according to a timing protocol. Information sent
by the instrument to SEP Central at the wrong time will be lost. For
outgoing information on the command port, SEP Central listens during a
\_\_\_\_\_\_\_ second interval after it sends a command to the
instrument. This allows the instrument to return a response to SEP
Central. However, it should be noted that commands are actually executed
by HET and SIT only on one-minute boundaries. Therefore, the command
response cannot contain any results of command execution. It can only
contain command validation information.

For outgoing information on the telemetry port, the timing protocol is
based on the one-second and one-minute pulse trains. Each instrument has
a predefined series of windows in each minute in which it is permitted
to transmit telemetry information. HET and SIT transmit one complete
packet during each transmission window. After all allocated telemetry
has been delivered, the instrument sends zero-filled packets.

The third major interface, the detector command and readout system,
operates using the read and write registers of the CPU. The HET and SIT
instruments differ in the nature of the detector interface.

The one-second and one-minute interrupts are derived from SEP Central
signals. The error interrupt occurs when a stack overflow or underflow
condition is detected. This interrupt is not used in flight. Finally,
the timer interrupt is derived from a programmable timer built into the
CPU. It is used for ADC sampling.

There are two STEREO spacecraft, and each one has a complete instrument
suite including HET and SIT. The two HET instruments run identical code,
as do the two SIT instruments. However, the uploadable tables are
different for the two instrument packages. The two flight instruments
are referred to as FM1 and FM2. In addition, each instrument has an
engineering model, referred to as EM, which may have its own unique set
of tables.

# Flight Software Architecture

The HET and SIT flight software operate in a background loop with
interrupt service routines to respond to external events. On power-up, a
one-time startup section executes before interrupts are enabled and the
background loop begins executing. In nearly all of their top-level
architecture, HET and SIT are identical. Instrument-specific differences
are noted in the discussion below.

## Startup Code

Both instruments follow the same startup routine. First, the interrupt
vector at address 1 is replaced with a pointer to the interrupt 0
service routine. The other interrupt vectors are hard-coded and loaded
at boot time. However, during the boot sequence the interrupt vector at
address 1 contains a jump to the startup code because it is used by the
boot loader to transfer control to the program after booting.

Next, the packed table image is located, and the tables are unpacked and
relocated to their working locations. Before unpacking and expanding the
tables, the entire table are is filled with zeros. The packed table
image begins on the next 128-word boundary after the end of the program
code. Each packed table begins with a three-word header, which contains
(in order) the destination or working address, the number of words in
the expanded image, and the compression type (one, two, or three bytes
per word). Armed with this header information, the flight software
expands and copies the table to its correct destination. Each subsequent
packed table image also begins on a 128-word boundary, and the table
expansion process continues until an invalid address (-1) is found in
the first header word.

Next, the "BSS" area (a term from C meaning the uninitialized static
data) is set to zero. Next, any variables whose values need to be
non-zero at startup are initialized. The four queues for the command
receiver, command transmitter, telemetry transmitter, and raw events are
set up. Next, the event detection front-end system and other hardware is
initialized, and the science data processing routines are initialized.
Finally, interrupts are enabled and control is transferred to the
background routine. At this stage, the interrupts corresponding to the
two serial port transmitters are not enabled. For each serial port, a
queued output system is maintained, and the transmitter interrupt is
enabled only when there are bytes in the queue ready to be transmitted.

## Interrupt Handling

The CPU24 design can handle 11 prioritized interrupts, of which the HET
and SIT flight software use the first 8. Interrupt 0 is the highest
priority, and interrupt 7 is the lowest priority. Interrupt service
routines execute with interrupts disabled, so the priority mechanism
only comes in to play when more than one interrupt is pending at one
time. The following table lists the interrupt assignments.

  ---------------- ------------------------------------------------------
  int 0            UART #1 (command) receiver data ready

  int 1            UART #1 (command) transmitter buffer empty

  int 2            UART #2 (telemetry) transmitter buffer empty

  int 3            event interrupt

  int 4            one second interrupt

  int 5            one minute interrupt

  int 6            stack problem

  int 7            timer
  ---------------- ------------------------------------------------------

The flight software uses two different interrupt entry-exit schemes.
Each interrupt service routine begins with a call to "EnterISR" or
"EnterISRAlt," reflecting the simple entry-exit scheme or the alternate
scheme. Both of these entry functions save the A register and the carry
flag on the return stack, and rearrange the return stack so that when
the ISR executes a "ret" instruction control is transferred to "ExitISR"
or "ExitISRAlt," respectively. Then the entry function returns and
control is transferred to the next instruction of the ISR.

EnterISRAlt performs an extra step. Before returning control to the ISR,
it saves the current interrupt enable mask on the R-stack, and then
enables only interrupt 0 (the receive character interrupt), returning
with interrupts enabled. It does this so the receive character interrupt
is not disabled for any length of time. The character receiver,
operating at 56K baud, can interrupt at a sustained rate of 5 kHz.
EnterISRAlt also enables the stack problem interrupt, so the software
can catch a stack error as early as possible.

An ISR using the EnterISR scheme executes with interrupts disabled. The
ISR and any called routine may change the interrupt mask (enable or
disable individual interrupts) but it cannot set the global interrupt
enable bit. When ExitISR regains control (ISR issues a ret instruction),
it implicitly sets the global interrupt enable bit by executing an rti
instruction.

The situation is more complex with the EnterISRAlt scheme. In order to
re-enable certain interrupts during the ISR, EnterISRAlt returns to the
calling ISR with an rti instruction and the global interrupt enable bit
turned on. The interrupt mask has been set to allow only the restricted
interrupts. However, ISR code may need to enable or disable further
interrupts. The problem is to recognize which interrupts have been
enabled or disabled by the ISR code, and whether to give effect to those
changes. The solution chosen for this implementation is to permit the
ISR code only to enable the telemetry UART transmitter output interrupt.
Both the one-second and one-minute ISRs need to decide whether to begin
transmitting telemetry, and this scheme permits them to do so.
Accordingly, when ExitISRAlt regains control (ISR issues a ret
instruction), it combines the telemetry UART transmit enable bit with
the saved interrupt state using an OR operation, and returns to the
point at which the interrupt occurred.

## Background Processing

The flight software operates on a simple foreground-background
principle. The background loop is performed continuously, and
interrupted by one of the prioritized interrupts described above.
Interrupt processing is self-contained as much as possible, so there
does not have to be any background-level processing after an interrupt
is dismissed. However, several of the interrupt service routines may set
flags that are tested and reset by the background routine.

Background tasks fall into three categories: continuous, once per
second, and once per minute.

***Continuous background processing.*** On a continuous basis, the
following tasks are performed:

-   Test for special diagnostic commands (push, dup). These commands can
    be used to estimate the stack depth of the return stack and the
    parameter stack, respectively, during flight software operation.
    They are destructive, however, and will eventually cause the system
    to crash.

-   Check H1 event queue, dequeue 1 event if non-empty, process event

-   Check stopping event queue, dequeue 1 event if non-empty, process
    event

-   Check penetrating event queue, dequeue 1 event if non-empty, process
    event

-   Check for and process any queued characters at command serial port.
    This is the first step of the command processing, in which incoming
    characters are deqeued and buffered into complete commands. When a
    complete command is detected (by the newline or return terminator),
    it is syntax checked and placed in a second-level queue. A command
    that does not pass the syntax check is not queued, and an error flag
    is set.

-   In immediate mode, check for and process any completed and queued
    commands. Normally the immediate mode flag is off, and commands are
    dequeued and processed only at major-frame time.

-   Handle delayed telemetry flag. This flag is set if the major frame
    (one-minute) sync pulse is detected during the transmission of a
    packet. This happens only because HET is required to send empty
    packets to SEP Central throughout the one-minute cycle. The flag is
    set at the end of the packet transmission, and the major frame
    processing is called from the background instead of from the
    one-minute interrupt service routine.

-   Check for and handle clock gating. When enabled (clkgating == 1),
    the processor clock will be turned off at the end of the continuous
    background loop, but only if all three particle queues were empty.
    The reason for this further check is that if any queue has more than
    one event, it could be never emptied if the clock is only restarted
    when the next event arrives.

***Once per second background processing.*** The one-second (minor
frame) sync pulse causes an interrupt once per second. The interrupt
processing is described elsewhere. The interrupt service routine sets a
flag to let the background routine know it has executed. The background
loop checks and clears this flag, then if it was set performs the
following tasks:

-   Test for command timeout. When the first character of a command is
    received, a counter is started and incremented once per second. If
    it reaches a count of 300 (5 minutes) before a complete command is
    received and processed, the partial command is discarded and an
    error flag is set.

***Once per minute background processing.*** Similarly to the one-second
flag, the one-minute flag is set by the minute sync interrupt service
routine. The background loop checks and clears this flag, and if it was
set performs the following tasks:

-   Start next sweep of 4 ADC channels. Each ADC reading is taken
    through a software rundown. The individual steps in the rundown are
    triggered by the clock interrupt. Once the sweep is started, all 4
    ADC channels will be set and run down and the results placed in
    memory. This process will be completed before the next one-minute
    sync, and the digitized results from this sweep will be placed in
    the next frame.

## Event Handling

The following tables define the raw and compressed event data formats.
Raw events are read out from the PHASIC hardware. The event readout
takes place in the event interrupt service routine. Hardware readout
continues until the last event word is read, signaled by a 1 in the Tok
bit. The Stim bit is not set by the PHASIC. Instead, the software
recognizes a stimulus event through a separate register, and sets or
clears the Stim bit based on that indicator flag.

Raw events are assigned to queues based on event category. Once the raw
event is placed in the appropriate queue, the interrupt-level event
processing is complete.

  --------- ----------- ------ ------------ ------ -------- ---- ---------------
  **Raw                                                          
  Event                                                          
  Format                                                         
  (23                                                            
  bits)**                                                        

  23        22-20       19     18-15        14     13-12    11   10-0

  Tok       ChipAdd     Stim   PhaAdd       Gain   Rsvd     Ov   PH
  --------- ----------- ------ ------------ ------ -------- ---- ---------------

  ----------------- -----------------------------------------------------
  Tok               Token bit, set to 1 on last PH of event

  ChipAdd           Chip address, 0 or 1 in HET system

  Stim              Stimulus event, set in software

  PhaAdd            Pha address (ChipAdd + PhaAdd uniquely identify
                    detector)

  Gain              High/low gain

  Rsvd              Reserved, unused

  Ov                Overflow bit

  PH                Pulse height
  ----------------- -----------------------------------------------------

The background routine examines the event category queues and processes
queued events in round-robin fashion. Processed events are compressed
from 23 to 16 bits, and a header word (16 bits) is prefixed. The
software counter bin number is assigned and attached in the event
header. The event also has the number of event words, because the token
bit was dropped in the compression.

The chip address and pha address read out of the PHASIC hardware are
combined into a single 3-bit detector number in the compressed event.
There is a lookup table, ADDR_TAB, which contains 32 entries (16 entries
x 2 PHASIC chips). Each entry is either 16 (no assignment) or the PHA ID
number 0-6 associated with the given chip address/pha address
combination. The lookup table is uploaded and unpacked with the initial
flight software table load.

  ---------------------- ---------- --------- ----------------------------
  **Compressed Event                          
  Format (16 bits)**                          

  15-13                  12         11        10-0

  PhaID                  Gain       Ov        PH
  ---------------------- ---------- --------- ----------------------------

  ------------ ----------------------------------------------------------
  PhaID        Pha ID number: 0=H1i, 1=H1o, 2=H2, 3=H3, 4=H4, 5=H5, 6=H6,
               7=Invalid

  Gain         High/low gain setting

  Ov           Overflow bit

  PH           Pulse height
  ------------ ----------------------------------------------------------

  --------------- ---------- --------- ----------------------- ------------
  **Compressed                                                 
  Event Header                                                 
  (16 bits)**                                                  

  15-13           12         11        10-3                    2-0

  Cat             Mode       Stim      SW Bin                  PH Cnt
  --------------- ---------- --------- ----------------------- ------------

  ------------ ----------------------------------------------------------
  Cat          PH category

  Mode         HET rate mode

  Stim         Stimulus event flag

  SW Bin       Software counter bin number 0-107

  PH Cnt       Number of compressed event words to follow
  ------------ ----------------------------------------------------------

# Flight Commanding

All commands are received from SEP Central over the bi-directional
serial port. The transmission scheme is asynchronous,
character-by-character. The baud rate is 57600. After the transmission
of a command string is completed, SEP Central listens on the same
command port for \_\_\_\_ milliseconds. This is the window in which
HET/SIT must transmit a response. The command response is a printable
ASCII string. The response provides confirmation that the command was
received, and permits a determination in which major frame the command
will be executed. After the response, the flight instrument issues its
prompt (either "HET\>" or "SIT\>"). SEP Central collects responses and
prompts from all instruments and multiplexes them into packets that it
transmits as part of its own telemetry stream.

Commands may be received by HET or SIT at any time, but they are
normally executed only on major frame boundaries. This strategy helps
preserve the integrity of each major frame. However, certain commands
are executed immediately, and an immediate mode is available in which
all commands are executed as they are received. In normal
(non-immediate) mode, commands are executed after the telemetry packets
are built from the previous frame's data and before events are reenabled
for the next major frame. That is, the following sequence of events
occurs at the end of each major frame:

-   Events are disabled

-   Telemetry is formatted for transmission during the next major frame

-   Event counters are cleared for next major frame

-   Commands that arrived during the previous major frame are executed
    in the order in which they were received

-   Events are reenabled.

The flight software maintains a circular queue of incoming characters.
The arrival of a character at the bi-directional serial port triggers
the highest-priority interrupt in the flight processor. The interrupt
service routine simply reads the character from the serial port and
writes it to the incoming character queue. No interpretation is done at
this stage. The queue can hold 2048 characters. The interrupt is
dismissed after this short service routine.

The background routine regularly checks the incoming character queue.
When a character is present, it is dequeued and passed to a finite-state
machine. The task of the finite-state machine is to accumulate and
recognize complete commands, issue a response to SEP Central when a
command is complete, and place completed commands in another queue for
execution at the next major frame. The command response is issued at the
time the command is placed in this second-level queue, which generally
occurs after only a very short delay from when the last character is
received. No response is issued when the command is actually executed
(SEP Central would not be listening at that time anyway). If a command
is not executed due to an error at execution time that was not detected
during the preprocessing step, a software error flag is set. The command
that caused the error can be identified by examining the "command
processing error" bit flags. The 16 bits in this variable, numbered from
least significant to most significant, correspond to the sequence
numbers of the commands received during the previous major frame. Each
bit is set to 0 or 1 if the set if the corresponding command was
executed correctly or caused an error, respectively.

Commands that are sent to SEP Central for execution by HET or SIT are
preceded by an identifier that informs SEP Central which instrument the
command is destined for, and whether the command is ASCII or binary.
These command keywords \-- "HET-CMD" and "HET-BIN" for HET, and
"SIT-CMD" and "SIT-BIN" for SIT \-- which precede any sequence of
commands routed through SEP Central, are interpreted by SEP Central and
not passed through to the instrument. However, in order to maintain
compatibility during instrument testing, these commands actually are
recognized by HET and SIT respectively and treated as a no-op, with no
echo. Therefore, if they are inadvertently sent directly to the flight
instrument there will be no error.

Command syntax is very simple. Each command consists of a mnemonic
keyword followed by zero or more numeric arguments. The complete list of
valid keywords for HET and SIT is set forth in the tables at the end of
this section. All numeric arguments are interpreted as hexadecimal
numbers (e.g., the parameter "10" means the number 16). Valid characters
for numeric arguments are 0-9, a-f, and A-F. Commands must end with
either a carriage return or a line feed (ASCII 0x0d or 0x0a).

The flight software performs minimal command syntax checking. You should
not rely on the flight software to screen invalid commands. A few
general rules for processing invalid commands can be stated. A command
mnemonic with extra characters at the end will be interpreted as though
the characters were not present (i.e, "immediate" and "immed1" are the
same as "immed"). A command with too few arguments will be interpreted
as though zero-valued arguments were appended to the command to fill the
missing arguments (i.e., "immed" is the same as "immed 0"). A numeric
argument with a non-numeric character (i.e., other than 0-9, a-f, A-F)
will be interpreted by discarding the bad character and any characters
that come after it. Commands with arguments that are out of limits are
unpredictable. In some cases, most-significant bits will be discarded,
but this is not always the rule.

## ASCII Command Processing

Except for binary commands (described below), all commands are in
printable ASCII. They may be terminated by either a carriage return (13)
or a newline (10). The command state machine recognizes a complete
command when one of these two characters is received. It then performs
command preprocessing. The command preprocessor takes the following
steps:

-   If the command string is empty (only a carriage return or newline
    received), then the instrument prompt is sent over the serial port
    to SEP Central.

-   If the command is one that requires immediate execution, it is
    dispatched to the command handler. Immediate execution commands are
    peekw, immed, load, and dump.

-   If the command string starts with a valid command keyword, then it
    is queued for later execution, and a command echo is sent, followed
    by the instrument prompt, both over the serial port.

-   If none of the above is true, an error message is sent and the
    prompt is issued.

For valid commands, the command echo consists of a 4-digit identifier
number (in hex) followed by a copy of the command string. The first four
digits of the identifier number are the current 16-bit major frame
number, and the second two digits are the command sequence number that
is reset to zero in each major frame. After the identifier, the command
string is echoed as it was received. (The "cmdstr" command has a special
echo to avoid repeating the entire 108-character string. In this echo,
the 108-character string is replaced by three dots.) The command echoes
can be parsed to verify in which major frame each command arrived.
Commands that are tagged with major frame N will have been executed
before the start of major frame N+1.

In immediate execution mode (immed 1), commands are queued for
processing, but they are pulled off the queue and executed immediately
instead of waiting for a major frame. The command echo contains an
asterisk inserted between the identifier number and the command echo.
This asterisk serves as a reminder that the command is executed
immediately instead of delayed until major frame time.

Two commands, "immed" and "load," always generate an immediate-style
echo with the asterisk following the identifier number. These commands
are always executed when they are received, without waiting for a major
frame. The operation of the "load" command is described further in the
section on binary command processing.

When a command does not begin with a recognized keyword, an error
message is sent, consisting of the received command followed by a
question mark. No identification number is sent in this case.

The final portion of the command echo is the instrument prompt, which is
sent in all cases (delayed command, immediate command, or error).

Several examples of command echoes follow.

  -------------------- --------------------------------------------------
  000901 phacont 0 1 f Command received in major frame 0009, will be
                       executed before the start of frame 000A.

  000902 phacont 0 2 f Command received in major frame 0009, will be
                       executed after previous command.

  000A01 \* immed 1    Immed command itself is always executed
                       immediately.

  000A02 \* phacont 0  Command received in major frame 000A, executed
  5 f                  immediately.

  000A03 \* immed 0    Immediate mode is off for future commands,
                       including any received in this frame.

  phaconf 0 7 f?       Syntax error in command, sequence number not
                       incremented. An error flag will be set in frame
                       000B.

  000A04 phacont 7 f   Command is missing a parameter, but nevertheless
                       it is executed at the start of frame 000B. First
                       parameter is interpreted as 1 (only 0 and 1 are
                       allowed), second as f, third parameter is
                       interpreted as zero.

  000A05 lgorsel 0 3 0 Second parameter is illegal, but the error will
                       not be recognized until the command is executed.
                       An error flag will be set in frame 000B and the
                       command will be discarded.
  -------------------- --------------------------------------------------

## Binary Command Processing

The general scheme for binary command processing requires two steps:
first, load a binary table into memory; second, issue an ASCII command
to activate the table by copying it to the appropriate memory location
and uncompressing it if necessary. The first step requires sending one
or more "binary" commands to the instrument. These commands allow the
efficient delivery of binary data from the ground to the instrument. The
flight software accepts the binary data as a byte stream, buffering it
in memory with no interpretation. Once the binary data has been
transmitted, a subsequent ASCII command is necessary to interpret and
activate the table. The ASCII command causes the flight software to copy
the buffered byte stream to a specified memory address, which
corresponds to a known table location. The binary data is optionally
unpacked, either one or two bytes per table word. The following
subsections describe these two steps in detail.

### Loading Binary Data

A binary command consists of an ASCII introducer followed by a binary
load package. The introducer is the ASCII command keyword "binary." This
introducer is followed by a carriage return or line feed, just like an
ASCII command. Binary commands do not go through the preprocessing
described above. Instead, when the state machine recognizes the binary
introducer keyword, it prepares to receive a binary load package.

The binary load package contains a two-byte length, which is the number
of bytes to follow (including checksum), then the command bytes
themselves, then a two-byte checksum. Two-byte numbers are transmitted
most-significant byte first. The checksum is the 16-bit sum of all of
the 8-bit command bytes. The following table depicts the binary load
package format.

  ----------------- -----------------------------------------------------
  0                 Length msb

  1                 Length lsb

  2, . . ., N-1     N-2 command bytes, where N = Length

  N                 Checksum msb

  N+1               Checksum lsb
  ----------------- -----------------------------------------------------

When the finite-state machine recognizes the "binary" command
introducer, it does not dispatch it to the command preprocessor as it
would for an ASCII command. Instead, it enters a series of states to
receive the length, the command bytes, and the checksum. The binary
command load is placed in a large memory buffer (the binary command load
staging area).

When the two-byte checksum is received, the binary command payload is
finished. An echo is sent in one of the following two forms:

binary A:aaaaaaaa N:nnnnnnnn OK

or

binary A:aaaaaaaa N:nnnnnnnn ckserr cccccccc dddddddd

If the computed checksum matches the received checksum, the OK echo is
sent. The number following the "A:" is the relative address (i.e., the
byte number within the command load staging area where the binary
command payload was placed), and the number following the "N:" is the
number of bytes in the command payload. If the checksums do not match,
then the ckserr echo is sent, followed by the received checksum and then
the computed checksum.

When large tables are uploaded, multiple "binary" commands are generally
sent before the ASCII command is issued to activate the table. One of
the reasons for breaking up large tables into multiple segments is to
avoid having to reload the entire table when a checksum error occurs. To
accommodate the receipt of multiple binary packages, the flight software
appends the data in each successive binary command payload is to any
data already in the command load staging area. The command echo verifies
that this is the case: in each successive echo the address will be
incremented by the length of the previous load.

When a command load checksum fails, the relative address for the next
load package is still incremented as though the load package were
received correctly. This is done so that a large number of command loads
may be transmitted, the resulting command echoes examined, and only
those loads that were not received correctly may be retransmitted.
Because of this, there needs to be a mechanism to reset the relative
address for a retransmitted command packet. In the absence of such a
mechanism, a retransmitted packet would be appended to the command load,
not inserted in the middle. This is the purpose of the "loadat" command.
The retransmission of a failed command packet must be preceded by a
"loadat" command, in order to specify the location at which the
retransmitted packet is to be inserted. The "loadat" command simply
specifies the relative address for the next command load. The correct
relative address can be extracted from the command echo corresponding to
the failed command load.

### Activating the Binary Load

A complete binary command load ordinarily consists of one or more
"binary" commands with binary payloads, followed by a single ASCII
command which may be either "load," "dload," or "loadn." The ASCII
command instructs the flight instrument to copy the binary load from the
command load staging area to a specific address in memory, which is the
absolute address of the table or memory area that is the ultimate
destination of the command load (its target address).

The "load" version of the ASCII command is used when the initial table
set is sent to the instrument after power-up, when multiple tables are
being sent in succession, and whenever the precise timing of the table
activation is not critical. The "load" command always executes
immediately (regardless of the "immed" flag). The reason for this is
that when multiple tables are to be sent to the instrument, delaying the
load operation could cause the binary data in the staging area to be
overwritten by the next command load, corrupting the process. By forcing
immediate execution, the integrity of each binary table can be assured.

The "dload" version of the ASCII command is syntactically identical to
the "load" command, but its execution is delayed until the next major
frame boundary. (Note that if immediate mode is on, the "dload" command
executes immediately and becomes synonymous with the "load" command.)
The reason for a delayed load is to avoid having to discard a major
frame that was processed with both old and new tables. Therefore, when
it is necessary to replace a table during instrument operation, the
"dload" command should be used to activate the table.

The "loadn" version of the ASCII command accepts an additional
parameter, which is the number of bytes that should be transferred from
the staging area during the table activation. This version of the
command should be used only when a non-standard binary upload sequence
occurred. Normally, the flight software knows how many bytes were
received during the binary upload phase, and that is the number of bytes
that will be copied to the active table by a "load" or "dload" command.
However, when a checksum error occurred on one packet of a large
sequence and that packet was retransmitted, the flight software loses
count. The "loadn" version can be used in this case to transfer the
entire table.

The "load" and "dload" commands accept two parameters. The first
parameter is the absolute address at which the uploaded binary data is
to be placed in order to activate the table. The absolute addresses of
the various HET and SIT tables are set forth in the tables below. The
second parameter is the copy method. There are three copy methods,
corresponding to the values 0, 1, and 2 for this second parameter. Load
type zero (24-bit words) packs three bytes into each word at the target
address. Bytes are packed msb, middle, lsb. The number of words in the
table that is actually loaded at the target address is n/3, where n is
the number of binary command bytes sent during the preceding binary
commands. Load type 1 (1 byte per word) copies one byte per word to the
target address. The two most-significant bytes of each target word are
set to zero. The number of words at the target address is equal to the
number of bytes uploaded. Load type 2 (2 bytes per word) packs two bytes
into each word at the target address. Bytes are packed msb, lsb (the
most-significant byte of each 24-bit word at the target address is set
to zero). The number of words in the table that is actually loaded at
the target address is n/2, where n is the number of binary command bytes
sent.

Load types 4, 5, and 6 define a byte-oriented, run-length encoding with
various overlay options. Load type 4 loads successive bytes of the table
into the least-significant bytes of successive words in memory, without
affecting the other bytes. Load type 5 loads successive bytes into the
middle bytes of successive words, again without affecting other bytes.
Load type 6 loads successive bytes into the most-significant bytes of
successive words without affecting other bytes. In this manner, three
different one-byte tables can be loaded into the same area of memory.

Through appropriate use of the load type parameter, some measure of
table compression can be achieved. When each table location contains
only one byte (i.e., values range between 0-255), only the one-byte
values need to be uploaded to the instrument. The table is then
activated using load type 1, and the byte values are expanded to 24-bit
words at the target memory location. Similarly, load type 2 can be used
for tables that contain at most 16-bit values. Load types 4, 5, and 6
have the potential to achieve a high degree of compression.

For the "load" and "dload" commands, the number of bytes transferred to
the target address is determined by the preceding binary command
sequence. All bytes sent and received during the immediately preceding
binary command load sequence (which may consist of one or more
individual command loads) are copied into the target load address using
the specified load method. If the number of bytes is insufficient to
fill out the last target word (for example, if an odd number of bytes
were received and the load method is two bytes per word), the last word
in the target area will have zeroes in the extra byte positions. The
"loadn" command accepts an additional parameter -- the number of bytes
to transfer -- and otherwise operates just like the "load" command. (If
the byte count on the "loadn" command exceeds the number of uploaded
bytes, the remainder will be undefined.)

After a "load," "dload," or "loadn" command, the flight software resets
the relative address within the binary command staging area to zero in
preparation for the next command load. When a "load" command is sent
with a target address of zero, the command has the effect of forcing the
relative address to zero, but no data are transferred. It would be good
practice to issue a "load 0" command before beginning any binary load
sequence because the "binary" commands rely on the flight software's
internal pointer mechanism.

The following command sequence illustrates the concepts described above
to load a 1024-word table, where each word is 3 bytes.

  ---------------- ----------------------- -------------------------------
  **Command**      **Response**            **Comments**

  load 0           0100 \* load 0          Reset load address, prepare for
                                           binary load

  binary                                   ASCII command, followed by CR
                                           or NL

  \[length=1026,   Binary A:000000         Binary payload, length includes
  1024 data bytes, N:000400 OK             2 checksum bytes
  checksum\]                               

  binary                                   ASCII command

  \[length=1026,   Binary A:000400         Second portion of binary
  1024 data bytes, N:000400 OK             payload
  checksum\]                               

  binary                                   ASCII command

  \[length=1026,   Binary A:000800         Third portion of binary payload
  1024 data bytes, N:000400 OK             
  checksum\]                               

  dload 7000 0     0101 dload 7000 0       Transfer binary command load to
                                           absolute address 7000 (hex), 3
                                           bytes per word at major frame 2
  ---------------- ----------------------- -------------------------------

## Command List

This section lists the HET/SIT common commands, the instrument-specific
commands, and the table load addresses. All commands are case-sensitive
\[THIS MAY CHANGE\]. All numeric arguments must be supplied in
hexadecimal. A missing argument or a non-numeric argument will be
interpreted as the number zero.

  --------------- -------------------------------------------------------
  **Common        **Description**
  Command**       

  tmode N         Set telemetry mode. N=0...5. See description above
                  under Telemetry System.

  modw A N        Modify word at address A to value N.

  peekw A         Examine word at address A.

  binary          Receive binary command load package. Note that this
                  command is generated automatically by SEP Central when
                  a HET-BINARY package is received.

  immed N         Immediate command execution mode on (1) or off (0).
                  Default for flight: immed off (0).

  gwrite R N      Write value N to G-bus register R. \[THIS MAY
                  DISAPPEAR\]

  load A T        Transfer binary command load to address A using load
                  method T (0=W24, 1=B, 2=W16). The number of bytes
                  transferred is equal to the maximum relative address
                  written since the last load or loadn command. This
                  command is always executed immediately, and not delayed
                  until the next major frame. The "dload" version of this
                  command is to be used for delayed execution.

  dload A T       Same as load, except execution of the command is
                  delayed until the next major frame. The "dload" version
                  should be used to replace a table while the instrument
                  is operational, to avoid corrupted major frames
                  processed partially with the new table. The "load"
                  version should be used for initial table loads to avoid
                  overrunning the table buffer.

  loadn N A T     Transfer N bytes from binary command load staging area
                  to address A using load method T (0=W24, 1=B, 2=W16).

  loadat A        Set relative address to A for next binary command load.
                  A is a byte number starting from zero within the
                  current table.

  cgate N         Turn clock gating on (1) or off (0).
  --------------- -------------------------------------------------------

  --------------- -------------------------------------------------------
  **HET Command** **Description**

  cmdstr N S      Command PHASIC N to string S. N=0, 1. S is 108 hex
                  bytes long, representing left-justified 846-bit bit
                  string.

  dump N          Return contents of PHASIC N (value is sent in ASCII to
                  serial port).

  testp P A B     Write 14-bit period, 9-bit DAC A and 9-bit DAC B values
                  to test pulser registers. The 9^th^ bit of each DAC
                  value is written to the respective DAC range bit. This
                  command stops the automatic background test pulser
                  algorithm. To resume automatic test pulser control, use
                  "testp auto" command.

  testp auto      Begin automatic background test pulser control
                  algorithm (default). This command is used after a
                  "testp" command has been sent to set manual values.

  scopesel N V    Write 9-bit value V to scope select bits, PHASIC N

  presel N V      Write 5-bit value V to preamp output mux select bits,
                  PHASIC N

  tpfbsel N P V   Test enable, test select, feedback select, PHASIC N
                  (0-1), PHA P(0-15), value V (9 bits)

  inresel N P V   Input resistor, input dac, PHASIC N (0-1), PHA P(0-15),
                  value V (16 bits)

  hgthrsel N P V  High gain threshold, PHASIC N (0-1), PHA P(0-15), value
                  V (10 bits)

  lgthrsel N P V  Low gain threshold, PHASIC N (0-1), PHA P(0-15), value
                  V (10 bits)

  phacont N P V   PHA control, PHASIC N (0-1), PHA P(0-15), value V (4
                  bits)

  lgorsel N X V   rndn-gor-X L enable, X=0,1,2, PHASIC N (0-1), value V
                  (16 bits)

  hgorsel N X V   rndn-gor-X H enable, X=0,1,2 PHASIC N (0-1), value V
                  (16 bits)

  setdac V        Set housekeeping dac to value V

  simevent N      Inject simulated events into processing system for N
                  major frames. Event values are taken from loadable
                  table. On each major frame, one pass is made through
                  the table. Note that external event interrupts are
                  still required to drive simulated event processing, but
                  the actual event contents are discarded and replaced by
                  values read from the table. Issue "simevent 0" to
                  resume normal external event processing.

  setindacs       Set all preamp leakage current balancing dacs (indac).
                  This command is not normally needed because the
                  balancing algorithm is run at startup.
  --------------- -------------------------------------------------------

  --------------- -------------------------------------------------------
  **SIT Command** **Description**

  hvenable N      Enable high voltage (N=0,1)

  eonly N         Control eonly bit (N=0,1)

  hvlevel V       Set 8-bit HV level

  toferror N      TOF error events (N=0,1)

  limhi V         Set LIMHI to 8-bit value

  junk N          Store junk events (N=0,1)
  --------------- -------------------------------------------------------

The addresses and sizes of the HET and SIT tables are set forth below.
Each table has two addresses and sizes associated with it. The first
address and size (in columns 1 and 2 below) represents the working
location of the table in flight. This address is used in the "load"
command, after new table contents have been uploaded, to copy the table
to its working location and activate the new table. The accompanying
size is the number of 24-bit words of memory occupied by the table in
its working form. This is generally equal to the number of table
entries, because for ease of access tables are organized in memory with
one entry per word.

The second address and size, listed as "packed source address" and
"packed size" (in columns 3 and 4 below) represents the original
location of the packed (i.e., compressed) version of the table within
the flight software load module. These compressed tables are stored with
the flight code in SEP Central EEPROM and uploaded to the instrument
flight computer by SEP Central during the initial boot sequence. The
packed address is never used with a "load" command to HET or SIT. The
packed tables at these addresses are unpacked and copied to their
working locations (column 1) during flight software initialization.
After they are unpacked, the packed images are discarded and overwritten
with other data. Accordingly, a table load to the "packed" address would
be disastrous. However, the "packed" addresses are used when the default
contents of a table in SEP Central EEPROM need to be replaced. For this
procedure, the new table contents are compressed by GSE software, and
the packed contents are sent to SEP Central by TBD commands. The packed
source address is the relative address in words from the start of the
HET or SIT instrument code in SEP Central EEPROM and needs to be
communicated to SEP Central by TBD commands along with the command load.
The packed size is the number of words occupied by the packed image,
including the three-word packed table header and any bytes necessary to
pad out the last word.

  ---------- --------- ---------- ---------- ------------------------------------
  **HET      **Size in **Packed   **Packed   **Description**
  Table      Words     Source     Size in    
  Address    (hex)**   Address    Words      
  (hex)**              (hex)**    (hex)**    

  18000      4000                            Software counters (128 x 128)

  1C000      1000                            Particle type (64 x 64)

  1D000      20                              Addrtab (16x2)

  1D020      10                              Offsetch (8 x 2)

  1D030      10                              C-Delta E-Log GnFctr (8 x 2)

  1D040      10                              gfctrnum (8 x 2)

  1D050      2                               C-Resid E-Log H2 GnFctr (2)

  1D052      200                             C-Delta E-Log 2

  1D252      200                             C-Resid E-Log 2

  1D452      B0                              PHASIC default fields (88 x 2)

  1D502      1000                            Simulated event list
  ---------- --------- ---------- ---------- ------------------------------------

  ---------- --------- ---------- ---------- ------------------------------------
  **SIT      **Size in **Packed   **Packed   **Description**
  Table      Words     Source     Size in    
  Address    (hex)**   Address    Words      
  (hex)**              (hex)**    (hex)**    

  7000       800                             SSDHI

  7800       800                             SSDLO

  8000       4000                            BOX_ARRAY

  C000       200                             TOFTAB
  ---------- --------- ---------- ---------- ------------------------------------

# Flight Telemetry System

The HET and SIT flight telemetry system is based on a generalized
table-driven model, allowing it to support the normal mission telemetry
format as well as a variety of alternative formats, including
accelerated data mode and expanded flight telemetry mode.

The flight telemetry data is packetized. Packet formats are described in
Reference \[N\]. Packets are fixed length, 272 bytes (11 byte header and
261-byte payload). The major frame interval is one minute, and the minor
frame interval is one second. In normal flight operations, in each major
frame, HET is allocated six science packets, one housekeeping packet,
and one beacon packet. SIT is allocated 12 science packets, one
housekeeping packet, and one beacon packet. These packets are
transmitted to the SEP Central computer according to an agreed-upon
schedule. In each minor frame, SEP Central opens a 200-millisecond
interval during which telemetry data can be transmitted over the
designated serial line. HET windows occur during every third minor frame
starting with the first minor frame after the major frame interrupt
(frame numbers 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42,
45, 48, 51, 54 and 57). SIT windows occur in every third minor frame
starting with the second minor frame after the major frame interrupt
(frame numbers 1, 4, etc.) By convention, a complete packet is
transmitted during every window, taking about 50 milliseconds. It will
be seen that there are more windows than packets. By convention, HET and
SIT send a special null packet in each unused window.

However, certain non-flight telemetry modes can be envisioned. For
example, during calibration and testing, it is desirable for HET to
transmit more telemetry than it is allocated in flight. One possibility
is simply to accelerate the major and minor frame pulses. However, this
still wastes bandwidth because there could be unused minor frames and
unused window time in each minor frame. A better solution is to transmit
more telemetry in each minor frame, and transmit during more minor frame
windows. Moreover, HET or SIT may want to take advantage of any
additional telemetry bandwith available during calibration by sending a
different sequence of packets rather than the default flight telemetry
sequence, or define new packets containing different data. Further
flexibility is desirable in case additional telemetry bandwidth becomes
available during flight because of instrument failure.

The flight telemetry system is designed to provide all the necessary
flexibility with a fairly small set of parameters. The telemetry system
is capable of allotting any amount of telemetry bandwith to the
instrument, and formatting and transmitting a variety of predefined
packet types. There are at least three ways to give HET additional
bandwidth: (1) remove the eight-packet limitation in a major frame,
allowing HET to transmit as many packets as desired; (2) remove the
every-third-frame limitation, allowing HET to transmit in every minor
frame; and (3) expand the transmission window in each minor frame from
one packet to potentially the whole second. The flight telemetry system
can accommodate all three of these axes of expansion. SIT is similarly
configurable in all three ways.

The operation of the flight telemetry system is based on a set of four
parameters: (1) the minor frame interval, (2) the number of packets per
minor frame, (3) the number of packets per major frame, and (4) the
defined packet sequence. A single telemetry mode byte is used to refer
to various combinations of these parameters that are defined on-board,
and there are certain flags and options that may be used to further
refine the telemetry format. Descriptions of the parameters follow.

***Minor frame interval.*** The minor frame interval defines how often
minor frames appear in the telemetry (in seconds). In flight operation,
this number is 3 (one minor frame every 3 seconds). It can be set to a
lower value to issue a minor frame more often. For example, during HET
integration and testing, SEP Central may be able to receive a packet
from HET during every minor frame rather than every third. Setting the
minor frame interval to 1 accomplishes this. Another variation could
occur if one or more instruments fail in flight. In that case, HET could
occupy the failed instrument's bandwidth. To accommodate all the
possibilities, the minor frame interval can be set to the special value
of zero. In this case, HET uses a table with 60 entries to determine
whether to send a packet in each respective minor frame window. The
minor frame interval must be a number between zero and 3, with zero
being a special value indicating a table lookup.

An additional flag is used in connection with the every-other and
every-third frame intervals. This flag defines whether the sequence
begins on frame 0 or 1 (for divide-by-two) or frame 0, 1, or 2 (for
divide-by-three). For example, in flight, HET transmits on frames 0, 3,
6, etc. and SIT transmits on frames 1, 4, 7, etc. The flag is set
appropriately for HET or SIT, but the rest of the telemetry system is
common to the two instruments.

***Number of packets per minor frame.*** HET normally sends a single
packet in each minor frame. The packet will either be one of the eight
defined packet types or a null packet. However, this process only uses
approximately 52 milliseconds of each 1-second minor interval (assuming
57K baud operation). To use more of the available time, the number of
packets per minor frame can be set to a value greater than 1. When HET
is connected to SEP Central, the number of packets per minor frame
cannot be greater than 4, since SEP Central only listens for 200
milliseconds. However, during HET standalone operation, there is, in
theory, time to send 19 full packets during each minor frame. However,
due to software space limitations, the number of packets per minor frame
must be between 1 and 9. At 9 packets per minor frame, and one minor
frame per second, there is enough bandwidth to transmit 765 event words
per second.

***Number of packets per major frame.*** Even though HET is allotted a
transmission opportunity in every third minor frame, it is ordinarily
not permitted to transmit a packet at every one of these opportunities,
because it is limited by its telemetry allocation. By convention, when
HET has transmitted all of its permitted telemetry allocation, it sends
null packets (which have a special predefined APID) to SEP Central in
any additional HET minor frames until the start of the next major frame.
The number of packets per major frame defines the point in the major
frame at which the instrument switches from sending HET data to sending
null packets. If the defined packet sequence runs out while there are
more HET packets to transmit in a major frame, the defined packet
sequence will be repeated as necessary to fill the desired telemetry
allocation.

***Defined packet sequence.*** The defined packet sequence defines the
packet types that are sent in each major frame. There are 20 entries but
only a maximum of 10 packets can be formatted in one sequence (the
reason for the excess will become apparent later on). The entries in the
defined packet sequence table are positive integers 1-N. A zero entry in
the table terminates the packet sequence. The integers roughly
correspond to the APIDs assigned to the instrument. In the case of HET,
the entries are 1-7 for HET packets A-G. Thus, for flight, the defined
packet sequence is 1, 2, 3, 3, 3, 5, 6, corresponding to packets A, B,
C, C, C, D, F, G. Any other sequence of up to eight packets can be
defined by changing the values in this table. The packets are filled in
from current data at the start of each major frame and transmitted in
the given order. A zero entry in the table terminates the defined packet
sequence. If the number of packets per major frame (see above) exceeds
the number of entries in the table, the packet formatter will run again,
and fill in a new set of packets. Whether these packets contain new data
will depend upon the way the data collection and packet formatting is
handled.

There are three flags that may be combined with any entry in the defined
packet sequence. These flags are TM_ONCE, TM_IN, and TM_OUT.

TM_ONCE, when added to a given entry, causes that particular packet to
be formatted and transmitted only once per major frame. If the defined
packet sequence is repeated, this packet will be skipped until the next
major frame. This can be used, for example, to transmit a beacon packet
once per major frame even though the packet sequence containing the
beacon packet may be repeated during that major frame.

TM_IN, when added to a given entry, causes that entry to be transmitted
only in major frames matching a specified bit mask. The bit mask is also
added in to the entry in the table. Possibilities for the bit mask are
every 2, 4, 8, 16, 32, 64, 128, or 256 major frames.

TM_OUT, when added to a given entry, causes that entry to be skipped in
major frames matching a specified bit mask. The bit mask is also added
in to the entry in the table. Refer to the bit masks and usage described
in connection with TM_IN, above.

The TM_IN and TM_OUT flags are intended to be used together, which
effectively causes one packet to be substituted for another in the
designated major frames. In this way, for example, HET can issue a table
readout packet every TBD major frames in place of a science packet.

***Telemetry mode.*** The telemetry mode is a single byte that
determines the settings of all five telemetry control parameters. A mode
switch is performed only on major frame boundaries. When a new mode is
commanded, the telemetry control parameters are copied from a set of
hard-coded values associated with the mode. The hard-coded values
associated with each mode are set forth in the following table.

  ------- ---------- --------- --------- ----------- -----------------------
  Mode    Minor      Pkts per  Pkts per  Defined     Description
          Frame      Minor     Major     Packet      
          Interval   Frame     Frame     Sequence    

  0       3          1         8         G, F, A, B, Flight telemetry (E
                                         C, C, C     replaces C every 64
                                         (E), D      frames)

  1       1          1         60        G, F, A, B, HET-only nonflight
                                         C, C, C, D, 
                                         52\*J       

  2       1          4         240       A, B, C, C, Accelerator (4 packets
                                         C, D, 54\*J per second)

  3       3          1         8         G, F, A, B, Spare flight mode
                                         C, D, J, J  (sequence commandable)

  4       0          1         60        G, F, A, B, Contingency mode to
                                         C, C, C, D  allow HET to occupy
                                                     additional minor frame
                                                     ticks (use minor frame
                                                     table)

  5       TBD        TBD       TBD       L           Telemetry test mode
  ------- ---------- --------- --------- ----------- -----------------------

***Byte ordering conventions.*** The telemetry system transmits
multiple-byte integers in "little-endian" order. For 16-bit values, the
least-significant byte is transmitted first, and the most-significant
byte is transmitted second. For 24-bit values, the byte order is least,
middle, then most-significant byte.

# Software Status Indicators

The flight software maintains a number of counters, status flags, error
indicators, and parameters as part of its operation. Certain of these
values are placed in the telemetry in each major frame as a check on
flight software operation. The tables below list each of the software
telemetry points for HET and SIT.

+-------------+-------------+------------------------------------------+
| **HET       | *           | **Description**                          |
| Variable**  | *Location** |                                          |
+-------------+-------------+------------------------------------------+
| Coi         | Pkt 590,    | Counts every event interrupt except      |
| ncidenceCnt | bytes 20-21 | stop_ev (g@8 bit 0 is set) and no_event  |
|             |             | (g@9 bit 8 is set). Cleared every        |
|             |             | minute.                                  |
+-------------+-------------+------------------------------------------+
| lastcmd     | Pkt 590,    | Highest command sequence number reached  |
|             | byte 44     | in major frame (equal to number of       |
|             |             | commands received that pass parsing).    |
|             |             | Resets from zero every minute.           |
+-------------+-------------+------------------------------------------+
| CmdErrBits  | Pkt 591,    | Bit set when command parsed correctly    |
|             | bytes 46-47 | but did not execute. Bit number          |
|             |             | corresponds to sequence number           |
|             |             | associated with command when received    |
|             |             | during previous major frame. Whenever    |
|             |             | any bit is set in this word, there will  |
|             |             | also be a software error flag set in bit |
|             |             | 6 of Errflags (see below).               |
+-------------+-------------+------------------------------------------+
| IdleCnt     | Pkt 591,    | Counts every pass through the background |
|             | bytes 48-49 | loop, read out and cleared every minute. |
|             |             | Provides a "livetime" check, since more  |
|             |             | time spent in interrupt and event        |
|             |             | processing will decrease this count. For |
|             |             | this check to work, clock gating needs   |
|             |             | to be off (cgate 0).                     |
+-------------+-------------+------------------------------------------+
| Errflags    | Pkt 598,    | Bit set corresponds to an error          |
|             | bytes 29-30 | encountered during previous major frame  |
|             |             | time. Cleared every minute.              |
|             |             |                                          |
|             |             | Bit 0: Receive queue full                |
|             |             |                                          |
|             |             | Bit 1: Transmit queue full               |
|             |             |                                          |
|             |             | Bit 2: Command queue full                |
|             |             |                                          |
|             |             | Bit 3: Command buffer overflow           |
|             |             |                                          |
|             |             | Bit 4: Command handler timeout           |
|             |             |                                          |
|             |             | Bit 5: Command syntax error (command     |
|             |             | rejected)                                |
|             |             |                                          |
|             |             | Bit 6: Command processing error          |
|             |             | (CmdErrBit set)                          |
|             |             |                                          |
|             |             | Bit 7: Callback timer error              |
|             |             |                                          |
|             |             | Bit 8: ADC timed out                     |
|             |             |                                          |
|             |             | Bit 9: Queuing error, queue reset to     |
|             |             | empty state                              |
+-------------+-------------+------------------------------------------+
| swVer       | Pkt 598,    | Software version tag. LSB (byte 31) is   |
|             | bytes 31-32 | day of month, MSB (byte 32) is month in  |
|             |             | which version was created.               |
+-------------+-------------+------------------------------------------+
| Err_event   | Pkt 598,    | Event read from hardware but no token    |
|             | bytes 33-34 | bit was set. Event was counted in        |
|             |             | CoincidenceCnt but not processed.        |
+-------------+-------------+------------------------------------------+
| No_event    | Pkt 598,    | Event interrupt handled but no_event bit |
|             | bytes 35-36 | was set to 1 (g@9 bit 8). Event not      |
|             |             | counted in CoincidenceCnt.               |
+-------------+-------------+------------------------------------------+
| Lost_event  | Pkt 598,    | Event could not fit in raw event queue.  |
|             | bytes 37-38 | The raw event queue is only used in      |
|             |             | laboratory testing. Data in raw event    |
|             |             | queue is used to fill packet 598. If     |
|             |             | this counter still exists in the flight  |
|             |             | version, it will increment at high data  |
|             |             | rates because the raw event queue is     |
|             |             | never emptied. However, it is not an     |
|             |             | error and the events are also processed  |
|             |             | normally.                                |
+-------------+-------------+------------------------------------------+
| t           | Pkt 598,    | Major frame number. This is necessary in |
| mMajorFrame | bytes 39-40 | order to correlate housekeeping packets  |
|             |             | with science packets. Each science       |
|             |             | packet has the major frame number in the |
|             |             | HET header following the CCSDS header.   |
|             |             | The housekeeping packet is merged into   |
|             |             | the SEP Central housekeeping and does    |
|             |             | not have a HET header.                   |
+-------------+-------------+------------------------------------------+
| ch          | Pkt 598,    | Three-byte checksum of entire table      |
| ecksum_csum | bytes 41-43 | area. The table checksum is computed on  |
|             |             | the ground during the flight software    |
|             |             | build process, and should match this     |
|             |             | computed checksum. The checksum is       |
|             |             | computed one word at a time in the       |
|             |             | background idle loop. This may take some |
|             |             | time if clock gating is enabled (cgate   |
|             |             | 1). Table entries are added using a      |
|             |             | 24-bit sum, ignoring carries. Once the   |
|             |             | entire table area has been added up, the |
|             |             | result is telemetered and the            |
|             |             | calculation is repeated.                 |
+-------------+-------------+------------------------------------------+

# Building HET Flight Software From Sources

This section describes how to build the HET flight software executable
images from the source code files.

There are two ways in which the build process may be accomplished. The
first is within the Microsoft Visual Studio build environment. Workspace
(.dsw) and project (.dsp) files are provided that set up the source
files, output files, and dependencies. The build process is automated,
and only the components that have changed (based on modification dates)
are built. The second build method is to use DOS command lines, either
typing the command lines one by one in a CMD window or using a batch
file. A batch file (.cmd) is provided.

Either build method requires (1) the source files and (2) the custom
build utility programs. The source files are ordinary text files that
may be read and modified by a text editor program (Visual Studio has a
built-in editor). They are written in the HET-SIT variant of the P24
assembly language. The required custom build utility programs are the
preassembler, the p24 assembler, and the tableizer. Each of these
programs is written in C and may be rebuilt from its own source code if
necessary.

## File Naming Conventions

The following table lists the various file types found in the HET flight
software system.

  --------------- ------------------------------------- --------------- -------------
  **Extension**   **Description**                       **Readable?**   **Program**

  .111            Asm24 secondary file                  Yes             asm24

  .bin            Binary load contents (actually an     Yes             asm24
                  ascii file)                                           

  .chk            Asm24 stack checking file             Yes             asm24

  .cmd            DOS command batch file                Yes             command

  .dsp            Visual Studio project file            No              VC++

  .dsw            Visual Studio workspace file          No              VC++

  .hex            Table source file                     Yes             tableize

  .lin            Asm24 line number file                Yes             asm24

  .log            Text file                             Yes             tableize

  .lst            Asm24 listing file with address       Yes             asm24
                  information                                           

  .ncb            Visual Studio secondary file          No              VC++

  .opt            Visual Studio secondary file          No              VC++

  .p24            P24 assembler source code             Yes             asm24

  .plg            Visual Studio secondary file          No              VC++

  .pre            Preassembler source directives        Yes             pre24

  .sym            Asm24 symbol file                     Yes             asm24

  .txt            Text file                             Yes             
  --------------- ------------------------------------- --------------- -------------

## Directory Structure

This document and the various build methods assume that the software is
organized into the proper directory structure. The flight software is
organized as a root or base directory and three subdirectories for the
engineering model, flight model 1, and flight model 2, respectively. The
directory structure is depicted in the following figure.

Generally, the root directory is the unique flight software release
folder. Each flight software release version is delivered in a folder
that is keyed to the date of the software revision. For example, as of
this writing the latest HET flight software release is FSW20040923.
There is a folder with this name, whose contents are organized as
depicted in the figure above, associated with this flight software
release. This folder and all its contents should be copied intact to a
directory on the computer where the build will take place.

In addition to the flight software delivery, there must be a separate
directory for the executable utility programs. These programs generally
do not change with software releases, so they should not be placed in a
flight software directory. Instead, they should be placed in a separate
subdirectory at the same level as the flight software root directory.

In order to use the command lines for rebuilding the software, the
system search path must be set up to search the directory containing the
executable utility programs.

An example directory structure is given below.

C:\\HET_FSW

C:\\HET_FSW\\BIN

C:\\HET_FSW\\FSW20040923

C:\\HET_FSW\\FSW20040923\\EM

C:\\HET_FSW\\FSW20040923\\FM1

C:\\HET_FSW\\FSW20040923\\FM2

## Source Files

The following table lists the source files that are required to build
the HET flight software. The files fall into four categories: common
files (i.e., those used in all bootable images); EM files (i.e., those
used only in building the engineering model bootable image); FM1 files
(i.e., those used only in building the flight model 1 bootable image);
and FM2 files (i.e., those used only in building the flight model 2
bootable image).

  --------------------- -------------------------------------------------
  **Common Files --     
  These files reside in 
  the root directory**  

  Bootvec.p24           Boot vector and low memory data

  Start.p24             Startup code

  Intserv.p24           Interrupt service routines

  Command.p24           General command handling routines

  Telem.p24             General telemetry formatting routines

  HETfunc.p24           HET-specific functions, including HET commands

  HETtelem.p24          HET-specific telemetry packet formatting

  Asic.p24              Control of PHASIC chips

  Tomutil.p24           General utility routines

  Queue.p24             General message queuing routines

  INIT.p24              Particle processing initializations

  RDCHTAB.p24           Initialize channel table for particle processing

  PHPROC.p24            First cut particle processing \-- place in queues

  H1EVNTS.p24           Process H1-only events

  STPEVNTS.p24          Process stopping events

  PENEVNTS.p24          Process penetrating events

  UTIL.p24              Particle processing utility routines

  PROC.p24              Offset correction, other processing functions

  CATEGORY.p24          Particle category lookup

  BEACONPROC.p24        Assemble beacon packet contents

  Bss.p24               Uninitialized memory for buffers and variables

  **Engineering Model   
  (EM) Files -- these   
  files reside in       
  subdirectory .\\EM**  

  fsw_em.pre            Preassembler control file

  HET_Tables.hex        Table source file

  **Flight Model 1      
  (FM1) Files -- these  
  files reside in       
  subdirectory .\\FM1** 

  fsw1.pre              Preassembler control file

  HET1_Tables.hex       Table source file

  HET1_Events.hex       Simulated event list table source file

  **Flight Model 2      
  (FM2) Files -- these  
  files reside in       
  subdirectory .\\FM2** 

  fsw2.pre              Preassembler control file

  HET2_Tables.hex       Table source file
  --------------------- -------------------------------------------------

## Utility Programs

The following are the utility programs used to build the HET flight
software. Asm24 is built from a single C source file using the Borland C
compiler. The other two programs are built using Microsoft Visual C++
version 6.0. Each has a workspace and project file.

### Asm24 

Asm24 translates p24 mnemonics into binary code. The mnemonics are those
listed in the CPU24 manual version 6, including "or". General line
syntax is

\[label:\] \[mnemonic\] \[value\] \[; comment\]

In addition to the 32 opcode mnemonics, certain assembler-specific
mnemonics are defined:

dw n ; assemble a single 24-bit word whose value is n

ds n ; assemble n x 24-bit words, all zeroes

org n ; assemble starting at address n

A label, if present, must be followed by a colon. A mnemonic, if
present, may follow directly after the colon or be separated by spaces
and tabs. Certain mnemonics require values. Specifically, jump, jnc, jz,
call, ldi, dw, ds, and org all require a value. A comment, if present,
is preceded by a semicolon which may itself be preceded by white space.

A label may be supplied as the value for any instruction, in which case
the assembler will calculate its numeric value. Other values may be
specified in decimal or hex following the usual convention (0xN = hex
number N). The assembler will perform certain arithmetic operations on
values. Thus,

ldi (9\*5)-4

jump target+1

dw SIZE+3

are all valid instructions.

The assembler also recognizes certain directives:

#define symbol value ; define a symbol

#expand on \| off ; turn on or off code expansion

#stack_check on \| off ; turn on or off simulator stack checking

The assembler accepts one source file and compiles it into a binary
image. It does not require a separate link step. Unless an org directive
changes the assembly address, code is assembled starting at address zero
and proceeding through consecutive addresses. (Note that no code is
permitted at address zero in the cpu24 chip, so either the first word
will not be written or the org should be used to set the address to 1.)

The command line is:

asm24 basefile

The base file name has no extension; the assembler adds ".p24". The
assembler creates a number of output files, each constructed using the
base file name with unique extensions. It will overwrite any files that
happen to exist in the current directory.

basefile.111 ; don't know

basefile.bin ; binary image file

basefile.chk ; stack checking file

basefile.lin ; correspondence between source file and listing file

basefile.lst ; listing file (combined source, assembly, and address)

basefile.sym ; symbol names and corresponding values

The two most important of these files are the bin file, containing the
binary image, and the lst file, containing the combined source,
assembly, and symbolic address information.

A binary image file consists of one or more segments. A segment consists
of a header line and a variable number of data lines. The header line is
the first line of the segment. It consists of two hex numbers: the base
address and the number of words to follow at this address. The following
N data lines are 24-bit hex values, where N is the second word on the
header line. Another segment may follow immediately after the end of the
previous segment, beginning with its own header line. The base address
for a segment is determined by any org directive that may appear in the
source file. If a source segment consists of nothing but "ds" mnemonics,
then no output segment is created.

The executable file is asm24.exe. The source file is asm24.c, dated
4/26/2003. This is Phong Le's program, version 7. It is not currently
capable of being rebuilt from source using Visual C++.

### Pre24

The preassembler does one trick that should have been included in the
assembler. it combines separate source files into one big source file
for input into asm24. A pre24 input file (\*.pre) consists of assembler
source code and #include directives. The output file consists of the
input base file name with a ".p24" extension. A #include directive
causes the preassembler to write the contents of the included file
(which follows the "#include" on the same line) to the output file. Any
other lines are copied straight to the output file. The assembler is
automatically invoked, unless the word "noasm" appears on the pre24
command line (i.e., pre24 filename.pre noasm). The HET flight software
uses one .pre file, which consists of #include lines specifying each
source file in turn.

Executable file is pre24.exe. Source file is pre24.cpp. Version 1, T.
Nolan 11/2/2002.

### Tableize

Tableize appends compressed tables to the code image for uploading to
the flight instrument.

Tableize requires a binary image file (the output of asm24) and a table
source file (\*.hex). The tables are compressed according to directives
in the table source file, and the compressed image is appended to the
binary image file. The output is a new binary image file bearing the
same name as the original, which has the tables attached.

A table upload file is a readable ASCII file consisting of four kinds of
lines: *introducers*, *addresses*, *table contents*, and *comments*.
They are described below.

An *introducer* line consists of the word "HETBINARY" or "SITBINARY" on
a line by itself, with no spaces or other characters before or after it.
The purpose of having two different introducers is so that tables cannot
be uploaded to the wrong instrument inadvertently.

An *address* line follows immediately after an introducer. It contains
three numbers, separated by spaces. The format for numbers obeys C
conventions. That is, each number is assumed to be decimal, unless it
begins with "0x," in which case it is assumed to be hexadecimal. The
first number is the address at which the table is to be loaded. This
address is an absolute address in the flight software address space. The
addresses of the major tables in the SIT and HET flight software are
found in the discussion above. The second number is the number of table
entries to follow. This normally corresponds to the size of the table.
If the second number is zero, tableize will calculate the size of the
table automatically (it will run until it finds the next introducer).
The third number is the load type, which can be 0, 1, 2, 4, 5, or 6.
Load type 0 treats each table entry as a 24-bit word. All three bytes of
each word are transmitted to the flight software, then recombined into
words and stored at successive address locations. Load type 1 treats
each table entry as an 8-bit value. Only a single byte is transmitted to
the flight software, which stores successive bytes at successive address
locations, filling the most-significant 16 bits of each word with zeros.
If the table entry in the file is larger than can fit in one byte, it is
truncated to 8 bits. Load type 2 treats each table entry as a 16-bit
value. Two bytes are transmitted to the flight software, which combines
the two bytes into a 16-bit word, storing successive words at successive
address locations, filling the most-significant 8 bits of each word with
zeros.

Load types 4, 5, and 6 apply bytewise run-length compression. Run-length
compression shortens a string of consecutive identical bytes by
converting it to two bytes: a count, and a value. This compression works
well on some kinds of files, but if the contents of the file are random
the "compressed" file will actually be longer (because a single byte
followed by a different value is converted to two bytes). The same
compression is used in load types 4, 5 and 6. The difference is that
type 4 causes the uncompressed bytes to appear in the least-significant
bytes of successive words; type 5 causes the uncompressed bytes to
appear in the middle bytes of successive words, and type 6 causes the
uncompressed bytes to appear in the most-significant bytes of successive
words. In this manner, an overlaid table can be built up in memory from
three compressed source files.

A *table contents* line consists of one or more numbers separated by
commas, spaces, or tabs. There must be the same number of table entries
following the address line as specified in the second number of the
address line (i.e., the table size). However, the table entries can be
spread out over any number of lines. For example, each table entry could
appear on a separate line, or all the table entries could appear on the
same line (but lines are limited to 512 characters in total length). As
before, number formats obey C conventions. They must begin with a digit,
a minus sign, or a "0x." Any other character appearing where a number
ought to be ends that line (effectively acting as an inline comment).

A *comment line* is any line whose first character (other than spaces,
tabs, or commas) is not a digit or a minus sign. Comment lines can
appear anywhere in the table upload file except between an introducer
and the following address line. The comment line immediately preceding
the introducer is special -- it is a shorthand description of the table
that can be used by the upload software to inform the user of the table
that is about to be uploaded. Other comment lines appearing before the
introducer are ignored, and any comment lines appearing in the table
contents area are skipped until a line beginning with a numeric value is
found.

Multiple table uploads can appear in one file. Each table upload begins
with an introducer and address line, and is followed by sufficient table
contents lines to fill up the table. Following the table contents (and
any optional comments), another introducer may begin a second table
upload, and so on.

An example follows.

  -----------------------------------------------------------------------
  This table upload file contains two uploads.

  First is a sample table containing 13 entries, where each entry is no
  larger than 16 bits.

  HETBINARY

  0x1f000 13 2

  0, 10, 20, 50, 100, 200, 500, 1000 first 8 entries

  2000, 5000, 10000, 20000, 50000 next 5 entries

  Second is a sample table containing 4 entries, 24 bits each

  HETBINARY

  0x1f020 4 0

  -1

  -1

  0x55aa55

  -1
  -----------------------------------------------------------------------

The executable file is tableize.exe. Source files are tableize.cpp,
compress.cpp, and upload.cpp. Version 3.0, T. Nolan, 8/15/2004.

## Command Lines to Rebuild Flight Software

This section sets forth the command lines to rebuild the flight software
from sources. They assume that the source files organized in directories
as described above. They also assume that the \\bin directory has been
added to the search path so the utility programs can be found by the
command interpreter. It is assumed that the command interpreter starts
in the root directory for the version of the flight software that needs
to be rebuilt (this will generally require a cd command).

FSW20040923\> cd em

FSW20040923\\EM\> pre24 fsw_em

FSW20040923\\EM\> tableize fsw_em HET_Tables.hex

FSW20040923\\EM\> copy fsw_em.bin ..

FSW20040923\\EM\> cd ..\\FM1

FSW20040923\\FM1\> pre24 fsw1

FSW20040923\\FM1\> tableize fsw1 HET1_Tables.hex HET1_Events.hex

FSW20040923\\FM1\> copy fsw1.bin ..

FSW20040923\\FM1\> cd ..\\FM2

FSW20040923\\FM2\> pre24 fsw2

FSW20040923\\FM2\> tableize fsw2 HET2_Tables.hex

FSW20040923\\FM2\> copy fsw2.bin ..

FSW20040923\\FM2\> cd ..

FSW20040923\>

At this point, three binary image files have been created and copied to
the root directory: fsw_em.bin, fsw1.bin, and fsw2.bin. Note that as
described above, these files are actually readable ascii, and contain
instructions to the various loader programs.

A batch command file, rebuild.cmd, is provided to automate this process.
The batch file does not require that the utility executables be in the
search path. Instead, it contains a symbolic reference to the directory
containing the executables. As a result, you need to edit the
rebuild.cmd file and change this symbolic reference to point to the
directory on your host computer where the utilities are stored. Once
that is accomplished, the rebuild command file can be executed in one of
three different ways: (1) locate rebuild.cmd in the flight software root
directory using Windows Explorer and double-click on it; (2) open a DOS
command window, set the current directory to the the flight software
root directory, and invoke the command by typing one of the following
lines:

\> rebuild all

\> rebuild EM

\> rebuild FM1

\> rebuild FM2

or (3) create a shortcut in which the target is "rebuild.cmd" with one
of the command line options listed above (all, EM, FM1, FM2) appended on
the end.

## Using the Visual Studio Environment to Build the Flight Software

The Microsoft Visual Studio (a component of Visual C++) provides a
customizable user environment for editing and building any program, not
just C programs. A workspace (.dsw) file and three project (.dsp) files
have been created to organize and build the HET flight software. Visual
Studio works like a "make" utility in that it pays attention to the
modification date of the files under its control and only builds those
portions of the build tree that need to be built.

In order to port the HET flight software workspace to a new computer,
there must be one customization performed. This customization will tell
Visual Studio where to find the HET build utility programs pre24.exe,
asm24.exe, and tableize.exe. As described above, you should create a
separate directory to hold these three programs, for example
C:\\HET_FSW\\BIN. Assuming you have done this, open Visual Studio,
select Tools, Options from the menu. In the Options dialog, select the
Directories tab. In the box labeled "Show directories for" select
"Executable files". Then click on the "new" icon from the mini-toolbar
above the list, and either type the name of the directory containing the
utility programs or use the browse button to point to the directory
graphically. Save these changes. This customization needs to be
performed only once. Visual Studio will remember the directory list the
next time it is started.

After you have made the directory customization described above, you can
copy the entire HET flight software source directory tree to the host
computer and open the fsw.dsw file either by double-clicking on it in
Windows Explorer or by selecting "File" and "Open workspace" from the
Visual Studio main menu.

Three projects appear in the left-hand pane. Each one contains a
complete list of the common flight software files. Double-clicking on
one of these brings up the corresponding source file in the editor.
Since these are common files, it does not matter which project is open
when you click on the file. Changing it in one project changes it in all
projects. In the "Extras" folder under each project are additional
files, including files unique to that project. This is where the table
file for the EM, FM1, and FM2 can be located.

Visual Studio ordinarily builds one project at a time. The active
project is highlighted in bold in the left-hand pane. To select a
project to build, either right-click on the project name and select "Set
as active project" or select "Set active project" from the "Project"
menu. Once a project is active, it can be built by pressing the F7
function key or selecting "Build" or "Rebuild All" from the "Build"
menu. Alternatively, all projects can be built at once by selecting
"Batch build" from the "Build" menu and clicking on "Rebuild all." The
new binary image files can be found under the respective EM, FM1, and
FM2 directories.

The instructions to rebuild the HET flight software from sources are
contained in the project settings. These settings do not have to be
modified because they travel with the workspace and project files.
However, for completeness, and to allow the project to be reconstructed
from scratch, here are the project settings that are used.

  ----------------- ------------------ -------------- ----------------------------------
  **File**          **Dependencies**   **Outputs**    **Commands**

  fsw_em.pre        asic.p24\          fsw_em.p24     pre24 fsw_em noasm
                    beaconproc.p24\                   
                    bootvec.p24\                      
                    bss.p24\                          
                    category.p24\                     
                    command.p24\                      
                    h1evnts.p24\                      
                    hetfunc.p24\                      
                    hettelem.p24\                     
                    init.p24\                         
                    intserv.p24\                      
                    penevnts.p24\                     
                    phproc.p24\                       
                    proc.p24\                         
                    queue.p24\                        
                    rdchtab.p24\                      
                    start.p24\                        
                    stpevnts.p24\                     
                    telem.p24\                        
                    tomutil.p24\                      
                    util.p24                          

  fsw_em.p24        fsw_em.pre         fsw_base.bin   asm24 fsw_em\
                                                      del fsw_base.bin\
                                                      ren fsw_em.bin fsw_base.bin\
                                                      copy fsw_em.sym fsw_base.sym

  HET_Tables.hex    fsw_base.bin       fsw_em.bin     tableize fsw_base HET_Tables.hex
                                                      -sprog_end\
                                                      -ofsw_em.bin

  fsw1.pre          asic.p24\          fsw1.p24       pre24 fsw1 noasm
                    beaconproc.p24\                   
                    bootvec.p24\                      
                    bss.p24\                          
                    category.p24\                     
                    command.p24\                      
                    h1evnts.p24\                      
                    hetfunc.p24\                      
                    hettelem.p24\                     
                    init.p24\                         
                    intserv.p24\                      
                    penevnts.p24\                     
                    phproc.p24\                       
                    proc.p24\                         
                    queue.p24\                        
                    rdchtab.p24\                      
                    start.p24\                        
                    stpevnts.p24\                     
                    telem.p24\                        
                    tomutil.p24\                      
                    util.p24                          

  fsw1.p24          fsw1.pre           fsw_base.bin   asm24 fsw1\
                                                      del fsw_base.bin\
                                                      ren fsw1.bin fsw_base.bin\
                                                      copy fsw1.sym fsw_base.sym

  HET1_Tables.hex   fsw_base.bin       fsw1.bin       tableize fsw_base HET1_Tables.hex\
                                                      HET1Events.hex\
                                                      -sprog_end -ofsw1.bin

  fsw2.pre          asic.p24\          fsw2.p24       pre24 fsw2 noasm
                    beaconproc.p24\                   
                    bootvec.p24\                      
                    bss.p24\                          
                    category.p24\                     
                    command.p24\                      
                    h1evnts.p24\                      
                    hetfunc.p24\                      
                    hettelem.p24\                     
                    init.p24\                         
                    intserv.p24\                      
                    penevnts.p24\                     
                    phproc.p24\                       
                    proc.p24\                         
                    queue.p24\                        
                    rdchtab.p24\                      
                    start.p24\                        
                    stpevnts.p24\                     
                    telem.p24\                        
                    tomutil.p24\                      
                    util.p24                          

  fsw2.p24          fsw2.pre           fsw_base.bin   asm24 fsw2\
                                                      del fsw_base.bin\
                                                      ren fsw2.bin fsw_base.bin\
                                                      copy fsw2.sym fsw_base.sym

  HET2_Tables.hex   fsw_base.bin       fsw2.bin       tableize fsw_base HET2_Tables.hex\
                                                      -sprog_end -ofsw2.bin
  ----------------- ------------------ -------------- ----------------------------------