/******************************************************************************
//  sbe.c  : Nov 2008
//  control of SBE CTD
//  for the Spray 2008 CF2 controller board
//
//  mar11 added DOX functions, as per BDJ changes in 0711 code.
//  dec11 added DO error-catch for too-big of a frequency.
//  oct14 add more catches for DO6 data return
//==== Future Expansion =======================================================
//		last update: Feb2009
//
//****************************************************************************/

#include	<cfxbios.h>		// Persistor BIOS and I/O Definitions
#include	<cfxpico.h>		// Persistor PicoDOS Definitions

#include	<assert.h>
#include	<ctype.h>
#include	<errno.h>
#include	<float.h>
#include	<limits.h>
#include	<locale.h>
#include	<math.h>
#include	<setjmp.h>
#include	<signal.h>
#include	<stdarg.h>
#include	<stddef.h>
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<time.h>

#include    "cf2_qsm332.h"
#include    "spi_cmd.h"
#include    "tcm2.h"
#include    "pitch_roll.h"
#include    "pump.h"
#include    "dat_fnx.h"
#include    "sbe.h"
#include    "gpio_mux.h"
#include    "setup.h"

// globals
extern char   Verbose;  // switch for displaying more info
extern char   IRQ_Flag; // interrupt flag: says what caused the interrupt
extern short  iparam [ MAX_PARAM ]; // global parameter settings
extern struct all_param all;

//--- internal prototypes -------------------
void   menu_sbe           ( void );
void   sbe_debug_test     ( void );
void   sbe_menu_debug     ( void );
void   sbe_daq_ts         (float *p, float *t, float *s);
void   all_cycle          ( void );

short  sbe_pump_lo ( void ) //*************************************************
{  // turn on the sbe pump, low speed
   short ierr = 0;
   struct spi_param *ss;
   
      ss = all.sspi; // points to the spi comms struct
      ss->pcs = CS_GPIO;   // command is for the GPIO chip
      init_qsm( CS_GPIO ); 
      init_spi();

  ierr = spi_aux_pwr(  AUX_ON_SBE_PMP, ss ); // make sure low speed is on
  DelayMilliSecs(50); // let happen
  ierr = spi_aux_pwr( -AUX_OFF_SBE_HI, ss ); // & high speed is off
  
  
  return ( ierr );
} //***************************************************************************

short  sbe_pump_hi ( void ) //*************************************************
{  // turn on the sbe pump, high speed
   short ierr = 0;
   struct spi_param *ss;
   
      ss = all.sspi; // points to the spi comms struct
      ss->pcs = CS_GPIO;   // command is for the GPIO chip
      init_qsm( CS_GPIO ); 
      init_spi();

  ierr = spi_aux_pwr( AUX_ON_SBE_HI, ss ); 
  
  
  return ( ierr );
} //***************************************************************************

short  sbe_pump_off ( void ) //************************************************
{  // turn on the sbe pump, low speed
   short ierr = 0;
   struct spi_param *ss;
   
      ss = all.sspi; // points to the spi comms struct
      ss->pcs = CS_GPIO;   // command is for the GPIO chip
      init_qsm( CS_GPIO ); 
      init_spi();

  ierr = spi_aux_pwr( -AUX_ON_SBE_PMP, ss ); 
  
  
  return ( ierr );
} //***************************************************************************


//*****************************************************************************
short  send_sbe ( TUPort *tup, char str[], char sget[] )  //*******************
{ // send str to SBE & get the reply
  // returns the # of bytes actually read
   short nget, found;  // = num char read
   
   TURxFlush(tup);   //  flush the tpu port
   tputs       ( tup, str);  //* send string
   nget = tgets( tup, sget, 80, 1, '\n', &found); //* read up to 80 char
   
   return ( nget );
} //***************************************************************************

void  cr_2_sbe ( void ) //****************************************************
{ // send a CR to the SBE to nudge it awake

  // char ch[80];
  TUPort    *tup;

  tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer

  TURxFlush  ( tup );   //  flush the tpu port
  TUTxFlush  ( tup );   // flush the transmit buffer
  TUTxPutByte( tup, '\n', 0); //0=don't wait for reply char
  
  return;
} //***************************************************************************



short  sbe_wakeup ( void ) //**************************************************
{ // wake up the CTD

  // returns TRUE if successful
  // PROMPT = 'S>' when SBE is ready

  char ch[80];
  short i, j, n=0, istat, found;
  TUPort    *tup;

  tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer

  TURxFlush(tup);   //  flush the tpu port
  TUTxFlush( tup); // flush the transmit buffer
  for (i=0;i<3;i++)
  { // xmit "\r\n" to wake up the SBE =====================

    tputs ( tup, "\n" ); // tputs adds "\r\n" to end
    // sending "\n\r\n" does a better job of waking up than just "\r\n"
    //TUTxPutByte( tup, '\r', 0); // \r = CR = 13
    //TUTxPutByte( tup, '\n', 0); // \n = LF = 10
    TUTxWaitCompletion ( tup ); // wait for the transmission to be complete
    DelayMilliSecs( 10 ); // wait 10ms for SBE to awaken
    // should get an immediate response if SBE is already awake

    // the following gives a longer delay for the SBE to wake up
    // if coming out of a sleep mode
    // this doesn't seem necessary with above "\n\r\n", 
    // but keeping anyway, just in case
    j=0; // else we are waking up from being asleep
    while (j<3 && TURxQueuedCount( tup )== 0 )
    { // no response yet, wait awhile longer
      DelayMilliSecs( 20 ); // wait 20ms for SBE to awaken
      j++;
    }
    
    if  (  TURxQueuedCount( tup ) > 0 ) break; // exit loop 
  } //=====================================================

  // cprintf("i=%d j=%d\n",i, j);
  // read in response : read up to 5 lines of jibberish
  i=0;
  istat=0;
  while ( (i++<5) && (!istat) ) //=====================================
  {
    n = tgets(  tup, ch, 79, 1, '>', &found);// read in reply, up to prompt
    // found = true if '>' was found
    //if (  n>0 ) cprintf("w%d: found=%d %s\n",i, found, ch); //debug
    if (  n>0 )  istat = ( ch[n-1] =='S'  && found );  // true if last char = S
    if ( n==0 ) i=5; // no response after 1s, quit now
    //if ( n>0 && !istat ) printf("WBAD%d:%d,%s\n",i, found, ch); // debug
        
  } //=================================================================
  
  return(istat);
} //***************************************************************************



void sbe_sleep( void ) //******************************************************
{ // put the SBE into low-power mode
  TUPort    *tup;

  tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer

  sbe_wakeup( );  // get a prompt

  // put in low power
  tputs( tup, "qs");
  
  return;
} //***************************************************************************


