#include "mba32a.h"
#include "usart.h"
#include "interface.h"


extern UART_HandleTypeDef huart5;
extern Menu_table menu;	

BtFrame btframe;
uint8_t resetcount_bt=0;
uint16_t resetFlag16=0;
BtStep btstep;
uint16_t u5length=0;
bool resetBTmodule = false;
uint16_t displayNum=0;
uint16_t 	bt_dataLength=0;				//bt接收有效数据长度
uint8_t 	bt_error_num=0;					//bt接收的错误事件
uint32_t 	bt_serial_num=0;				//bt接收的流水号
uint8_t 	bt_battery=0;					//bt剩余电量百分比
uint8_t 	bt_log_num=0;					//bt记录事件数量
uint8_t 	bt_lock_machinesta=0;			//bt锁（电机）状态（0x00开；0x01关；0x02异常）
uint8_t 	bt_lock_ropesta=0;				//bt锁（锁绳）状态（0x00插入；0x01拔出）
uint16_t 	bt_hwver=0;						//bt硬件版本号
uint16_t 	bt_sfver=0;						//bt软件版本号
uint8_t g_MBA32A_8buf[2048]={0};  			//蓝牙接收数组
uint8_t g_MBA32A_8buf_Down[2048]={0} ;		//蓝牙搬移数组

void MBA32AReset(void);
uint8_t sendCmd_BT(char *pCmd,char *pRes, uint32_t timeOut, uint8_t sendNum);


uint8_t DtuBtKey[16] = {0x4A, 0x49, 0x41, 0x4C, 0x4F, 0x4E, 0x47, 0x5F, 0x32, 0x40, 0x38, 0x21, 0x35, 0x23, 0x39, 0x32};//JIALONG_2@8!5#92
uint8_t iv[16] = {0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31};//偏移
/**
  * @breaf 蓝牙启动位读写检查
  */
void Start_Read_resetFlag16(void)
{
	resetFlag16 = read_flash_16(resetDevAddr);
	if(resetFlag16==0xFFFF)//开机检测（首次启动）
	{
		if(sendCmd_BT("AT+RESET=1\r\n","OK",1,1))
		{
			Write_Information(resetDevAddr, 0xAAAA);//写入0xAAAA
			printf("###复位设备成功\r\n");
			btstep = UUIDS;
		}
	}
	else if(resetFlag16==0xAAAA)//开机检测（大于1次启动）
	{
		printf("###蓝牙模块非首次启动\r\n");
		if (!sendCmd_BT("AT+UUIDS?\r\n","+UUIDS:0002",1,1))
		{
			PRINT_NUUID("UUIDS");//UUID项不符合
			btstep = UUIDS;
		}
		if (!sendCmd_BT("AT+UUIDN?\r\n","+UUIDN:FF04",1,1))
		{
			PRINT_NUUID("UUIDN");//UUID项不符合
			btstep = UUIDN;
		}
		if (!sendCmd_BT("AT+UUIDW?\r\n","+UUIDW:FFF5",1,1))
		{
			PRINT_NUUID("UUIDW");//UUID项不符合
			btstep = UUIDW;
		}
		else
		{
			
			PRINT_UUID("UUID项");//UUID项符合设置项
			btstep = BtStepDefault;
		}
	}
}

/**
  * @breaf 蓝牙初始化，工作接口
  */
