/* **********************************************************************
 * *                                                                    *
 * *       Parameters For Antenna Library Processes and Routines        * 
 * *                                                                    *
 * ********************************************************************** 
 * File: libs/antenna/ant_global.h
 *
 * COPYRIGHT (c) 1988, 1989, 1991, 1996, 1999, 2000, 2001, 2004, 2005  BY
 *         SIGMET INCORPORATED, WESTFORD MASSACHUSETTS, U.S.A. 
 * 
 * THIS SOFTWARE IS FURNISHED UNDER A LICENSE AND MAY BE USED AND  COPIED
 * ONLY  IN  ACCORDANCE WITH  THE  TERMS  OF  SUCH  LICENSE  AND WITH THE
 * INCLUSION OF THE ABOVE COPYRIGHT NOTICE.  THIS SOFTWARE  OR  ANY OTHER
 * COPIES  THEREOF MAY NOT BE PROVIDED OR OTHERWISE MADE AVAILABLE TO ANY
 * OTHER PERSON.  NO TITLE TO AND OWNERSHIP OF  THE  SOFTWARE  IS  HEREBY
 * TRANSFERED. 
 */    

/* ------------------------------
 * Structure for Holding I/O status information
 */
struct io_information
{
  UINT2 lXmtExpected;           /* Xmt process should be running */
  UINT2 lRcvExpected;           /* Rcv process should be running */
  UINT4 iXmtPid;                /* Process IDs for the two processes */
  UINT4 iRcvPid;

  MESSAGE ixmt_status;          /* Status for xmt process, 0 until started  */
  MESSAGE ircv_status;          /* status for rcv process, 0 until started  */

  /* These are not applicable to the sa3860 format */
  /* Last transmission starting with an 80hex which got an error
   */
  UINT1 sant_diagnostic[ANTRCV_MAX_LENGTH];
  SINT4 iant_diag_size;

  /* Largest last transmission not starting with an 80, C0, or B0
   */
  UINT1 sother_diagnostic[ANTRCV_MAX_LENGTH];
  SINT4 iother_diag_size;

  SINT4 iin_cnt;                /* Input Operation count */
  SINT4 iout_cnt;               /* Output Operation count */
  SINT4 iin_ercnt;              /* Input Error count */
  SINT4 iout_ercnt;             /* Output Error count */
};

/* ------------------------------
 * The antenna information structure itself.
 */
struct antenna_info
{
  struct io_information io[2] ;   /* I/O information (2 possible channels) */

  UINT1 lShuttingDown ;		/* Library attempting to shutdown */

  UINT1 lauto ;			/* Automatic startup of simulator */
  UINT1 lSimXmtExpected;
  UINT1 lSimRcvExpected;
  UINT4 iSimXmtPid;             /* Simulator XMT process is active */
  UINT4 iSimRcvPid;             /* Simulator RCV process is active */

  MESSAGE iLogStatus ;		/* Status and PID of logging process */
  UINT4   iLogPid ;

  UINT4 iChatPid;               /* Chatter process is active */
  UINT4 iChatDestination;       /* Desired destination for chatting */

                                /* See antenna_lib.h file for definitions */
  UINT2 iazmode, ielmode;       /* Servo mode for each axis */

  BIN2 idaz , idel  ;		/* Desired AZ/EL angles */
  FLT4 fdazv, fdelv ;		/* Desired AZ/EL velocities */

  UINT4 icbits;                 /* Control Flags */
  UINT4 isbits;                 /* Status Flags  */

  UINT2 iActualPwbw, iDesiredPwbw;    /* Actual and Desired Pulse/Band Width */

  UINT2 iActualPolar, iDesiredPolar;  /* Actual and Desired Polarization XMT
				 * See dsp_lib.h for choices */

  SINT4 isiggen_value;          /* Actual signal generator value */
  SINT4 idsiggen_value;         /* Desired signal generator value */

  char  scurrent_rst_mode[20];  /* Current rst mode name */
  UINT4 icurrent_rst_mode;      /* Current rst mode number */
  UINT4 irequested_rst_mode;    /* Requested rst mode number */

  UINT4 icurrent_nst_faults;    /* Current faults in low 4 bits */
  UINT4 iNstUpdateTimes[4] ;	/* Binary times of last NST update calls */
  UINT4 iNstTimeout ;		/* Timeout in milliseconds, zero means no timeout */

  UINT4 iBtimePkt ;		/* Relative binary time of last packet */
  UINT4 iBtimeAng ;		/*   antenna position update. */
  UINT4 iBtimeShip ;		/*   shipboard position update. */

