/**
* author wulianwei
* title mqtt注册实现
*/
#include "regist.h"
#include "module_wrapper.h"
#include "TypeDefine.h"
#include "SystemAlarm.h"
#include "string.h"
#include "sys.h"
#include "DrawLCDGUI.h"
#include "ProgramData.h"
#include "cJSON.h"
#include "AES.h"


extern uart_recv_t uart_recv;
extern valid_data_t valid_data;
extern uint8_t mcu_id[8];              //mcu ID号缓冲区
extern uint16_t Version_data;  //版本号

int registModuleStartCou = 0; //注册是模块启动次数

char registData[200] = {0};         //设备注册信息,${mcu_id}&${PRODUCT_KEY}

unsigned char key[17]="tuorenzhinenghua";
unsigned char expansionkey[15 * 16];

void ModuleKeepLine(void)
{
	if(TaskSchedulerFlag.ModuleInitFlag == TASK_FLAG_SET)
	{
		registModuleStartCou++;
		TaskSchedulerFlag.ModuleInitFlag = TASK_FLAG_CLEAR;
		TaskSchedulerTimer.ModuleInitTimer = FIFTEEN_SECOND_TIMER;
		if(module_start_status == MODULE_FAIL)
		{
			at_module_start();
		}
		else if(module_init_status == MODULE_FAIL)
		{
			at_module_init();
		}
		else if(tcp_connect_status == TCP_CLOSED)
		{
			at_module_connect(REGIST_SERVER,REGIST_PORT);
		}
	}
	
}

static void packRegistDataAndSend(void)
{
	int i=0;
	int datalen = 0;
	uint8_t data[50]={0};
	const char *CCID_SIGN = "+QCCID: ";
	char *ccidStr = NULL;
	memset(registData,0, sizeof(registData));
	char* dataPtr = registData+2;
	byteToHexStr(mcu_id, dataPtr, sizeof(mcu_id));
	
//	memcpy(dataPtr+strlen(dataPtr),"&",1);
//	memcpy(dataPtr+strlen(dataPtr),PRODUCT_KEY,strlen(PRODUCT_KEY));
	//复制CCID
	at_module_cmd_back("AT+QCCID\r\n",(char*)data,sizeof(data));
//	UsartPrintf(USART_DEBUG,"QCCID:%s\r\n",data);
	memcpy(dataPtr+strlen(dataPtr),"&",1);
	ccidStr = strstr((const char*)data,CCID_SIGN);
	if(ccidStr && strlen(ccidStr)>0)
	{
		ccidStr+=strlen(CCID_SIGN);
		memcpy(dataPtr+strlen(dataPtr),ccidStr,20);
	}
	//复制版本号
	snprintf(dataPtr+strlen(dataPtr),10,"&%d.%03d",Version_data/1000,Version_data%1000);
	UsartPrintf(USART_DEBUG,"device data:%s\r\n",dataPtr);
	datalen = ECBAesEncrypt((unsigned char*)dataPtr, expansionkey, 10);		//2、AES 加密
	registData[0] = datalen>>8;
	registData[1] = datalen;	

	at_module_send_rai(registData,datalen+2,KEPP_RRC);
}


//处理Coap注册信息,0: 成功, 1: 失败
static int handleRegistInfo(void)
{
	int flag = 1;
	//char str_mcu_id[20]={0};
	cJSON *json = NULL,*json_address=NULL,*json_port=NULL,*json_productKey = NULL,*json_deviceName = NULL,*json_deviceSecret = NULL,*json_code = NULL;
	json = cJSON_Parse(valid_data.buf);
	if(!json)
	{
		UsartPrintf(USART_DEBUG, "json parse error,%s\r\n",cJSON_GetErrorPtr());
		goto end;
	}
	json_code = cJSON_GetObjectItem(json,"code");
	json_address = cJSON_GetObjectItem(json,"address");
	json_port = cJSON_GetObjectItem(json,"port");
  json_productKey = cJSON_GetObjectItem(json,"productKey");
	json_deviceName = cJSON_GetObjectItem(json,"deviceName");
	json_deviceSecret = cJSON_GetObjectItem(json,"deviceSecret");
	if(json_productKey)
	{
		memset(registInfo,0,sizeof(RegistInfo));
		registInfo->flag='Y';
		//byteToHexStr(mcu_id, str_mcu_id, sizeof(mcu_id));
		memcpy(registInfo->address,json_address->valuestring,strlen(json_address->valuestring));
		memcpy(registInfo->port,json_port->valuestring,strlen(json_port->valuestring));
		memcpy(registInfo->productKey,json_productKey->valuestring,strlen(json_productKey->valuestring));
		memcpy(registInfo->deviceName,json_deviceName->valuestring,strlen(json_deviceName->valuestring));
		memcpy(registInfo->deviceSecret,json_deviceSecret->valuestring,strlen(json_deviceSecret->valuestring));
		WriteProgramData();
		flag = 0;
	}
	
	end:
	    cJSON_Delete(json);
	return flag;
}

void DeviceRegist()
{
	int flag = 1;  //0:成功,1 失败
	if(registInfo->flag == 'Y')
	{
		return;
	}
	ScheduleKey(key, expansionkey, 4, 10);	//1、密钥扩展生成
	DrawRegistingPicture();
	while(1)
	{
		ModuleKeepLine();
		
		at_module_handle_event();
		
		if(tcp_connect_status == TCP_OPEN)
		{
			TaskSchedulerFlag.NET_ONLINE_FLAG = TASK_FLAG_SET;//模块联网
			DrawSignalDisplay();
			packRegistDataAndSend(); //远程注册设备
			delay_ms(5000);
			at_module_handle_event();
			UsartPrintf(USART_DEBUG, "AesDecrypt valid_data len,%d\r\n",valid_data.len);
			if(valid_data.len>0)
			{
				if(valid_data.len%AES_BLOCK_SIZE == 0)
				{
					ECBAesDecrypt((unsigned char*)valid_data.buf,valid_data.len, expansionkey, 10);//AES 解密
					UsartPrintf(USART_DEBUG, "AesDecrypt valid_data,%s\r\n",valid_data.buf);
					
					flag = handleRegistInfo();
					valid_data_clear(); //清除有效数据
				}
				else
				{
					UsartPrintf(USART_DEBUG, "AesDecrypt valid_data length error\r\n");
				}
				
				
			}
			if(flag)
			{
				DrawRegistFailPicture();
			}
			else
			{
				DrawRegistSucPicture();
			}
			at_module_close();
			TaskSchedulerFlag.NET_ONLINE_FLAG = TASK_FLAG_CLEAR;//模块断网
			Delay_ms(1000);
			break;
		}
		
		if(registModuleStartCou == 3)
		{
			DrawRegistFailPicture();
			Delay_ms(1000);
			break;
		}
	}
	
	
}