void MBA32A_Init(void)
{
	
	btframe.serialNum1 = 0x00000001; 
	btframe.serialNum2 = 0x00000001; 
	btframe.serialNum3 = 0x00000001; 
	btframe.serialNum4 = 0x00000001; 
	btframe.userId 	  = 0x64747531; 
	btframe.Autoseal  = 0xFF; \
	printf("\t###01\tBT_init%d...\r\n", resetcount_bt); 
	
	
	Start_Read_resetFlag16();/** 启动位读写检查 **/
	if(sendCmd_BT("AT+DISCONN=0\r\n","ERROR",1,1))//断开连接
	{
		printf("#已无设备连接\n");
	}
	switch(btstep)
	{
		case BtStepDefault:
			break;
		case UUIDS:
		{
			if(sendCmd_BT("AT+UUIDS?\r\n","+UUIDS:FFF0",1,1))//蓝牙芯片默认值，需要修改
			{
				if(sendCmd_BT("AT+UUIDS=0002\r\n","OK",1,1))
				{
					printf("#01设置主服务成功\n");
					btstep++;
				}
			}
			else
			{	//ERROR 其他值
				MBA32AReset();
				break;
			}
		}
		case UUIDN:
		{
			if(sendCmd_BT("AT+UUIDN?\r\n","+UUIDN:FFF1",1,1))//蓝牙芯片默认值，需要修改
			{
				if(sendCmd_BT("AT+UUIDN=FF04\r\n","OK",1,1))
				{
					printf("#02设置读服务成功\n");
					btstep++;
				}
			}
			else
			{	//ERROR 其他值
				MBA32AReset();
				break;
			}
		}
		case UUIDW:
		{
			if(sendCmd_BT("AT+UUIDW?\r\n","+UUIDW:FFF2",1,1))//蓝牙芯片默认值，需要修改
			{
				if(sendCmd_BT("AT+UUIDW=FFF5\r\n","OK",1,1))
				{
					printf("#03设置写服务成功\n");
					btstep++;
				}
			}
			else
			{	//ERROR 其他值
				MBA32AReset();
				break;
			}
		}
	}

	menu.current=0;//回到初始
	refresh=true;
}





/**
  * @breaf 串口发送命令子函数
  */


void USART_SendString(UART_HandleTypeDef *huart,char *str)
{
	printf("\r\n\CMD:\t");
	HAL_UART_Transmit(huart, (uint8_t*)str, strlen(str), 0xFFFF);
    HAL_UART_Transmit(&huart3, (uint8_t*)str, strlen(str), 0xFFFF);
	
}
/**
  * @breaf 模块复位函数（接收数组清0）
  */		
void MBA32AReset(void)
{
	resetcount_bt+=1;
	printf("Bt reset\r\n");   
	HAL_GPIO_WritePin(REST_BT_GPIO_Port,REST_BT_Pin,GPIO_PIN_RESET);
	HAL_Delay(4000);
	btstep = UUIDS;
	resetBTmodule=true;//freertos监测模块重启位
}


void Echo_BT(uint8_t echosize)
{
	HAL_UART_Transmit(&huart3,g_MBA32A_8buf_Down, echosize, 0xFFFF);//TTL回显
}


/**
  * @breaf 串口发送命令，有接收数组比较函数
  */
uint8_t sendCmd_BT(char *pCmd,char *pRes, uint32_t timeOut, uint8_t sendNum)
{
    uint8_t i = 0;
    uint32_t time;          
    for(i = 0; i < sendNum; i++)
	{
        time = timeOut * 10;
        USART_SendString(&huart5, pCmd);
		HAL_Delay(30);
		printf("------->%s",g_MBA32A_8buf_Down);
		
        while(time--)
		{
			if(strstr((const char *)g_MBA32A_8buf_Down, pRes) != NULL)             // 如果检索到关键词
			{
				memset(g_MBA32A_8buf_Down,0,50);
				return 1;
			}
			HAL_Delay(100);
        }
    }
    return 0;
}


void lock_searchInfo(void)				//蓝牙查询信息帧
{
	uint8_t header[2] 		= {0x66, 0x01};//Jl_lock帧头
	uint8_t serchInfo_CMD[] = {0x01, 0x00};//查询信息命令帧
	sendCombinedArray(header,sizeof(header),serchInfo_CMD,sizeof(serchInfo_CMD),0);
	Echo_BT(20);
}
/**
  * @breaf 蓝牙开锁信息帧
  */
