/*
 * apf_init.h
 *
 *  Created on: Feb 26, 2024
 *      Author: tm, from lc cf2 apf_main.h
 */

#ifndef APF_INIT_H_
#define APF_INIT_H_

extern double apf_EcoefData[256+1][3];

void apf_init_hmi_vars(void);

// return 1 on success, <= 0 on failure
int apf_init_msc(void);

int IOPwrUp( void );
int IOPwrDown( void );

// return 1 on success, <= 0 on failure
int apf_init_runtime_vars(void);                       //called on each boot, was init_apf_global_vars
int apf_init_apf_struct_defaults(void);                 // called by 'defaults' serial command
void apf_init_apfArray_struct_defaults(void);           // called by 'defaults' serial command
void init_zcoef_ecoef_apfArray_into_fram(void);
void init_apf_apfArray_defaults( void );

int apf_deployment_init(void);
void apf_create_logFile_names( void );

// new versions of matrix, operate directly on global instances rather than alloc with pointers
void apf_initEcoefFileMatrix(void);
void apf_initEcoefDataMatrix(void);
void apf_copyEcoefsFileToData(void);
void apf_copySwEcoefsFileToData(void);
void apf_XformSwEcoefs(double *Lambda, double *Tcoefs, double CalTemp, double SamTemp);
int apf_loadIsusECoefs(double *Lambda, double *Zeros, double *Tcoefs, double *CalTemp, char *CalDate);

#ifdef OLDMSC1CODE


void SetDuraDefaultsIntoNVRAM( void );
void SetIsusDefaultsIntoNVRAM( void );
void GetVarsFromNVRAM( void );
void SetDefaultsIntoNVRAM( void );
void GetSysVarsFromNVRAM( void );
void SetSysDefaultsIntoNVRAM( void );
void GetIsusVarsFromNVRAM( void );
void SetIsusDefaultsIntoNVRAM( void );
void GetDuraVarsFromNVRAM( void );
#endif

//--------------------


//SYS UCHAR value and memory address in DS3234 SRAM (0x0000 - 0x000F)

#define SYS_INITSRAM_VAL        0xAA            // for detecting unitialized DS3234 SRAM

#define SYS_SYNCMODE_VAL        4               // Scheduled Logging Sync Modes 1=Sync Immediate 2=Sync to Delay in Hours 3=Sync to Given Hours and Mins in LocalTime 4=Sync to Given Mins

#define SYS_DEPLMODE_VAL        1               // Deployment mode 1=Scheduled 2=Continuous 3=Triggered

#define SYS_DATAMODE_VAL        1               // Scheduled Data Collection Mode 1=Real Data 2=Pseudo Data (TEST MODE)

#define SYS_TIMETYPE_VAL        1               // Report time in WholeSecs=1 or FractionalSecs=2, using CF2 RTC

#define SYS_WDOGENABLE_VAL      0               // boolean for enabling watchdog reset

#define SYS_MSGENABLE_VAL       0               // boolean for enabling the printing of error/status messages

#define SYS_PUMPENABLE_VAL      0               // boolean for enabling the flushing pump cycle

#define SYS_SENSORTYPE_VAL      4               // Sensor Type Return Values 1=No Sensors 2=ISUS Only Sensor 3=DURA Only Sensor 4=ISUS & DURA Sensors


//SYS USHORT value and memory address in DS3234 SRAM (0x0010 - 0x002F)

#define SYS_DELAYHR_VAL         3               // number of hours until start of data logging

#define SYS_SYNCHR_VAL          6               // local hour to sync start of data logging to

#define SYS_SYNCMIN_VAL         0               // local minute to sync start of data logging to

#define SYS_DFLIMIT_VAL         5               // max size (in Mbytes) for any datafile

#define SYS_SFLIMIT_VAL         256             // max size (in kbytes) for data spool file (e.g., OASIS dat file) before removal

#define SYS_EFLIMIT_VAL         256             // max size (in kbytes) for error log file (ERROR.LOG) before removal

#define SYS_LASTDOY_VAL         0               // last day of year value used in datafile naming