void sbe_p_reset(  void ) //***************************************************
{ // reset pressure offset
  short i, n;
  float p;
  TUPort    *tup;

  tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer

  if ( sbe_wakeup( ) )  //=============================================
  {  // reset only if get a correct response

    TURxFlush( tup );   //  flush the tpu port
    tputs( tup,"resetoffset"); // send reset command
    cprintf("will wait 60-90 s for SBE pressure reset\n");
    for (i=0;i<35;i++) DelayMilliSecs(1000);
    
    i=0; p =-99;
    while ( (i++<40) && (p<-98) ) //-----------------------------
    { // try to get a pressure reading
      DelayMilliSecs( 1000 );
      n = sbe_wakeup(  ); 
      if ( n) // then awake
         p = sbe_fp(  ); // get pressure
      else
         cprintf("SBE not done yet, will try again...\n");
         
    } //---------------------------------------------------------
    
    printf("NEW surface p= %6.2f\n",p);
  } //=================================================================
  
  return;
} //***************************************************************************


void   sbe_status ( void ) //**************************************************
{ 
  char sget[82];
  short n, found;
  TUPort *tup;
  
  tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer
  
  // cprintf("sbe_status\n");
  n = sbe_wakeup (  );
  if (n) //============================================================
  { // then it is awakened, get the status
    n = send_sbe ( tup, "ds", sget ); // send the request, returns the echo
    // if (n>0) cprintf("1: %s\n",sget); // show 1st line = echo
    n = tgets( tup, sget, 80, 1,'\n', &found); // read in response
    if (n>0) cprintf("%s\n", sget);  // got a 2nd line response, display
  } //=================================================================
  else
  { cprintf ( " NO SBE response\n"); }
  
  return;
} //***************************************************************************



float sbe_fp_samp ( void ) //**************************************************
{ // sample pressure only
  // return float value : p=-99 = bad value
  
  char ch[20];
  float p = -99; // set to an illegal value
  short n,nval, j, found;
  TUPort    *tup;

  tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer

  TURxFlush(tup);   //  flush the tpu port
  tputs( tup,"fp");  // send the request

  // read in stuff until we get ~right length
  j=0; // counter
  n=0; // # char read in
  while (j++<5  &&  n<6) //======================
  {
    n = tgets( tup, ch, 18, 1, '\n', &found);
  } // if n>6, then it is likely legal ==========

  if (n>4) // then likely good
  { 
    nval = sscanf( (char*) ch,"%f",&p);
    if (nval != 1) p = -99;  // if can't read set flag
  }
  
  return(p);
} //***************************************************************************

float sbe_fp( void ) //********************************************************
{ // complete function to sample P only
  // wake up sbe, get p and return : if bad p = -99
  short istat;
  float p;
  
  istat = sbe_wakeup( );  // see if SBE is awake
  if (!istat) istat = sbe_wakeup( );  // if not, try again
  p = sbe_fp_samp(  );  // and try to get press no matter what
  return(p);
} //***************************************************************************


void  sbe_send_tsp( void ) //**************************************************
{ // wake up the SBE and send the tsp command
  // this will leave the SBE powered up
  char ch[80];
  short n, found;
  TUPort    *tup;

  tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer
  sbe_wakeup (     );   // wake up SBE, takes ~0.8 s
  TURxFlush  ( tup );   // flush the tpu port
  
    tputs( tup,"tsp");
    // read in echo and ignore
    n = tgets(  tup, ch,10,1,'\n',&found);// get echo string, terminates w/LF
    
    DelayMilliSecs(500); // wait 0.5 s for SBE to start up
    // the SBE puts out a spurious char on start-up so
  TURxFlush  ( tup );   // flush the tpu port

  return ;
} //***************************************************************************

#if DOX==1 //*** dissolved oxygen, send different command request *************
  void  sbe_send_tspo( void ) //***********************************************
  { // mar11: wake up the SBE and send the tspo command
  // this will leave the SBE powered up
  char ch[80];
  short n, found;
  TUPort    *tup;

  tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer
  sbe_wakeup (     );   // wake up SBE, takes ~0.8 s
  TURxFlush  ( tup );   // flush the tpu port
  
    tputs( tup,"tspo"); //mar11 change from send_tsp cmd
    // read in echo and ignore
    n = tgets(  tup, ch,10,1,'\n',&found);// get echo string, terminates w/LF
    
    DelayMilliSecs(500); // wait 0.5 s for SBE to start up
    // the SBE puts out a spurious char on start-up so
  TURxFlush  ( tup );   // flush the tpu port

  return ;
  } //*************************************************************************
#endif  // end if DOX compile option ******************************************


//*****************************************************************************
short sbe_get_tsp(  float *p, float *t, float *s) //***************************
{ // get a sbe sample; does a cal and stays in high current
  // return 0 if bad, 1 if good
  char ch[80];
  short istat =0, n, nval, found;
  TUPort    *tup;

  tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer

  *p = -99; *t=-99; *s=-99;  // set values to bad settings

  sbe_send_tsp(  );  // request a 'tsp'  
    
    // get the reply
    n = tgets( tup, ch,40,6,'\n', &found);// get string
    
    if (n) //========================================================
    { // true if got a reply
      nval = sscanf(  ch,"%f,%f,%f",p,t,s);
      if (nval == 3) istat=1;  // set istat=1 = good, if read is good
    } //=============================================================

  return(istat);
} //***************************************************************************


//*****************************************************************************
short sbe_get_lts(  float *p, float *t, float *s) //******
{ // get the last sbe sample; also causes sbe to take another & stay in lowpower 
  // return 0 if bad, 1 if good
  char ch[80];
  short istat =0, n, nval, found;
  TUPort    *tup;

  tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer

  *p = -99; *t=-99; *s=-99;  // set values to bad settings

  TURxFlush  ( tup );   // flush the tpu port
  tputs( tup, "lts");  //send the command
    // read in echo & ignore
    n = tgets( tup, ch,10,1,'\n',&found);
    
    // get the reply
    n = tgets( tup, ch,40,1,'\n', &found);// get string
    //cprintf("\nCH=%s\n",ch);
    
    if (n) //========================================================
    { // true if got a reply
      nval = sscanf(  ch,"%f,%f,%f",p,t,s);
      if (nval == 3) istat=1;  // set istat=1 = good, if read is good
    } //=============================================================

  return(istat);
} //***************************************************************************

