/*
 * apf_cmd.c
 *
 *  Created on: Feb 26, 2024
 *      Author: tm
 */


#if BOARD_MSC3 >= 1


//******************************************************************************
// Commands for ISUS/DURA APF Deployment
//******************************************************************************

if( SCIRxQueuedCount() == 0 ) {
    DelayMilliSecs( 100 );                  // delay 100ms
    ++Rx_loop;
    continue;
}

//reset the system errno variable on each pass
//ERANGE is used in commands that parse passed values, e.g, RTC, CTD, FIT
errno    = 0;

//reset the timeout and byte counter
Rx_loop  = 0;
Rx_chars = 0;

memset(abuf, '\0', sizeof(abuf));
memset(cbuf, '\0', sizeof(cbuf));

while( (SCIRxQueuedCount()) && (Rx_chars < CMDBUFSIZE) ) {
    cbuf[Rx_chars]= (char)SCIRxGetByte( false );
    ++Rx_chars;
    if( SCIRxQueuedCount() == 0 ) {
        DelayMilliSecs( 100 );          //wait around another 100ms before giving up.
    }
}

if( Rx_chars == 1 ) {

    CMD_char = (int)cbuf[0];

    if( isalpha(CMD_char) == 0 ) {
        printf("NAK,NON-ALPHA Character Received!\n");
        SCIRxFlush();
        continue;
    }

    switch( toupper( CMD_char ) ) {

    case 'W':
        printf("ACK\n");
        break;

    case 'M':
        SCIRxSetBuffered( false );  //MENU_MODE is char based, zmodem, if used, sets the buffer too!
        RootMenu();

        if( isus_spec_pwr == TRUE ){
            SpecPwrOff( SpecPort );
            printf("\n  Spectrometer Power was left ON! Powering DOWN...\n");
            }
        if( isus_lamp_pwr == TRUE ){
            LampPwrOff();
            printf("\n  Fiberlight Power was left ON! Powering DOWN...\n");
            }
        if( isus_ref_pwr == TRUE ){
            RefPwrOff();
            printf("\n  Ref Detector Power was left ON! Powering DOWN...\n");
            }
        if( dura_atod_pwr == TRUE ){
            AtodPowerOff();
            printf("\n  ATOD Interface Power was left ON! Powering DOWN...\n");
            }

        SCIRxSetBuffered( true );
        SCIRxFlush();;
        break;

    case 'E':
        if( sys_sensor_mode == ISUS_SENSOR_MODE )
            printf("ACK,E,%lu,%lu\n", isus_error_ctr, isus_error_time);
        else if( sys_sensor_mode == DURA_SENSOR_MODE )
            printf("ACK,E,%lu,%lu\n", dura_error_ctr, dura_error_time);
        else
            printf("NAK,E,InvalidModeValue: %d\n", sys_sensor_mode);
        break;

    case 'P':
        printf("ACK,P,%lu,%lu,%lu\n", sys_por_ctr, sys_reset_ctr, sys_reset_time);
        break;

    case 'S':
        if( sys_sensor_mode == ISUS_SENSOR_MODE )
            printf("ACK,S,%lu,%lu\n", isus_sample_ctr, isus_sample_time);
        else if( sys_sensor_mode == DURA_SENSOR_MODE )
            printf("ACK,S,%lu,%lu\n", dura_sample_ctr, dura_sample_time);
        else
            printf("NAK,S,InvalidModeValue: %d\n", sys_sensor_mode);
        break;

    case 'T':
        if( gotSample == TRUE )
            printf("ACK,T,%.3f\n", acquire_time);
        else
            printf("NAK,T,-1.0\n");
        break;

    case 'C':
        if( sys_sensor_mode == ISUS_SENSOR_MODE )
            OutputIsusHeader(stdout);
        else if( sys_sensor_mode == DURA_SENSOR_MODE )
            OutputDuraHeader(stdout);
        else
            printf("NAK,C,InvalidModeValue: %d\n", sys_sensor_mode);
        break;

    case 'Q':
        printf("ACK,Q,%d\n", sys_sensor_type);
        break;

    case 'H':
        printf("\nCommands: [W,M,E,P,S,T,C,Q,TS,SL,SE,SLP,OFF,RTC,FIT,CTD,MODE,INIT,BAKE,SPECTRA]\n");
        break;

    default:
        printf("NAK,UnrecognizedCmdChar: %s\n", cbuf);
        break;

    }     //end switch

    SCIRxFlush();

}                 //end if Rx_chars == 1

