/*
 * apf.h
 *  Created on: 8 May 2024    Porting CF2 ISUS and APF code
 *      Author: thom maughan
 *
 */

#ifndef APF_H_
#define APF_H_

#include <time.h>
#include <assert.h>

//******************************************************************************
// ISUS Global Variables and DEFINEs
//******************************************************************************
                                        //APFTODO, sys_data.isus_vin_min_volt was used instead of apf. struct due to EEPROM edit routine available as a backdoor to edit.  22 Apr 2025
#define ISUS_SYS_V_MIN      11.2        // changed to 11.2 from 10.0 after reviewing float data  // per Ken Johnson, PI 14 Apr 2025
#define DURA_SYS_V_MIN      8.0   // added 19 Apr 2025

#define MAX_NUMOF_ZCOEFS    5
#define ZCOEFS          MAX_NUMOF_ZCOEFS       // Zeiss Spectrometer Wavelength Coefs
#define MAX_NUMOF_TCOEFS    5
#define TCOEFS          MAX_NUMOF_TCOEFS       // Bromide Temperature Compensation Coefs
#define MAX_NUMOF_FITVALUES     10
#define FITVALUES       MAX_NUMOF_FITVALUES      // Returned Values from lsqfit(), // Use to dimension an array of type double
#define SALINITY            0               // Returned Salinity  Value from Fitting
#define NITRATE             1               // Returned Nitrate   Value from Fitting
#define BISULFIDE           2               // Returned BiSulfide Value from Fitting
#define BASELINE_A          3               // Returned Baseline a Coef from Fitting
#define BASELINE_B          4               // Returned Baseline b Coef from Fitting
#define BASELINE_C          5               // Returned Baseline c Coef from Fitting
#define FIT_ERROR           6               // Returned RMS ABS Err Val from Fitting
#define FIT_CHISQ           7               // Returned CHISQ Error Val from Fitting
#define FIT_GAMMQ           8               // Returned Fit Quality Val from Fitting

#define NO3_SAL_FIX         FALSE
#define NO3_SAL_FIT         TRUE

#define APF_ERROR           (-2)
#define TIMEOUT             (-2)        // APFTODO - place this in the right .h file - LJC had it in zmodem.h wtf

/* Local Defines */
#define ACKBUFSIZE          32
#define CMDBUFSIZE          64
#define DATBUFSIZE          2048

#define MAX_LOGNAME_SIZE    24      //8.3 plus 4 for directory name   /DURA/PROF1234.log  (18) + 6 pad

#define GET_ACK_TIMEOUT_MSEC    3000



// All data is stored in FRAM and stored as 32bit integers (CF2 had uchars and shorts)

struct apfRtcTime
{
    time_t     DS3234_secs;     // time in secs from Dallas DS3234 RTC (batt backed)
    time_t     CF2_secs;        // time in secs from CF2 TPU RTC (NOT batt backed)
    time_t     alarm_time;      // time in secs to set the wakeup alarm time to, gets passed to PWRSuspendUntil()
    time_t     wake_time;       // time in secs indicating when PWRSuspendUntil() returned
    time_t     current_time;    // time in secs indicating the current time
    time_t     data_time;       // time in secs indicating when data sample was taken
    float      data_time_fsecs; // time in fractional decimal secs indicating when data sample was taken (if time_type == FRACSECS)
};

#define MAX_ISUS_CAL_DATE  32
struct apfIsusArrays            //apfArray struct def 18,856 bytes in SRAM and FRAM
{
    uint32_t    initNumBeg;
    char        CalDate[MAX_ISUS_CAL_DATE];
    uint32_t    ZcoefsCnt;       //Zcoefs;
    uint32_t    EcoefsCnt;       //Ecoefs;
    uint32_t    ZerosCnt;        //5 for a proper Zeiss file
    uint32_t    ModuleNum;       //Zeiss Module number from ZCOEFDAT.CAL
    uint32_t    spare[4];        //a couple spare ints, for adding a minor var and preserving FRAM layout
    double      SwCalTemp;       // from ECOEFZER.CAL
    double      ZeissCoefs[ZCOEFS];          //   40 bytes = 8*5
    double      EcoefFile[260][3];           // 6240 bytes = 8*260*3, array populated by reading ZCOEFDAT.CAL and ECOEFZER.CAL files
    double      LambdaData[260];             // 2080 bytes = 8*260,
    double      ZeroData[260];               // 2080 bytes = 8*260
    double      TcompCoefs[10];              //   80 bytes = 8*10
    uint32_t    initNumEnd;
    uint32_t    pad[2];
};