#if DOX ==1 //mar11 compile if DOX is installed *******************************
//*****************************************************************************
  short sbe_get_tspo(  float *p, float *t, float *s, float *d) //**************
  { // get a sbe sample; does a cal and stays in high current
    // mar11 DOX includes *d = DOX value
    // return 0 if bad, 1 if good
    char ch[80];
    short istat =0, n, nval, found;
    TUPort    *tup;

    tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer

    *p = -99; *t=-99; *s=-99; *d=-99; // set values to bad settings

    sbe_send_tspo(  );  // mar11, get DOX value as well
    
    // get the reply, mar11, includes more char for DOX
    n = tgets( tup, ch,50,6,'\n', &found);// get string
    
    if (n) //========================================================
    { // true if got a reply, mar11 read in DOX as well (comma-separated)
      nval = sscanf(  ch,"%f,%f,%f,%f",p,t,s,d);
      if (nval == 4) //----------------------------------- 
      { // correct # was read in
        istat=1;  // set istat=1 = good, if read is good
        // dec11, catch a bad value of DO
        if ( *d > 10000 ) *d= 890; //SBE firmware fails at <=900 Hz, giving roll-over #
      } //------------------------------------------------
    } //=============================================================


    return(istat);
  } //*************************************************************************

  short sbe_get_ltso(  float *p, float *t, float *s, float *d ) //*************
  { // get last sbe sample; also causes sbe to take another & stay in lowpwr
    // mar11 DOX version includes *d for do value 
    // return 0 if bad, 1 if good
    char ch[80];
    short istat =0, n, nval, found;
    TUPort    *tup;

    tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer

    *p = -99; *t=-99; *s=-99; *d=-99; // set values to bad settings

    TURxFlush  ( tup );   // flush the tpu port
    tputs( tup, "ltso");  // mar11 send command that includes DOX
    // read in echo & ignore
    n = tgets( tup, ch,10,1,'\n',&found);
    
    // get the reply: DOX, get more char & wait a little longe
    n = tgets( tup, ch,50,2,'\n', &found);// get string
    
    if (n) //========================================================
    { // true if got a reply, including DOX (NOT comma separated)
      nval = sscanf(  ch,"%f,%f,%f %f",p,t,s,d);
      if (nval == 4) //----------------------------------- 
      { // correct # was read in
        istat=1;  // set istat=1 = good, if read is good
        // dec11, catch a bad value of DO
        if ( *d > 10000 ) *d= 890; //SBE firmware fails at <=900 Hz, giving roll-over #
      } //------------------------------------------------
    } //=============================================================
    

    return(istat);
  } //*************************************************************************
#endif  // end if DOX compile option ******************************************


//*****************************************************************************
//*****************************************************************************
// float to integer, integer to float conversion functions
ushort intPval(float p) //*****************************************************
{ // convert SBE p to integer value for storage/satellite xmit
  long ip;
  ip = ( p - PR_OFF)*INV_PGN;  // 10 dBar offset & 0.04 dBar resolution
  if (ip<0) ip=0;
  if (ip>65535) ip=65535;  //keep to legal limits
  
  return( (ushort)ip );
} //***************************************************************************

float fltPval(ushort ip) //****************************************************
{ // convert SBE intPval back to dBar
  float p;
  p = (float)ip *F_PR_GN + PR_OFF;  // 10 dBar offset & 0.04 dBar resolution
  
  return(p);
} //***************************************************************************

ushort intTval(float t) //*****************************************************
{ // convert SBE T to integer value for storage/satellite xmit
  long ip;
  ip = ( t - T_OFF)*INV_TSGN;  // 5 deg offset & 0.001 deg resolution
  if (ip<0) ip=0;
  if (ip>65535) ip=65535;  //keep to legal limits
  
  return( (ushort)ip );
} //***************************************************************************

ushort intSval(float s) //*****************************************************
{ // convert SBE S to integer value for storage/satellite xmit
  long ip;
  ip = ( s - S_OFF)*INV_TSGN;  // 1 PSU offset & 0.001 PSU resolution
  if (ip<0) ip=0;
  if (ip>65535) ip=65535;  //keep to legal limits
  
  return( (ushort)ip );
} //***************************************************************************


#if DOX==1 //  mar11, if we have a SBE43 DOX sensor
  ushort intDval(float d) //***************************************************
  { // convert SBE DOX to integer value for storage/satellite xmit
    long ip;
    ip = d;  // 
    if (ip<0) ip=0;
    if (ip>65535) ip=65535;  //keep to legal limits
    return( (ushort)ip );
  } //*************************************************************************
#endif  // end if DOX compile option ******************************************

#if DO6==1 || PH==1 //if we have a SBE63 DOX sensor //JUL13 bdj
ushort intDval(float d) //******************************************
{ // convert SBE DOX to integer value for storage/satellite xmit
  long ip;
  ip = ( d ) * 1000;  // 
  if (ip<0) ip=0;
  if (ip>65535) ip=65535;  //keep to legal limits
  return( (ushort)ip );
} // end intDval ****************************************************
#endif

void    sbe_stop_profile ( void  ) //******************************************
{ // turn off things at the end of ascent

  sbe_pump_off(); // turn off the pump
  sbe_sleep();    // leave sbe in low power
  all.dat->sbe_pro_on = 0;  // set flag that we're no longer profiling  
  
  return;
} //***************************************************************************

void    sbe_start_profile ( void  ) //*****************************************
{ // turn off things at the end of ascent
  // --- apr13 ---------
  // sbe_get_tsp does initial calibration stuff, and
  // is part of the reason it takes ~4-5s to spit out an answer.
  // It then is supposed to load it into the 'last data scan' buffer.
  // however SBE v3.0 does NOT do this.  
  // the code is modified below to make it work with 3.0 stuff,
  // by taking a 'lts', but effectively dumping that point.
  //--bench-testing shows 0.7s delays between samples is OK
  //  0.6s NOT OK.
  //  but went for a 2s/2s delay times

  float p, t, s, d=0;
  
  all.dat->i = 0;   // reset profile ram data buffer to 1st record
  #if PH==1
    all.ph->i   = 0; //reset pH ram data buffer to 1st record
  #endif
  
  sbe_pump_lo (); // switches the pump from high to low speed
  #if DOX==1 // mar11
    sbe_get_tspo(&p,&t,&s, &d); // get a sample...
    //--apr13, get last-value needed for v3.0
    DelayMilliSecs(2000);
    sbe_get_ltso(&p,&t,&s,&d); //get a sample
    // this will be a bogus value from the LAST profile,
    // but will trigger another scan, which will be correct
    printf("%6.2f %8.4f %8.4f %5.0f\n",p,t,s,d);
    DelayMilliSecs(2000);
  #else // no DO sensor
    sbe_get_tsp(&p,&t,&s); // get a sample w/o DO
    printf("%6.2f %8.4f %8.4f\n",p,t,s);
    //--apr13, get last-value needed for v3.0
    DelayMilliSecs(2000);
    sbe_get_lts(&p,&t,&s);
    // this will be a bogus value from the LAST profile
    // but will trigger another scan, which will be correct
    printf("%6.2f %8.4f %8.4f\n",p,t,s);
    DelayMilliSecs(2000);
  #endif
  // this turns on sbe, cals the a/d, gets a sample, & leaves on.
  all.dat->sbe_pro_on = 1; // set flag that we're in profile mode
    
  return;
} //***************************************************************************

