/****************************************************************************
 *  F i l e   D a t a                                                        
 *  $Id: SCM_Manager_INFN.c,v 1.54 2005/03/23 10:24:12 sebastiani Exp $
 *  $Revision: 1.54 $
 *  $Date: 2005/03/23 10:24:12 $
 *  $RCSfile: SCM_Manager_INFN.c,v $
 *                                                                           
 ****************************************************************************
 *  S W   D e v e l o p m e n t   E n v i r o n m e n t                      
 *                                                                           
 *  $Author: sebastiani $
 *               :                                                           
 ****************************************************************************
 *  U p d a t i n g                                                          

 *  $Log: SCM_Manager_INFN.c,v $
 *  Revision 1.54  2005/03/23 10:24:12  sebastiani
 *  more logging in PowerOffOn
 *
 *  Revision 1.53  2005/03/20 18:26:20  sebastiani
 *  status = PWR_InitBoard_twice();
 *
 *  Revision 1.52  2005/03/13 18:24:47  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.51  2005/03/06 14:54:46  sebastiani
 *  version running on 06 03 2005
 *
 *  Revision 1.50  2005/02/24 17:50:18  sebastiani
 *  different PRH_VAR_POWER_MODE manages in SCM_Manager_INFN task main as a switch (2) PRH_VAR_ND_OK in custom mode get the same value as PRH_VAR_S4_OK and PRH_TAB_CONF[PRH_VAR_CONF_SEL][5]
 *
 *  Revision 1.49  2005/02/21 14:26:01  sebastiani
 *  TSB bugfixes.
 *
 *  Revision 1.48  2005/02/21 08:58:29  sebastiani
 *  all log comments completed
 *
 *  Revision 1.47  2005/02/19 10:19:38  sebastiani
 *  ALM_S4_CALIB_00_HARD,ALM_S4_CALIB_00_SOFT,ALM_S4_128TRIGGER_0 added
 *
 *  Revision 1.46  2005/01/26 18:46:48  sebastiani
 *  new bug fixes for WS
 *
 *  Revision 1.45  2004/12/23 13:54:34  faber
 *  PWR_HVSetting() introduced
 *
 *  Revision 1.44  2004/12/20 14:02:04  faber
 *  @LOG entry introduced in all ALM_WriteLog occurrences
 *
 *  Revision 1.43  2004/12/15 09:32:47  sebastiani
 *  invocation of PWR_TRBSetting() moved into invocation of PWR_TRB_On()
 *
 *  Revision 1.42  2004/11/30 11:51:53  faber
 *  AC+AC2 software moved into AC_1 AC_2
 *  new calibration and initialization for AC
 *  first version,never run
 *
 *  Revision 1.41  2004/11/25 09:20:17  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.40  2004/11/23 22:54:06  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.39  2004/11/19 15:14:52  sebastiani
 *  PRH_EXTERN_{VAR,ARR,TABLE} removed and put them on the autogenerated parameter heeader file
 *
 *  Revision 1.38  2004/11/18 16:02:34  sebastiani
 *  GAS/TRD removed
 *
 *  Revision 1.37  2004/11/05 09:36:35  sebastiani
 *  first version of the PM state machine. tried but not deeply tested
 *
 *  Revision 1.36  2004/11/02 15:41:39  faber
 *  *** empty log message ***
 *
 *  Revision 1.35  2004/10/22 16:05:06  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.34  2004/10/19 16:59:27  sebastiani
 *  first text for IPM/ciclyc
 *
 *  Revision 1.33  2004/10/18 10:43:02  faber
 *  Power check new fligh mode
 *
 *  Revision 1.32  2004/09/30 09:56:52  alfarano
 *  thermistors check funcs
 *
 *  Revision 1.31  2004/09/28 15:34:30  alfarano
 *  *** empty log message ***
 *
 *  Revision 1.30  2004/09/28 15:10:51  alfarano
 *  little bug
 *
 *  Revision 1.28  2004/09/27 15:42:43  alfarano
 *  tracker sensor board functions
 *
 *  Revision 1.27  2004/09/22 15:54:54  alfarano
 *  S4 functions
 *
 *  Revision 1.26  2004/09/17 15:01:00  faber
 *  LU_INFN_LOG flags fixing
 *
 *  Revision 1.25  2004/09/14 13:05:37  alfarano
 *  update TM constants and definitions
 *
 *  Revision 1.23  2004/09/10 15:27:28  sebastiani
 *  added PWR dcdc procedures
 *
 *  Revision 1.22  2004/08/30 07:08:18  sebastiani
 *  little modify
 *
 *  Revision 1.21  2004/08/27 13:13:49  alfarano
 *  High voltage functions
 *
 *  Revision 1.20  2004/08/26 16:54:34  sebastiani
 *  version work fine
 *
 *  Revision 1.19  2004/08/05 16:19:07  sebastiani
 *  fix close run
 *  add cal handler error
 *  fix tmtc
 *  ok protocol betwen pm-rm-scm
 *
 *  Revision 1.18  2004/08/02 15:49:47  alfarano
 *  alarm handling , scm & pm communication rewrite
 *
 *  Revision 1.17  2004/08/02 12:16:06  sebastiani
 *  little fix
 *
 *  Revision 1.16  2004/07/27 10:13:48  faber
 *  LU_ALARM macro introduced,
 *  LU_XXXX bit field "logtype" redefined.
 *  HistoryArea 5 now log a 32 bit word as "info1"
 *  and logging is reformatted.
 *
 *  Revision 1.15  2004/07/15 10:50:28  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.14  2004/07/13 14:35:54  alfarano
 *  *** empty log message ***
 *
 *  Revision 1.13  2004/07/12 09:19:33  sebastiani
 *  some fixing about alamrs
 *
 *  Revision 1.12  2004/06/15 08:24:37  sebastiani
 *  *** empty log message ***
 *
 *  Revision 1.11  2004/04/29 14:31:46  sebastiani
 *  SAVETM bugfix
 *
 *  Revision 1.10  2004/04/20 14:54:13  faber
 *  work before Brussel
 *
 *  Revision 1.9  2004/03/09 19:07:22  faber
 *  introduced timer cancelling when disable sampling/storing of TMTC
 *
 *  Revision 1.8  2004/03/09 15:10:29  faber
 *  HK_DoCyclicAcquisition takes a void *all_values_ptr param
 *  removed check cycle in the TMTC Module
 *
 *  Revision 1.7  2004/03/08 15:49:09  alfarano
 *  improved handling functions for FE
 *
 *  Revision 1.6  2004/02/27 15:40:46  tassa
 *  TMTC function moved in SCM MANAGER
 *  add function blocking to send FE command in HK MANAGER
 *
 *  Revision 1.5  2003/12/06 08:32:38  faber
 *  startup procedure tuned. TMTC sampling storing  at startup
 *
 *  Revision 1.4  2003/12/05 17:14:34  alfarano
 *  update
 *
 *  Revision 1.3  2003/12/04 17:16:08  sebastiani
 *  GS debug/tests, and other
 *
 *  Revision 1.2  2003/11/27 17:53:23  faber
 *  -Power management poweron procedure done and some tested in the simulator
 *  -history entry 5 now takes OBT
 *
 *  Revision 1.1  2003/11/19 15:47:03  faber
 *  System Control Manager (SCM) and Power Handler (PWR) modules introduced
 *
 *  Revision 1.1  2003/10/03 16:12:26  faber
 *  *** empty log message ***
 *
 *                                                                           
 *****************************************************************************/