else if( Rx_chars > 1 ) {

    if( (srchptr=strchr(cbuf,0x0D)) != NULL )    // If string contains CR change char to '\0'
        *srchptr='\0';
    if( (srchptr=strchr(cbuf,0x0A)) != NULL )    // If string contains LF change char to '\0'
        *srchptr='\0';

    strupr(cbuf);

    if( (strstr(cbuf, "TS") != NULL) && (strlen(cbuf) == 2) ) {

        if( sys_sensor_mode == ISUS_SENSOR_MODE ) {
            printf("ACK,TS,CMD\n");
            if( sys_data_mode == 2 )
                ret = TakeIsusPseudoSample(dbuf, &acquire_time, CTD_Time, CTD_Temp, CTD_Salinity, CTD_Depth);
            else
                ret = TakeIsusSample(dbuf, &acquire_time, CTD_Time, CTD_Temp, CTD_Salinity, CTD_Depth);
        }
        else if( sys_sensor_mode == DURA_SENSOR_MODE ) {
            printf("ACK,TS,CMD\n");
            ret = TakeDuraSample(dbuf, &acquire_time, CTD_Time, CTD_Temp, CTD_Salinity, CTD_Depth);
        }
        else{
            printf("NAK,TS,InvalidModeValue: %d\n", sys_sensor_mode);
            SCIRxFlush();
            continue;
        }

        if( ret == OK ) {
            printf("ACK,TS,DAT\n");
            gotSample = TRUE;
        }
        else{
            printf("NAK,TS,DAT\n");
            gotSample = FALSE;
        }
        SCIRxFlush();
        continue;
    }

    if( (strstr(cbuf, "T1") != NULL) && (strlen(cbuf) == 2) ) {

        printf("ACK,T1,CMD\n");
        if( sys_data_mode == 2 )
            ret = TakeIsusPseudoSample(dbuf, &acquire_time, CTD_Time, CTD_Temp, CTD_Salinity, CTD_Depth);
        else
            ret = TakeIsusSample(dbuf, &acquire_time, CTD_Time, CTD_Temp, CTD_Salinity, CTD_Depth);

        if( ret == OK ) {
            printf("ACK,T1,DAT\n");
            gotSample = TRUE;
        }
        else{
            printf("NAK,T1,DAT\n");
            gotSample = FALSE;
        }
        SCIRxFlush();
        continue;
    }

    if( (strstr(cbuf, "T2") != NULL) && (strlen(cbuf) == 2) ) {

        printf("ACK,T2,CMD\n");
        ret = TakeDuraSample(dbuf, &acquire_time, CTD_Time, CTD_Temp, CTD_Salinity, CTD_Depth);

        if( ret == OK ) {
            printf("ACK,T2,DAT\n");
            gotSample = TRUE;
        }
        else{
            printf("NAK,T2,DAT\n");
            gotSample = FALSE;
        }
        SCIRxFlush();
        continue;
    }

    if( (strstr(cbuf, "SL") != NULL) && (strlen(cbuf) == 2) ) {
        if( gotSample == TRUE ) {
            printf("%s\n", dbuf);
            fflush(stdout);
        }
        else
            printf("NAK,SL\n");
        SCIRxFlush();
        continue;
    }

    if( (srchptr=strstr(cbuf, "SE")) != NULL ) {
        if(strchr(srchptr, '?') != NULL) {
            if( (Erecs=CalcRecsPending((uchar)ERRORLOG_FILE)) >= 0 )
                printf("ACK,SE?,%ld\n", Erecs);
            else
                printf("NAK,SE?,%ld\n", Erecs);
        }
        else
            SendRecords((uchar)ERRORLOG_FILE, &Efpos);

        SCIRxFlush();
        continue;
    }

    if( (strstr(cbuf, "SLP") != NULL) && (strlen(cbuf) == 3) ) {
        printf("ACK,SLP\n");
        SCIRxFlush();
        goto nightynite;
    }

    if( (strstr(cbuf, "OFF") != NULL) && (strlen(cbuf) == 3) ) {
        printf("ACK,OFF\n");
        SysShutDown();
    }

    if( (strstr(cbuf, "INIT") != NULL) && (strlen(cbuf) == 4) ) {

        sys_watchdog_enable=TRUE;           DS3234_WrSRAM(SYS_WDOGENABLE_PTR, sizeof(uchar), (uchar*)&sys_watchdog_enable);
        sys_message_enable=0;                   DS3234_WrSRAM(SYS_MSGENABLE_PTR, sizeof(uchar), (uchar*)&sys_message_enable);
        sys_data_mode=1;                            DS3234_WrSRAM(SYS_DATAMODE_PTR, sizeof(uchar), (uchar*)&sys_data_mode);
        isus_tcomp_mode=TRUE;                   DS3234_WrSRAM(ISUS_TCOMPMODE_PTR, sizeof(uchar), (uchar*)&isus_tcomp_mode);
        isus_salfit_mode=FIX;                       DS3234_WrSRAM(ISUS_SALFITMODE_PTR, sizeof(uchar), (uchar*)&isus_salfit_mode);
        dura_led_enable=0;                              DS3234_WrSRAM(DURA_LEDENABLE_PTR, sizeof(uchar), (uchar*)&dura_led_enable);

        isus_fit_concs=2;                           DS3234_WrSRAM(ISUS_FITCONCS_PTR, sizeof(ushort), (ushort*)&isus_fit_concs);
        sys_ef_limit=128;                               DS3234_WrSRAM(SYS_EFLIMIT_PTR, sizeof(ushort), (ushort*)&sys_ef_limit);
        sys_df_limit=5;                 DS3234_WrSRAM(SYS_DFLIMIT_PTR, sizeof(ushort), (ushort*)&sys_df_limit);
        sys_apf_tmout=10;                               DS3234_WrSRAM(SYS_APFTMOUT_PTR, sizeof(ushort), (ushort*)&sys_apf_tmout);

        sys_por_ctr=0L;                                     DS3234_WrSRAM(SYS_PORCTR_PTR, sizeof(ulong), (ulong*)&sys_por_ctr);
        sys_reset_ctr=0L;                               DS3234_WrSRAM(SYS_RESETCTR_PTR, sizeof(ulong), (ulong*)&sys_reset_ctr);

        sys_last_error=0;                               DS3234_WrSRAM(SYS_LASTERROR_PTR, sizeof(int), (int*)&sys_last_error);
        sys_error_ctr=0L;                               DS3234_WrSRAM(SYS_ERRORCTR_PTR, sizeof(ulong), (ulong*)&sys_error_ctr);
        sys_error_time=0L;                              DS3234_WrSRAM(SYS_LASTERRTIME_PTR, sizeof(ulong), (ulong*)&sys_error_time);

        isus_last_error=0;                              DS3234_WrSRAM(ISUS_LASTERROR_PTR, sizeof(int), (int*)&isus_last_error);
        isus_error_ctr=0L;                              DS3234_WrSRAM(ISUS_ERRORCTR_PTR, sizeof(ulong), (ulong*)&isus_error_ctr);
        isus_error_time=0L;                             DS3234_WrSRAM(ISUS_LASTERRTIME_PTR, sizeof(ulong), (ulong*)&isus_error_time);
        isus_sample_ctr=0L;                     DS3234_WrSRAM(ISUS_SAMPLECTR_PTR, sizeof(ulong), (ulong*)&isus_sample_ctr);
        isus_sample_time=0L;                    DS3234_WrSRAM(ISUS_LASTSAMPTIME_PTR, sizeof(ulong), (ulong*)&isus_sample_time);

        dura_last_error=0;                     DS3234_WrSRAM(DURA_LASTERROR_PTR, sizeof(int), (int*)&dura_last_error);
        dura_error_ctr=0L;                      DS3234_WrSRAM(DURA_ERRORCTR_PTR, sizeof(ulong), (ulong*)&dura_error_ctr);
        dura_error_time=0L;                     DS3234_WrSRAM(DURA_LASTERRTIME_PTR, sizeof(ulong), (ulong*)&dura_error_time);
        dura_sample_ctr=0L;                     DS3234_WrSRAM(DURA_SAMPLECTR_PTR, sizeof(ulong), (ulong*)&dura_sample_ctr);
        dura_sample_time=0L;                    DS3234_WrSRAM(DURA_LASTSAMPTIME_PTR, sizeof(ulong), (ulong*)&dura_sample_time);

        if( (Zcoefs > 0) || (Ecoefs == 256) ) { //wavelength info SHOULD be loaded
            //SET FIT WINDOW
            lambda_beg=217;
            lambda_end=240;
            MatchPixelsToLambda(LambdaData, lambda_beg, lambda_end, &isus_pixel_beg, &isus_pixel_end);
            DS3234_WrSRAM(ISUS_PIXELBEG_PTR, sizeof(ushort), (ushort*)&isus_pixel_beg);
            DS3234_WrSRAM(ISUS_PIXELEND_PTR, sizeof(ushort), (ushort*)&isus_pixel_end);
            isus_fit_pixels = (isus_pixel_end - isus_pixel_beg) + 1;

            //SET DATA WINDOW (SEE TS AND SL COMMANDS)
            lambda_beg=217;
            lambda_end=250;
            MatchPixelsToLambda(LambdaData, lambda_beg, lambda_end, &isus_datpixel_beg, &isus_datpixel_end);
            DS3234_WrSRAM(ISUS_DATPIXELBEG_PTR, sizeof(ushort), (ushort*)&isus_datpixel_beg);
            DS3234_WrSRAM(ISUS_DATPIXELEND_PTR, sizeof(ushort), (ushort*)&isus_datpixel_end);
        }

        printf("ACK,INIT\n");
        SCIRxFlush();
        continue;
    }

#include "cmds\mode.c"
#include "cmds\rtc.c"
#include "cmds\fit.c"
#include "cmds\ctd.c"
#include "cmds\bake.c"
#include "cmds\spectra.c"

    printf("NAK,UnrecognizedCmdStr: %s\n", cbuf);
    SCIRxFlush();
    continue;

}           // end else Rx_chars > 1

//******************************************************************************
// Command Mode for ISUS/DURA APF Deployment
//******************************************************************************

#endif
