#include "soft_flow.h"
#include "can_link.h"
#include "soft_can.h"
#include "tim.h"
#include <string.h>


volatile uint32_t g_arr_update_count = {0}; // ARR更新（溢出）次数
volatile uint32_t g_last_ccr_value[2] = {0};   // 最后一次捕获的CCR值
uint32_t flow_raw[2] ={0};

//流量计结构体
flow_hl flow_dev1;
flow_hl flow_dev2;

void Flow_Function()
{
	  
//	flow_dev1.speed = ( 1000.0f  ) / FlOW_KP *
//				( 1000000.0f /flow_raw[0]  ); //ml/min
//	//flow_dev1.irq_last_count = flow_dev1.irq_count;
//	
//	flow_dev2.speed = ( 1000.0f  ) / FlOW_KP *
//				( 1000000.0f /flow_raw[0]  ); //ml/min
//	//flow_dev2.irq_last_count = flow_dev2.irq_count;
	uint8_t canTxData[8] = {0};
//	memcpy(&canTxData[0], &flow_dev1.speed, 4);
//	memcpy(&canTxData[4], &flow_dev2.speed, 4);
//	Can_Txmsg_Target_Init(FLOW_SPEED_MSG_ID, canTxData);
//	can_send(&hfdcan2);
	
	memcpy(&canTxData[0], &flow_dev1.irq_count, 4);
	memcpy(&canTxData[4], &flow_dev2.irq_count, 4);
	Can_Txmsg_Target_Init(FLOW_COUNT_MSG_ID, canTxData);
	can_send(&hfdcan2);
	
	
}

// 输入捕获中断回调函数
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
    if (htim->Instance == TIM2 && htim->Channel == HAL_TIM_ACTIVE_CHANNEL_3) 
	{	
		flow_raw[1] = 20000 * g_arr_update_count + HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_3) - g_last_ccr_value[0];
        g_last_ccr_value[1] = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_3); // 记录当前CCR1值
       
		g_arr_update_count = 0;
		flow_dev2.irq_count++;
    }
	
	if (htim->Instance == TIM2 && htim->Channel == HAL_TIM_ACTIVE_CHANNEL_4) 
	{
		flow_raw[0] = 20000 * g_arr_update_count + HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_4) - g_last_ccr_value[1];
        g_last_ccr_value[0] = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_4); // 记录当前CCR1值
        
		g_arr_update_count = 0;
		flow_dev1.irq_count++;
    }
	
}



bool Start_80_hz = false;
bool Start_10_hz = false;
bool Start_5_hz = false;
bool Start_1_hz = false;

uint32_t time2 = 0,ret;
// 定时器周期溢出（ARR更新）中断回调函数
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
    if (htim->Instance == TIM2) 
	{
        g_arr_update_count++; // ARR更新时，计数加1
	}
	
	if (htim->Instance == TIM5)
	{
		static uint8_t time_count = 0;

		Start_80_hz = true;

		time_count++;

		if (time_count % 8 == 0)
		{
			Start_10_hz = true;
		}
		if (time_count % 26 == 0)
		{
			Start_5_hz = true;
		}
		if (time_count % 80 == 0)
		{
			Start_1_hz = true;
			time_count = 0;
		}
	}
}
