/*
 * apf_util.h
 *
 *  Created on: May 14, 2024
 *      Author: tm
 */

#ifndef APF_UTIL_H_
#define APF_UTIL_H_

#define DATBUFSIZE      2048        // from apf_util
#define TCOEFS             5        // Bromide Temperature Compensation Coefs

// apf_util.h
int CheckFileSize(unsigned int select);
FILE *OpenApfLogFile( unsigned int select );     // was uint8_t select
int LogErrorMsg(char *emsg, int ecode, uint8_t outp);
long CalcRecsPending(unsigned int select);
int SendRecords(unsigned int select, fpos_t *fpsrc);
int CheckFileSize(unsigned int select);
int LoadIsusECoefs(double *Lambda, double **Ecoefs, double *Zeros, double *Tcoefs, double *CalTemp, char *CalDate);
int LoadIsusZCoefs(double *ZeissCoefs);
int LoadDuraFetIIITCoefs(double *Coefs);



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);
int SyncNextSample( void );
void CheckRtcDelta(void);
int DayOfYear(int yy, int mm, int dd);
int DayOfWeek(int yy, int mm, int dd);
short Sleep(unsigned long us, bool absolute);
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, uint8_t ByteVal);
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);
int MatchPixelsToLambda(double *Lambda, int lambda_beg, int lambda_end, unsigned short *pixel_beg, unsigned short *pixel_end);
void InitLambdaArray(double *Lambda, double *ZeissCoefs);





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);

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





short QueryChar(char *prompt, short defChar, char *scanSet, char *reply);
int QueryNum(char *prompt, char *defFmt, char *scanFmt, unsigned long *value);     // ptr prompt
int QueryFloat(char *prompt, char *defFmt, char *scanFmt, float *value);
int InputLine(char *linebuf, short linelen);
int kbflush(void);
//int kbhit(void);

#ifdef NOWINFRAM_MOVEDFROMSRAM

//******************************************************************************
// SYS NV VARIABLES OCCUPY (0x0001 - 0x0064) IN THE 256 BYTE DS3234 SRAM
//******************************************************************************

//SYS UCHAR value and memory address in DS3234 SRAM (0x0000 - 0x000F)
#define SYS_INITSRAM_PTR        0x0000
#define SYS_INITSRAM_VAL        0xAA            // for detecting unitialized DS3234 SRAM
#define SYS_SYNCMODE_PTR        0x0001
#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_PTR        0x0002
#define SYS_DEPLMODE_VAL        1               // Deployment mode 1=Scheduled 2=Continuous 3=Triggered
#define SYS_DATAMODE_PTR        0x0003
#define SYS_DATAMODE_VAL        1               // Scheduled Data Collection Mode 1=Real Data 2=Pseudo Data (TEST MODE)
#define SYS_TIMETYPE_PTR        0x0004
#define SYS_TIMETYPE_VAL        1               // Report time in WholeSecs=1 or FractionalSecs=2, using CF2 RTC
#define SYS_WDOGENABLE_PTR      0x0005
#define SYS_WDOGENABLE_VAL      0               // boolean for enabling watchdog reset
#define SYS_MSGENABLE_PTR       0x0006
#define SYS_MSGENABLE_VAL       0               // boolean for enabling the printing of error/status messages
#define SYS_PUMPENABLE_PTR      0x0007
#define SYS_PUMPENABLE_VAL      0               // boolean for enabling the flushing pump cycle
#define SYS_SENSORTYPE_PTR      0x0008
#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_PTR         0x0010
#define SYS_DELAYHR_VAL         3               // number of hours until start of data logging
#define SYS_SYNCHR_PTR          0x0012
#define SYS_SYNCHR_VAL          6               // local hour to sync start of data logging to
#define SYS_SYNCMIN_PTR         0x0014
#define SYS_SYNCMIN_VAL         0               // local minute to sync start of data logging to
#define SYS_DFLIMIT_PTR         0x0016
#define SYS_DFLIMIT_VAL         5               // max size (in Mbytes) for any datafile
#define SYS_SFLIMIT_PTR         0x0018
#define SYS_SFLIMIT_VAL         256             // max size (in kbytes) for data spool file (e.g., OASIS dat file) before removal
#define SYS_EFLIMIT_PTR         0x001A
#define SYS_EFLIMIT_VAL         256             // max size (in kbytes) for error log file (ERROR.LOG) before removal
#define SYS_LASTDOY_PTR         0x001C
#define SYS_LASTDOY_VAL         0               // last day of year value used in datafile naming
#define SYS_SERIALN_PTR         0x001E
#define SYS_SERIALN_VAL         777             // Default Serial Number
#define SYS_APFTMOUT_PTR        0x0020
#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_PTR        0x0022
#define SYS_TZOFFSET_VAL        8               // hrs local time is offset from GMT (+) is W (-) is E
#define SYS_LASTERROR_PTR       0x0024
#define SYS_LASTERROR_VAL       0               // Clear any value