/*============================= Include File ================================*/
  
#include <src/INFN/LU_SourceFileID_INFN.h>
#define __FILEID__ _SCM_Manager_INFN__c
#include <src/INFN/PRH_ParamHandler_INFN.h>
#include <src/INFN/LU_LogUtility_INFN.h>
#include <src/INFN/PRH_ParamHandler_INFN_auto.h>
LU_DECL_MASK();

#include <src/INFN/SCM_Manager_INFN.h>
#include <src/TM_TCManager/TMTCManager/TM_TMTCManager_op.h>
#include <src/INFN/HK_Manager_INFN.h>
#include <src/INFN/HB_HKBuffer_INFN.h>
#include <src/INFN/KHB_Driver_INFN.h>
#include <src/INFN/PWR_PowerHandler_INFN.h>
#include <src/INFN/GS_Gas_INFN.h>
#include <src/INFN/PM_PamManager_INFN.h>
#include <src/INFN/MH_ModeHandler_INFN.h>
#include <src/INFN/ALM_Alarm_INFN.h>
#include <src/INFN/TRK_Tracker_INFN.h>
#include <src/INFN/OS_rtems_INFN_p.h>


#define SCM_IPM_CHECK(var,ipm)  (var &   (1 << ipm))


//static BOOL SCM_Therm_Alarm,SCM_Pamela_OffOn,SCM_Pamela_OnOff,SCM_IPM_Alarm,SCM_Switch_OffAll,SCM_KHB_Alarm,SCM_IDAQ_Alarm;