void open_lock(BtFrame btframe)			//蓝牙开锁信息帧
{
	uint8_t header[2] 	= {0x66, 0x01};//Jl_lock帧头
	uint8_t open_CMD[] = {0x02, 0x0C, 	0x00,0x00,0x00,0x00,		0x00,0x00,0x00,0x00,	\
												0x00,0x00,0x00,0x00,   0x00};//开锁命令帧
	
	uint32_t serialNum;
	if(menu.current==4)
	{
		serialNum = btframe.serialNum1;//流水号
	}
	if(menu.current==5)
	{
		serialNum = btframe.serialNum2;//流水号
	}
	if(menu.current==6)
	{
		serialNum = btframe.serialNum3;//流水号
	}
	if(menu.current==7)
	{
		serialNum = btframe.serialNum4;//流水号
	}
	open_CMD[2]=(serialNum>>24) & 0xff;
	open_CMD[3]=(serialNum>>16) & 0xff;
	open_CMD[4]=(serialNum>>8) & 0xff;
	open_CMD[5]= serialNum & 0xff;
												
	uint32_t userid = btframe.userId;//用户id
	open_CMD[6]=(userid>>24) & 0xff;
	open_CMD[7]=(userid>>16) & 0xff;
	open_CMD[8]=(userid>>8) & 0xff;
	open_CMD[9]= userid & 0xff;
												
	uint32_t ntime = btframe.Ntime;//现在时间
	open_CMD[10]=(ntime>>24) & 0xff;
	open_CMD[11]=(ntime>>16) & 0xff;
	open_CMD[12]=(ntime>>8) & 0xff;
	open_CMD[13]= ntime & 0xff;
												
	open_CMD[14] = btframe.Autoseal;//自动施封时间										
													
	sendCombinedArray(header,sizeof(header),open_CMD,sizeof(open_CMD),1);//加密
	Echo_BT(20);
}

/**
  * @breaf 蓝牙关锁信息帧
  */
void close_lock(BtFrame btframe)		//蓝牙关锁信息帧
{
	uint8_t header[2] 	= {0x66, 0x01};//Jl_lock帧头
	uint8_t close_CMD[] = {0x03, 0x0B, 0x00,0x00,0x00,0x00,		0x00,0x00,0x00,0x00, \
												0x00,0x00,0x00,0x00};//关锁命令帧
	uint32_t serialNum;
	if(menu.current==4)
	{
		serialNum = btframe.serialNum1;//流水号
	}
	if(menu.current==5)
	{
		serialNum = btframe.serialNum2;//流水号
	}
	if(menu.current==6)
	{
		serialNum = btframe.serialNum3;//流水号
	}
	if(menu.current==7)
	{
		serialNum = btframe.serialNum4;//流水号
	}
	
	
	close_CMD[2]=(serialNum>>24) & 0xff;
	close_CMD[3]=(serialNum>>16) & 0xff;
	close_CMD[4]=(serialNum>>8) & 0xff;
	close_CMD[5]= serialNum & 0xff;
												
	uint32_t userid = btframe.userId;//用户id
	close_CMD[6]=(userid>>24) & 0xff;
	close_CMD[7]=(userid>>16) & 0xff;
	close_CMD[8]=(userid>>8) & 0xff;
	close_CMD[9]= userid & 0xff;											
												
	uint32_t ntime = btframe.Ntime;//现在时间
	close_CMD[10]=(ntime>>24) & 0xff;
	close_CMD[11]=(ntime>>16) & 0xff;
	close_CMD[12]=(ntime>>8) & 0xff;
	close_CMD[13]= ntime & 0xff;											
	
	sendCombinedArray(header,sizeof(header),close_CMD,sizeof(close_CMD),1);
	Echo_BT(20);
}

