/*
 * David Muller; Germán Alfaro
 * davehmuller@gmail.com; alfaro.germanevera@gmail.com
 *
 * 2018 Thom Maughan, tm@mbari.org (thommaughan@gmail.com)
 */




#include "system.h"
#include "uartstdio.h"
#include "user_io.h"
#include "ctd_base.h"
#include "ctd_sbe37_microcat.h"




extern struct ctdDriver ctd;        // struct defd in ctd_base.h
extern struct systemSamplingData sys_samp;

#ifdef CAPTUREDFROMTERATERM
SBE 37-SI

<Executed/>
ts
  23.3971,  0.00007,    0.127,   0.0113, 29 Apr 2021, 15:51:19
<Executed/>
#endif

#ifdef CAPTUREDFROMTERATERM_NEWSBE37

ts
  22.0757,  0.00002,   -0.015,   0.0109, 22 Mar 2022, 20:35:58
S>

#endif


//(power on)
//SBE 37-SI
//ts
//21.4218,  0.00006,   -0.147,   0.0105, 02 May 2021, 12:37:24
//<Executed/>
//
// "%f %f %f %s %s", &tempC, &dummy, &salt, buff, buff) != 5)
//21.4218,  0.00006,   -0.147,   0.0105, 02 May 2021, 12:37:24
//
//ds
//SBE37SI-RS232 v3.1  SERIAL NO. 15864  02 May 2021 14:09:00
//vMain =  9.79, vLith =  2.83
//samplenumber = 441540, free = 117700
//status = not logging
//sample interval = 10 seconds
//data format = converted engineering
//output salinity
//output time
//sample mode = interval sample
//auto run = no
//store data = yes
//pump installed = no
//<Executed/>
//
//getcd
//<ConfigurationData DeviceType = 'SBE37SI-RS232' SerialNumber = '03715864'>
//   <PressureInstalled>yes</PressureInstalled>
//   <PumpInstalled>no</PumpInstalled>
//   <MinCondFreq>3000.0</MinCondFreq>
//   <SampleMode>interval sample</SampleMode>
//   <SampleDataFormat>converted engineering</SampleDataFormat>
//   <OutputSalinity>yes</OutputSalinity>
//   <OutputSV>no</OutputSV>
//   <OutputDepth>no</OutputDepth>
//   <Latitude>0.0</Latitude>
//   <OutputDensity>no</OutputDensity>
//   <OutputTime>yes</OutputTime>
//   <SampleInterval>10</SampleInterval>
//   <AutoRun>no</AutoRun>
//   <StoreData>yes</StoreData>
//</ConfigurationData>
//<Executed/>
//
//getsd
//<StatusData DeviceType = 'SBE37SI-RS232' SerialNumber = '03715864'>
//   <DateTime>2021-05-02T14:16:09</DateTime>
//   <EventSummary numEvents = '255'/>
//   <Power>
//      <vMain> 9.79</vMain>
//      <vLith> 2.83</vLith>
//   </Power>
//   <MemorySummary>
//      <Bytes>6623100</Bytes>
//      <Samples>441540</Samples>
//      <SamplesFree>117700</SamplesFree>
//      <SampleLength>15</SampleLength>
//   </MemorySummary>
//   <Logging>no</Logging>
//</StatusData>
//<Executed/>
//
//getcc
//<CalibrationCoefficients DeviceType = 'SBE37SI-RS232' SerialNumber = '03715864'>
//   <Calibration format = 'TEMP1' id = 'Temperature'>
//      <SerialNum>03715864</SerialNum>
//      <CalDate>08-Jun-17</CalDate>
//      <A0>-1.891422e-04</A0>
//      <A1>3.149672e-04</A1>
//      <A2>-4.663049e-06</A2>
//      <A3>2.081193e-07</A3>
//   </Calibration>
//   <Calibration format = 'WBCOND0' id = 'Conductivity'>
//      <SerialNum>03715864</SerialNum>
//      <CalDate>08-Jun-17</CalDate>
//      <G>-9.961355e-01</G>
//      <H>1.295421e-01</H>
//      <I>-1.182784e-04</I>
//      <J>2.546682e-05</J>
//      <PCOR>-9.570000e-08</PCOR>
//      <TCOR>3.250000e-06</TCOR>
//      <WBOTC>-6.006736e-08</WBOTC>
//   </Calibration>
//   <Calibration format = 'STRAIN0' id = 'Pressure'>
//      <SerialNum>10622791</SerialNum>
//      <CalDate>05-Jun-17</CalDate>
//      <PA0>2.177361e-01</PA0>
//      <PA1>4.857985e-04</PA1>
//      <PA2>-2.395150e-12</PA2>
//      <PTCA0>5.234422e+05</PTCA0>
//      <PTCA1>4.447764e+01</PTCA1>
//      <PTCA2>-1.089407e+00</PTCA2>
//      <PTCB0>2.510075e+01</PTCB0>
//      <PTCB1>-6.500000e-04</PTCB1>
//      <PTCB2>0.000000e+00</PTCB2>
//      <PTEMPA0>-6.966136e+01</PTEMPA0>
//      <PTEMPA1>5.072205e-02</PTEMPA1>
//      <PTEMPA2>-3.512728e-07</PTEMPA2>
//      <POFFSET>0.000000e+00</POFFSET>
//      <PRANGE>1.600000e+02</PRANGE>
//   </Calibration>
//</CalibrationCoefficients>
//<Executed/>
//
/*
 * ASCII characters for parseData
 */
