#include "usart.h"
#include "gateway_message.h"
#include "string.h"
#include "tcp_server.h"
#include "timer.h"
#include "updata.h"

/*    上位机功能    */

//储存上位机发送的config数据，并返回上位机操作结果
void save_config_232(uint8_t* buf)
{	
		GATEWAY_PARAMS *get;
		get= get_gateway_config_params();
		char* saveData = mymalloc(SRAMEX,20 * 1024);//(RECV_BUF_SIZE);// 存储config数据			最大20K，暂定3K
		if(saveData == NULL) 
			LogPrint(LOG_ERROR,__FILE__,__FUNCTION__,__LINE__,"recv buf malloc fail");
		memset(saveData,0,strlen(saveData));	
		// 插入tcp_config标志位，后续不通过http获取默认配置数据
		sprintf(saveData, "tcp_config");
		sprintf(saveData + strlen(saveData),"%s",buf);
		// 删除当前文件，写入新文件
		DeleteDirFile("device.txt");
		write_file("device.txt",saveData,strlen(saveData));// 储存到flash 不用判断失败
		// 释放结构体
		myfree(SRAMEX, get->device_params->params->gateway_read_dlt645_command);
		get->device_params->params->gateway_read_dlt645_command = NULL;
		myfree(SRAMEX, get->device_params->params->gateway_read_modbus_command);
		get->device_params->params->gateway_read_modbus_command = NULL;
		myfree(SRAMEX, get->device_params->params->gateway_write_modbus_command);
		get->device_params->params->gateway_write_modbus_command = NULL;
		myfree(SRAMEX, get->device_params->params);
		get->device_params->params = NULL;
		myfree(SRAMEX, get->device_params);
		get->device_params = NULL;
		get = NULL;
		// 重新解析config数据
		addGatewayParams(saveData);
		myfree(SRAMEX, saveData);
		
		char* retMsg = mymalloc(SRAMEX,32);
		memset(retMsg, 0, strlen(retMsg));
		retMsg = "{\"write_config\":\"success\"}";
		USART_232_Send((uint8_t*)retMsg, strlen(retMsg));
		myfree(SRAMEX ,retMsg);
}


void read_device_params(char* device_params)
{
	GATEWAY_PARAMS *get;
	get= get_gateway_config_params();
	DEVICE_PARAMS *current_device=get->device_params;
	sprintf(device_params, "{\"read_config\":\"success\",\"baudrate\":%d,\"checkBit\":%d,\"commandTopic\":\"%s\",\"dataBit\":%d,\
\"deviceId\":\"%s\",\"host\":\"%s\",\"inboundTime\":%d,\"messageTopic\":\"%s\",\"port\":%d,\"stopBit\":%d,\"deviceList\":[",get->baudrate,
			get->checkBit,get->commandTopic,get->dataBits,get->deviceId,get->host,get->inboundTime,get->messageTopic,get->port,get->stopBit);
	while(current_device != NULL)
	{	
		sprintf(device_params + strlen(device_params),"{\"protocol\":%d,\"bigLittleFormat\":%d,\"deviceId\":\"%s\",\"sensorData\":[",
												current_device->protocol,current_device->MDBbigLittleFormat,current_device->deviceID);
			GATEWAY_READ_DLT645_COMMAND *read_dlt645_command = current_device->params->gateway_read_dlt645_command;
			GATEWAY_READ_MODBUS_COMMAND *read_modbus_command = current_device->params->gateway_read_modbus_command;
			GATEWAY_WRITE_MODBUS_COMMAND *write_modbus_command = current_device->params->gateway_write_modbus_command;
			
			// dlt645 read
			while(read_dlt645_command != NULL)
			{	
				sprintf(device_params + strlen(device_params),"{\"identifier645\":%d,\"identifier\":\"%s\",\"deviceID645\":\"%s\"},",
											read_dlt645_command->Identification,read_dlt645_command->keyword,read_dlt645_command->deviceID645);
				read_dlt645_command = read_dlt645_command->nextParams;
			}
		
			// modbus read
			while(read_modbus_command != NULL)
			{
				sprintf(device_params + strlen(device_params),"{\"rFunctionCode\":%d,\"registerAddress\":%d,\"slaveAddress\":%d,\"registerByteNum\":%d,\"identifier\":\"%s\",\"precise\":%d},",
																											read_modbus_command->functionCode, read_modbus_command->registerAddress,read_modbus_command->slaveAddress,
																											read_modbus_command->registerByteNum,read_modbus_command->keyword,read_modbus_command->decimalPoint);
				read_modbus_command = read_modbus_command->nextParams;
			}
			
			// modbus write
			sprintf(device_params + strlen(device_params)-1,"], \"commandData\":[");//sensorData:[ 
			while(write_modbus_command != NULL)
			{
				sprintf(device_params + strlen(device_params),"{\"registerAddress\":%d,\"slaveAddress\":%d,\"wFunctionCode\":%d,\"registerByteNum\":%d},",
								write_modbus_command->registerAddress,write_modbus_command->slaveAddress,write_modbus_command->functionCode,write_modbus_command->registerByteNum);
				write_modbus_command = write_modbus_command->nextParams;
			}		
			sprintf(device_params + strlen(device_params)-1,"]},");// commandData:[
			current_device = current_device->nextDevice;	
	}
	sprintf(device_params + strlen(device_params) -1 ,"]}");
}
void read_config_232(void)
{
	GATEWAY_PARAMS *get;
	get= get_gateway_config_params();
	char* device_params = mymalloc(SRAMEX, 3 * 1024);
	memset(device_params,0,3 * 1024);
	if(get->device_params == NULL)
	{
		sprintf(device_params, "{\"read_config\":\"error\"}");
		USART_232_Send((uint8_t*)device_params, strlen(device_params));
	}
	else
	{
		read_device_params(device_params);
		USART_232_Send((uint8_t*)device_params, strlen(device_params));
	}
	myfree(SRAMEX, device_params);
}

