//=================================================================================================
//
// Company:       Paul Scherrer Institut
//                5232 Villigen PSI
//                Switzerland
//
//-------------------------------------------------------------------------------------------------
//
// Project:       Peltier Controller V2
// Author:        Noah Piqué (noah.pique@psi.ch)
//
//-------------------------------------------------------------------------------------------------
//
// Module:        Analog Ports Input
// Filename:      ANPI_AnalogPortsIn.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 the analog input ports
//
//=================================================================================================

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

#include "../PDEF_ProjectDefinitions.h"
#include "ANPI_AnalogPortsIn.h"



//Application
#include "../Application/VARH_VariableHandler.h"

// Drivers
#include "PECO_PeltierController.h"

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

// include STM32 drivers
#include "stm32l4xx_hal.h"

#include "cmsis_os2.h" 

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

#define ADC_RES         (4096)                       // ADC resolution: 12 bits
#define NR_OF_ADCS   		ANPI_eInNumberOfInputs                            // number of internal adc channels

#define INT_ADC_REF    (3.3f)// int. reference voltage for conversion

#define BUFFER_SIZE                         NR_OF_ADCS *  2
#define BUFFER_HALF_SIZE                    NR_OF_ADCS

#define ANPI_ADC_HALF_COMPLETE              ((U32)1<<0)
#define ANPI_ADC_FULL_COMPLETE              ((U32)1<<1)

#define ANPI_FLAGS_ALL                      ( ANPI_ADC_HALF_COMPLETE | ANPI_ADC_FULL_COMPLETE )

#define OVERSAMPLING_DIVISOR 16.0f  // calculated with parameters from hardware oversampling
                                    // 6 bits(64x) - 2 bit shift = 4bit -> 16x

//=================================================================================================
// 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 U16 m_au16ADCDataBuffer[BUFFER_SIZE];

LOCAL osThreadId_t        m_pstThreadID       = NULL;
LOCAL osEventFlagsId_t    m_pstEventID  		  = NULL;
LOCAL osMutexId_t         m_pstMutexID        = NULL;

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

// conversion factors for the values
// Order must fit enumeration "ANPI_EnAnalogInput"
LOCAL CONST FLOAT m_aflConversionFactor[ANPI_eInNumberOfInputs] =
{
  10,          	// 01 ANPI_eSupplyVoltage24V
  5,        	  // 02 ANPI_eSupplyCurrent24V
  10,  					// 03 ANPI_eOutputVoltage
  5,        		// 04 ANPI_eOutputCurrent
};

// Order must fit enumeration "ANPI_EnAnalogInput"
LOCAL CONST FLOAT m_aflOffset[ANPI_eInNumberOfInputs] =
{
  0.0f,                 // 01 ANPI_eSupplyVoltage24V
  8.25f,               // 02 ANPI_eSupplyCurrent24V
  14.85f,                 // 03 ANPI_eOutputVoltage
  8.25f, 						  // 04 ANPI_eOutputCurrent
};

// inputs are connected to the following ADCs
// ANPI_eSupplyVoltage24V     	ADC1, Channel 6
// ANPI_eSupplyCurrent24V    		ADC1, Channel 16
// ANPI_eOutputVoltage       		ADC1, Channel 7
// ANPI_eOutputCurrent          ADC1, Channel 15

LOCAL CONST osThreadAttr_t stTaskAttribute =
{
  "ANPI_Thread",                    // name of the thread
  osThreadDetached,                 // attribute bits
  NULL,                             // memory for control block
  0,                                // size of provided memory for control block
  NULL,                             // memory for stack
  1024,                          // size of stack
  osPriorityBelowNormal,            // initial thread priority (default: osPriorityNormal)
  0,                                // TrustZone module identifier
  0,                                // reserved (must be 0)
};

LOCAL CONST osEventFlagsAttr_t stEventAttribute =
{ 
  "ANPI_Event_Flags",               // name of the event flags 
  0,                                // attribute bits 
  NULL,                             // memory for control block
  0,                                // size of provided memory for control block
};