#define SPACE 0x20
#define OPENBRACE 0x7b
#define COMMA 0x2C


//Timing
// ctd microcat serial analyzer, bytes and times  Ctrl-X to quit
//
//open (ctd power on)
//   time = 260 msec
//SBE 37-SI
//ts
//   time = 2630+160 msec
//  28.8567,  0.00008,   -0.141,   0.0132, 03 May 2021, 17:06:57
//<Executed/>

#ifdef SERIALTIMING
Enter Selection [9]: r
ctd microcat serial analyzer, bytes and times  Ctrl-X to quit
open
RX:  time = 220 msec
RX: S [0x53]  time = 250 msec
TX: crlf
RX: B [0x42]  time = 0 msec
RX: E [0x45]  time = 0 msec
RX:   [0x20]  time = 0 msec
RX: 3 [0x33]  time = 0 msec
RX: 7 [0x37]  time = 0 msec
RX: - [0x2d]  time = 0 msec
RX: S [0x53]  time = 0 msec
TX: crlf
RX: I [0x49]  time = 0 msec
 [0x0d]  time = 0 msec
RX:
 [0x0a]  time = 10 msec
TX: ts cr
 [0x0d]  time = 0 msec
RX:
 [0x0a]  time = 0 msec
RX: t [0x74]  time = 0 msec
RX: s [0x73]  time = 10 msec
RX:   [0x20]  time = 2630 msec
RX:   [0x20]  time = 0 msec
RX: 2 [0x32]  time = 0 msec
RX: 6 [0x36]  time = 0 msec
RX: . [0x2e]  time = 0 msec
RX: 1 [0x31]  time = 0 msec
RX: 5 [0x35]  time = 0 msec
RX: 5 [0x35]  time = 0 msec
RX: 9 [0x39]  time = 10 msec
RX: , [0x2c]  time = 0 msec
RX:   [0x20]  time = 10 msec
RX:   [0x20]  time = 0 msec
RX: 0 [0x30]  time = 0 msec
RX: . [0x2e]  time = 0 msec
RX: 0 [0x30]  time = 0 msec
RX: 0 [0x30]  time = 0 msec
RX: 0 [0x30]  time = 0 msec
RX: 0 [0x30]  time = 0 msec
RX: 7 [0x37]  time = 10 msec
RX: , [0x2c]  time = 0 msec
RX:   [0x20]  time = 10 msec
RX:   [0x20]  time = 0 msec
RX:   [0x20]  time = 0 msec
RX: - [0x2d]  time = 0 msec
RX: 0 [0x30]  time = 0 msec
RX: . [0x2e]  time = 0 msec
RX: 1 [0x31]  time = 0 msec
RX: 4 [0x34]  time = 0 msec
RX: 7 [0x37]  time = 10 msec
RX: , [0x2c]  time = 20 msec
RX:   [0x20]  time = 0 msec
RX:   [0x20]  time = 0 msec
RX:   [0x20]  time = 0 msec
RX: 0 [0x30]  time = 0 msec
RX: . [0x2e]  time = 10 msec
RX: 0 [0x30]  time = 0 msec
RX: 1 [0x31]  time = 0 msec
RX: 2 [0x32]  time = 0 msec
RX: 3 [0x33]  time = 0 msec
RX: , [0x2c]  time = 60 msec
RX:   [0x20]  time = 0 msec
RX: 0 [0x30]  time = 10 msec
RX: 3 [0x33]  time = 0 msec
RX:   [0x20]  time = 0 msec
RX: M [0x4d]  time = 0 msec
RX: a [0x61]  time = 0 msec
RX: y [0x79]  time = 0 msec
RX:   [0x20]  time = 0 msec
RX: 2 [0x32]  time = 0 msec
RX: 0 [0x30]  time = 10 msec
RX: 2 [0x32]  time = 0 msec
RX: 1 [0x31]  time = 0 msec
RX: , [0x2c]  time = 0 msec
RX:   [0x20]  time = 0 msec
RX: 2 [0x32]  time = 0 msec
RX: 0 [0x30]  time = 0 msec
RX: : [0x3a]  time = 0 msec
RX: 1 [0x31]  time = 10 msec
RX: 8 [0x38]  time = 0 msec
RX: : [0x3a]  time = 0 msec
RX: 5 [0x35]  time = 0 msec
RX: 4 [0x34]  time = 0 msec
 [0x0d]  time = 0 msec