void query_sbe(void) //********************************************************
{  // send cmd, and get multi-line response
   short i,nget, n, found;  // = num char read
   char str[80], sget[80];
   TUPort    *tup;

   tup = all.tu_port[TU_SBE].tup;  // correct tpu uart port pointer

   
   cprintf(" type line to send out to SBE >\n");
   SerInFlush();
   gets(str);
   cprintf(" give time (s) to wait for a response \n");
   i = get_num(&n);
   if (i==0) return;  //didn't read a valid #
   
   TURxFlush(tup);   //  flush the tpu port
   tputs( tup, str);  //* send string
   
   nget=1; i=0;
   while ( (i++<120) && (nget>0) ) //---------------------------------
   { // calib output is ~28 lines
     nget = tgets( tup, sget,80,n,'\n',&found); //* read up to 80 char
     if (nget>0) cprintf("%s",sget);
   } // end while ---------------------------------------------------
   
   return;
} //***************************************************************************



ushort   sbe_avg_p ( short n  ) //*********************************************
{ // take n samples of p and return the average
  float p, pavg=0;
  unsigned short i, m=0;
  
  for (i=0;i<n;i++)
  { // try to take n samples
    p = sbe_fp();
    DelayMilliSecs(200);
    if (p>-98)
    { // then valid
      m++;
      pavg += p;
      printf("p=%6.2f\n",p);
    }
  } // take n samples
  
  // average if something is there
  if (m>0)
  { pavg /=m; i= intPval(pavg); }
  else i = 0; // set to bad value
  
  return ( i );
} //***************************************************************************

void  sbe_daq_ts(float *p, float *t, float *s) //******************************
{ // mimics the test code in dat_fnx.c : UPDATED Apr 2005 for SBE 1.8 code
  // sbe_start_profile must precede, and sbe_stop_profile must proceed
  short i=0, ierr, err, opt_flag, dms, val;
  struct dat_param *DP;
  ulong ms;
  RTCTimer rt;
  
  DP = all.dat;

  service_wdog();  // 0902 update the watchdog heartbeat
  opt_flag = iparam [ IA_use_opt ]; // can be changed via shore command
  if (opt_flag) Opt_On; // turn on optical sensor

  cr_2_sbe;      // write out cr to get attn of SBE

  // collect all other data ===========================================
  // compass timing: get_tcm2( 1 ) = cycle-power takes ~1.5s
  // turn on, get other sensors, then get_tcm2 takes ~1.2s total
  RTCElapsedTimerSetup(&rt);
  tcm2_on(); //turn on compass & let it do the first acq.
  
  //initiate a/d transactions with ea module
  DelayMilliSecs( 5 ); //0902 changed from 20 to 5
  err = rqst_a2d ( CS_GPIO,  AD_AUX_V_14 );
  if (err != SPI_CRC_OK) cprintf("Err rqst gpio V_14 %c\n", err);
  err = rqst_a2d ( CS_PITCH, AD_POT );
  if (err != SPI_CRC_OK) cprintf("Err rqst pitch pot %c\n", err);
  err = rqst_a2d ( CS_ROLL,  AD_POT );
  if (err != SPI_CRC_OK) cprintf("Err rqst roll pot %c\n", err);
  if ( all.hyd->status != PUMP_WAIT ) 
  {
     err = rqst_a2d (CS_HYD, AD_HYD_AMPS );
     if (err != SPI_CRC_OK) cprintf("Err rqst hyd amps %c\n", err);
  }
  // get results
  DelayMilliSecs( 300 ); //0902 changed from 20 to 300
  // this is to avoid tcm2 xmit, causing potential glitches on spi
  
  val = last_a2d     ( CS_GPIO, AD_AUX_V_14 ); 
  if (val<0) 
  {
      val = r_get_a2d( CS_GPIO, AD_AUX_V_14 ); //0902 try again
      cprintf("V14 2x = %4d",val);
  }
  DP->es.ad_bat_14  = val;
  rqst_a2d ( CS_GPIO,  AD_AUX_V_07 );
  val = last_a2d     ( CS_PITCH, AD_POT );
  if (val<0) 
      val = r_get_a2d( CS_PITCH, AD_POT ); //0902 try again
  DP->es.ad_pitch   = val;
  val =      last_a2d( CS_ROLL, AD_POT );   
  if (val<0) 
      val = r_get_a2d( CS_ROLL, AD_POT ); //0902 try again
  DP->es.ad_roll    = val;
  if ( all.hyd->status == PUMP_WAIT ) //hhhhhhhhhhhhhhhhhhh
  { // then the pump is on
     get_hyd_ad ( ); // this samples all, even if pump is off
     DP->es.ad_current = all.hyd->amp;
     DP->es.ad_oil     = all.hyd->oil;
  }  // else the pump is off, just get the amps
  else {
    DP->es.ad_current = last_a2d ( CS_HYD, AD_HYD_AMPS );
    DP->es.ad_oil = 0;  
  } //hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
  val = last_a2d     ( CS_GPIO, AD_AUX_V_07 ); 
  if (val<0) 
      val = r_get_a2d( CS_GPIO, AD_AUX_V_07 ); //0902 try again
  DP->es.ad_bat_07  = val;

  ms = RTCElapsedTime( &rt)/1000 +1;
  dms = 800 - ms; //minimum delay time for compass
  // 0.45 s to here : 0902, 0.75s
  if (dms>0) DelayMilliSecs( dms );
  ierr = get_tcm2(  0 );  //takes 1 sample, doesn't cycle power
  DP->es.eng_err = ierr*0x10;
  if (ierr) 
  {
     ierr = get_tcm2( 0 ); // try again
     DP->es.eng_err += ierr;  //record the error flag
  }
  tcm2_off();
  ms = RTCElapsedTime( &rt)/1000 +1;

  //cprintf("tcm2 dms=%d,tot=%ld err=%x  ", dms, ms, DP->es.eng_err);
  if (ierr==0) //------------------------------------------------
  {  // only use good compass value
     // else the old values will be used: good enough for a glitch
     DP->es.comp  =  10*all.comp->head;  //=deci-degrees
     DP->es.roll  =  10*all.comp->roll;
     DP->es.pitch =  10*all.comp->pitch;
  } //-----------------------------------------------------------

  // minimum time to sample optics ~1.7 s
  if (opt_flag) //-----------------------------------------------
  {  
     val = r_get_a2d     (CS_GPIO, AD_AUX_OPT ); 
     if (val<0) 
         val = r_get_a2d (CS_GPIO, AD_AUX_OPT ); //0902 try again
     DP->ds.optic  = val;
     Opt_Off; // turn off optical sensor
  } //-----------------------------------------------------------
  
  cprintf(" ms=%4d v=%4d",dms, DP->es.ad_bat_14);
  
  ierr = sbe_get_lts(p,t,s); //Apr2005, get last PTS taken & take new one
  // this leaves sbe powered up
  cprintf(" pi=%4d ro=%4d amp=%2d oil=%3d  opt=%4d \n",
       DP->es.ad_pitch, DP->es.ad_roll, DP->es.ad_current,
       DP->es.ad_oil, DP->ds.optic );
  return;
} //***************************************************************************

