#include <cstdio>
#include <cstdint>

#include "system_stm32h7xx.h"
#include "tim.h"

#include "fan_thread.h"

static constexpr unsigned INPUT_BUF_SIZE = 256U;  // Must be dev by 4

alignas(32) static char ibuf[INPUT_BUF_SIZE]									__attribute__((section(".RAM1")));
alignas(32) static char obuf[INPUT_BUF_SIZE]									__attribute__((section(".RAM1")));

VOID fanThread(ULONG initial_input)
{
	(void)initial_input;
	extern DMA_HandleTypeDef hdma_tim3_ch1;

	// Compute the value of ARR register to generate signal frequency at 25Khz
	//uint32_t uwTimerPeriod = (uint32_t)((SystemCoreClock/2 /25000) - 1);

	//__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_2, 200);
	//htim3.Instance->CCR2 = U;
	HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
	//HAL_TIM_IC_Start(&htim3, TIM_CHANNEL_1);


	auto start = __HAL_TIM_GET_COMPARE(&htim3, TIM_CHANNEL_2);
	auto end = __HAL_TIM_GET_AUTORELOAD(&htim3) - 300;

	HAL_TIM_IC_Start_IT(&htim8, TIM_CHANNEL_1);//, (uint32_t*)ibuf, INPUT_BUF_SIZE);
	//__HAL_DMA_DISABLE_IT(&hdma_tim3_ch1, DMA_IT_HT);



	while(1)
	{
		/*for (auto i = start; i < end; i++)
		{
			__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_2, i);
			tx_thread_sleep(10);
		}

		for (auto i = end; i > start; i--)
		{
			__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_2, i);
			tx_thread_sleep(10);
		}*/

		//while(__HAL_TIM_GET_FLAG(__HANDLE__, __FLAG__));
		//HAL_DMA_PollForTransfer()

		tx_thread_sleep(1000);
	}
}

//------------------------------------------------------------------------------

void pulseMeasured(void)
{
	volatile static uint32_t rawCnt;
	//static uint32_t lastTime;
	/*extern DMA_HandleTypeDef hdma_tim3_ch1;
	SCB_InvalidateDCache_by_Addr((uint32_t*)ibuf, INPUT_BUF_SIZE);
	memcpy(obuf, ibuf, INPUT_BUF_SIZE);
	HAL_TIM_IC_Start_DMA(&htim3, TIM_CHANNEL_1, (uint32_t*)ibuf, INPUT_BUF_SIZE);
	__HAL_DMA_DISABLE_IT(&hdma_tim3_ch1, DMA_IT_HT);*/
	//printf("\t\t\t\t\t\t%u - %u\n", htim3.Instance->CCR1, HAL_GetTick() - lastTime);
	//__HAL_TIM_CLEAR_FLAG(&htim3, TIM_FLAG_CC1OF);
	//lastTime = HAL_GetTick();

	rawCnt = HAL_TIM_ReadCapturedValue(&htim8, TIM_CHANNEL_1);

}