  SINT4 iactive;                /* User activity count */
  UINT4 ichange_count;          /* User change count */

  /* Store info here about which network hosts are currently transmitting */
#define ANT_NETHOST_MAX (5)
  struct ant_nethost_info NetHost[ANT_NETHOST_MAX];

  /* Masks indicate what control and status bits are available
   */
  UINT4 ic_mask;                      
  UINT4 is_mask;

  /* Mask indicates which status bits are considered critical faults
   */
  UINT4 iStatusCritical;

  /* Mask indicating which INU information is invalid */
  UINT2 iInuFaultBits;

  /* Indicates that the last call to ant_set_radiate wanted to toggle
   * radiate
   */
  UINT2 lwanted_to_toggle;

  /* Time of the first desire to toggle */
  struct ymds_time ToggleYmds;

  /* Time that the radiate was last turned on.  Value is N/A if radiate is off */
  struct ymds_time RadiateOnYmds;

  /* Flag to indicate that a time packet was received.  If zero, then
   * the following fields are not defined.
   */
  UINT4 ltime_packet_received ;
  UINT4 ltime_set_from_packet ;   /* System time has been set from this packet */
  UINT4 lset_system_time ;	  /* Request to set system time */
  SINT4 iLastTimeChange;          /* Change in seconds last time system time was set */
  SINT4 itime_error;              /* Packet time minus system time at arrival (ms) */
  UINT4 itime_btime;		  /* Time that last time packet was received (ms) */
  struct ymds_time time_in_packet;/* Time reported in the last packet */

  UINT2 lsa_ack;		/* SA format acknowledge sent */
  UINT2 lsa_nack;		/* SA format not-acknowlege sent */

  /* Dual RCP system parameters
   */
  struct drcp_status drcp ;	/* Dual system status received from our unit */
  UINT2 iDrcpModeReq ;		/* Requested mode (A/B/Auto) */
  UINT1 lDrcpWouldUseReq ;	/* Requested "Would use if available" flag */
  UINT1 lDrcpRelinquishReq ;	/* Requested "Relinquish control to other" flag */
};

/* ------------------------------
 * Bite information structures
 */
struct bite_unit_info
{
  /* Last data received from each of the units
   */
  UINT1 sbite_reception[BITE_MAX_LENGTH];

  /* Input and output operation counts
   */
  SINT4  iin_cnt;
  SINT4 iout_cnt;

  /* Relative binary time of last update
   */
  UINT4 ibtime;
  UINT1 lInterrogate;	/* Request new BITE from RCP */
  UINT1 lSpare1;
  UINT1 lSample;	/* Sample data from external units */
  UINT1 lSetValues ;	/* Send commands to external units */
  UINT1 lReset;		/* Reset external units */
  char pad145x3[3] ;
};

struct bite_info
{
  /* Last data received which starts with a C0 byte.  The length is
   * fairly arbitrary.  Size indicates the number of bytes in the
   * buffer.
   */
  UINT1 sbite_diagnostic[BITE_MAX_LENGTH];
  SINT4 idiag_size;

  /* Transmission requests
   */
  UINT1 lInterrogateBite;	/* Request new BITE from RCP */
  UINT1 lSetValuesBite;		/* Send commands to external units */
  UINT1 lSampleBite;		/* Sample data from external units */
  UINT1 lResetBite;		/* Reset external units */

  UINT2 lcnt_send_asap ;	/* Requests to send new control BITE transmission */
  UINT2 lcnt_send_changed ;	/*   either right away of if changed. */

  /* Current mask data, fault data, and error flag
   */
  UINT4 data_mask[BITE_MASK_SIZE];	   /* Array of all the data bits */
  UINT4 FaultMask[BITE_MASK_SIZE];	   /* Array of all the fault bits */
  UINT4 CriticalMask[BITE_MASK_SIZE];	   /* Array of all the critical fault bits */
  UINT4 FaultableMask[BITE_MASK_SIZE];     /* Status bits which can currently be faulted */
  UINT4 IrisFlagMask[BITE_MASK_SIZE];      /* Mask of flagged control buttons pressed */
  FLT4  fQBiteValues[BITE_NUM_FIELD_DEFS]; /* Q-BITE values */

  UINT4 iFaultSummaryFlag;	/* Summary info about faults */
  SINT4 ifault_field ;		/* Lowest field number containing fault */

  struct bite_unit_info Unit[BITE_MAX_UNITS];
};

