//=================================================================================================
//
// Company:       Paul Scherrer Institut
//                5232 Villigen PSI
//                Switzerland
//
//-------------------------------------------------------------------------------------------------
//
// Project:       Peltier Controller V2
// Author:        Noah Piqué (noah.pique@psi.ch)
//
//-------------------------------------------------------------------------------------------------
//
// Module:        Variable Handler
// Filename:      VARH_VariableHandler.c
// Date:          Handled by Subversion (version control system)
// Revision:      Handled by Subversion (version control system)
// History:       Handled by Subversion (version control system)
//
//-------------------------------------------------------------------------------------------------
//
// Description:   This source file contains all functions dealing with global variables
//
//=================================================================================================

//=================================================================================================
// Section:       INCLUDES
// Description:   List of required include files.
//=================================================================================================

#include "VARH_VariableHandler.h"

#include "USFL_UserFlash.h"

// Toolbox
#include "../Toolbox/UTIL_Utility.h"

#include "cmsis_os2.h" 

//=================================================================================================
// Section:       DEFINITIONS
// Description:   Definition of local constants (visible by this module only).
//=================================================================================================

//=================================================================================================
// Section:       MACROS
// Description:   Definition of local macros (visible by this module only).
//=================================================================================================

//=================================================================================================
// Section:       ENUMERATIONS
// Description:   Definition of local enumerations (visible by this module only).
//=================================================================================================

//=================================================================================================
// Section:       STRUCTURES
// Description:   Definition of local Structures (visible by this module only).
//=================================================================================================

//=================================================================================================
// Section:       LOCAL VARIABLES
// Description:   Definition of local variables (visible by this module only).
//=================================================================================================

LOCAL VARH_StVar  	      m_auVariable[VARH_eNumberOfVariables];

LOCAL osMutexId_t         m_pstMutexID    = NULL;

//=================================================================================================
// Section:       LOCAL CONSTANTS
// Description:   Definition of local constants (visible by this module only).
//=================================================================================================

/*
  If you set the VARH_FLAGINFO_FLASH, don't forget to update the Number of variables saved into Flash!!!
  Middlewares\ST\EEPROM_Emul\Core\eeprom_emul_conf.h
*/