//SYS ULONG value and memory address in DS3234 SRAM (0x0030 - 0x0064)
#define SYS_ERRORCTR_PTR        0x0030
#define SYS_ERRORCTR_VAL        0               // counter indicating number of System errors
#define SYS_LASTERRTIME_PTR     0x0034
#define SYS_LASTERRTIME_VAL     0               // time of the last error event
#define SYS_RESETCTR_PTR        0x0038
#define SYS_RESETCTR_VAL        0               // counter indicating total number of system resets
#define SYS_RESETTIME_PTR       0x003C
#define SYS_RESETTIME_VAL       0               // time of the last system reset event
#define SYS_PORCTR_PTR          0x0040
#define SYS_PORCTR_VAL          0               // counter indicating total number of Power On Resets
#define SYS_FILECTR_PTR         0x0044
#define SYS_FILECTR_VAL         1               // counter indicating number of files used in current DOY
#define SYS_SLEEPPER_PTR        0x0048
#define SYS_SLEEPPER_VAL        60              // number of minutes between RTC wakeups (not used in APF firmware)
#define SYS_PUMPPER_PTR         0x004C
#define SYS_PUMPPER_VAL         60              // number of seconds to run pump prior to sampling

#endif      //#ifdef NOWINFRAM_MOVEDFROMSRAM

//******************************************************************************
// SYS Global Variables used and or shared in any build
//******************************************************************************

// Memory Mapped Latches
//unsigned short WrRegVal;
//unsigned short WhichRxd;

// UCHARs Stored in DS3234 NVRAM:
//uint8_t  sys_slog_delay, sys_deploy_mode, sys_sensor_type;
//uint8_t  sys_data_mode, sys_time_type, sys_watchdog_enable;
//uint8_t  sys_message_enable, sys_pump_enable;

// UCHARs NOT Stored in DS3234 NVRAM:
//uint8_t  sys_sensor_mode;                 // CF2 Logger Sensor Select, 0=Default 1=ISUS 2=DuraFET
//uint8_t  sys_por_flag;
//uint8_t  sys_pump_pwr;

// USHORTs Stored in DS3234 NVRAM:
//unsigned short sys_delay_hour, sys_sync_hour, sys_sync_min;
//unsigned short sys_df_limit, sys_sf_limit, sys_ef_limit;
//unsigned short sys_last_doy, sys_serial_num, sys_apf_tmout;

// INTs Stored in DS3234 NVRAM
//int  sys_tzoffset, sys_last_error;
//
// ULONGs Stored in DS3234 NVRAM
//ulong  sys_error_ctr, sys_error_time;
//ulong  sys_reset_ctr, sys_reset_time;
//ulong  sys_por_ctr, sys_file_ctr;
//ulong  sys_sleep_period, sys_pump_period;


#ifdef NOCODE
// ALL RTC TIMES ARE GMT - SHOULD BE ANYWAY!
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 apf.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)
#endif


#endif /* APF_UTIL_H_ */