static UINT32 SCM_TMValues[TM_MAX_TELEMETRY];

#define SCM_SAMPLED 30
#define SCM_SAMPLE_UNDEFINED 0xFFFFFFFF
static UINT32 SCM_SampleTMValues_Index;
static UINT32 SCM_SampleTMVAlues[SCM_SAMPLED][TM_MAX_TELEMETRY];
static UINT32 SCM_SampleAverage[TM_MAX_TELEMETRY];
static UINT32 SCM_TM_Reference[TM_MAX_TELEMETRY];
static UINT16 SCM_TM_Therm_Count[TM_THERMISTOR_COUNT];
static BOOL   SCM_SampleIsFull;
static BOOL   SCM_EnableCyclicCheck;
static BOOL   SCM_do_skip_detectors;
static UINT32 SCM_count_failed_power_on=0;
static UINT32 SCM_pamela_switched_off_therm=0;

/* task status: */
SCM_ACTION SCM_Action=SCM_NO_ACTION;
/*****************************************************************************/
/*============================= Object variables ============================*/


/*****************************************************************************/

/*       P a y l o a d s   O P E R A T I O N A L  F U N C T I O N S          */

/*****************************************************************************/
/* @Function: SCM_InitHKManager                                               */
/* @Purpose :                                                                */
/*  Initialialization function of the HK component.                          */
/*                                                                           */
/* @@                                                                        */
/* @Parameter Name      @Mode   @Description                                 */
/*  status_code          OUT     Return code                                 */
/* @@                                                                        */
/*****************************************************************************/

status_code SCM_InitSCManager (void)
  {
    status_code       status;
    void            * p;
    unsigned short  * pR;
    unsigned int      OldPriority;
    
    // Task initialization

    if ((status=OS_piTaskReady_INFN(SCM_INFN_TASK,SCM_tkSCManager)) != SUCCESSFUL)
      {
        /*@LOG Task is not correctly started - status */
	LU_INFN_LOG (LU_FATAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);    
	status = UNSATISFIED;
      }

    if ( (status=OS_piTaskPriority_INFN(SCM_INFN_TASK,  SCM_MANAGER_PRIORITY,  &OldPriority)) != SUCCESSFUL)
      {
        /*@LOG Task priority is not correctly updated - status */
	LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);    
        status = UNSATISFIED;
      }
    SCM_InitSampledValues();
    SCM_do_skip_detectors=0;
    SCM_count_failed_power_on=0;
    return (status);
  }