/* ------------------------------
 * History of most recent data and command 'updates' from all possible
 * sources.
 */
#define ANTUPDSTRLEN MAX( ANTSETCMDLEN, MAX( BITE_MAX_LENGTH, ANTRCV_MAX_LENGTH ) )
struct antUpdateItem {		/* A single antenna history element */
  SINT4 iClientType ;		/*   Who made this entry.  Client type */
  SINT4 iPID ;			/*     as well as PID of that client. */
  UINT4 iSendMask;		/*   Bit Mask of who has sent this packet */
  SINT4 iLength ;		/*   Length of Text/Packet/Data */
  char  sData[ ANTUPDSTRLEN ] ;	/*   Text/Packet/Data contents */
} ;
struct antUpdateHistory {
  struct antUpdateItem cmds[ ANTSET_NUMCOMMANDS ] ;
  struct antUpdateItem bite[ BITE_MAX_UNITS ] ;
  struct antUpdateItem  ant ;
} ;
#define ANTUPDMAXITEMS (ANTSET_NUMCOMMANDS + BITE_MAX_UNITS + 1)

/* ------------------------------
 * Transient data.
 */
struct antenna_voldata {
  /* Realtime history models for basic antenna position and optional
   * shipboard data.
   */
  RTVECALLOCATE( ANTPEDX_SLOTS, ANTPEDX_TERMS ) rtpedx_history ;
  RTVECALLOCATE( ANTSHIP_SLOTS, ANTSHIP_TERMS ) rtship_history ;

  /* Most recent data and command update history.
   */
  struct antUpdateHistory updHist ;

  /* Chat-mode incoming and outgoing FIFOs.  The incoming buffer must
   * be large enough to hold the largest possible transmission from
   * the RCP, that is the "help listall" command.  On the network,
   * this arrives so fast the terminal is effectively stopped.  It was
   * 16K on the RCP8 in June 2004.
   */
  BFIFO( 20000 ) ChatIn  ;
  BFIFO(    80 ) ChatOut ;

  /* Buffers used when the device file is blank
   */
  BFIFO( 400 ) FromSimulator;
  BFIFO( 100 ) ToSimulator;

  /* A single logging mechanism is used across the entire antenna
   * library.  Any process or client may write to this log provided
   * that ANTENNA_LOGFILE_SEM is locked at the time.
   */
  struct ymds_time LogYMDS ;	/* Time of most recent entry */
  BFIFO( 12000 ) LogFIFO ;	/* Queue of text to be logged */
} ;

/* ------------------------------
 * The actual shared global antenna structure.
 */
struct antenna_global
{
  /* Current information for the antenna
   */
  struct antenna_info info;

  /* Setup information for the antenna
   */
  struct ant_manual_setup LocalSetup;  /* Version on local system */
  struct ant_manual_setup setup;       /* Version in effect */
  
  /* Current information for the Bite
   */
  struct bite_info binfo ;

  /* Setup information for bitex definition structures
   */
  UINT4 ibite_setup_serialnum ;	/* Serially numbered changes */
  struct bitex_setup bitex ;

  /* Transient volatile data, put in a separate structure because it
   * does not affect the permanent state of the library.
   */
  struct antenna_voldata vdat ;
} ;

#define REDUNDANT_RECS (3) /* # of same records needed by RCP for validation */

/* =============== Information for I/O Protocols ================
 * EEC machine units per (degree/second).  Multiply the speed by this
 * to get the machine number sent on the serial line.
 */
#define ANT01_VEL_UNITS (1.81)
#define ANT02_VEL_UNITS (8192.0/180.0)
#define ANTSA_VEL_UNITS (32768.0/45.0)

/* **********************************************
 * *                                            *
 * *  Common Variables for Each Antenna Client  *
 * *                                            *
 * **********************************************
 */
#ifdef ANT_GLOBAL_ALLOCATE
#define EXTERN
#else
#define EXTERN extern
#endif

/* Pointer to global section for this process to use.
 */
EXTERN volatile struct antenna_global *antGlobal_c ;

/* Private data for this particular client/process
 */
struct ant_client_info {
  SINT4 iClientType ;		/* Client type, one of ANT_IAM_xxx */

  struct rtvec pedx ;		/* How to access the realtime history */
  struct rtvec ship ;		/*   for the antenna and nav data. */
  SINT4  iPedxSkipState ;	/* Counter/state to prevent oversignalling */
  SINT4  iShipSkipState ;	/*   of angle insertion errors */
} ;
EXTERN struct ant_client_info antClient_c ;