void all_cycle ( void ) //*****************************************************
{ // simulate profile data collection
  short b=' ';
  float p, t, s;
  short ip, it, is, n=0, irq_flag;
  long tnow;

  cprintf("Type '.' to exit\n");
  tnow = RTCGetTime(0,0);  // get the time
  do //==========================================================
  { // repeat until done
       irq_flag = hibernate( &tnow, 3, PIT_IRQ2 );
       if ( irq_flag == IRQ2_F ) //----------------------------
       { // interrupt from msp430,
         cprintf("Wake-up from CF2_ATTN\n");
         service_wdog(); // service the CF2
       } //----------------------------------------------------
       sbe_daq_ts(&p,&t,&s);
       ip = intPval(p); it=intTval(t); is=intSval(s);
       n++; // sample counter
       //printf("%6.2f %8.4f %8.4f\n",p,t,s);
       cprintf("%4d %2d %5u %5u %5u ",n, irq_flag, ip,it,is);
    b =  SCIRxGetCharWithTimeout( 500 ); // get a new character
  } while ( b != '.' );
  cprintf("total samples taken = %4d\n",n);
  
  return;
} //***************************************************************************

#if DO6==1
short  start_do6(  void ) //*****************************************************
{  // power up the DO6
   short ierr = 0;
   struct spi_param *ss;
   
      ss = all.sspi; // points to the spi comms struct
      setup_spi ( CS_GPIO, ss );
      //ss->pcs = CS_GPIO;   // command is for the GPIO chip
      //init_qsm( CS_GPIO ); 
      //init_spi();
  //printf("start_do6...\n"); //debug

#if PH
  Opt_On; // do6 shares power with optical
#else   
  ierr = spi_aux_pwr( AUX_ON_SPARE1, ss ); // DO6 now has power
#endif  
  ierr = spi_mux( 1, SER_ISUS, ss ); // turn on rs232 & configure mux
     if ( !ierr )
     cprintf("Err Stat mux_ntk\n" );
  
  return ( ierr );
} //***************************************************************************

short  close_do6( void ) //*****************************************************
{  // power off the SBE63
   short ierr = 0;
   struct spi_param *ss;

   
      ss = all.sspi; // points to the spi comms struct
      setup_spi ( CS_GPIO, ss );
      //ss->pcs = CS_GPIO;   // command is for the GPIO chip
      //init_qsm( CS_GPIO ); 
      //init_spi();

#if PH
	Opt_Off; // do6 shares power with optical
#else   
    ierr = spi_aux_pwr( -AUX_ON_SPARE1, ss );
#endif
    DelayMilliSecs(10);  //** wait 
  
    ierr = spi_mux( 0, SER_ISUS, ss ); // turn off rs232 
    
    //the danger I can see is if we dont switch the mux back to the compass,
    //we could have problems.  As of JUL13 I see all calls to get_tcm2() where
    //power is NOT cycled have the tcm2_on() call a few steps before.  This 
    //will ensure the mux is set to the compass

  return ( ierr );
} //***************************************************************************

short send_ts_do6( TUPort *tup ) 
{ // oct14: send 'ts' to do6 & get the reply
  // returns an error based on the echo status
   char sget[20], sget2[20];  // echo
   short nget, found, found2, n2, echo_err;  // = num char read
   // oct14, added echo_err
   // bit0 = 0 = got "ts", 1= "ts" not matched
   // bit1 = 1 = got "\n" first time,  0 = did NOT
   // bit2 = 0 = got "\n" second time, 1 = did NOT
   
   TURxFlush(tup);   //  flush the tpu port
   tputs    (tup, "ts\n");  //* send ts cmd
   sget[2] = 0; sget[3] = 0; // init
   nget = tgets( tup, sget, 10, 1, '\n', &found); //* read up to 10 char
   // tgets uses 50ms timing after first char rcvd. This might be too fast
   // to catch the '\n', as it appears that SBE sends 'ts', does something 
   // else (dependent upon #avg) and then sends '\n'
   //printf("nget=%d, s[0]=%02x s[1]=%02x\n",nget,sget[0],sget[1]);
   //printf("sget= %s\n",sget);
   if ( sget[2] =='t' && sget[3] == 's' )
   { //then got a good echo
     echo_err = 0; // so far so good
   }
   else { echo_err = 1; } // set b0=1 = bad echo, COMMENT OUT JAN19
   
   if (found) //=========================================
   {  // CR was found w/first string:
      // for the SBE63, this is an exception, as
      // a delay is actually expected
      echo_err +=2; // set b1=1
   } //==================================================
   else
   {  // no CR on the first pass
      // for the SBE63, a delay is actually expected
      // now try a 2nd time to get a CR
      n2 = tgets( tup, sget2,10, 1, '\n', &found2 );
      // waits up to another 1s for the '\n'
      if (!found2) echo_err +=4; // did NOT get it the 2nd time
     //printf("f2=%d, n=%d:%s; %02x \n", found2, n2, sget2, sget2[n2 -1]);
   } //==================================================
   //printf("f1=%d, n=%d:%s; %02x \n", found, nget, sget, sget[nget-1]);
   
   return ( echo_err ); 
} //***************************************************************************