status_code SCM_SendCode(SCM_ACTION action) {
  MsgTsk SndMsg;
  SndMsg.Code = action;
  return SCM_SndMsgSCManager(&SndMsg);
}


status_code SCM_SndMsgSCManager(MsgTsk* SndMsg)
  {
    status_code   status;
    status = OS_piMsgQueueSend_INFN(SCM_INFN_MAILBOX,  (void *) SndMsg,  sizeof(MsgTsk));
    if(status != SUCCESSFUL)
      /*@LOG Failed sending message to SCM - status */
      LU_INFN_LOG (LU_FATAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);    
    return (status);
  }


void SCM_SetCyclicCheck(BOOL b) {
  SCM_EnableCyclicCheck=b;
}

SCM_ACTION SCM_GetCurrentAction() {
  UINT32 level;
  SCM_ACTION action;
  OS_PROTECTED_INT(level,action=SCM_Action);
  return action;
}


task SCM_tkSCManager (task_argument unused)
{
  status_code       status;
  MsgTsk            RxMsg,SndMsg;
  unsigned int      MsgSize;
  unsigned int      no_cyclic=0;
  UINT32 level;

  while (FOREVER) 
    {
      if ((status = OS_piMsgQueueReceive_INFN(SCM_INFN_MAILBOX,(void *)&RxMsg,&MsgSize,WAIT,NO_TIMEOUT)) == SUCCESSFUL) {
	OS_PROTECTED_INT(level,SCM_Action=(SCM_ACTION)RxMsg.Code);
	switch (SCM_Action) {
	case SCM_SAVE_TMTC_VALUES:
	  status = HK_SaveTMTCValues();
	  if (status != CM_RC_SUCCESSFUL)
	    /*@LOG Error saving TMTC Values - status */
	    LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);
	  break;
	case SCM_CYCLIC_ACQUISITION:

	  /*
	    if(RxMsg.Info[0])
	    {
	    SCM_InitSampledValues();
	    no_cyclic=0;
	    }
	  */
	  no_cyclic++;
	  status = HK_DoCyclicAcquisition((void*)SCM_TMValues);
	  if(status != CM_RC_SUCCESSFUL)
	    status = CM_RC_DO_STOP_WAIT;
	  else {
	    SCM_StoreSampledTMValues();

	    if(PRH_VAR_SCM_TM_DO_CHECK_VALUES_FREQ && 
	       no_cyclic >= PRH_VAR_SCM_TM_DO_CHECK_VALUES_FREQ &&
	       SCM_EnableCyclicCheck) 
	      {
		status = SCM_CyclicChecks();
		if(status)
		  /*@LOG SCM_CyclicChecks return unsuccessfull - status */
		  LU_INFN_LOG (LU_DEBUG_TRACE|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);
		no_cyclic=0;
	      }
	  }
	  break;
	case SCM_POWER_ON:
	  {

	    PRH_VAR_PAMELA_ON = 0;
	    SCM_pamela_switched_off_therm=0;

	    PWR_IPM_WaitOK();
	    status = PWR_PowerCheck(TRUE);
	    /*@LOG SCM_POWER_ON : PWR_PowerCheck(TRUE) - status */
	    LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);
	  
	    if (status) 
	      {
		// status==CM_RC_DO_STOP_WAIT and called dcdcOFF(true)
		status = CM_RC_DO_STOP_WAIT;
	      }
	    else
	      {
		status = PWR_DcdcON();
		/*@LOG SCM_POWER_ON: PWR_DcdcON - status */
		LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);

		if (status == CM_RC_SUCCESSFUL)
		  {
		    PRH_VAR_N_CALIB = 0;
		    PRH_VAR_PAMELA_ON = 1;

		    if(PRH_VAR_TRB_OK) {
		      status = PWR_TRB_On();
		      /*@LOG SCM_POWER_ON: PWR_TRB_On(); - status */
		      LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);
		    }
		    
		    if(status == CM_RC_SUCCESSFUL/**/){ 
		      if(PRH_ARR_TSB_BOARD_OK[0] || PRH_ARR_TSB_BOARD_OK[1]) {
			status = PWR_CMD2PSB(PRH_ARR_PSB_COMMANDS[PWR_PSB_TRACKER_SENSOR_ON],TM_PSB_ALARM,CM_OFF,
					     ALM_TRK_TRKSNS_1,ALM_TRK_TRKSNS_2,PWR_PSB_STANDARD_ANSWER);
			if(status)
			  /*@LOG SCM_POWER_ON: TSB Switch on error - status */
			  LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);
			else
			  OS_piTaskSuspend(TRK_SENSORS_WAIT);
			
			status = PWR_InitBoard_twice();
			if(status != CM_RC_SUCCESSFUL){
			  /*@LOG PWR_DcdcON - KHB INIT BOARD at end of function: - status */
			  LU_INFN_LOG(LU_DEBUG_TRACE|LU_HA,LU_MASK(__FILEID__),__FILEID__,__LINE__,status);
			  status=CM_RC_DO_POWER_OFF_ON;
			}						
		      }
		      
		      if(status==CM_RC_SUCCESSFUL && PRH_VAR_HV_OK) {
			status = PWR_HVSetting();
			/*@LOG SCM_POWER_ON: PWR_HVSetting() - status */
			LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);
		      }
		      
		      if(status == CM_RC_SUCCESSFUL) 
			switch(PRH_VAR_PULSER_ACTION) {
			case 1:
			  status=PWR_SendTC(TM_PULSER_RESET);
			  /*@LOG SCM_POWER_ON: Reset Pulser - status */
			  LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,status); 		
			  break;
			case 2:
			  status=PWR_SendTC(TM_PULSER_025);
			  /*@LOG SCM_POWER_ON: Set Pulser 0.25 - status */
			  LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,status); 		
			  break;
			case 3:
			  status=PWR_SendTC(TM_PULSER_100);
			  /*@LOG SCM_POWER_ON: Set Pulser 100 - status */
			  LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,status); 		
			  break;
			}
		    }
		    else
		      status=CM_RC_DO_POWER_OFF_ON;
		  }
		else{ // CM_RC_DO_POWER_OFF_ON;		
		  /*@LOG PWR_DcdcON returns unsuccessfull: goto  CM_RC_DO_POWER_OFF_ON */
		  LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status); 		
		}
	      }
	    /* if startup terminates with CM_RC_DO_POWER_OFF_ON, is not usefull to skip detectors in 
	       SCM_PowerOffOn() */
	    SCM_do_skip_detectors=(status!=CM_RC_DO_POWER_OFF_ON);
	    if(status==CM_RC_SUCCESSFUL)
	      SCM_count_failed_power_on=0;
	  }	  
	  break;
	case SCM_POWEROFF_ON:
	  status = SCM_PowerOffOn();
	  break;
	case SCM_POWEROFFSHUTDOWN:
	  PWR_DcdcOFF(TRUE);
	  status = CM_RC_SUCCESSFUL;
	  break;
	case SCM_POWEROFF:
	  PWR_DcdcOFF(FALSE);
	  status = CM_RC_SUCCESSFUL;
	  break;
	case SCM_TSB_T_CHECK:
	  if(PRH_VAR_TSB_T_OK) 
	    status = TRK_CheckTSensors();
	  else
	    status = CM_RC_SUCCESSFUL;
	  if(status != CM_RC_SUCCESSFUL) {
	    /*@LOG SCM_TSB_T_CHECK error : - status */
	    LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);    
	    status = CM_RC_DO_POWER_OFF_ON;
	  }
	  break;
	case SCM_TSB_B_CHECK:
	  if(PRH_VAR_TSB_B_OK) 
	    status = TRK_CheckBSensors();
	  else
	    status = CM_RC_SUCCESSFUL;
	  if(status != CM_RC_SUCCESSFUL) {
	    /*@LOG SCM_TSB_B_CHECK error : - status */
	    LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);    
	    status = CM_RC_DO_POWER_OFF_ON;
	  }
	  break;
	default:
	  /*@LOG SCM error operation code - status */
	  LU_INFN_LOG (LU_INTERNAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__, status);    
	  break;
	}
	SCM_BC2PM((SCM_ACTION)RxMsg.Code,status);
	OS_PROTECTED_INT(level,SCM_Action = SCM_NO_ACTION);
      }
    }
}


