#include "main.h"
#include "dataHandling.h"
#include "md5c.h"


void Flash_ReadBytes(uint16_t* sorBuf,uint32_t FlashAddr,uint16_t len)
{
	uint16_t* p = sorBuf;
	uint8_t i = 0,j = 0;
	uint32_t addr = FlashAddr;
	while(len--)
	{
		i = *(uint32_t*)addr++;
		j = *(uint32_t*)addr++;
		*p++ = j<<8|i;
	}
}

uint16_t iapbuf[1024];
uint16_t iapversion[5];
uint16_t iapmd5[10];

// 定义一个长度为16的字符数组，用于存储MD5摘要
unsigned char digest[16];

int App2_MD5_Check(uint32_t addr,unsigned int all_len)
{
    // 定义变量i和update_len
    unsigned int i,update_len;
    // 定义一个MD5上下文结构体
    MD5_CTX md5c;
    // 减去摘要的长度，得到实际数据长度
//    all_len -= 16;
    // 初始化MD5上下文结构体
    MD5Init(&md5c);
    // 循环处理数据
    for(i=0;i<all_len;)
    {
        // 判断剩余数据长度是否大于512，如果是则取512，否则取剩余长度
        if(all_len>(i+512))
            update_len = 512;
        else
            update_len = all_len-i;
        // 将数据从指定地址拷贝到iapbuf缓冲区
        memcpy(iapbuf,(const void *)(addr+i),update_len);
        // 更新MD5上下文
        MD5Update (&md5c, (unsigned char *)iapbuf, update_len);
        // 更新i的值
        i += update_len;
    }
    // 计算最后的MD5摘要
    MD5Final(digest,&md5c);
    // 验证摘要是否与给定地址的数据一致
    for(i=0;i<16;++i)
    {
//        if(digest[i]!=*(unsigned char *)(addr+all_len+i))
        if(digest[i]!=*(unsigned char *)(MD5_ADDR+i))
            break;
    }
    // 如果验证通过，则返回1，否则返回0
    if(i>=16)
        return 1;
    else
        return 0;
}

void delay_sys_us(uint32_t Delay)//1个delay，大概1.5us
{
	uint32_t cnt = Delay * 8;  
    uint32_t i = 0;
    for(i = 0; i < cnt; i++)__NOP();
}


uint16_t STMFLASH_ReadHalfWord(uint32_t faddr)
{
	return *(uint16_t*)faddr; 
}

void STMFLASH_Read(uint32_t ReadAddr,uint16_t *pBuffer,uint16_t NumToRead)   	
{
	uint16_t i;
	for(i=0;i<NumToRead;i++)
	{
		pBuffer[i]=STMFLASH_ReadHalfWord(ReadAddr);//读取2个字节.
		ReadAddr+=2;//偏移2个字节.	
	}
}


void STMFLASH_Write_NoCheck(uint32_t WriteAddr,uint16_t *pBuffer,uint16_t NumToWrite)   
{ 			 		 
	uint16_t i;
	for(i=0;i<NumToWrite;i++)
	{
		HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD,WriteAddr,pBuffer[i]);
	  WriteAddr+=2;//地址增加2.
	}  
} 



// 定义Flash缓冲区
uint16_t Flashbuf[2048] __attribute__((at(0X20001000)));
// Flash写入函数
void Flash_WriteBytes(uint16_t* sorBuf, uint32_t FlashAddr, uint16_t len)
{
    uint32_t Offset_ADDR = 0, Page_StartAddr = 0, i = 0;
    // 计算偏移地址和起始地址
    Offset_ADDR = FlashAddr % FLASH_PAGE_SIZE;
    Page_StartAddr = FlashAddr - Offset_ADDR;
    // 设置PageError
    uint32_t PageError = 0;
    // 初始化擦除参数
    FLASH_EraseInitTypeDef f;
    f.TypeErase = FLASH_TYPEERASE_PAGES;
    f.PageAddress = Page_StartAddr;
    f.NbPages = 1;
	
    // 读取Flash缓冲区数据
    Flash_ReadBytes(Flashbuf, Page_StartAddr, 0x400);//写一半先1024字节
    // 将源缓冲区数据写入Flash缓冲区
    for (i = 0; i < len; i++)
        Flashbuf[Offset_ADDR / 2 + i] = sorBuf[i];	 //后一半也存入缓存中
    // 解锁FLASH
    HAL_FLASH_Unlock();
    // 擦除FLASH
    HAL_FLASHEx_Erase(&f, &PageError);
    // 写入Flash缓冲区数据到FLASH
    for (uint16_t i = 0; i < 0x400; i++)
    {
        HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, Page_StartAddr + (i * 2), Flashbuf[i]);
    }
    // 锁住FLASH
    HAL_FLASH_Lock();
}

void Set_App2_Flag(void)
{
	uint16_t update_flag1[2];
	update_flag = Startup_APP2;
	update_flag1[1] = (uint16_t)update_flag;
	update_flag1[0] = (uint16_t)(update_flag >> 16);
	Flash_WriteBytes(update_flag1, StartMode_Addr, 2);
	
//	__set_FAULTMASK(0);			   //先关闭全局中断
////	
//	HAL_NVIC_SystemReset();
	
}