void workinfo_W(void)
{	
	if(*g_MBA32A_8buf_Down == NULL)
		return;
//	if(g_MBA32A_8buf_Down[0]==0x66 && g_MBA32A_8buf_Down[1]==0x00  )//未加密帧头(命令字0x01)
//	{
//		if(g_MBA32A_8buf_Down[2]==0x01)
//		{
//			bt_dataLength = g_MBA32A_8buf_Down[3];//接收数据长度
//			bt_error_num = g_MBA32A_8buf_Down[4];	//错误事件数
//			// 将4个字节存入 bt_serial_num流水号
//			bt_serial_num |= g_MBA32A_8buf_Down[5]<<24;
//			bt_serial_num |= g_MBA32A_8buf_Down[6]<<16;
//			bt_serial_num |= g_MBA32A_8buf_Down[7]<<8;
//			bt_serial_num |= g_MBA32A_8buf_Down[8];
//			bt_battery = g_MBA32A_8buf_Down[9];	//电量百分比
//			bt_log_num = g_MBA32A_8buf_Down[10];//记录型事件
//			bt_lock_machinesta = g_MBA32A_8buf_Down[11];	//电机状态
//			bt_lock_ropesta    = g_MBA32A_8buf_Down[12];	//锁绳状态
//			bt_hwver |= g_MBA32A_8buf_Down[13]<<8; 			//硬件版本号
//			bt_hwver |= g_MBA32A_8buf_Down[14]; 
//			bt_sfver |= g_MBA32A_8buf_Down[15]<<8; 			//软件版本号
//			bt_sfver |= g_MBA32A_8buf_Down[16]; 
//		}
//	}
	if(g_MBA32A_8buf_Down[0]==0x66 && g_MBA32A_8buf_Down[1]==0x01  )//加密帧头(命令字0x01)
	{
		if(g_MBA32A_8buf_Down[2]==0x01)
		{
			bt_dataLength = g_MBA32A_8buf_Down[3];//接收数据长度
			bt_error_num = g_MBA32A_8buf_Down[4];	//错误事件数
			// 将4个字节存入 bt_serial_num流水号
			bt_serial_num |= g_MBA32A_8buf_Down[5]<<24;
			bt_serial_num |= g_MBA32A_8buf_Down[6]<<16;
			bt_serial_num |= g_MBA32A_8buf_Down[7]<<8;
			bt_serial_num |= g_MBA32A_8buf_Down[8];
			bt_battery = g_MBA32A_8buf_Down[9];	//电量百分比
			bt_log_num = g_MBA32A_8buf_Down[10];//记录型事件
			
			bt_lock_machinesta = g_MBA32A_8buf_Down[11];	//电机状态
			bt_lock_ropesta    = g_MBA32A_8buf_Down[12];	//锁绳状态
			
			bt_hwver |= g_MBA32A_8buf_Down[13]<<8; 			//硬件版本号
			bt_hwver |= g_MBA32A_8buf_Down[14]; 
			bt_sfver |= g_MBA32A_8buf_Down[15]<<8; 			//软件版本号
			bt_sfver |= g_MBA32A_8buf_Down[16]; 
		}
	}
	
//	if (L1bd)
//	{
//		displayNum |= 0x1000;
//	}
//	if (L2bd)
//	{
//		displayNum |= 0x0100;
//	}
//	if (L3bd)
//	{
//		displayNum |= 0x0010;
//	}
//	if (L4bd)
//	{
//		displayNum |= 0x0001;
//	}
//	
//	
//	
//	//0x1000 1开
//	//0xF000 1关
//	//0x1100 1开2开
//	//0xFF00 1关2关
//	if(bt_lock_machinesta==0x00 && bt_lock_ropesta==0x01)//电机打开锁绳插入——开
//	{
//		if (displayNum == 0x1000 || displayNum == 0x0100 || displayNum == 0x1100)//1 2 12
//		{
//			menu.home = displayNum;
//		}
//	}
//	if(bt_lock_machinesta==0x00 && bt_lock_ropesta==0x01)//电机打开锁绳拔出——开
//	{
//		if (displayNum == 0x1000 || displayNum == 0x0100 || displayNum == 0x1100)//1 2 12
//		{
//			menu.home = displayNum;
//		}
//	}
//	
//	if(bt_lock_machinesta==0x01 && bt_lock_ropesta==0x00)//电机关闭锁绳插入——关
//	{

//		if(displayNum==0x1100)//12绑定
//        {
//            menu.home=0xFF00;
//        }
//        if(displayNum==0x1000)//1绑定
//        {
//            menu.home=0xF000;
//        }
//        if(displayNum==0x0100)//2绑定
//        {
//            menu.home=0x0F00;
//        }
//	}
//	if(bt_lock_machinesta==0x01 && bt_lock_ropesta==0x00)//电机关闭锁绳拔出——开
//	{
//		if (displayNum == 0x1000 || displayNum == 0x0100 || displayNum == 0x1100)//1 2 12
//		{
//			menu.home = displayNum;
//		}
//	}
	
	
}