status_code SCM_InitSampledValues() {
  int i,j;
  SCM_SampleTMValues_Index=0;
  SCM_SampleIsFull = FALSE;

  for(i=0;i<SCM_SAMPLED;i++)
    for(j=0;j<TM_MAX_TELEMETRY;j++)
      SCM_SampleTMVAlues[i][j]=SCM_SAMPLE_UNDEFINED;

  for(i=0; i < TM_THERMISTOR_COUNT; i++)
    SCM_TM_Therm_Count[i]=0;
  
}

status_code SCM_StoreSampledTMValues() 
{
  int i,j;
  unsigned int loc_mask;

  if(SCM_SampleTMValues_Index >= SCM_SAMPLED) 
    {
      SCM_SampleIsFull = TRUE;
      SCM_SampleTMValues_Index=0;
    }

  memcpy(SCM_SampleTMVAlues[SCM_SampleTMValues_Index],
	 SCM_TMValues,
	 sizeof(SCM_TMValues));

  SCM_SampleTMValues_Index++;

  return(CM_RC_SUCCESSFUL);
}


status_code SCM_ComputeSampleAverage() 
{
  status_code status=CM_RC_SUCCESSFUL;
  UINT32 i,j;
  BOOL termfault=FALSE;
  if(SCM_SampleIsFull == TRUE) {

    /* TH_ANA: */
    for(j=TM_TH_ANA_1;j<=TM_TH_ANA_16;j++) {
      SCM_SampleAverage[j]=0;
      termfault=FALSE;
      for(i=0;i<SCM_SAMPLED && !termfault; i++){
	if(SCM_SampleTMVAlues[i][j] >= SCM_THERM_FAULTVALUE)
	  termfault=TRUE;	
	SCM_SampleAverage[j]+=SCM_SampleTMVAlues[i][j];
      }
      if(termfault)
	SCM_SampleAverage[j]=SCM_THERM_FAULTVALUE;
      else
	SCM_SampleAverage[j]/=SCM_SAMPLED;
    }
  }
  else
    status=CM_RC_NOINFO;
  
  return status;
}