LOCAL CONST osMutexAttr_t m_stMutexAttr =
{
  "ANPI_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).
//=================================================================================================

PRIVATE VOID vTask( PVOID arg );

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



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

extern ADC_HandleTypeDef hadc1;

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

//-------------------------------------------------------------------------------------------------
// Function:      ANPI_boInitializeModule
// Description:   Initializes the module. Function must be called once immediately after power-up.
// Parameters:    None
// Returns:       Boolean TRUE if successful
//-------------------------------------------------------------------------------------------------
BOOL ANPI_boInitializeModule( VOID )
{
  BOOL boOK = TRUE;
  
  boOK &= ( ( m_pstThreadID = osThreadNew( vTask, NULL, &stTaskAttribute )) == NULL ) ? FALSE : TRUE;
  boOK &= ( ( m_pstEventID = osEventFlagsNew( &stEventAttribute )) == NULL) ? FALSE : TRUE;
  
  boOK &= ( ( m_pstMutexID = osMutexNew( &m_stMutexAttr )) == NULL) ? FALSE : TRUE;

  return( boOK );
}

//-------------------------------------------------------------------------------------------------
// Function:      ANPI_vTask
// Description:   ANPI_vTask
// Parameters:    None
// Returns:       None
//-------------------------------------------------------------------------------------------------
VOID vTask( PVOID arg )
{
  U32 u32Flags;
  U16 u16Offset;
  FLOAT flUadc;
  U32 au32ADCRawData[ANPI_eInNumberOfInputs];
  FLOAT aflValues[ANPI_eInNumberOfInputs];          // values
  
  osDelay( 1 ); // Wait 1ms to have a Valid Value
  
  HAL_ADC_Start_DMA( &hadc1, (PU32)&m_au16ADCDataBuffer[0], BUFFER_SIZE );
  
  while ( TRUE )
  {
    u32Flags = osEventFlagsWait( m_pstEventID, ANPI_FLAGS_ALL, osFlagsWaitAny, osWaitForever );

    if( u32Flags & ANPI_ADC_FULL_COMPLETE ) u16Offset = BUFFER_HALF_SIZE;
    else if( u32Flags & ANPI_ADC_HALF_COMPLETE ) u16Offset = 0;
    else continue;
    
    // aquire mutex: access to m_afcValues blocked for ANPI_flGetInputValue
    osMutexAcquire( m_pstMutexID, osWaitForever );                                  // aquire mutex

    // copy the values in the buffer...
    for( U16 u16Cnt = 0; u16Cnt < BUFFER_HALF_SIZE; u16Cnt++ )
      au32ADCRawData[ u16Cnt ] = m_au16ADCDataBuffer[u16Cnt + u16Offset];

    // multiply conversion factor and add the offset
    for( U16 u16Cnt = 0; u16Cnt < ANPI_eInNumberOfInputs; u16Cnt++ )
    {
      flUadc = (FLOAT)au32ADCRawData[u16Cnt] / OVERSAMPLING_DIVISOR / ADC_RES * INT_ADC_REF;
      aflValues[u16Cnt] = flUadc * m_aflConversionFactor[u16Cnt] - m_aflOffset[u16Cnt];
    }

    VARH_vSetVariableDataFromSystemFloat( VARH_ePeltier_U, aflValues[ANPI_eOutputVoltage] );
    VARH_vSetVariableDataFromSystemFloat( VARH_ePeltier_I, aflValues[ANPI_eOutputCurrent] );
    VARH_vSetVariableDataFromSystemFloat( VARH_ePeltier_R, aflValues[ANPI_eOutputVoltage] / aflValues[ANPI_eOutputCurrent] );
    VARH_vSetVariableDataFromSystemFloat( VARH_ePeltier_R, aflValues[ANPI_eOutputVoltage] * aflValues[ANPI_eOutputCurrent] );

    VARH_vSetVariableDataFromSystemFloat( VARH_eSupply_U, aflValues[ANPI_eSupplyVoltage24V] );
    VARH_vSetVariableDataFromSystemFloat( VARH_eSupply_I, aflValues[ANPI_eSupplyCurrent24V] );
    VARH_vSetVariableDataFromSystemFloat( VARH_eSupply_P, aflValues[ANPI_eSupplyVoltage24V] * (aflValues[ANPI_eSupplyCurrent24V]) );

    osMutexRelease( m_pstMutexID );                   															// release mutex
  }
}

//-------------------------------------------------------------------------------------------------
// Function:      HAL_ADC_ConvCpltCallback
// Description:   Handles the ADC interrupts
// Parameters:    None
// Returns:       None
//-------------------------------------------------------------------------------------------------
void HAL_ADC_ConvCpltCallback( ADC_HandleTypeDef* hadc )
{
  osEventFlagsSet( m_pstEventID, ANPI_ADC_FULL_COMPLETE );
}

//-------------------------------------------------------------------------------------------------
// Function:      HAL_ADC_ConvHalfCpltCallback
// Description:   Handles the ADC interrupts
// Parameters:    None
// Returns:       None
//-------------------------------------------------------------------------------------------------
void HAL_ADC_ConvHalfCpltCallback( ADC_HandleTypeDef* hadc )
{
  osEventFlagsSet( m_pstEventID, ANPI_ADC_HALF_COMPLETE );
}

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

//-------------------------------------------------------------------------------------------------
// Function:      HAL_ADC_ErrorCallback
// Description:   Error Callback for the ADC
// Parameters:    ADC_HandleTypeDef* hadc 
// Returns:       None
//-------------------------------------------------------------------------------------------------
void HAL_ADC_ErrorCallback( ADC_HandleTypeDef* hadc )
{
  // TODO: Error Handling
  if( hadc->ErrorCode == HAL_ADC_ERROR_NONE )
  {
    
  }
  
  if( hadc->ErrorCode == HAL_ADC_ERROR_INTERNAL )
  {
    
  }

  if( hadc->ErrorCode == HAL_ADC_ERROR_OVR )
  {

  }
  
  if( hadc->ErrorCode == HAL_ADC_ERROR_DMA )
  {

  }
  
  if( hadc->DMA_Handle->ErrorCode & HAL_DMA_ERROR_TE )
  {

  } 
  
}