RX:
 [0x0a]  time = 0 msec
RX: < [0x3c]  time = 0 msec
RX: E [0x45]  time = 10 msec
RX: x [0x78]  time = 0 msec
RX: e [0x65]  time = 0 msec
RX: c [0x63]  time = 0 msec
RX: u [0x75]  time = 0 msec
RX: t [0x74]  time = 0 msec
RX: e [0x65]  time = 0 msec
RX: d [0x64]  time = 0 msec
RX: / [0x2f]  time = 10 msec
RX: > [0x3e]  time = 0 msec
 [0x0d]  time = 0 msec
RX:
 [0x0a]  time = 0 msec
 [0x0d]  time = 0 msec
RX:
 [0x0a]  time = 0 msec
#endif

/*
 * ctd_microCat_poll() wakes up the microCAT with a carriage return
 * and then sends "tss" to the microCAT.  Data is received
 * via the MicroCAT's interrupt handler.
 * assumes ctd_init and ctd_open have been called
 */
void ctd_microCat_poll(void)        // pollMicroCAT(void)
{
    ctd_write("\r\n", 1);
    ROM_SysCtlDelay(ONESEC);    // Give MicroCAT a second to wake up

    ctd_write("tss\r\n", 4);
    ROM_SysCtlDelay(MILLISECOND * 100);
    ctd_flushRx();     // Get rid of "tss"
}


/*
 * Parse the data returned by the microCAT and put it in the output form we'd like (tab delimited etc.).
 * While parsing, move the data out of poll_Buffers.microBuffer and into the instrument buffer which
 * will have all of our measurements.
 */
void ctd_microCat_parseData(void)
{
    unsigned char datebuff[20];
    unsigned char timebuff[20];
    float tempC, depth, salt;
    float dummy;


    // TODO, get the instrument back, and figure out depth field

    // "%f %f %f %s %s", &tempC, &dummy, &salt, buff, buff) != 5)
    //21.4218,  0.00006,   -0.147,   0.0105, 02 May 2021, 12:37:24
    if( sscanf( ctd.buf, "%f\t%f\t%f\t%s\t%s", &tempC, &dummy, &salt, datebuff, timebuff) != 5)
    {
        uprintf("\r\nError:  sscanf for parsing MicroCat does not return 5 args.  ctd.state = %d.  TempC and salt are 0.0\r\n", ctd.state);
        uprintf("%s\r\n", ctd.buf);
        tempC = salt = 0.0;
    }

    sys_samp.sensor_sal = salt;     // sys_data.sensor_sal is used when CTD is configured for vrse ph calc


    ctd.tempC = tempC;
    ctd.salt = salt;
    //ctd.depth = depth;


#ifdef OLDCODE

    //bytesRead holds the # of bytes received from microCAT
    int bytesRead, i;
    bytesRead = ctd_rxBytesAvail();
    if(bytesRead)
    {
        ctd_gets(ctd.buf, bytesRead);

        for(i=0; i<bytesRead; ++i)
        {
            if(ctd.buf[i] == COMMA)
            {
                ctd.buf[i] = '\t'; //replace commas with tabs
            }
        }
    }
    else strcpy(ctd.buf, "NAN\tNAN\tNAN\tNAN\tNAN");   // RCG 5/14
#endif
}

void ctd_microCat_comm_test(void)
{
    unsigned char charInput;

    UARTEchoSet(false); // Disable console echo for MicroCAT
    uprintf("\r\n\r\n*Press CTRL-X to stop communicating with the SBE37 MicroCAT.*\r\n\r\n");

    //set up the MicroCAT
	ctd_init();  // moved from init()
    ctd_open();

    while(1)
    {
        //if MicroCAT sent anything, print it out on UART1 (the desktop)
        //if( ctd_rxBytesAvail() )
        if( ctd_rxBytesAvail() )

        {
            //uprintf( "%c", ctd_getc() );
            uprintf( "%c", ctd_getc() );
        }

        //if user types anything, send it to the MicroCAT--exit on CTRL-X
        if(UARTRxBytesAvail())
        {
            charInput = UARTgetc();

            if(charInput == 24)  // ctrl-x
            {
                break;
            }

            //ctd_putc(charInput);
            ctd_putc(charInput);
        }
    }


    //close up the MicroCAT
    //ctd_close();
    ctd_close();
    UARTEchoSet(true);  // Enable console echo
}