/* OLD
short do6_get_ts(float *d, float *dT, float *dU)//*****************************
{ // get the SBE63 data response to a 'ts' command
  // d  = SBE63 DO value [mL/L]
  // dT = SBE63 T value [degC]
  // dU = SBE63 U value = raw phase delay
  // ==== oct14 returns an error code ====================
  // 0 = NO errors, else sets bit depending upon error
  // b0 = 1 = "ts" not matched
  // b1 = 1 = DID get '\n' match w/first echo (not expected)
  // b2 = 1 = did NOT get '\n' 2nd pass of echo
  // b3 = 1 = did NOT get '\n' for the data string
  // b4 = 1 = did NOT read in 4 variables in sscanf
  // b5 = 1 = data string <10 bytes.
  

  char ch[80];
  short i, n=0, nval,ierr=0,found=9;
  short err_do6; // oct14 keep track of error
  float temp;
  TUPort    *tup;
  struct spi_param *ss;
   
  ss = all.sspi; // points to the spi comms struct
  setup_spi ( CS_GPIO, ss );
  
  for(i=0;i<80;i++)ch[i]=0; //debug
  
  //set up the mux now, shared with the tcm2
  ierr = spi_mux( 1, SER_ISUS, ss ); // turn on rs232 & configure mux
  tup = all.tu_port[TU_ISUS].tup;  // correct tpu uart port pointer
  TURxFlush(tup);   //  flush the tpu port

  *d = -99; *dT=-99;  // set values to bad settings

  err_do6 = send_ts_do6(tup);  //send the command and get the echo
  // oct14 we are here after sending 'ts'...
  // should now take >1.5s for the answer
  // BUT removed the delay, as it seemed to come back much faster on the bench.
  //DelayMilliSecs(500); // nothing should have arrived yet
  TURxFlush(tup);   // flush the tpu port - clear out any 'CR' missed above.
  // now set for the real thing

    
    // oct14, removed waiting for another cr, as added code in
    // send_ts_do6 should get the cr if needed.  
    // This could have been the problem: if send_do6 GOT the CR,
    // then the below forced a 2s wait for the CR, which would have gotten 
    // the data, and then tossed it.    
    // OLD n = tgets( tup, ch, 10, 2, '\n', &found); //* read up to 40 char
    
    // and now the data reply; oct14, waiting up to 4s instead of 2
    n = tgets( tup, ch, 40, 4, '\n', &found); //* read up to 40 char
    if (!found) err_do6 +=8; // b3 = 0=OK, 1=no CR on data scan
    //printf("f=%d, n=%d:%s; %02x \n", found, n, ch, ch[n-1]);
    //printf("ch= %s\n",ch);
    
    if (n>10) //=====================================================
    { // true if got partial-something
      nval = sscanf(  ch,"%f,%f,%f,%f",dU,&temp,d,dT);
      if (nval == 4) 
      { // then read all 4 values just fine
        // all OK, don't have to set any flags
      }
      else  { err_do6 +=16; } // set b4=1 as bad data scan.
      //*dU = 0.003; //will show up as int = 3 in sat file
    } // end if valid string
    else  //=========================================================
    { err_do6 +=32; } // set b5=1 as <10 char back.
    //===============================================================
    
    TURxFlush(tup);   //  flush the tpu port
    // oct14: if any errors, store in dU
    if ( err_do6>0 )
    { // record the exception in dU, which normally is >16
      *dU = err_do6*0.001;  // this goes to flash
      // keep tabs of set bit flags: sent back via satellite
      all.exc->sbe_err = all.exc->sbe_err | err_do6;
    }
    
        
  return ( err_do6 );
} //**************************************************************************/
// ****************************************************************************
short do63_attn ( TUPort *tup )
{ // get attn of the DO, jul17
  // returns found=1 if got '>' reply, else returns 0
   char sget[41],  esc; 
   short nget, found;  
   
   esc = 0x1B; // escape char
   TURxFlush(tup);   //  flush the tpu port
   // ju17, get attn first of DO by sending ESC & waiting for S> prompt
   TUTxPutByte( tup, esc, 0); // jul17, send the escape char
   // wait up to 1s to get the prompt '>' reply
   nget = tgetsTmax( tup, sget, 40, 1, '>', &found); //Jeff's call
   
   
   return ( found );
} // **************************************************************************
short   do6_get_ts  (float *d, float *dT, float *dU) 
{ // get the SBE63 data response to a 'ts' command
  // d  = SBE63 DO value [mL/L]
  // dT = SBE63 T value [degC]
  // dU = SBE63 U value = raw phase delay
  // ==== oct14 returns an error code ====================
  // 0  = NO errors, else sets bit depending upon error
  // b0 = 1 = no '>' after sending ESC (did not get DO63's attn)
  // b1 = 1 = "ts" not echoed.
  // b2 = 1 = did NOT get the '>' at the end
  // b3 = 1 = did NOT read in 4 variables in sscanf
  // b4 = 1 = data string <10 bytes.
  // b5 = 1 = no valid decimal in str.
  

  char ch[80];
  short i, n=0, nval,ierr=0,found=9, ok;
  short err_do6=0; // oct14 keep track of error
  float temp;
  TUPort    *tup;
  struct spi_param *ss;
   
  ss   = all.sspi; // points to the spi comms struct
  setup_spi ( CS_GPIO, ss );
  //set up the mux now, shared with the tcm2
  ok   = spi_mux( 1, SER_ISUS, ss ); // turn on rs232 & configure mux
  // jul17, try 2x to set up the mux
  if (!ok) ok = spi_mux( 1, SER_ISUS, ss ); // try again
  tup  = all.tu_port[TU_ISUS].tup;  // correct tpu uart port pointer

  *d = -99; *dT=-99;  // set values to bad settings

  //OLD: err_do6 = send_ts_do6(tup);  
  // jul17, do entire parsing here
  for (i=0; i<2; i++) //-----
  { // jul17 try to get do6 attn
    ok = do63_attn( tup );
    if (ok) break;
  } //-----------------------
  if (!ok) err_do6 |= 1; // set b0==1, no SBE63 start-prompt
  
  // no matter what, send the ts command.
  DelayMilliSecs(50);
  TURxFlush(tup);   // flush the tpu port - clear out any 'CR' missed above.
  tputs( tup, "ts");  // tputs tacks on '\r\n'
  // jul17, will now wait up to 2s for a FULL reply
  // this includes the 'ts' echo, plus the data str: terminates with new '>'
  
    n = tgetsTmax( tup, ch, 79, 3, '>', &found); // read up to 79 char //JTS call
    if (Verbose) cprintf("do6 f=%d, n=%d:%s; %02x \n", found, n, ch, ch[n-1]);
    // the above includes the echo, plus the data
    if ( ch[0] !='t' || ch[1] != 's' )
    { //then bad echo
      err_do6 |= 2; // set b1=1 = bad echo
      if (Verbose) cprintf("do6_bad_echo: %d: %c%c\n", n, ch[0], ch[1] );
    }
    if (!found) 
    { // flag if did not get the '>' at the end.
      if (Verbose) cprintf("do6_bad_end: %d: %s\n last-char=%x", n, ch[n-1] );
      err_do6 |= 4; // b2 = 0=OK, 1=no '>' at the end
    }
    i = findFirstDec( ch, n );  // jul17 search for 1st valid number
    if (Verbose) cprintf("firstDec=%d, %s\n", i, &ch[i] );
    n = n -i; // #of char in remaining string
    if ( i>=0 && n>10) //============================================
    { // true if got partial-something
      nval = sscanf(  &ch[i],"%f,%f,%f,%f",dU,&temp,d,dT);
      if (nval != 4) 
      { // then did NOT read all 4 correctly
        err_do6 |= 8; // set b3=1 as bad data scan.
        if (Verbose) cprintf("do6_bad_nval: nval=%d: %s\n", nval, &ch[i] );
      }
    } // end if valid string
    else  //=========================================================
    { 
      ierr = 0;
      if (n<10)  ierr |= 16; //<10 char
      if (i<0 )  ierr |= 32; // no decimal found
      err_do6 |= ierr; // set flags
      if (Verbose) cprintf("do6_bad_str: i=%d, n=%d: %s\n", i, n, ch);
    } 
    //===============================================================
    
    TURxFlush(tup);   //  flush the tpu port
    // oct14: if any errors, store in dU
    if ( err_do6>0 )
    { // record the exception in dU, which normally is >16
      *dU = err_do6*0.001;  // this goes to flash
      // keep tabs of set bit flags: sent back via satellite
      all.exc->sbe_err = all.exc->sbe_err | err_do6;
    }
    
  return ( err_do6 );
} //***************************************************************************
//****************************************************************************
    short findFirstDec ( char *str, short n )
    { // search the first n char of str[] for the first decimal = '0'..'9',
      // include the '-' if it precedes the first decimal
      // return k, where str[k] = first valid value
      // if NOT valid, k=-1
      // --- used as valid input for a sscanf call

      short i, done;
        

      for (i=0; i<n; i++)
      //===================================
      { // look for a valid char
        done = (  (str[i]>='0' && str[i]<='9') );
        if (done) break;
      } //=====================================================
      

      if (i>0) //-----------------------
      { // see if decimal: if true, decrement i
        if ( str[i-1]=='.' ) i--;
      } //------------------------------
      

      if (i>0) //-----------------------

      { // see if negative sign: if true, decrement i
        if ( str[i-1]=='-' ) i--;
      } //------------------------------
      

      if (!done) i=-1;  // set flag that no value was found.
      

      return (i);

    } //**************************************************************************