status_code SCM_TM_Thermistors_Check() 
{
  status_code status = CM_RC_SUCCESSFUL;
  int i,j,loc_mask;
  BOOL can_switch = TRUE;
  
  for(j=TM_TH_ANA_1,loc_mask=1;j <= TM_TH_ANA_16;j++,loc_mask<<=1) 
    {
      if ( (loc_mask & PRH_VAR_THERM_MASK) && SCM_SampleAverage[j]!= SCM_THERM_FAULTVALUE)
	{
	  if (SCM_SampleAverage[j] < PRH_ARR_THERM_LOW[j-TM_TH_ANA_1]) // too high temperature 
	    {
	      /*@LOG TM_Thermistors_Check() : temperature too high ! */
	      LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,j);    
	      /*@LOG TM_Thermistors_Check() : temperature too high ! */
	      LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,SCM_SampleAverage[j]);    
	      if(PRH_VAR_PAMELA_ON) {
		SCM_pamela_switched_off_therm++;
		return CM_RC_DO_STOP_WAIT; // some temperature is too high and pamela is on: swith off
	      }
	      else
		return CM_RC_SUCCESSFUL; // some tempetarure is too high but pamela already off: do nothing
	    }	  
	  if (SCM_SampleAverage[j] < PRH_ARR_THERM_HIGH[j-TM_TH_ANA_1]) // some temperature still not in the range
	    can_switch = FALSE;
	}
    }
  
  if (PRH_VAR_PAMELA_ON == 0 && can_switch && SCM_pamela_switched_off_therm)
    {

      /*
	All temperatures are fine we can power on and last pamela_swith off was because therm.
	PAMELA can be switched on if and only if the last power off was due a temperature too high.
	if PAMELA had been swithed on because of some other reason, SCM_pamela_switched_off_therm is zeroed.
       */

      /*@LOG TM_Thermistors_Check() : all temperature go back to granted values: switch on pamela! */
      LU_INFN_LOG (LU_WARNING|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,0xBE11E);    
      status=CM_RC_DO_POWER_ON;
    }
  return status;
}