void Set_jump_Flag(void)
{
	uint16_t update_flag1[2];
	update_flag = Jump_app;
	update_flag1[1] = (uint16_t)update_flag;
	update_flag1[0] = (uint16_t)(update_flag >> 16);
	Flash_WriteBytes(update_flag1, StartMode_Addr, 2);

}

void Set_normal_Flag(void)
{
	uint16_t update_flag1[2];
	update_flag = Startup_Normal;
	update_flag1[1] = (uint16_t)update_flag;
	update_flag1[0] = (uint16_t)(update_flag >> 16);
	Flash_WriteBytes(update_flag1, StartMode_Addr, 2);
}



void convertHexToAscii(uint16_t version[4], uint32_t* System_version) {

    *System_version = (((((version[0] >> 8 & 0xF) << 4) | (version[0] & 0xF)) & 0xFF) << 24) |
	(((((version[1] >> 8 & 0xF) << 4) | (version[1] & 0xF)) & 0xFF) << 16) | 
	(((((version[2] >> 8 & 0xF) << 4) | (version[2] & 0xF)) & 0xFF) << 8) | 
	((((version[3] >> 8 & 0xF) << 4) | (version[3] & 0xF)) & 0xFF);
}

/*
    uint8_t hexData[] = {0x34, 0x34, 0x30, 0x30, 0x00};
    size_t length = sizeof(hexData) / sizeof(hexData[0]);
    uint16_t intValue = convertHexToInt(hexData, length);
*/
void convertToUint16(uint8_t* uint8Data, size_t length, uint16_t* uint16Data)
{
    for (size_t i = 0; i < length; i += 2)
    {
        uint16Data[i / 2] = (uint16_t)uint8Data[i] << 8 | uint8Data[i + 1];
    }
}


void search_seat(const uint8_t* hexData)
{
    int i, j, k;
    for (i = 0; i < sizeof(hexData); i++) {
        if (hexData[i] == 0x00) {  // 找到第一个占位符
            break;  // 结束循环
        }
        binName[i] = hexData[i]; // 将第一个占位符之前的数据放入binName中
    }
	
	
    for (j = i + 1; j < sizeof(hexData); j++) {
        if (hexData[j] == 0x00) {  // 找到第二个占位符
            break;  // 结束循环
        }
        binLength[j - i - 1] = hexData[j]; // 将第一个占位符至第二个占位符之间的数据放入binLength中
    }
	
	
    for (k = j + 1; k < sizeof(hexData); k++) {
        if (hexData[k] == 0x00) {  // 找到第三个占位符
            break;  // 结束循环
        }
        binMd5[k - j - 1] = hexData[k]; // 将第三个占位符至第四个占位符之间的数据放入binMd5中
    }

}


uint16_t crc16_xmodem(uint8_t *data, uint16_t length) {
    uint16_t crc = 0;
    for (uint16_t i = 0; i < length; i++) {
        crc ^= (uint16_t)data[i] << 8;
        for (uint8_t j = 0; j < 8; j++) {
            if (crc & 0x8000) {
                crc = (crc << 1) ^ 0x1021;
            } else {
                crc <<= 1;
            }
        }
    }
    return crc;
}

void Set_Update_Down(void)
{
//	uint16_t update_flag1[2];
//	update_flag = Startup_Update; 
//	update_flag1[0] = (uint16_t)update_flag;
//	update_flag1[1] = (uint16_t)(update_flag >> 16);
//	Flash_WriteBytes(update_flag1, StartMode_Addr, 2);
	
	uint16_t update_flag1[2];
	update_flag = Startup_Update;
	update_flag1[0] = (uint16_t)update_flag;
	update_flag1[1] = update_flag & 0xFFFF;
	memcpy(&update_flag1, &update_flag, sizeof(uint16_t) * 2);
	Flash_WriteBytes(update_flag1, StartMode_Addr, sizeof(update_flag1));
	
//	int txLen = sprintf((char *)USART_IAP_RX, "reboot\r\n");
//	HAL_UART_Transmit_IT(&huart1,USART_IAP_RX,txLen);		
//	while (huart1.gState == HAL_UART_STATE_BUSY_TX)
//	{
//		HAL_Delay(1);
//	}
	
//	__NOP();__NOP();
//	__disable_irq();
	NVIC_SystemReset();
}


void readFlashToArr(uint8_t *arr, uint32_t addr) {
	if(lenindex!=0)
	{
		for (int i = 0; i < 5; i++) {
			arr[i] = *(uint8_t*)(addr + i);
		}
	}
	else 
	{
		for (int i = 0; i < 4; i++) {
			arr[i] = *(uint8_t*)(addr + i);
		}
	}

	
}