//*****************************************************************************
void   DOxTransparent   (  void )  //Transparent COMM to SBE63
{ 
  short COM_to, ifecho;
  char c;
  unsigned long now,tl_com;
  TUPort    *tup;

  tup = all.tu_port[TU_ISUS].tup;  // tpu uart port pointer
  
  /*acm_off();
  printf("Power Up ");fflush(stdout);
  err=acm_Power_Up(); //make sure LOC is powered up
  if (err>=0)
    printf("OK\n");
  else 
  { printf("Err=%d\n",err);
    return;
  }*/
 
  SerInFlush();  //flush Spray COMM input buffer
  printf("Idle channel timeout (seconds)? ");fflush(stdout);
  scanf("%d",&COM_to);
  printf("Local echo of Spray output (y/n)? ");fflush(stdout);
  ifecho=YesNo();

 
  TURxFlush  ( tup );   // flush the tpu port input buffer
  SerInFlush();  //flush Spray COMM input buffer
  
  start_do6(); //Turn on the DOx
  
  //transfer bytes in both directions until neither end has transmitted
  //for tl_com seconds
  now=tl_com=RTCGetTime(0,0);
  while( (short)(now-tl_com) <= COM_to )
  { if( SCIRxQueuedCount() )
    { //xfer byte waiting at Spray COMM port to AC modem
      c = (char)SCIRxGetChar();
      TUTxPutByte ( tup, c, 0);   
      if(ifecho)SCITxPutChar(c);  //provide local echo
      tl_com=RTCGetTime(0,0);  //secs of last char from COMM
    }
   
    if( TURxQueuedCount(tup) )
    { //xferbyte waiting at AC modem to Spray COMM port
	    c = (char)TURxGetByte(tup,FALSE);  	//read in character
	    SCITxPutChar(c);
      tl_com=RTCGetTime(0,0);  //secs of last char from modem
    }
    
    now=RTCGetTime(0,0); 
  }
  
  close_do6(); //turn off the DOx
  
  printf("Channel has been Idle for %d seconds\n",COM_to);
  
  return;
}  //end Transparent
//*****************************************************************************