LOCAL CONST VARH_StVarInfo m_astVarInfo[VARH_eNumberOfVariables] =
{ 
  { VARH_FLAGINFO_NONE, (VARH_UVariable)(U32)1, (VARH_UVariable)(U32)0, (VARH_UVariable)(U32)1}, // VARH_eMode

  { VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)-2.0f, (VARH_UVariable)12.0f}, // VARH_eControlVoltage

  { VARH_FLAGINFO_FLASH | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)0.0f, (VARH_UVariable)100.0f }, // VARH_ePID_kp
  { VARH_FLAGINFO_FLASH | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)0.0f, (VARH_UVariable)100.0f }, // VARH_ePID_ki
  { VARH_FLAGINFO_FLASH | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)0.0f, (VARH_UVariable)100.0f }, // VARH_ePID_kd
  { VARH_FLAGINFO_FLOAT, (VARH_UVariable)23.0f, (VARH_UVariable)-40.0f, (VARH_UVariable)50.0f }, // VARH_ePID_Temp
  { VARH_FLAGINFO_FLASH | VARH_FLAGINFO_FLOAT, (VARH_UVariable)10.0f, (VARH_UVariable)0.0f, (VARH_UVariable)12.0f }, // VARH_ePID_Max
  { VARH_FLAGINFO_FLASH | VARH_FLAGINFO_FLOAT, (VARH_UVariable)-2.0f, (VARH_UVariable)-2.0f, (VARH_UVariable)0.0f }, // VARH_ePID_Min

  { VARH_FLAGINFO_READONLY | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)-60.0f, (VARH_UVariable)100.0f }, // VARH_eTemp_Water
  { VARH_FLAGINFO_READONLY | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)-60.0f, (VARH_UVariable)100.0f }, // VARH_eTemp_Module
  { VARH_FLAGINFO_READONLY | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)-50.0f, (VARH_UVariable)70.0f }, // VARH_eTemp_Diff

  { VARH_FLAGINFO_READONLY | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)-5.0f, (VARH_UVariable)14.0f }, // VARH_ePeltier_U
  { VARH_FLAGINFO_READONLY | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)-10.0f, (VARH_UVariable)10.0f }, // VARH_ePeltier_I
  { VARH_FLAGINFO_READONLY | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)0.0f, (VARH_UVariable)5.0f }, // VARH_ePeltier_R
  { VARH_FLAGINFO_READONLY | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)-50.0f, (VARH_UVariable)150.0f }, // VARH_ePeltier_P

  { VARH_FLAGINFO_READONLY | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)20.0f, (VARH_UVariable)30.0f }, // VARH_eSupply_U
  { VARH_FLAGINFO_READONLY | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)0.0f, (VARH_UVariable)5.0f }, // VARH_eSupply_I
  { VARH_FLAGINFO_READONLY | VARH_FLAGINFO_FLOAT, (VARH_UVariable)0.0f, (VARH_UVariable)0.0f, (VARH_UVariable)150.0f }, // VARH_eSupply_P

  { VARH_FLAGINFO_READONLY, (VARH_UVariable)(U32)0, (VARH_UVariable)(U32)0, (VARH_UVariable)(U32)1 }, // VARH_ePowerState
  { VARH_FLAGINFO_READONLY, (VARH_UVariable)(U32)0, (VARH_UVariable)(U32)0, (VARH_UVariable)(U32)0xFFFFFFFF }, // VARH_eError
  { VARH_FLAGINFO_FLASH | VARH_FLAGINFO_FLOAT, (VARH_UVariable)3.3f, (VARH_UVariable)(U32)2.0f, (VARH_UVariable)4.0f }, // VARH_eRef_U
};

LOCAL CONST osMutexAttr_t m_stMutexAttr =
{
  "VARH_Mutex",                             // human readable mutex name
  osMutexRecursive | osMutexPrioInherit,    // attr_bits
  NULL,                                     // memory for control block   
  0U                                        // size for control block
};

//=================================================================================================
// Section:       LOCAL FUNCTIONS (PROTOTYPES)
// Description:   Definition of local functions (visible by this module only).
//=================================================================================================

// check functions
PRIVATE BOOL boCheckRange( U8 u8Variable, VARH_UVariable uNewData );

PRIVATE BOOL boBooleanVarCheck( U32 u32NewValue );
PRIVATE BOOL boU32VarCheck( U8 u8Variable, U32 u32NewValue );
PRIVATE BOOL boS32VarCheck( U8 u8Variable, S32 s32NewValue );
PRIVATE BOOL boFloatVarCheck( U8 u8Variable, FLOAT flNewValue );

//=================================================================================================
// Section:       EXTERNAL FUNCTIONS
// Description:   Definition of external (global) functions.
//=================================================================================================

//=================================================================================================
// Section:       EXTERNAL VARIABLES
// Description:   Definition of external (global) variables.
//=================================================================================================

//=================================================================================================
// Section:       GLOBAL FUNCTIONS
// Description:   Definition (implementation) of global functions.
//=================================================================================================