#if STM32_FLASH_SIZE<256
#define STM_SECTOR_SIZE 1024 //字节
#else 
#define STM_SECTOR_SIZE	2048
#endif		 
uint16_t STMFLASH_BUF[STM_SECTOR_SIZE/2];//最多是2K字节
void STMFLASH_Write(uint32_t WriteAddr,uint16_t *pBuffer,uint16_t NumToWrite)	
{
	uint32_t secpos;	   //扇区地址
	uint16_t secoff;	   //扇区内偏移地址(16位字计算)
	uint16_t secremain; 	//扇区内剩余地址(16位字计算)	   
 	uint16_t i;    
	uint32_t offaddr;   //去掉0X08000000后的地址
	
	if(WriteAddr<STM32_FLASH_BASE||(WriteAddr>=(STM32_FLASH_BASE+1024*STM32_FLASH_SIZE)))return;//非法地址
	
	HAL_FLASH_Unlock();					//解锁
	
	offaddr=WriteAddr-STM32_FLASH_BASE;		//实际偏移地址.
	secpos=offaddr/STM_SECTOR_SIZE;			//扇区地址  0~127 for STM32F103RBT6
	secoff=(offaddr%STM_SECTOR_SIZE)/2;		//在扇区内的偏移(2个字节为基本单位.)
	secremain=STM_SECTOR_SIZE/2-secoff;		//扇区剩余空间大小   
	if(NumToWrite<=secremain)secremain=NumToWrite;//不大于该扇区范围
	while(1) 
	{	
		STMFLASH_Read(secpos*STM_SECTOR_SIZE+STM32_FLASH_BASE,STMFLASH_BUF,STM_SECTOR_SIZE/2);//读出整个扇区的内容
		for(i=0;i<secremain;i++)	//校验数据
		{
			if(STMFLASH_BUF[secoff+i]!=0XFFFF)break;//需要擦除  	  
		}
		if(i<secremain)			//需要擦除
		{
			FLASH_PageErase(secpos*STM_SECTOR_SIZE+STM32_FLASH_BASE);	//擦除这个扇区
			FLASH_WaitForLastOperation(FLASH_WAITETIME);            	//等待上次操作完成
			CLEAR_BIT(FLASH->CR, FLASH_CR_PER);							//清除CR寄存器的PER位，此操作应该在FLASH_PageErase()中完成！
																		//但是HAL库里面并没有做，应该是HAL库bug！
			for(i=0;i<secremain;i++)//复制
			{
				STMFLASH_BUF[i+secoff]=pBuffer[i];	  
			}
			STMFLASH_Write_NoCheck(secpos*STM_SECTOR_SIZE+STM32_FLASH_BASE,STMFLASH_BUF,STM_SECTOR_SIZE/2);//写入整个扇区  
		}else 
		{
			FLASH_WaitForLastOperation(FLASH_WAITETIME);       	//等待上次操作完成
			STMFLASH_Write_NoCheck(WriteAddr,pBuffer,secremain);//写已经擦除了的,直接写入扇区剩余区间. 
		}
		if(NumToWrite==secremain)break;//写入结束了
		else//写入未结束
		{
			secpos++;				//扇区地址增1
			secoff=0;				//偏移位置为0 	 
		   	pBuffer+=secremain;  	//指针偏移
			WriteAddr+=secremain*2;	//写地址偏移(16位数据地址,需要*2)	   
		   	NumToWrite-=secremain;	//字节(16位)数递减
			if(NumToWrite>(STM_SECTOR_SIZE/2))secremain=STM_SECTOR_SIZE/2;//下一个扇区还是写不完
			else secremain=NumToWrite;//下一个扇区可以写完了
		}	 
	};	
	HAL_FLASH_Lock();		//上锁
}

uint16_t pagesize;
uint32_t addrtowrite;
int z;
void iap_write_appbin(uint32_t appxaddr, uint32_t appbuf, uint32_t appsize)
{
    uint16_t size = appsize;
    uint32_t fwaddr = appbuf; // 当前写入的地址
	addrtowrite = ADD_UPDATE_PROG;
	
	
	pagesize =(size + 2048) / 2048;
	memset(iapbuf, 0, sizeof(iapbuf));	
	
	uint8_t ACK_Arr[5] = "ack=";
	
	for( z =1; z<=pagesize ;z++)
	{
		
		HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_SET);
		HAL_Delay(5);  
		HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_RESET);
		
		Flash_ReadBytes(&iapbuf[0], fwaddr, 2048);//2048
		Flash_WriteBytes(&iapbuf[0],addrtowrite,1024);
		delay_sys_us(80);
			
//		memset(iapbuf, 0, sizeof(iapbuf));	
		int txLen;
		txLen = sprintf((char *)USART_IAP_RX, "%s%d\r\n", ACK_Arr,z);
		HAL_UART_Transmit_IT(&huart1,USART_IAP_RX,txLen);	

		fwaddr = fwaddr + 0x800;
		addrtowrite = addrtowrite + 0x800;	
		HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_SET);
		HAL_Delay(5);  
		HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_RESET);	

	}
	
}