//1 apf.
struct apfBootInitGlobals       //plain old global vars, init'd after reset
{
    uint32_t   storage_size;            // size of uSD or NAND flash in Kbytes
    uint32_t   storage_free;            // storage available
    uint32_t   isus_spec_pwr;           //
    uint32_t   isus_lamp_pwr;           //
    uint32_t   isus_lamp_deuterium;     //
    uint32_t   isus_lamp_tungsten;      //
    uint32_t   isus_ref_pwr;            //
    uint32_t   isus_lampStart_msec;     // start time (if on)

    float      pH;                      //
    float      dura_pH;                 //

    uint32_t   CTD_Time;                //
    float      CTD_Temp;                //
    float      CTD_Salinity;            //
    float      CTD_Depth;               //

    uint32_t   sys_humidity;            //

    double     isus_sal;                //   //Added by TM to globals 7 Oct 2024, from temp var isus_sal = FitData[SALINITY];
    double     isus_no3;                //   //was uint32_t    from = FitData[NITRATE];
    double     isus_hs;                 //  //= FitData[BISULFIDE];
    double     isus_err;                //  //= FitData[FIT_ERROR];
    uint32_t   dura_atod_pwr;           //  Not needed

    float      backupVoltage;           //  NOT NEEDED
    float      VrsExt;                  //
    float      StdDevVrs;               //
    float      Vk;                      //
    float      StdDevVk;                //
    float      Ik;                      //
    float      Ib;                      //
    float      sys_temperature;         //
    float      sys_pressure;            //
    float      sys_current;             //
    float      sys_voltage;             //
    float      acquire_time;            //

    float      DataMean;                //
    float      DataStdDev;              //

    uint32_t   gotSample;               //    // flag for indicating sample taken
    uint32_t   spareUint32;

    uint32_t   chkSum;                  //
};

//2 apf_eeprom.
struct apfCfgGlobals            //stored in EEPROM, seldom changing.   500k cycle EEPROM
{
    uint32_t   initNumBeg;
    uint32_t   isus_ref_limit;          //
    uint32_t   isus_fit_concs;          //
    uint32_t   isus_spec_period;        //  tint
    uint32_t   isus_pre_scans;          //
    uint32_t   isus_scan_num;           //
    uint32_t   isus_dark_num;           //
    uint32_t   isus_bsl_model;          //
    uint32_t   isus_warm_shut;          // msc1 menu
    uint32_t   isus_ref_samples;        // msc1 menu
    uint32_t   isus_warm_lamp;          // msc1 menu
    uint32_t   isus_clean_lamp;         // msc1 menu
    uint32_t   isus_scans_per_dc;       // msc1 menu
    uint32_t   isus_samps_per_clean;    // msc1 menu
    uint32_t   no3_span;                // msc1 menu
    uint32_t   no3_offset;              // msc1 menu

    uint32_t   lambda_beg;              //
    uint32_t   lambda_end;              //
    uint32_t   isus_pixel_beg;          //  FIT
    uint32_t   isus_pixel_end;          //
    uint32_t   isus_fit_pixels;         //
    uint32_t   isus_tcomp_mode;         //
    uint32_t   isus_salfit_mode;        //
    uint32_t   lambda_dat_beg;          //
    uint32_t   lambda_dat_end;          //
    uint32_t   isus_datpixel_beg;       //  SPECTRA
    uint32_t   isus_datpixel_end;       //


    uint32_t   dura_atod_readings;      //  //NOT NEEDED
    uint32_t   dura_atod_delay;         //  //NOT NEEDED
    uint32_t   dura_samps_per_cal;      //  //NOT NEEDED
    uint32_t   dura_led_enable;         //  //NOT NEEDED

    uint32_t   sys_delay_hour;            //?
    uint32_t   sys_sync_hour;             //?
    uint32_t   sys_sync_min;              //?
    uint32_t   sys_df_limit;              //?