// 设备嗅探
void find_device_232(void)
{
	char deviceId[50];// 发送设备名
	GATEWAY_PARAMS *get;
	get= get_gateway_config_params();
	if(get->device_params == NULL)
	{	
//		sprintf(deviceId, "{\"find_device\":\"%s\"}", gatewayId);		
		sprintf(deviceId, "{\"find_device\":\"error\"}");		
		USART_232_Send((uint8_t*)deviceId, strlen(deviceId));
	}
	else
	{
		sprintf(deviceId, "{\"find_device\":\"%s\"}", get->deviceId);		
		USART_232_Send((uint8_t*)deviceId, strlen(deviceId));
	}
	memset(deviceId, 0, 50);
}


// 储存上位机发送的config_add数据，并返回上位机操作结果
void add_config_232(uint8_t* dataBuf)
{	
	GATEWAY_PARAMS *get;
	get= get_gateway_config_params();
	DEVICE_PARAMS *device=get->device_params;
	char* retMsg = mymalloc(SRAMEX,32);
	memset(retMsg, 0, strlen(retMsg));
	while(device != NULL)// 一直轮询到当前为NULL
	{
		device = device->nextDevice;
	}
	addDevice((char*)dataBuf);
	// 再检查更新后的deviceId是否为NULL
	if(device == NULL)// error
	{	
		retMsg = "{\"write_config\":\"error\"}";
		USART_232_Send((uint8_t*)retMsg, strlen(retMsg));
	}
	else// success
	{
		retMsg = "{\"write_config\":\"success\"}";
		USART_232_Send((uint8_t*)retMsg, strlen(retMsg));
	}
		myfree(SRAMEX, retMsg);
}


// 切换工作模式
void work_mode_232(uint8_t* buf)
{
		/* 用标志位开关data_task任务中，发送数据的方式 */
		// 内置协议模式
		if(strstr((char*)buf,"protocolsMode") != NULL)
		{
			ProtocolsModeFlag = 1;// 开启内置协议模式
			TransparentModeFlag = 0; // 关闭透明传输模式
			LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"ProtocolsMode");	
		}
		// 透明传输模式
		if(strstr((char*)buf,"TransparentMode") != NULL)
		{
			ProtocolsModeFlag = 0;// 关闭内置协议模式
			TransparentModeFlag = 1; // 开启透明传输模式
			LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"TransparentModeFlag");	
		}
}