#define SYS_SERIALN_VAL         777             // Default Serial Number

#define SYS_APFTMOUT_VAL        10              // number of hours to keep system active before self-powering OFF

//SYS INT value and memory address in DS3234 SRAM (0x0010 - 0x002F)

#define SYS_TZOFFSET_VAL        8               // hrs local time is offset from GMT (+) is W (-) is E

#define SYS_LASTERROR_VAL       0               // Clear any value

//SYS ULONG value and memory address in DS3234 SRAM (0x0030 - 0x0064)

#define SYS_ERRORCTR_VAL        0               // counter indicating number of System errors

#define SYS_LASTERRTIME_VAL     0               // time of the last error event

#define SYS_RESETCTR_VAL        0               // counter indicating total number of system resets

#define SYS_RESETTIME_VAL       TI_CCS_UNIX_EPOCH_OFFSET               // time of the last system reset event

#define SYS_PORCTR_VAL          0               // counter indicating total number of Power On Resets

#define SYS_FILECTR_VAL         1               // counter indicating number of files used in current DOY

#define SYS_SLEEPPER_VAL        60              // number of minutes between RTC wakeups (not used in APF firmware)

#define SYS_PUMPPER_VAL         60              // number of seconds to run pump prior to sampling




//------------------

//ISUS UCHAR value and memory address in DS3234 SRAM (0x0065 - 0x006F)

#define ISUS_TCOMPMODE_VAL      1               // Br temperature compensation mode

#define ISUS_SALFITMODE_VAL     0               // fitting algorithim, fix/fit salinity, mode  0=fix, 1=fit

#define ISUS_WARMSHUT_VAL       1               // boolean of shutter state during warmup

//ISUS USHORT value and memory address in DS3234 SRAM (0x0070 - 0x008F)

#define ISUS_INTSCANS_VAL       3               // number of intensity scans

#define ISUS_DCSCANS_VAL        1               // number of dark current scans

#define ISUS_PRESCANS_VAL       2               // number of spectromter 4ms pre scans (to clear PDA)

#define ISUS_PIXELBEG_VAL       17              // start  fitting pixel

#define ISUS_PIXELEND_VAL       87              // ending fitting pixel

#define ISUS_FITCONCS_VAL       2               // number of concentrations to fit

#define ISUS_BSLNMODL_VAL       1               // baseline model to use in curve fitting

#define ISUS_REFLIMIT_VAL       5000            // min number of spectrometer A/D counts that establishs when the DU Lamp is on

#define ISUS_REFSAMPS_VAL       15              // number of reference detector readings

#define ISUS_DATPIXELBEG_VAL    17              // start  reported spectra pixel (APF)

#define ISUS_DATPIXELEND_VAL    87              // ending reported spectra pixel (APF)

#define ISUS_LAMPWARM_VAL       3               // number secs to warmup lamp after power on

#define ISUS_CLEANUV_VAL        30              // number of seconds for UV "cleaning" cycle

//ISUS INT value and memory address in DS3234 SRAM (0x0070 - 0x008F)

#define ISUS_LASTERROR_VAL      0               // Clear any value

//ISUS ULONG value and memory address in DS3234 SRAM (0x0090 - 0x00C8)

#define ISUS_ERRORCTR_VAL       0               // counter indicating number of ISUS errors

#define ISUS_LASTERRTIME_VAL    TI_CCS_UNIX_EPOCH_OFFSET               // time of the last error event

#define ISUS_SAMPLECTR_VAL      0               // counter indicating total number of ISUS samples

#define ISUS_LASTSAMPTIME_VAL   TI_CCS_UNIX_EPOCH_OFFSET               // time of the last ISUS sample

#define ISUS_PERIOD_VAL         1000            // number of milliseconds to integrate spectrometer

#define ISUS_SAMPSPERDC_VAL     25              // number of samples per dark current reading

#define ISUS_SAMPSPERUV_VAL     24              // number of samples per UV "cleaning" cycle

//ISUS FLOAT value and memory address in DS3234 SRAM

