
/*
 * misc.c
 *
 *  Created on: 21 Sep 2016
 *      Author: Mike
 */
#include "stm32l1xx_hal.h"
#include "misc.h"
#include "main.h"

extern TIM_HandleTypeDef htim2;
extern TIM_HandleTypeDef htim3;
extern TIM_HandleTypeDef htim6;

unsigned volatile long RPM_Time[RPM_SAMPLES];  // sampled on both  edges
unsigned volatile char RPM_Level[RPM_SAMPLES]; // active level when sampled
unsigned volatile long RPM_Count; // incremented every reading

// this is set if there is a timer timeout interrupt
unsigned char volatile periodPulse = 0;

static void
triggerTim3 (void)
{
  htim3.Instance->CNT = 0;
  htim3.Instance->CR1 |= TIM_CR1_CEN;

}

void
TIM2_IRQHandler (void)
{
  if (__HAL_TIM_GET_FLAG(&htim2, TIM_FLAG_CC1))
    {
      __HAL_TIM_CLEAR_FLAG(&htim2, TIM_FLAG_CC1);
      RPM_Time[RPM_Count] = __HAL_TIM_GET_COMPARE(&htim2, TIM_CHANNEL_1);
      int CB_level = HAL_GPIO_ReadPin (CB_Pulse_GPIO_Port,
				       CB_Pulse_Pin);
      RPM_Level[RPM_Count] = CB_level;
      RPM_Count = (RPM_Count + 1) % RPM_SAMPLES;

      if ( CB_level == 0)
	{
	  periodPulse = 0;
	  triggerTim3 ();
	}
    }
}

char chtTimer = 0;
char blink = 0;
// 100mS periodic sampler handler
void
TIM6_IRQHandler (void)
{
  if (__HAL_TIM_GET_FLAG(&htim6, TIM_FLAG_UPDATE))
    {
      __HAL_TIM_CLEAR_FLAG(&htim6, TIM_FLAG_UPDATE);

      blink = !blink;
      HAL_GPIO_WritePin (LED_Blink_GPIO_Port, LED_Blink_Pin,
			 blink ? GPIO_PIN_SET : GPIO_PIN_RESET);

      TimerFlag = 1;
      if (NoSerialInCTR < 5)
	{
	  NoSerialInCTR++;
	  if (NoSerialInCTR == 5)
	    {
	      NoSerialIn = 1;
	    }
	}

      if (periodPulse == 1)
	{
	triggerTim3 ();

	}
      periodPulse = 1;


      chtTimer++;
    }

}

void
TIM3_IRQHandler (void)
{
  if (__HAL_TIM_GET_FLAG(&htim3, TIM_FLAG_UPDATE))
    {
      __HAL_TIM_CLEAR_FLAG(&htim3, TIM_FLAG_UPDATE);

      if (chtTimer >= 3)  // every 300mS
	{
	  chtTimer = 0;

	  for (int instance = 0; instance < 2; instance++)
	    {
	      uint8_t buffer[2];
	      uint16_t Pin =
		  (instance == 0) ? SPI_NS_Temp_Pin : SPI_NS_Temp2_Pin;

	      HAL_GPIO_WritePin (SPI_NS_Temp_GPIO_Port, Pin, GPIO_PIN_RESET);

	      HAL_SPI_Receive (&hspi1, buffer, 2, 2);

	      HAL_GPIO_WritePin (SPI_NS_Temp_GPIO_Port, Pin, GPIO_PIN_SET);

	      uint16_t obs = (buffer[0] << 8) | buffer[1];

	      // good observation if the status bit is clear, and the reading is less than 1023

	      uint16_t temp_c = obs >> 5;

	      uint8_t good = ((obs & 7) == 0) && (temp_c > 0) && (temp_c < 250);

	      if (good)
		{
		  CHT_Observations[instance] = temp_c;
		}
	    }
	}
    }
}

void
resetSerialTimeout (void)
{
  __disable_irq ();
  NoSerialInCTR = 0;
  NoSerialIn = 0;
  __enable_irq ();
}