#endif //DO6==1

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
void  test_sbe  (   void )  
{ // test all of the SBE functions
  char ch=' ';
  float p, t, s;
  short ip, it, is,tmo=0;
 #if DOX==1
  float d;
  ushort id;
 #elif DO6==1 //oct12 bdj
  float d,dT,dU;
  ushort id,idT,idU, err_do;
 #endif

  cprintf("              Test of SBE : %s \n", __DATE__);
  menu_sbe();
  while ( ch !='Q') //=======================================================
  {
	SerInFlush();  // flush any characters

        if (ch !=' ' && ch>0 ) 
            cprintf("Z_1>\n"); // display directory prompt

	    ch = -1; // illegal value - means it timed out
	    ch = SCIRxGetCharWithTimeout( 1000 ); // get a new character
	    tmo = check_tmo ( &ch, tmo );
	    // increments the tmo counter if ch<0, and
	    // goes to sleep mode after max_tmo.  Returns *ch as upper-case
	    
	   
    switch (ch) { // call the desired function ++++++++++++++++++++++++++++
        case 'Q' : break;  // will quit the program
        case '?' : break;  // displays the directory prompt
        case 'U' : menu_sbe(); break;
        case  -1 :  break; // wait for another character
	    case '+' :  toggle_verbose(); // toggle verbose mode
				    break;


   #if DOX==1
        case 'C' : cprintf("getting P, T, S, DO...\n");
                   sbe_get_tspo(&p,&t,&s,&d);
                   ip = intPval(p); it=intTval(t); is=intSval(s);
                   id = intDval(d);
        		   printf("%6.2f %8.4f %8.4f %8.0f\n",p,t,s,d);
        		   printf("%6u %8u %8u %8u\n",ip,it,is,id);
        		   break;
   #elif DO6==1
         case 'C' :start_do6();
                   DelayMilliSecs(2000);
        		   sbe_get_tsp(&p,&t,&s);
                   ip = intPval(p); it=intTval(t); is=intSval(s);                 
        		   err_do = do6_get_ts(&d,&dT,&dU);
        		   close_do6();
        		   id = intDval(d); idT = intTval(dT); idU = intTval(dU);
        		   printf("%6.2f %8.4f %8.4f\n",p,t,s);
        		   printf("%6u %8u %8u\n",ip,it,is);
        		   printf("%5.4f %8.4f %8.4f err=%4x\n",d,dT,dU, err_do);
        		   printf("%8u %8u %8u\n",id,idT,idU);
        		   break;
         case 'T' :  DOxTransparent();
        		   break;
   #else
        case 'C' : cprintf("getting P, T, S...\n");
                   sbe_get_tsp(  &p, &t, &s);
                   ip = intPval(p); it=intTval(t); is=intSval(s);
        		   printf("%6.2f %8.4f %8.4f\n",p,t,s);
        		   printf("%6u %8u %8u\n",ip,it,is);
        		   break;
   #endif


	    case 'D' : sbe_debug_test();  break;  // debug tests
        case 'P' : p = sbe_fp(  ); 
        			printf("Press= %6.2f dBar\n",p); break; // read in P only

	    case 'S' : sbe_status( ); break;
	    
	    case 'Z' : sbe_sleep (  ); break;
	    
	    case '0' : cprintf("Resets SBE P to zero, proceed (Y/N)? >\n");
	               if ( YesNo() )
	               {  sbe_p_reset (  ); }
	               break;

        // pump control
        case 'H' : sbe_pump_hi(  );  
        		cprintf("SBE pump is on, high speed\n");
        		break;  // turn on  sbe pump
        case '1' : sbe_pump_lo(  );  
        		cprintf("SBE pump is on, low speed\n");
        		break;  // turn on  sbe pump
        case '2' : sbe_pump_off(  ); 
        		cprintf("SBE pump is OFF\n");
        		break;  // turn off sbe pump

        default  : cprintf(" input unknown \n");
    } // end switch +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    
  }  //=== end while ========================================================
  sbe_pump_off (  );
  sbe_sleep    (  );
  cprintf("SBE pump is off & SBE is in low power \n");

   return;
}  //**************************************************************************

void menu_sbe(void) //********************************************************
{ //print out menu selections 
 cprintf("                SBE Menu\n"
         "Q.uit SBE test  :  U.pdate menu    :  D.ebug SBE \n"
         "C.TD sample     :  P.ressure sample:  S.tatus of SBE\n"
         "Z.zz sleep      :  0.ZERO Pressure :  T.alk to 63\n\n"
         "1. SBE pump on  :  2. SBE pump off :  H.igh speed pump\n");

 return;
} //***************************************************************************


void   sbe_debug_test ( void ) //**********************************************
{ // debug lower level commands
  char ch=' ';
  float p, t, s;
  ushort ip, it, is;
  short n=1, istat, tmo;
  struct dat_param *DP;
  
  DP = all.dat;

  cprintf("\n                SBE Debug %s \n",__DATE__);
  sbe_menu_debug();

  while ( ch !='Q') //=======================================================
  {
	SerInFlush();  // flush any characters

        if (ch !=' ' && ch>0 ) 
            cprintf("Z_2>\n"); // display directory prompt

	    ch = -1; // illegal value - means it timed out
	    ch = SCIRxGetCharWithTimeout( 1000 ); // get a new character
	    tmo = check_tmo ( &ch, tmo );
	    // increments the tmo counter if ch<0, and
	    // goes to sleep mode after max_tmo.  Returns *ch as upper-case
	    
	   
    switch (ch) { // call the desired function ++++++++++++++++++++++++++++
        case 'Q' : break;  // will quit the program
        case '?' : break;  // displays the directory prompt
        case 'U' : sbe_menu_debug(); break;
        case  -1 :  break; // wait for another character
	    case '+' :  toggle_verbose(); // toggle verbose mode
				    break;
		
        case 'A' :  ip = sbe_avg_p(4); 
        			cprintf("ip=%u\n",ip);
        			t = fltPval(ip); // hardwired gain, offset
        			printf("fltPval=%6.2f\n",t);
        			p = dBar(ip,all.flt);
        			printf("dBar = %6.2f\n",p);
        			break; 

	    case 'L' : sbe_sleep();  break;  // put into low power
	    case 'W' : istat = sbe_wakeup();
                   if (istat) cprintf("SBE ok\n");
                   else cprintf("SBE did NOT respond\n"); 
                   break;
        case '1' : sbe_stop_profile( );
                   DelayMilliSecs(2000);
        		   sbe_start_profile( );
        		   sbe_get_lts(&p,&t,&s); // 0=error, 1=OK
                   printf("press = %f, temp = %f, sal = %f\n",p,t,s);		
                   break;
        case '2' : sbe_get_lts(&p,&t,&s); // 0=error, 1=OK
                   printf("press = %f, temp = %f, sal = %f\n",p,t,s);		
                   break;
        case 'S' : query_sbe(); break; // send request to SBE
        case '3' : sbe_start_profile( ); // turn on pump & prepare SBE
        			break;
        case '4' : sbe_stop_profile( ); // turn off pump & lowpower SBE
        			break;
        case '5' : sbe_daq_ts(&p,&t,&s);
                   ip = intPval(p); it=intTval(t); is=intSval(s);
        		   printf("%6.2f %8.4f %8.4f\n",p,t,s);
        		   printf("%6u %8u %8u\n",ip,it,is);
        			break;
          case '6' : cprintf("Ms to wait?"); // turn off pump & lowpower SBE
                    scanf("%u",&n);      			
        			cr_2_sbe;      // write out cr to get attn of SBE
        			DelayMilliSecs(n);
        			sbe_get_lts(&p,&t,&s); 
        			printf("%6.2f %8.4f %8.4f\n",p,t,s);
        			break;

        case '9' : all_cycle( ); // profile all-sample simulation
        			break;
		default  : cprintf(" input unknown \n");
    } // end switch +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    
  }  //=== end while ========================================================

   return;
}  // end debug_test *************************************************

void sbe_menu_debug(void) //***************************************************
{ //print out menu 
 cprintf("       SBE Debug Menu\n"
         "       Q.uit Debug    :   U.pdate menu\n"
         "A.vg pressure   :  L.owpower mode : W.akeup\n"
         "S.end query to SBE                : 9.sample all loop\n"
         "3.sbe_start_pro :  4.sbe_stop_pro : 5.sbe_daq_ts\n");
 return;
} //***************************************************************************


//*** end *********************************************************************