#define ISUS_NO3SPAN_VAL        45.0

#define ISUS_NO3OFFSET_VAL      5.0

//---------------------------------------------------------------

//******************************************************************************
// DURA NV VARIABLES OCCUPY (0x00C9 - 0x00FF) IN THE 256 BYTE DS3234 SRAM
//******************************************************************************

//DURA UCHAR value and memory address in DS3234 SRAM (0x00C9 - 0x00CF)

#define DURA_LEDENABLE_VAL      1               // boolean for enabling LED status during AtoD sampling

//DURA USHORT value and memory address in DS3234 SRAM (0x00D0 - 0x00DF)

#define DURA_ATODREADINGS_VAL   10              // number of AtoD readings to average per sample reading

#define DURA_ATODDELAY_VAL      100             // number of mSecs to delay from AtoD mux change to the starting of AtoD reading(s)

//DURA INT value and memory address in DS3234 SRAM (0x00D0 - 0x00DF)

#define DURA_LASTERROR_VAL      0               // Clear any value

//DURA ULONG value and memory address in DS3234 SRAM (0x00E0 - 0x00FF)

#define DURA_ERRORCTR_VAL       0               // counter indicating number of DuraFET errors

#define DURA_LASTERRTIME_VAL    TI_CCS_UNIX_EPOCH_OFFSET               // time of the last error event

#define DURA_SAMPLECTR_VAL      0               // counter indicating total number of DuraFET samples

#define DURA_LASTSAMPTIME_VAL   TI_CCS_UNIX_EPOCH_OFFSET               // time of the last DuraFET sample

#define DURA_SAMPSPERCAL_VAL    250             // number of AtoD samples per AtoD (re)calibration


#ifdef NOCODE
#include    <msc_config.h>

#include    <io_regs.h>
#include    <io_spi.h>
#include    <io_i2c.h>
#include    <ds1683.h>
#include    <ds2433.h>
#include    <ds2482.h>
#include    <ds3234.h>
#include    <pcal6416.h>
#include    <hih6130.h>
#include    <ina219.h>
#include    <tca6424.h>
#include    "mms_spec.h"
#include    <fibrlite.h>
#include    <dura_adc.h>


#include    <nr.h>
#include    <nrutil.h>
#include    <lsqfit.h>
#include    <cf2_zmod.h>
#include    <userio.h>
#endif




#ifdef NOCODE

/* MSC Main Functions */
int     TakeDuraSample(char *dbuf, float *atime, ulong CTD_Time, float CTD_Temp, float CTD_Salinity, float CTD_Depth);
int     TakeIsusSample(char *dbuf, float *atime, ulong CTD_Time, float CTD_Temp, float CTD_Salinity, float CTD_Depth);
int     TakeIsusPseudoSample(char *dbuf, float *atime, ulong CTD_Time, float CTD_Temp, float CTD_Salinity, float CTD_Depth);


/* MSC Init Functions */
void    InitMSC( void );
void    InitVars( void );
void    GetVarsFromNVRAM( void );
void    SetDefaultsIntoNVRAM( void );
void    GetSysVarsFromNVRAM( void );
void    SetSysDefaultsIntoNVRAM( void );
void    GetIsusVarsFromNVRAM( void );
void    SetIsusDefaultsIntoNVRAM( void );
void    GetDuraVarsFromNVRAM( void );
void    SetDuraDefaultsIntoNVRAM( void );
int     IOPwrUp( void );
int     IOPwrDown( void );
void    InitWatchDogKeepAlive( void );
void    EnableWatchDog( void );
void    DisableWatchDog( void );
void    SysShutDown( void );


/* MSC Util Functions */

// File Routines
FILE    *OpenApfLogFile(uchar select);
int     LogErrorMsg(char *emsg, int ecode, uchar outp);
long    CalcRecsPending(uchar select);
int     SendRecords(uchar select, fpos_t *fpsrc);
int     CheckFileSize(uchar select);
int     LoadIsusECoefs(double *Lambda, double **Ecoefs, double *Zeros, double *Tcoefs, double *CalTemp, char *CalDate);
int     LoadIsusZCoefs(double *ZeissCoefs);
int     LoadDuraFetIIITCoefs(double *Coefs);
int     pdx_access(const *path, int amode);

