#include "firmware_upgrade.h"
#include "hal_can.h"
#include "string.h"
#include "hal_flash.h"
#include "app_protocol.h"

extern sys_paratemer_info_t sys_paratemer_info;

extern QueueHandle_t can1_recieve1_data_queue;

 

void firmware_upgrade_task(void *pvParameters)
{
	can1_recieve1_data_queue = xQueueCreate(5,sizeof(stc_mcan_rx_msg_t));//can1存放升级帧的队列
 
	stc_mcan_rx_msg_t  rx_msg;
	stc_mcan_tx_msg_t  tx_msg;
	while(1)
	{
		if(pdTRUE==xQueueReceive(can1_recieve1_data_queue,&rx_msg,pdFALSE))	/*CAN升级 下线检测*/
		{			
			printf("recive id =%x\r\n",rx_msg.ID);
			if(rx_msg.ID== MSG_RECEIVE_ID_UDS)//下线检测
			{
				//UDSAnsFunc(rx_msg.au8Data);		
			}
			else//CAN升级
			{				
				//判断接收的数据地址是否和本节点地址匹配	
				if(rx_msg.IDE == 0x01)//扩展帧
				{
					if(rx_msg.ID!= MSG_RECEIVE_ID_EXTD) 
					{
						printf("recive ex_id err\r\n");
					}
										
					tx_msg.ID = MSG_SEND_ID_EXTD;
					tx_msg.IDE = 1U;
				}
				else if(rx_msg.IDE == 0x00)//标准帧
				{
					if(rx_msg.ID!= MSG_RECEIVE_ID_STD) 
					{
						printf("recive std_id err\r\n");			
					}
										
					tx_msg.ID = MSG_SEND_ID_STD;
					tx_msg.IDE = 0U;
				}

				
				//满足id 
				if(rx_msg.ID== MSG_RECEIVE_ID_EXTD||rx_msg.ID== MSG_RECEIVE_ID_STD)
				{
					switch(rx_msg.au8Data[0])
					{
						case 0xB6:	//进入boot
							hc32_flash_read(BOOTLOADER_INFO_ADDR,(uint8_t*)&sys_paratemer_info,sizeof(sys_paratemer_info));	
							sys_paratemer_info.destination_address = (uint32_t)APPLICATION_A_ADDR; 
							sys_paratemer_info.is_can_write_flag = 1;					
							/*写入升级标志*/
							hc32_flash_write(BOOTLOADER_INFO_ADDR,(uint8_t*)&sys_paratemer_info,sizeof(sys_paratemer_info));	
							
							__disable_irq();//关闭所有中断
							NVIC_SystemReset();
							break;
						case 0xB1:					
							tx_msg.au8Data[0] = 0x1B; 
							tx_msg.au8Data[1] = VER_MAJOR_H;//主版本号，两字节
							tx_msg.au8Data[2] = VER_MAJOR_L; 
							tx_msg.au8Data[3] = VER_SLAVE_H;//次版本号，两字节
							tx_msg.au8Data[4] = VER_SLAVE_L;
							tx_msg.au8Data[5] = 0xAA;//0x55固件是Bootloader,0xaa:固件是App
							tx_msg.au8Data[6] = 0xFF;
							tx_msg.au8Data[7] = 0xFF;
							tx_msg.DLC = 8;
							
							if(rx_msg.ID== MSG_RECEIVE_ID_STD) tx_msg.IDE = 0;
							else if(rx_msg.ID== MSG_RECEIVE_ID_EXTD) tx_msg.IDE = 1;
						
						  tx_msg.u32TxBuffer = MCAN_TX_BUF0;
							MCAN_AddMsgToTxFifoQueue(CM_MCAN1,&tx_msg);
							printf("ack\r\n");		
							break;
					}
				}			
			}

			memset(&rx_msg,0,sizeof(rx_msg));
			memset(&tx_msg,0,sizeof(tx_msg));
		}	
		
		vTaskDelay(10);		
	}
}