    uint32_t   sys_last_doy;              //
    uint32_t   sys_serial_num;            //  4 digits
    uint32_t   sys_tmout;                 //
    uint32_t   sys_tzoffset;              //
    uint32_t   sys_sleep_period;          //
    uint32_t   sys_pump_period;           //

    uint32_t   sys_sf_limit;            //  Limit on size of OFFLOAD.DAT   CheckFileSize   Added 14 May 2024
    uint32_t   sys_ef_limit;            //  ERROR.LOG size limit Added 14 May

    uint32_t   sys_apf_tmout;           //  NOT NEEDED?? (fptr, "H, Power Active  Timeout , %hu\n", sys_apf_tmout);

    uint32_t   sys_slog_delay;            //
    uint32_t   sys_deploy_mode;           //

    uint32_t   sys_time_type;             //
    uint32_t   sys_watchdog_enable;       //
    uint32_t   sys_message_enable;        //
    uint32_t   sys_pump_enable;           //
    uint32_t   sys_sensor_type;           //

    char       logIsus[MAX_LOGNAME_SIZE];     //
    char       logDura[MAX_LOGNAME_SIZE];     //

    uint32_t   spare[8];                    //

    uint32_t    initNumEnd;
    uint32_t    pad[2];

};
static_assert((sizeof(struct apfCfgGlobals) % 4) == 0, "apfCfgGlobals size must be evenly divisible by 4");

// apf_fram. (was apf.)
struct apfVolatileGlobals       //stored in FRAM
{
    uint32_t   initNumBeg;              //byte signature

    uint32_t   sendlast_byteCnt;        //
    uint32_t   isus_error_ctr;          //
    uint32_t   isus_last_error;         // Added 14 May
    uint32_t   isus_error_time;         //, maybe 1
    uint32_t   isus_sample_time;
    uint32_t   isus_reset_flag;         // used for writing header to PROF file (can be eliminated)
    uint32_t   isus_lampOn_mSec;        // elapsed lamp ON time
    uint32_t   isus_lampOn_ctr;         // number of times lamp has been turned on
//    uint32_t   isus_lamp_elp;         //
//    uint32_t   isus_lamp_evt;         // this is the odometer
    uint32_t   isus_sample_ctr;         //

    uint32_t   dura_error_time;         //
    uint32_t   dura_sample_time;        //
    uint32_t   dura_error_ctr;          //
    uint32_t   dura_last_error;         // Added 14 May
    uint32_t   dura_reset_flag;         //   // flag to mark initialization for outputting header info
    uint32_t   dura_sample_ctr;         //

    uint32_t   sys_por_flag;            //  NOT NEEDED  Power on reset ==
    uint32_t   sys_sensor_mode;         //   ISUS_SENSOR_MODE or DURA_SENSOR_MODE
    uint32_t   sys_wdog_ctr;        // was sys_por_ctr;             //  Used to count watchdog events

    uint32_t   profileCnt;              // or 2   incremented by PROFILE command, zeroed by INIT command
    uint32_t   profileStartTime;        // or 2 Added 30 Jan 2025

    uint32_t   sys_reset_ctr;           //
    uint32_t   sys_reset_time;          //
    uint32_t   sys_data_mode;             //

    int32_t    sys_last_error;            //
    uint32_t   sys_error_ctr;             //
    uint32_t   sys_error_time;            //
    uint32_t   sys_file_ctr;              //   NOT NEEDED MSC1 menu

    uint32_t   logIsus_fsize;             //?   //fsize of PROFxxxx.log file
    uint32_t   logDura_fsize;             //

    //--------------New Vars, add here ----
    uint32_t   isus_sampleCnt_perProfile;     //
    uint32_t   dura_sampleCnt_perProfile;     //

    int32_t    errNum;                      // used by FRAM soak test

    uint32_t   errorLog_errorCnt;             // used to count the number of errors written to the error log

    uint32_t   microSD_errCnt;              // new 9 May 2025
    uint32_t   Efpos;                       // store error.log pointer. FSIZE_t not know, using uint32_t for now

    uint32_t   spare[8];                    //

    uint32_t    initNumEnd;
    uint32_t    pad[2];
};