//-------------------------------------------------------------------------------------------------
// Function:      VARH_boInitializeModule
// Description:   Initializes the module. Function must be called once immediately after power-up.
// Parameters:    BOOL boInitConfig
// Returns:       Boolean TRUE if successful
//-------------------------------------------------------------------------------------------------
BOOL VARH_boInitializeModule( VOID )
{
  BOOL boOK = TRUE;

	boOK &= ( ( m_pstMutexID = osMutexNew( &m_stMutexAttr ) ) == NULL ) ? FALSE : TRUE;
	
  VARH_vSetAllVariablesToInitData();
  
  return( boOK );
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSetVariableData
// Description:   Sets the Variable Data and checks the parameters (Readonly and Min/Max)
// Parameters:    U8 u8Variable
//                VARH_UVariable uData
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID VARH_vSetVariableData( U8 u8Variable, VARH_UVariable uData )
{
	// check parameters
  if( m_astVarInfo[u8Variable].u8Flags & VARH_FLAGINFO_READONLY )
  {
    return;
  }

	osMutexAcquire( m_pstMutexID, osWaitForever );                                        // aquire mutex
  if( boCheckRange( u8Variable, uData ) ) { m_auVariable[u8Variable].uData = uData; }   // store new value
  osMutexRelease( m_pstMutexID );                   															      // release mutex
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSetVariableDataU32
// Description:   Sets the Variable Data and checks the parameters (Readonly and Min/Max)
// Parameters:    U8 u8Variable
//                U32 u32Data
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID VARH_vSetVariableDataU32( U8 u8Variable, U32 u32Data )
{
  VARH_vSetVariableData( u8Variable, (VARH_UVariable)u32Data );
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSetVariableDataS32
// Description:   Sets the Variable Data and checks the parameters (Readonly and Min/Max)
// Parameters:    U8 u8Variable
//                S32 s32Data
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID VARH_vSetVariableDataS32( U8 u8Variable, S32 s32Data )
{
  VARH_vSetVariableData( u8Variable, (VARH_UVariable)s32Data );
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSetVariableDataFloat
// Description:   Sets the Variable Data and checks the parameters (Readonly and Min/Max)
// Parameters:    U8 u8Variable
//                FLOAT flData
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID VARH_vSetVariableDataFloat( U8 u8Variable, FLOAT flData )
{
  VARH_vSetVariableData( u8Variable, (VARH_UVariable)flData );
}


//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSetVariableDataFromSystem
// Description:   Sets the Variable Data from System
//                Use only internal, not for User!
// Parameters:    U8 u8Variable
//                VARH_UVariable uData
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID VARH_vSetVariableDataFromSystem( U8 u8Variable, VARH_UVariable uData )
{
	osMutexAcquire( m_pstMutexID, osWaitForever );                                        // aquire mutex
  if( !boCheckRange( u8Variable, uData ) ) 
  { 
    m_auVariable[u8Variable].u8Flags |= VARH_FLAG_OUTOFRANGE;                           // check the value
  }
  m_auVariable[u8Variable].uData = uData;                                               // store new value
  osMutexRelease( m_pstMutexID );                   															      // release mutex
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSetVariableDataFromSystemU32
// Description:   Sets the Variable Data from System
//                Use only internal, not for User!
// Parameters:    U8 u8Variable
//                U32 u32Data
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID VARH_vSetVariableDataFromSystemU32( U8 u8Variable, U32 u32Data )
{
  VARH_vSetVariableDataFromSystem( u8Variable, (VARH_UVariable)u32Data );
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSetVariableDataFromSystemS32
// Description:   Sets the Variable Data from System
//                Use only internal, not for User!
// Parameters:    U8 u8Variable
//                S32 s32Data
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID VARH_vSetVariableDataFromSystemS32( U8 u8Variable, S32 s32Data )
{
  VARH_vSetVariableDataFromSystem( u8Variable, (VARH_UVariable)s32Data );
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSetVariableDataFromSystemFloat
// Description:   Sets the Variable Data from System
//                Use only internal, not for User!
// Parameters:    U8 u8Variable
//                FLOAT flData
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID VARH_vSetVariableDataFromSystemFloat( U8 u8Variable, FLOAT flData )
{
  VARH_vSetVariableDataFromSystem( u8Variable, (VARH_UVariable)flData );
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_uGetVariableData
// Description:   Gets the Variable Data
// Parameters:    U8 u8Variable
// Returns:       VARH_UVariable
//-------------------------------------------------------------------------------------------------
VARH_UVariable VARH_uGetVariableData( U8 u8Variable )
{
	osMutexAcquire( m_pstMutexID, osWaitForever );                  // aquire mutex
  VARH_UVariable uVar = m_auVariable[u8Variable].uData;
	osMutexRelease( m_pstMutexID );                   							// release mutex
  return( uVar );
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_u32GetVariableData
// Description:   Gets the Variable Data
// Parameters:    U8 u8Variable
// Returns:       U32
//-------------------------------------------------------------------------------------------------
U32 VARH_u32GetVariableData( U8 u8Variable )
{
  return VARH_uGetVariableData( u8Variable ).u32Val;
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_s32GetVariableData
// Description:   Gets the Variable Data
// Parameters:    U8 u8Variable
// Returns:       S32
//-------------------------------------------------------------------------------------------------
S32 VARH_s32GetVariableData( U8 u8Variable )
{
  return VARH_uGetVariableData( u8Variable ).s32Val;
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_flGetVariableData
// Description:   Gets the Variable Data
// Parameters:    U8 u8Variable
// Returns:       FLOAT
//-------------------------------------------------------------------------------------------------
FLOAT VARH_flGetVariableData( U8 u8Variable )
{
  return VARH_uGetVariableData( u8Variable ).flVal;
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_uGetVariableFlags
// Description:   Gets the Variable Flags
// Parameters:    U8 u8Variable
// Returns:       u8Flags
//-------------------------------------------------------------------------------------------------
U8 VARH_uGetVariableFlags( U8 u8Variable )
{
	osMutexAcquire( m_pstMutexID, osWaitForever );                  // aquire mutex
  U8 u8Flags = m_auVariable[u8Variable].u8Flags;
	osMutexRelease( m_pstMutexID );                   							// release mutex
  return( u8Flags );
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSetVariableToInitData
// Description:   Sets the variable to its initial data
// Parameters:    U8 u8Variable
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID VARH_vSetVariableToInitData( U8 u8Variable )
{
	VARH_vSetVariableDataFromSystem( u8Variable, m_astVarInfo[u8Variable].uInitData );
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSetAllVariablesToInitData
// Description:   Sets all variables to its initial data
// Parameters:    VARH_EnVariables enVariable
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID VARH_vSetAllVariablesToInitData( VOID )
{
  for( U16 u16Var = 0; u16Var < VARH_eNumberOfVariables; u16Var++ )
  {
    VARH_vSetVariableToInitData( u16Var );
  }
}

//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSaveVariablestoFlash
// Description:   Saves all Variables with Flag VARH_FLAGINFO_FLASH to Flash
// Parameters:    None
// Returns:       TRUE if successful
//-------------------------------------------------------------------------------------------------
BOOL VARH_vSaveVariablestoFlash( VOID )
{
  BOOL boOK = TRUE;
  boOK &= USFL_vUnlock();
  for( U8 u8Var = 0; u8Var < VARH_eNumberOfVariables; u8Var++ )
  {
    if( (m_astVarInfo[u8Var].u8Flags & VARH_FLAGINFO_FLASH) == VARH_FLAGINFO_FLASH ){
      boOK &= USFL_boSetVariable(u8Var, VARH_uGetVariableData(u8Var));
    }
  }
  boOK &= USFL_vLock();

  return boOK;
}


//-------------------------------------------------------------------------------------------------
// Function:      VARH_vSaveVariablestoFlash
// Description:   Saves all Variables with Flag VARH_FLAGINFO_FLASH to Flash
// Parameters:    None
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID VARH_vLoadVariablesfromFlash( VOID )
{
  BOOL boOK = TRUE;
  for( U8 u8Var = 0; u8Var < VARH_eNumberOfVariables; u8Var++ )
  {
    if( (m_astVarInfo[u8Var].u8Flags & VARH_FLAGINFO_FLASH) == VARH_FLAGINFO_FLASH ){
      VARH_UVariable uData;
      boOK &= USFL_boGetVariable(u8Var, &uData);
      if( boOK ) VARH_vSetVariableDataFromSystem(u8Var, uData);
    }
  }
  if( !boOK ){
    for( U8 u8Var = 0; u8Var < VARH_eNumberOfVariables; u8Var++ )
    {
      if( (m_astVarInfo[u8Var].u8Flags & VARH_FLAGINFO_FLASH) == VARH_FLAGINFO_FLASH ){
        VARH_vSetVariableToInitData( u8Var );
      }
    }
  }
}


//=================================================================================================
// Section:       LOCAL FUNCTIONS
// Descriptionn:  Definition (implementation) of local functions.
//=================================================================================================

//-------------------------------------------------------------------------------------------------
// Function:      boBooleanVarCheck
// Description:   Checks the range of a boolean
// Parameters:    U32 u32NewValue
// Returns:       TRUE, the variable can be written
//-------------------------------------------------------------------------------------------------
PRIVATE BOOL boBooleanVarCheck( U32 u32NewValue )
{
  return( u32NewValue > 1 ? FALSE : TRUE );
}

//-------------------------------------------------------------------------------------------------
// Function:      boU32VarCheck
// Description:   Checks the range of a U32
// Parameters:    U8 u8Variable
//                U32 u32NewValue
// Returns:       TRUE, the variable can be written
//-------------------------------------------------------------------------------------------------
PRIVATE BOOL boU32VarCheck( U8 u8Variable, U32 u32NewValue )
{
  return(  (m_astVarInfo[u8Variable].uMinData.u32Val <= u32NewValue) && (u32NewValue <= m_astVarInfo[u8Variable].uMaxData.u32Val) ? TRUE : FALSE );
}

//-------------------------------------------------------------------------------------------------
// Function:      boS32VarCheck
// Description:   Checks the range of a S32
// Parameters:    U8 u8Variable
//                S32 s32NewValue
// Returns:       TRUE, the variable can be written
//-------------------------------------------------------------------------------------------------
PRIVATE BOOL boS32VarCheck( U8 u8Variable, S32 s32NewValue )
{
  return(  (m_astVarInfo[u8Variable].uMinData.s32Val <= s32NewValue) && (s32NewValue <= m_astVarInfo[u8Variable].uMaxData.s32Val) ? TRUE : FALSE );
}

//-------------------------------------------------------------------------------------------------
// Function:      boFloatVarCheck
// Description:   Checks the range of a Float
// Parameters:    U8 u8Variable
//                FLOAT flNewValue
// Returns:       TRUE, the variable can be written
//-------------------------------------------------------------------------------------------------
PRIVATE BOOL boFloatVarCheck( U8 u8Variable, FLOAT flNewValue )
{
  return(  (m_astVarInfo[u8Variable].uMinData.flVal <= flNewValue) && (flNewValue <= m_astVarInfo[u8Variable].uMaxData.flVal) ? TRUE : FALSE );
}

//-------------------------------------------------------------------------------------------------
// Function:      boCheckRange
// Description:   Checks the range of the variable
// Parameters:    U8 u8Variable
//                VARH_UVariable uNewData
// Returns:       TRUE, if the value is in the range, otherwise FALSE
//-------------------------------------------------------------------------------------------------
PRIVATE BOOL boCheckRange( U8 u8Variable, VARH_UVariable uNewData )
{
  if( m_astVarInfo[u8Variable].u8Flags & VARH_FLAGINFO_FLOAT )
  {
    return( boFloatVarCheck(u8Variable, uNewData.flVal ) );
  } else if( m_astVarInfo[u8Variable].u8Flags & VARH_FLAGINFO_SIGNED )
  {
    return( boS32VarCheck(u8Variable, uNewData.s32Val ) );
  } else if( m_astVarInfo[u8Variable].u8Flags & VARH_FLAGINFO_BOOL )
  {
    return( boBooleanVarCheck( uNewData.s32Val ) );
  } else
  {
    return( boU32VarCheck( u8Variable, uNewData.u32Val ) );
  }
  
}