#undef EXTERN

/* Opaque structure used for antenna log history analysis
 */
struct antHistLogfile {
  void *pMapAddr ;		/* Pointer to open mapped log file, */
  SINT4 iMapSize, iMapChan ;	/*   and size/channel statistics. */
  SINT4 iSize ;			/* Actual usable size */
  struct ymds_time begin, end ;	/* Beginning/Ending time span */
} ;
struct antHistInfo {
  struct antHistLogfile logfiles[ ANTLOGMAXFILES ] ;
} ;

/* *************************
 * *                       *
 * *  Function Prototypes  *
 * *                       *
 * *************************
 */
/* Function prototypes for functions only used locally within the
 * antenna library package.  Externally referenced functions are
 * declared in the antenna_lib.h file
 */
void bite_fault_update( void ) ;
#define WILD_UNIT (-1)
void bite_local_update( SINT4 iUnit_a );

UINT1 lAntSimulator( void ) ;

UINT2 lokay_to_set_time_int
  (volatile struct antenna_info* pant_a) ;

void antMakeHistoryEntry
( const UINT1 *pStr_a, 
  SINT4 iLength_a, 
  UINT4 iClientMask_a,   /* Mask indicating which client we are */
  volatile struct antUpdateItem *pItem_a ) ;

/* ------------------------------
 * The following are defined in both ant_global.h and antsim_global.h
 */
FLT4 fbound( FLT4 fmax_a, FLT4 fval_a );
void velocity_matrix_compute
( FLT4 fmatrix_a[3][3],
  FLT4 frotation_vel[3],	/* Order pitch, roll, heading */
  FLT4 frotation_pos[3],
  FLT4 fplatform_offset[3]
  ) ;
void position_matrix_compute
( FLT4 fmatrix_a[3][3],
  FLT4 frotation_pos[3]
  ) ;
void  matrix_mul3
( FLT4 fvelocity_a[3],		/* resulting velocity */
  FLT4 fmatrix_a[3][3],
  FLT4 fplatform_offset_a[3]
  );

/* ------------------------------
 * Internal control routines, called via AntSet() to do the actual
 * work of each operation.
 */
void __ant_set_az_vel( FLT4 fspeed_a ) ;
void __ant_set_el_vel( FLT4 fspeed_a ) ;
void __ant_set_az_pos( BIN2 iangle_a ) ;
void __ant_set_el_pos( BIN2 iangle_a ) ;
void __ant_stop_az( void ) ;
void __ant_stop_el( void ) ;
void __ant_set_auto( UINT2 lon_a ) ;
void __ant_set_iris( UINT2 lon_a ) ;
void __ant_set_noise( UINT2 lon_a ) ;
void __ant_toggle_noise( void ) ;
void __ant_set_nst_timeout( UINT4 imilisec_a ) ;
void __ant_set_nst( const char *snst_site3_a, UINT2 lfault_a ) ;
void __ant_set_rstmode( const char *srst_name_a, UINT2 lwait_a ) ;
void __ant_set_servo( UINT2 lon_a ) ;
void __ant_set_radiate( UINT2 lon_a ) ;
void __ant_toggle_radiate( SINT4 iWarmTimeMs_a ) ;
void __ant_wait_for_radiate( SINT4 iWarmTimeMs_a ) ;
void __ant_set_sigcw( UINT2 lon_a ) ;
void __ant_set_siggen( UINT2 lon_a ) ;
void __ant_set_siggen_value( const SINT4 ivalue_a, const UINT2 lwait_a ) ;
void __ant_set_trpower( UINT2 lon_a ) ;
void __ant_set_reset( void ) ;
void __ant_set_pwbw( UINT2 ipwbw_a ) ;
void __ant_set_polar( UINT2 iPolar_a ) ;
void __ant_set_time( void ) ;
void __ant_put_chat( UINT1 ichar_a ) ;
void __ant_set_drcp_mode( UINT2 iDrcpMode_a ) ;
void __ant_set_drcp_relinquish( UINT2 lRelinquish_a ) ;
void __ant_set_drcp_wouldUse( UINT2 lWouldUse_a ) ;

void __bite_set_button( UINT2 lbutton_in_a, SINT4 ifield_a ) ;
void __bite_send_command( UINT1 icommand_a ) ;
void __bite_send_unit_command( UINT1 iCommand_a, UINT1 iUnitId_a ) ;

#undef EXTERN