// 更新OTA数据
void updata_232(void)
{
	int i;
	uint16_t crc;	
	uint8_t databuf[1024];// 保存包数据	
	uint16_t packId = 0x01;
	uint8_t stx = 0x02,eot = 0x04,ack = 0x06,nak = 0x15,C = 0x43;

	// 向上位机发送就绪信号
	char* retMsg = mymalloc(SRAMEX,32);
	memset(retMsg, 0, strlen(retMsg));
	retMsg = "{\"software_update\":\"ready\"}";
	USART_232_Send((uint8_t*)retMsg,  strlen(retMsg));
	myfree(SRAMEX, retMsg);
	memset(rx_232_Buffer, 0, strlen((char*)rx_232_Buffer));
	delay_ms(300);
	
	// 发送第一个C
	USART_232_Send(&C, 1);
	delay_ms(300);
__start:
	i = 0;
	//等待接收到消息，最长等待3S
	while(recv_232_done == 0 && i < 3000) 
	{
		delay_ms(1);
		i++;
	}
	if(recv_232_done == 0)	USART_232_Send(&C, 1);//如果还没接收到消息，再发送一个C
	do{
			// 接收到结束信号，反馈ack
			if(rx_232_Buffer[0] == eot)
			{
				USART_232_Send(&ack, 1);
				delay_ms(300);
				break;
			}
			// 检测头标志
			if(rx_232_Buffer[0] != stx)
			{
				USART_232_Send(&nak, 1);
				delay_ms(300);
				goto __start;
			}
			// 检测包序列
			if(rx_232_Buffer[1] != packId)
			{
				USART_232_Send(&nak, 1);
				delay_ms(300);
				goto __start;
			}
			// 检测包号反码
			if(rx_232_Buffer[2] !=(~packId & 0xff))
			{
				USART_232_Send(&nak, 1);
				delay_ms(300);
				goto __start;
			}
			// 提取数据包
			for(int i = 0; i < 1024; i++)
			{
				databuf[i] = rx_232_Buffer[3 + i];
			}
			crc = Checkcrc16(databuf, 1024);
			// 检测数据包的校验码
			if (((crc & 0x00FF) != rx_232_Buffer[1028]) || (((crc & 0xFF00) >> 8) != rx_232_Buffer[1027]))
			{	
				USART_232_Send(&nak, 1);
				delay_ms(300);
				goto __start;
			}
			// 对数据包进行操作
			/*                */
			memset(databuf, 0, sizeof(databuf));
			
			// 准备接收下一包数据
			USART_232_Send(&ack, 1);
			delay_ms(300);
			packId += 1;

	}while(recv_232_done);

		// 所有数据包接受完成，准备重启
		__set_PRIMASK(1);
		NVIC_SystemReset();
}

void USART_232_task(void const * argument)
{	
	int j;
	char* recv_cmd[] = {"\"cmd\":\"write_config\"","\"cmd\":\"write_config_add\"",
											"\"cmd\":\"read_config\"","\"cmd\":\"find_device\"",
											"\"cmd\":\"ip_config\"","\"cmd\":\"toggle_work_mode\"",
											"\"cmd\":\"software_update\"","\"cmd\":\"reboot\"",
											"\"cmd\":\"cmd error\""	};
	while(1)
	{
		j = 0;
		for(int i = 0; i < sizeof(recv_cmd)/sizeof(recv_cmd[0]); i++)
		{
			if(strstr((char*)rx_232_Buffer,recv_cmd[i]) != NULL)
			{
				i = sizeof(recv_cmd)/sizeof(recv_cmd[0]);
			}
			j++;
		}
		
		if (ProtocolsModeFlag) {
					switch (j) {
						case WRITE_CONFIG:
							while(!recv_232_done)		vTaskDelay(100);// 等待串口接收完成
								save_config_232(rx_232_Buffer);
								LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "write config");
//								__set_PRIMASK(1);
//								NVIC_SystemReset();
								break;
						case WRITE_CONFIG_ADD:
								add_config_232(rx_232_Buffer);
								LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "write config add");
								break;
						case READ_CONFIG:
								read_config_232();
								LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "read config");
								break;
						case FIND_DEVICE:
								find_device_232();
								LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "find device");
								break;				
						case TOGGLE_MODE:
								work_mode_232(rx_232_Buffer);
								LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "toggle work mode");
								break;
						case UPDATE:
								LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "update");
								updata_232();
								break;
						case REBOOT:
								LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "reboot");
								__set_PRIMASK(1);
								NVIC_SystemReset();
								break;
						case CMD_ERROR:
								goto __exit;
					}
				} else {
					switch (j) {
						case FIND_DEVICE:
								find_device_232();
								LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "find device");
								break;
						case TOGGLE_MODE:
								work_mode_232(rx_232_Buffer);
								LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "toggle work mode");
								break;
						case UPDATE:
								updata_232();
								LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "update");
								break;
						case REBOOT:
								LogPrint(LOG_INFO, __FILE__, __FUNCTION__, __LINE__, "reboot");
								__set_PRIMASK(1);
								NVIC_SystemReset();	
								break;
						case CMD_ERROR:
								goto __exit;
				}
			}
				memset(rx_232_Buffer, 0, strlen((char*)rx_232_Buffer));
			__exit:
				vTaskDelay(500);
		}
}

void USART_232_task_creat()
{
	osThreadDef(USART_task, USART_232_task, osPriorityNormal, 0, configMINIMAL_STACK_SIZE*4);
  osThreadCreate(osThread(USART_task), NULL);
}