//#define TRUE                    1
//#define FALSE                   0

#define ENABLE                  1
#define DISABLE                 0

#define HIGH                    1
#define LOW                     0

#define OK                      0
#define ERROR                   (-1)
#define TIMEOUT                 (-2)

#define CTRL_A                  0x01
#define CTRL_C                  0x03
#define CTRL_D                  0x04
#define CAPS_B                  0x42
#define CAPS_R                  0x52
#define CAPS_U                  0x55
#define CAPS_S                  0x53
#define CAPS_Q                  0x51
#define ACK                     0x06
#define NAK                     0x15



// from MSC_ERR_SYS.H
//--- SYSTEM ERROR CODES for LogErrorMessage ----
#define SLEEP_TIME_MISSED           -101
#define MYSTERY_WAKEUP              -102
#define ALARM_TIME_TIMEOUT          -103
#define POWER_FAIL_SUSPEND          -104
#define POWER_FAIL_IRQ2             -105
#define ALARM_TIME_STALE            -106
#define COMMAND_MODE_EMPTY          -107
#define ERROR_FILE_TOO_BIG          -108
#define OFFLOAD_FILE_TOO_BIG        -109
#define COMMAND_ACK_FAILURE         -110
#define RTC_DELTA_EXCEEDED          -111
#define FILE_OPEN_FAILURE           -112
#define FLASH_CARD_FULL             -113
#define MAX_SLEEP_TIME_MISSED       -114
#define MALLOC_FAILURE              -115
#define INIT_NVRAM_WITH_DEFAULTS    -116
#define ERROR_LOG_TEST              -117        //New MSC3, for testing error.log
#define PROFNNNN_FILE_ERROR         -118
#define FRAM_FAIL                   -119        //FRAM failed init, FATAL ERROR
#define EEPROM_FAIL                 -120        //EEPROM failed init, FATAL ERROR
#define WATCHDOG_RESET              -121
#define INIT_ERROR                  -122
#define FRAM_ERROR                  -123        //FRAM struct was found to have incorrect contents.  This can be from new uninitialized FRAM or corrupted contents
#define SERIAL_TIME_ERROR           -124

// from MSC_ERR_ISUS.H
//--- ISUS ERROR CODES for LogErrorMessage ----
#define SPEC_PWR_ON_FAILURE         -201
#define LAMP_PWR_ON_FAILURE         -202
#define REF_PWR_ON_FAILURE          -203
#define NRC_FIT_FAILURE             -204
#define SPEC_TPU_INIT_ERROR         -205
#define SPEC_CTS_SCAN_ERROR         -206
#define SPEC_CTS_DATA_ERROR         -207
#define SPEC_DAT_READ_ERROR         -208
#define LAMP_PWR_ON_ABORT_VINMIN    -209        //New MSC3
#define ERROR_LOG_ISUS_TEST         -210
#define LAMP_BAKE_DIAG              -211        //New MSC3 in BAKE command

// from msc_err_dura.h
//--- ISUS ERROR CODES for LogErrorMessage ----
#define ATOD_PWR_ON_FAILURE         -301
#define ATOD_READ_TIMEOUT           -302
#define ATOD_READ_FAILURE           -303
#define ATOD_RESET_FAILURE          -304
#define DS2482_INIT_FAILURE         -305
#define ERROR_LOG_DURA_TEST         -306

// from msc_config.h
//Possible DuraFET Sensor Types
#define DURA_III                1
#define DURA_MBARI              2
#define DURA_SENSOR_TYPE        DURA_MBARI

// sensor type, as defined by sys_sensor_mode
#define UNSELECTED_MODE         0           //CarbonLab legacy mode (pH with different output format than DURA_SENSOR_MODE
#define LEGACY_CARBONLAB_PH_MODE  UNSELECTED_MODE
#define ISUS_SENSOR_MODE        1
#define DURA_SENSOR_MODE        2
#define DURAISUS_SENSOR_MODE    3

// OpenApfLogFile()
#define ISUS_DATA_FILE          1
#define DURA_DATA_FILE          2

#define OK                      0
#define ERROR                   (-1)
#define TIMEOUT                 (-2)


#endif /* APF_H_ */