status_code SCM_IPM_Voltages_Check()
{
  return PWR_PowerCheck(FALSE);  
}

status_code SCM_KHB_IDAQ_Error_Check()
{
  unsigned int idaqcc=0,khbcc=0;
  status_code s;
  CM_HOT_COLD hc;
  
  s = HK_KHB_GetHotCold(&hc);
  if(s == CM_RC_SUCCESSFUL){
    if(hc==CM_HOT){
      idaqcc = SCM_TMValues[TM_IDAQ_HOT_ALARM];
      khbcc  = SCM_TMValues[TM_KHB_HOT_LATCHUP];
    }
    else{
      idaqcc = SCM_TMValues[TM_IDAQ_COLD_ALARM];
      khbcc  = SCM_TMValues[TM_KHB_COLD_LATCHUP];
    }
  }
  if(s!=CM_RC_SUCCESSFUL){
    /*@LOG Idaq Error Check: error retriving HOT/COLD status. Bug!! - status */
    LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,s);    
    return CM_RC_DO_POWER_OFF_ON;// ??
  }
  if(khbcc)
    {
      /*@LOG khbcc not zero goto POWER_OFF_ON - khbcc */
      LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,khbcc);    
      return CM_RC_DO_POWER_OFF_ON;
    }
  if(idaqcc)
    {
      /*@LOG idaqcc not zero goto POWER_OFF_ON - idaqcc */
      LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,idaqcc);    
      return CM_RC_DO_POWER_OFF_ON;
    }
  return CM_RC_SUCCESSFUL;
}