// Serial I/O Routines
unsigned short  SerGetsTmout(char *buf, unsigned short buflen, unsigned short seconds);
int     SerPuts(char *str);
int     safegets(char *buffer, int n);
char    *strupr (char *string);
int     MatchACK(char *buf);

// Time Routines
int     SyncNextSample( void );
void    CheckRtcDelta( void );
int     DayOfYear(int yy, int mm, int dd);
int     DayOfWeek(int yy, int mm, int dd);
void    DelaySecs( unsigned short secs );
void    DelayMilliSecs( unsigned short msecs );
short   Sleep(ulong us, bool absolute);

// Output Routines
void    OutputIsusHeader(FILE *fptr);
void    OutputDuraHeader(FILE *fptr);
void    DisplaySystemInfo(void);
void    DisplayTimes(void);
void    DisplayAlarmTime( void );
void    DisplayChipSelectSettings(void);
void    DisplayFormattedTime(time_t ptime);
void    DisplayLambdaInfo(FILE *fptr);
void    DisplayByteVal(char *msgstr, uchar ByteVal);

#endif

#ifdef OLDCODENOWINMATHH
// Math Routines
int     CalcAbs(double *ZeroVals, unsigned short *IntenVals, double *AbsVals, double DCMean, unsigned short fit_pixels);
void    XformSwEcoefs(double **Ecoefs, double **XformedEcoefs, double *Lambda, double *Tcoefs, double CalTemp, double SamTemp);
void    InitEcoefMatrix(double **SrcEcoefs);
void    CopyEcoefs(double **SrcEcoefs, double **DstEcoefs);
void    CopySwEcoefs(double **SrcEcoefs, double **DstEcoefs);
void    InitLambdaArray(double *Lambda, double *ZeissCoefs);
int     MatchPixelsToLambda(double *Lambda, int lambda_beg, int lambda_end, unsigned short *pixel_beg, unsigned short *pixel_end);
double  CellNumToLambda(int cell, double *ZeissCoefs);
void    FloatVectorMinMax(unsigned short end, float data[], float *min, float *max);
void    FloatVectorMeanStdDev(unsigned short end, float data[], float *mean, float *stdev);
void    ShortVectorMinMax(unsigned short end, unsigned short data[], unsigned short *min, unsigned short *max);
void    ShortVectorMeanStdDev(unsigned short end, unsigned short data[], float *mean, float *stdev);
float   CtoF(float degC);
double  poly(double x, int degree, double p[]);
double  rtot(double r, double a[]);
double  ttor(double t, double a[]);
unsigned short  fCrc16Bit(const unsigned char *msg);
#endif


#ifdef NOCODE
/* APF Menu Functions */

void    RootMenu(void);

void    SetupMenu(void);
void    IsusSetup(void);
void    IsusSpecSetup(void);
void    IsusLampSetup(void);
void    IsusFitSetup(void);
void    DuraSetup(void);
void    LoggerSetup(void);
void    RtcSetup(void);

void    DataMenu(void);
void    IsusDataMenu(void);
void    IsusAcquireData(FILE *fptr);
void    DuraDataMenu(void);
void    DuraAcquireData(FILE *fptr);
void    DuraAcquireAtodValues(FILE *fptr);

void    TestMenu(void);
void    IsusTestMenu(void);
void    IsusLampTest(void);
void    IsusRefChTest(void);
void    DuraTestMenu(void);

void    InfoMenu(void);

void    FileMenu(void);
void    DownloadFile(void);
void    UploadFile(void);
void    DisplayFile(void);
void    RenameFile(void);
void    EraseFile(void);
void    EraseFiles(void);
void    ScanDir( void );

void    FNameError(void);
void    RangeError(long val1, long val2);
int     SysPass( void );

#endif




#endif /* APF_INIT_H_ */