void open_close_lock(void)
{
    if(menu.enter == 4 && (menu.current == 4 || menu.current == 5 || menu.current == 6 || menu.current == 7))
    {
		if(menu.current==4)
		{
			btframe.serialNum1 += 1;
			//Sn1StatusAddr  0x1111 开 0x2222 关
			if(menu.up == 1)
			{
				close_lock(btframe); //施封操作
				Write_Information(Sn1StatusAddr, 0x2222);
				//lock_searchInfo();
				HAL_Delay(500);
				S1 = read_flash_16(Sn1StatusAddr);
				S2 = read_flash_16(Sn2StatusAddr);
			}
			else if(menu.up == 0)
			{
				open_lock(btframe); //解封操作
				Write_Information(Sn1StatusAddr, 0x1111);
				//lock_searchInfo();
				HAL_Delay(500);
				S1 = read_flash_16(Sn1StatusAddr);
				S2 = read_flash_16(Sn2StatusAddr);
			}
		}
		if(menu.current==5)
		{
			btframe.serialNum2 += 1;
			//Sn1StatusAddr  0x1111 开 0x2222 关
			if(menu.up == 1)
			{
				close_lock(btframe); //施封操作
				Write_Information(Sn2StatusAddr, 0x2222);
				HAL_Delay(500);
				S1 = read_flash_16(Sn1StatusAddr);
				S2 = read_flash_16(Sn2StatusAddr);
				//lock_searchInfo();
			}
			else if(menu.up == 0)
			{
				open_lock(btframe); //解封操作
				Write_Information(Sn2StatusAddr, 0x1111);
				HAL_Delay(500);
				S1 = read_flash_16(Sn1StatusAddr);
				S2 = read_flash_16(Sn2StatusAddr);
				//lock_searchInfo();
			}
		}	
		if(menu.current==6)
		{
			btframe.serialNum3 += 1;
			//Sn1StatusAddr  0x1111 开 0x2222 关
			if(menu.up == 1)
			{
				close_lock(btframe); //施封操作
//				Write_Information(Sn3StatusAddr, 0x2222);
				HAL_Delay(500);
				S1 = read_flash_16(Sn1StatusAddr);
				S2 = read_flash_16(Sn2StatusAddr);
				//lock_searchInfo();
			}
			else if(menu.up == 0)
			{
				open_lock(btframe); //解封操作
//				Write_Information(Sn3StatusAddr, 0x1111);
				HAL_Delay(500);
				S1 = read_flash_16(Sn1StatusAddr);
				S2 = read_flash_16(Sn2StatusAddr);
				//lock_searchInfo();
			}
		}
		if(menu.current==7)
		{
			btframe.serialNum4 += 1;
			//Sn1StatusAddr  0x1111 开 0x2222 关
			if(menu.up == 1)
			{
				close_lock(btframe); //施封操作
//				Write_Information(Sn4StatusAddr, 0x2222);
				HAL_Delay(500);
				S1 = read_flash_16(Sn1StatusAddr);
				S2 = read_flash_16(Sn2StatusAddr);
				//lock_searchInfo();
			}
			else if(menu.up == 0)
			{
				open_lock(btframe); //解封操作
//				Write_Information(Sn4StatusAddr, 0x1111);
				HAL_Delay(500);
				S1 = read_flash_16(Sn1StatusAddr);
				S2 = read_flash_16(Sn2StatusAddr);
				//lock_searchInfo();
			}
		}
		

		
		menu.enter=3;
        refresh = true;
    }
}


#include <stdio.h>
#include <stdint.h>
#include "dtuaes.h"
int dtu_test(void) {
	
    //uint8_t i;
    struct AES_ctx ctx;
//    uint8_t in[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
//    uint8_t iv[16] = {0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31};
//    uint8_t key[16] = {0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31};
	
	
uint8_t DtuBtKey[16] = { 0x4A, 0x49, 0x41, 0x4C, 0x4F, 0x4E, 0x47, 0x5F, 0x32, 0x40, 0x38, 0x21, 0x35, 0x23, 0x39, 0x32 };//JIALONG_2@8!5#92
uint8_t iv[16] = { 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31 };
uint8_t in[16] = { 0x02, 0x0C, 0x00, 0x00, 0x00, 0x02, 0x64, 0x74, 0x75, 0x31, 0x00, 0x00, 0x00, 0x00, 0x10, 0x48 };

//    for (i = 0; i < sizeof(in); i++) {
//        printf("%02x ", DtuBtKey[i]);
//    }
//    printf("\n");
    AES_init_ctx_iv(&ctx, DtuBtKey, iv);
    AES_CBC_encrypt_buffer(&ctx, in, 16);
//    for (i = 0; i < sizeof(in); i++) {
//        printf("%02x ", in[i]);
//    }
//    printf("\n");
//    printf("Hello World!\n");
    return 0;
}