status_code SCM_PowerOffOn()
{
  status_code status;
  
  if (PRH_VAR_OFF < PRH_VAR_NOFF)
    {
      PRH_VAR_OFF++;

      /*@LOG PowerOffOn: number of switched off - PRH_VAR_OFF */
      ALM_WriteLog(ALM_OFF,PRH_VAR_OFF);
      /*@LOG PowerOffOn: number of reset - PRH_VAR_RES */
      ALM_WriteLog(ALM_RES,PRH_VAR_RES);
      PWR_DcdcOFF(FALSE);
      status = CM_RC_DO_POWER_ON;
    }
  else
    {

      /*@LOG PowerOffOn: number of switched off (PRH_VAR_OFF) exceedes NOFF (PRH_VAR_NOFF) - PRH_VAR_OFF  */
      LU_INFN_LOG (LU_WARNING|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,PRH_VAR_OFF);    
      
      switch(PRH_VAR_POWER_MODE) {
      case 1:
      case 2:
	PRH_VAR_POWER_MODE++;
	PWR_DcdcOFF(FALSE);
	status = CM_RC_DO_POWER_ON;
	break;
      case 3:
	{

	  PWR_DcdcOFF(FALSE);
	  status = CM_RC_DO_POWER_ON;
	  
	  
	  if(!SCM_do_skip_detectors) {
	    if(SCM_count_failed_power_on++ > PRH_VAR_NFAILED_POWER_ON) {
	      /* if numerb of failed pwoer_on > PRH_VAR_NFAILED_POWER_ON, do nothing and STOP&WAIT */

	      /*@LOG PowerOffOn: maximum number of power off/on - SCM_count_failed_power_on */
	      LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,SCM_count_failed_power_on);    

	      status = CM_RC_DO_STOP_WAIT;
	      return status;
	    }
	  }
	  else{	  
	    if (PRH_VAR_CONFOK < 2)
	      {
		if(PRH_VAR_CONF_SEL < 5) {

		  /*@LOG PowerOffOn: remove some FE - PRH_VAR_CONF_SEL */
		  LU_INFN_LOG (LU_CRITICAL|LU_HA, LU_MASK(__FILEID__), __FILEID__, __LINE__,PRH_VAR_CONF_SEL);
		  
		  PRH_VAR_CAL_OK = PRH_TAB_CONF[PRH_VAR_CONF_SEL][0];
		  PRH_VAR_TRK_OK = PRH_TAB_CONF[PRH_VAR_CONF_SEL][1];
		  PRH_VAR_TOF_OK = PRH_TAB_CONF[PRH_VAR_CONF_SEL][2];
		  PRH_VAR_AC_1_OK = PRH_TAB_CONF[PRH_VAR_CONF_SEL][3];
		  PRH_VAR_AC_2_OK = PRH_TAB_CONF[PRH_VAR_CONF_SEL][4];
		  PRH_VAR_ND_OK =	PRH_VAR_S4_OK = PRH_TAB_CONF[PRH_VAR_CONF_SEL][5];
		  
		  if (PRH_VAR_CONFOK == 1)
		    PRH_VAR_CONF_SEL++;
		  
		}else{
		  status = CM_RC_DO_STOP_WAIT;
		}	      
		/*@LOG PowerOffOn: PRH_VAR_CONFOK < 2 */
		ALM_WriteLog(ALM_CONFOK,PRH_VAR_CONFOK);
		/*@LOG PowerOffOn: PRH_VAR_CONFOK < 2 */
		ALM_WriteLog(ALM_CONF,PRH_VAR_CONF_SEL);
		PRH_VAR_OFF = 0;
		PRH_VAR_RES = 0;
	      }
	  }
	}
      }
    }
  return status;
}


status_code SCM_BC2PM(SCM_ACTION opcode,status_code code) 
{
  status_code status;
  MsgTsk      SndMsg;
  unsigned char *pc;

  SndMsg.Code = PM_INFN_SCMMANAGER_MSG;

  pc = SndMsg.Info;
  *(SCM_ACTION*)pc = opcode;        pc += sizeof(SCM_ACTION);
  *(status_code*)pc = code;  //pc += sizeof(status_code);

  SndMsg.LlInfo = sizeof(SCM_ACTION) + sizeof(status_code);

  status=PM_SndMsgPamManager_INFN(&SndMsg);
  return status;
}

status_code SCM_CyclicChecks()
{
  status_code status=CM_RC_SUCCESSFUL,ret=CM_RC_SUCCESSFUL;
  BOOL go_on;
  unsigned int ipm;
    

  if(SCM_ComputeSampleAverage() == CM_RC_SUCCESSFUL)
    if (PRH_VAR_THERMISTORS_CHECK) {
      status = SCM_TM_Thermistors_Check();
      if(status != CM_RC_SUCCESSFUL) {
	return status;
      }
    }
  
  if (PRH_VAR_PAMELA_ON)
    {
      if (PRH_VAR_IPM_VOLTAGES_CHECK)
	status = SCM_IPM_Voltages_Check();

      if(status != CM_RC_SUCCESSFUL) 
	return CM_RC_DO_POWER_OFF_ON;
      
      if (PRH_VAR_KHB_IDAQ_CHECK)
	return SCM_KHB_IDAQ_Error_Check();
      
    }
  return CM_RC_SUCCESSFUL;
}
