#include "remote.h"
#include "ML307A.h"
#include "main.h"
#include "uType.h"
#include "cmsis_os.h"
#include "w25qxx.h"
#include "spi.h"

extern time_t epoch_time;
extern uint8_t sensor_status[6];
extern uint16_t trigger_info[3];
//extern uint8_t temp_cloud_send_buffer[420];

/*
 *@ 终端ID			202400000300
 *@ 终端手机号	202412040003
*/
uint8_t terminalId[7] = {0};
uint8_t g_board_id[6] = {0};

//uint8_t g_board_id[6] = {0x20, 0x24, 0x12, 0x04, 0x00, 0x03}; 					// 终端手机号
//uint8_t terminalId[7] = {0x20, 0x24, 0x00, 0x00, 0x00, 0x03, 0x00}; 		// 终端ID

uint8_t license[9] = {0xD5, 0xE3, 0x41, 0x39, 0x39, 0x39, 0x39, 0x39, 0x00}; 	// 车牌

//uint16_t g_remote_sequence = 1; // 消息流水号
uint16_t Register_Serial_number = 1;// 注册消息流水号
uint16_t Heartbeat_Serial_number = 1;// 心跳消息流水号
uint16_t response_Serial_number = 1;// 通用应答消息流水号
uint16_t sensorline_Serial_number = 1;// 掉线上传消息流水号
uint16_t systemlevel_Serial_number = 1;// 预警等级消息流水号
uint16_t Temperature_Serial_number = 1;// 温度数据消息流水号
uint16_t Pressure_CO_H2_Serial_number = 1;// 压气数据消息流水号

uint8_t g_remote_databuffer[450]__attribute__((section(".ccmram")));
char g_remote_atbuffer[512]__attribute__((section(".ccmram")));
uint8_t systemlevel_body[12]__attribute__((section(".ccmram")));
uint8_t General_response[5]__attribute__((section(".ccmram")));
uint8_t temp_body[424]__attribute__((section(".ccmram")));
uint8_t prc0h2_body[62]__attribute__((section(".ccmram")));

extern volatile SystemLevel_t system_level;
extern uint16_t msg_serial ;

extern uint32_t adc_val; // ADC读取电压
extern uint8_t voltage_int;
extern uint8_t percent;
extern uint8_t flash_temp_prc0h2[512]; // 存入flash的温度和压力数据

//异或校验和
uint8_t Calculate_Checksum(uint8_t* data, uint16_t length)
{
    uint8_t checksum = 0;
    for (uint16_t i = 0; i < length; i++)
    {
        checksum ^= data[i];
    }
    return checksum;
}

void my_memmove(char* dest, const char* src, size_t count)
{
	if(0 == count){
		return;
	}
	
	 for(int i=count-1; i>=0; i-- ){
			dest[i] = src[i];
	 }
	
}

uint16_t escape_7E(char* data, uint16_t data_len )
{
//	return data_len;
	for(uint16_t i=0; i<data_len; i++){
		
		if(0x7E == data[i]){
			my_memmove(data+i+2, data+i+1, data_len-i-1);

			data[i]=0x7D;
			data[i+1]=0x02;
			data_len++;
			i++;
			
		}else if(0x7D == data[i]){

			my_memmove(data+i+2, data+i+1, data_len-i-1);
			data[i+1]=0x01;
			data_len++;
			i++;
		}
	
	}
	
	return data_len;

}


uint8_t Send_Register(void)
{
	
	Msg_Header header;
	Register_Body body;
	uint16_t data_len = 0;
	uint16_t at_len = 0;

	memset(&header,0,sizeof(Msg_Header));
	
	header.id = 0x0001;
	memcpy(header.phone_number, g_board_id, 6);
	
	header.sequence = (Register_Serial_number<<8&0xFF00)|(Register_Serial_number>>8);
	Register_Serial_number++;
	header.attr.length = sizeof(Register_Body);
	

	memset(&body, 0, sizeof(Register_Body));
	memcpy(body.terminalId, terminalId, 7); 
	
	body.license_color = 0x00;
	memcpy(body.license, license, 9);

	g_remote_databuffer[data_len++] = 0x7E;
	
	memcpy(g_remote_databuffer+data_len, &header, sizeof(Msg_Header));
	data_len += sizeof(Msg_Header);
	
	memcpy(g_remote_databuffer+data_len, &body, sizeof(Register_Body));
	data_len += sizeof(Register_Body);
	
	g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
	data_len++;
	
	data_len = escape_7E((char*)g_remote_databuffer+1, data_len-1);
	data_len++;
	
	g_remote_databuffer[data_len++] = 0x7E;
	
	// 发送AT buffer
	at_len += sprintf(g_remote_atbuffer, "AT+MIPSEND=0,%d,\"", data_len); // 改为HEX不用乘2
	for (uint16_t i = 0; i < data_len; i++)
	{
			at_len += sprintf(g_remote_atbuffer+at_len, "%02X", g_remote_databuffer[i]);
	}
	at_len += sprintf(g_remote_atbuffer+at_len,"%s", "\"\r\n");	
	// 打印AT+MIPSEND=0发送内容	
//	printf("MIP_REGISTER:\r\n");	
//	printf("%s\r\n", g_remote_atbuffer); 
	
	if (sendCmd_4G_3(g_remote_atbuffer, "OK", "+MIPURC: \"rtcp\",0,26", 6, 1)) { // +MIPSEND: 0,61 // +MIPURC: \"rtcp\",0,26,26			
//		printf("Send_Cloud_Register_SUCCESS\r\n");
		return 0;
	} else {
		printf("Send_Cloud_Register_fail\r\n");
		return 1;
//		return 0;
	}
}

uint8_t Send_Heartbeat(void)
{
	
	Msg_Header header;
	uint16_t data_len = 0;
	uint16_t at_len = 0;
	
	memset(&header,0,sizeof(Msg_Header));
	header.id = 0x0200;
	memcpy(header.phone_number, g_board_id, 6);
	header.sequence = (Heartbeat_Serial_number<<8&0xFF00)|(Heartbeat_Serial_number>>8);
	Heartbeat_Serial_number++;
	header.attr.length = 0;
	
	g_remote_databuffer[data_len++] = 0x7E;
	
	memcpy(g_remote_databuffer+data_len, &header, sizeof(Msg_Header));
	data_len += sizeof(Msg_Header);
	
	g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
	data_len++;
	
	data_len = escape_7E((char*)g_remote_databuffer+1, data_len-1);
	data_len++;
	
	g_remote_databuffer[data_len++] = 0x7E;
	
		// 发送AT buffer
	at_len += sprintf(g_remote_atbuffer, "AT+MIPSEND=0,%d,\"", data_len); // 改为HEX不用乘2
	for (uint16_t i = 0; i < data_len; i++)
	{
			at_len += sprintf(g_remote_atbuffer+at_len, "%02X", g_remote_databuffer[i]);
	}
	at_len += sprintf(g_remote_atbuffer+at_len,"%s", "\"\r\n");	
//	printf("%s\r\n", g_remote_atbuffer); 
	if (sendCmd_4G_3(g_remote_atbuffer, "OK","+MIPURC: \"rtcp\",0,20", 6, 1)) {	
//			printf("MIPSEND_Heart_OK\r\n");
			return 0;
	} else {			
			printf("MIPSEND_Heart_fail\r\n");		
			return 1;
	}
}

uint8_t Send_General_response(void)
{
	
	Msg_Header header;
	uint16_t data_len = 0;
	uint16_t at_len = 0;
	uint16_t general_len = 0;
	
	memset(&header,0,sizeof(Msg_Header));
	header.id = 0x0100;
	memcpy(header.phone_number, g_board_id, 6);
	header.sequence = (response_Serial_number<<8&0xFF00)|(response_Serial_number>>8);
	response_Serial_number++;
	header.attr.res = 0x00;
	header.attr.length = 0x05;
	
	g_remote_databuffer[data_len++] = 0x7E;
	
	memcpy(g_remote_databuffer+data_len, &header, sizeof(Msg_Header));
	data_len += sizeof(Msg_Header);
	
	General_response[general_len++] = (msg_serial<<8 & 0xFF);
	General_response[general_len++] = (msg_serial & 0xFF);
	General_response[general_len++] = 0x81;
	General_response[general_len++] = 0x03;
	General_response[general_len++] = 0x00;
	
	memcpy(g_remote_databuffer + data_len, General_response, general_len);
  data_len += general_len;
	
	g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
	data_len++;
	
	data_len = escape_7E((char*)g_remote_databuffer+1, data_len-1);
	data_len++;
	
	g_remote_databuffer[data_len++] = 0x7E;
	
		// 发送AT buffer
	at_len += sprintf(g_remote_atbuffer, "AT+MIPSEND=0,%d,\"", data_len); // 改为HEX不用乘2
	for (uint16_t i = 0; i < data_len; i++)
	{
			at_len += sprintf(g_remote_atbuffer+at_len, "%02X", g_remote_databuffer[i]);
	}
	at_len += sprintf(g_remote_atbuffer+at_len,"%s", "\"\r\n");	
	printf("%s\r\n", g_remote_atbuffer); 
	if (sendCmd_4G_3(g_remote_atbuffer, "OK","+MIPURC: \"rtcp\",0,20", 6, 1)) {	
//			printf("Send_General_response_OK\r\n");
			return 0;
	} else {			
			printf("Send_General_response_fail\r\n");		
			return 1;
	}
}
uint8_t Send_sensorline(void)
{
	
	Msg_Header header;
	uint16_t data_len = 0;
	uint16_t at_len = 0;
	
	memset(&header,0,sizeof(Msg_Header));
	header.id = 0x0009;
	memcpy(header.phone_number, g_board_id, 6);
	header.sequence = (sensorline_Serial_number<<8&0xFF00)|(sensorline_Serial_number>>8);
	sensorline_Serial_number++;
	header.attr.res = 0X00; // 存储高字节
	header.attr.length = 0x0A; // 存储低字节
	
	g_remote_databuffer[data_len++] = 0x7E;
	
	memcpy(g_remote_databuffer+data_len, &header, sizeof(Msg_Header));
	data_len += sizeof(Msg_Header);

	memcpy(g_remote_databuffer + data_len, sensor_status, 6);
  data_len += 6;
	
	uint32_t epoch_time_value = epoch_time; // 获取 epoch 时间戳
	g_remote_databuffer[data_len++] = (uint8_t)(epoch_time_value >> 24); // 高字节
	g_remote_databuffer[data_len++] = (uint8_t)(epoch_time_value >> 16); // 次高字节
	g_remote_databuffer[data_len++] = (uint8_t)(epoch_time_value >> 8);  // 次低字节
	g_remote_databuffer[data_len++] = (uint8_t)(epoch_time_value);       // 低字节
	
	g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
	data_len++;
	
	data_len = escape_7E((char*)g_remote_databuffer+1, data_len-1);
	data_len++;
	
	g_remote_databuffer[data_len++] = 0x7E;
	
		// 发送AT buffer
	at_len += sprintf(g_remote_atbuffer, "AT+MIPSEND=0,%d,\"", data_len); // 改为HEX不用乘2
	for (uint16_t i = 0; i < data_len; i++)
	{
			at_len += sprintf(g_remote_atbuffer+at_len, "%02X", g_remote_databuffer[i]);
	}
	at_len += sprintf(g_remote_atbuffer+at_len,"%s", "\"\r\n");	
	printf("%s\r\n", g_remote_atbuffer); 
	
	if (sendCmd_4G_3(g_remote_atbuffer, "OK","+MIPURC: \"rtcp\",0,20", 6, 1)) {	
			printf("Send_sensorline_OK\r\n");
			return 0;
	} else {			
			printf("Send_sensorline_fail\r\n");		
			return 1;
	}
}
uint8_t Send_systemlevel(void)
{
	uint32_t systemlevelbody_len = 0;
	Msg_Header header;
	uint16_t data_len = 0;
	uint16_t at_len = 0;
	
	memset(&header,0,sizeof(Msg_Header));
	header.id = 0x0103;
	memcpy(header.phone_number, g_board_id, 6);
	header.sequence = (systemlevel_Serial_number<<8&0xFF00)|(systemlevel_Serial_number>>8);
	systemlevel_Serial_number++;
	header.attr.res = 0x00;
	header.attr.length = 0x0C;
	
	g_remote_databuffer[data_len++] = 0x7E;
	
	memcpy(g_remote_databuffer+data_len, &header, sizeof(Msg_Header));
	data_len += sizeof(Msg_Header);
	
	systemlevel_body[systemlevelbody_len++] = 0x01;
	systemlevel_body[systemlevelbody_len++] = 0xF0;
	systemlevel_body[systemlevelbody_len++] = 0x01;
	systemlevel_body[systemlevelbody_len++] = system_level;
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(trigger_info[0] >> 8); // 传感器类型高字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(trigger_info[0]);      // 传感器类型低字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(trigger_info[1]);      // 传感器编号低字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(trigger_info[2]);      // 触发值低字节
	
	uint32_t epoch_time_value = epoch_time; // 获取 epoch 时间戳
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(epoch_time_value >> 24); // 高字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(epoch_time_value >> 16); // 次高字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(epoch_time_value >> 8);  // 次低字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(epoch_time_value);       // 低字节
	memcpy(g_remote_databuffer + data_len, systemlevel_body, systemlevelbody_len);
  data_len += systemlevelbody_len;
	
	g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
	data_len++;
	
	data_len = escape_7E((char*)g_remote_databuffer+1, data_len-1);
	data_len++;
	
	g_remote_databuffer[data_len++] = 0x7E;
	
	// 发送AT buffer
	at_len += sprintf(g_remote_atbuffer, "AT+MIPSEND=0,%d,\"", data_len); // 改为HEX不用乘2
	for (uint16_t i = 0; i < data_len; i++)
	{
			at_len += sprintf(g_remote_atbuffer+at_len, "%02X", g_remote_databuffer[i]);
	}
	at_len += sprintf(g_remote_atbuffer+at_len,"%s", "\"\r\n");	
	
	printf("%s\r\n", g_remote_atbuffer); 
	if (sendCmd_4G_3(g_remote_atbuffer, "OK","+MIPURC: \"rtcp\",0,23", 6, 2)) {	
			printf("MIPSEND_systemlevel_change_OK\r\n");
			return 0;
	} else {			
			printf("MIPSEND_systemlevel_fail\r\n");		
			return 1;
	}
}


uint8_t Send_Temperature_Data(SensorDataBuffer* sensor_data)
{
		uint32_t tempbody_len = 0;
    uint16_t data_len = 0;
    uint16_t at_len = 0;
    Msg_Header header;
	
		temp_body[tempbody_len++] = 0xF0; // 温度数据的类型标识
		temp_body[tempbody_len++] = 0x0A; // 固定值
		
//		memcpy(&temp_body[tempbody_len], temp_cloud_send_buffer, 390);
//    tempbody_len += 390;  
		
	  for (uint8_t sensorId = 0; sensorId < MAX_TEMP_NODE_NUM; sensorId++) 
    {

			temp_body[tempbody_len++] = 0x00; // 固定值
			temp_body[tempbody_len++] = sensorId + 1; // 传感器编号从 1 开始
			memcpy(temp_body + tempbody_len, sensor_data->temp_data[sensorId], 12);
			tempbody_len += 12;

    }

		uint32_t epoch_time_value = epoch_time; // 获取 epoch 时间戳
		temp_body[tempbody_len++] = (uint8_t)(epoch_time_value >> 24); // 高字节
		temp_body[tempbody_len++] = (uint8_t)(epoch_time_value >> 16); // 次高字节
		temp_body[tempbody_len++] = (uint8_t)(epoch_time_value >> 8);  // 次低字节
		temp_body[tempbody_len++] = (uint8_t)(epoch_time_value);       // 低字节
		
    // 构造 header
    memset(&header, 0, sizeof(Msg_Header));
    header.id = 0x2602;
    memcpy(header.phone_number, g_board_id, 6);
    header.sequence = (Temperature_Serial_number << 8 & 0xFF00) | (Temperature_Serial_number >> 8);
    Temperature_Serial_number++;
//    header.attr.length = tempbody_len ;
		header.attr.res = (uint8_t)(tempbody_len >> 8); // 存储高字节
		header.attr.length = (uint8_t)(tempbody_len & 0xFF); // 存储低字节
	
    // 拼接完整数据
    g_remote_databuffer[data_len++] = 0x7E; // 开始符

    memcpy(g_remote_databuffer + data_len, &header, sizeof(Msg_Header));
    data_len += sizeof(Msg_Header);

    memcpy(g_remote_databuffer + data_len, temp_body, tempbody_len);
    data_len += tempbody_len;

    g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
    data_len++;

    data_len = escape_7E((char*)g_remote_databuffer + 1, data_len - 1);
    data_len++;

    g_remote_databuffer[data_len++] = 0x7E; // 结束符
		
//		for( int i = 0 ; i < data_len;  i++ )
//		{
//			printf("%02X", g_remote_databuffer[i]); 
//		}
//		printf("\r\n");
		
//		flash_write_temp_data(g_remote_databuffer, data_len);
		memcpy(flash_temp_prc0h2, g_remote_databuffer, 441);
    // 发送 AT 命令
    at_len += sprintf(g_remote_atbuffer, "AT+MIPSEND=0,%d,\"", data_len); // 改为 HEX 格式
    for (uint16_t i = 0; i < data_len; i++) 
    {
        at_len += sprintf(g_remote_atbuffer + at_len, "%02X", g_remote_databuffer[i]);
    }
    at_len += sprintf(g_remote_atbuffer + at_len, "%s", "\"\r\n");
//    printf("%s\r\n", g_remote_atbuffer); // 打印温度数据

    if (sendCmd_4G_3(g_remote_atbuffer, "OK", "+MIPSEND: 0,441" , 6, 2)) 
    {
//				printf("MIPSEND_Temperature_Data_OK\r\n");
        return 0;
    } 
    else 
    {
			printf("MIPSEND_Temperature_Data_fail\r\n");
        return 1;
    }
}


uint8_t Send_Pressure_CO_H2_Data(SensorDataBuffer* sensor_data)
{
    
    uint8_t body_len = 0;
    uint16_t data_len = 0;
    uint16_t at_len = 0;
    Msg_Header header;

		prc0h2_body[0] = 0xF0; // 压力数据类型标识
    prc0h2_body[1] = 0x0C; // 固定值
		body_len = 2;
    // 拼接压力数据
    for (uint8_t sensorId = 0; sensorId < MAX_PRESSURE_NODE_NUM; sensorId++) 
    {
//        if (sensor_data->pressure_valid[sensorId]) 
//        {
            
            prc0h2_body[body_len++] = 0x00; // 固定值
            prc0h2_body[body_len++] = sensorId + 1; // 传感器编号从 1 开始
            memcpy(prc0h2_body + body_len, sensor_data->pressure_data[sensorId], 2);
            body_len += 2;
//        }
    }

		prc0h2_body[body_len++] = 0xF0; // CO 数据类型标识
    prc0h2_body[body_len++] = 0x08; // 固定值
    // 拼接 CO 数据
    for (uint8_t sensorId = 0; sensorId < MAX_CO_NODE_NUM; sensorId++) 
    {
//        if (sensor_data->co_valid[sensorId]) 
//        {
            
            prc0h2_body[body_len++] = 0x00; // 固定值
            prc0h2_body[body_len++] = sensorId + 1; // 传感器编号从 1 开始
            memcpy(prc0h2_body + body_len, sensor_data->co_data[sensorId], 4);
            body_len += 4;
//        }
    }

		prc0h2_body[body_len++] = 0xF0; // H2 数据类型标识
    prc0h2_body[body_len++] = 0x06; // 固定值
    // 拼接 H2 数据
    for (uint8_t sensorId = 0; sensorId < MAX_H2_NODE_NUM; sensorId++) 
    {
//        if (sensor_data->h2_valid[sensorId]) 
//        {
            
            prc0h2_body[body_len++] = 0x00; // 固定值
            prc0h2_body[body_len++] = sensorId + 1; // 传感器编号从 1 开始
            memcpy(prc0h2_body + body_len, sensor_data->h2_data[sensorId], 4);
            body_len += 4;
//        }
    }
		prc0h2_body[body_len++] = 0xF0; // 电压数据类型标识
    prc0h2_body[body_len++] = 0x05; // 固定值
		prc0h2_body[body_len++] = voltage_int; // 电压
    prc0h2_body[body_len++] = percent; // 电量百分比
		
		uint32_t epoch_time_value = epoch_time; // 获取 epoch 时间戳
		prc0h2_body[body_len++] = (uint8_t)(epoch_time_value >> 24); // 高字节
		prc0h2_body[body_len++] = (uint8_t)(epoch_time_value >> 16); // 次高字节
		prc0h2_body[body_len++] = (uint8_t)(epoch_time_value >> 8);  // 次低字节
		prc0h2_body[body_len++] = (uint8_t)(epoch_time_value);       // 低字节

		// 构造 header
    memset(&header, 0, sizeof(Msg_Header));
    header.id = 0x2602;
    memcpy(header.phone_number, g_board_id, 6);
    header.sequence = (Pressure_CO_H2_Serial_number << 8 & 0xFF00) | (Pressure_CO_H2_Serial_number >> 8);
    Pressure_CO_H2_Serial_number++;
    header.attr.length = body_len;

    // 拼接完整数据
    g_remote_databuffer[data_len++] = 0x7E; // 开始符

    memcpy(g_remote_databuffer + data_len, &header, sizeof(Msg_Header));
    data_len += sizeof(Msg_Header);

    memcpy(g_remote_databuffer + data_len, prc0h2_body, body_len);
    data_len += body_len;

    g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
    data_len++;

    data_len = escape_7E((char*)g_remote_databuffer + 1, data_len - 1);
    data_len++;

    g_remote_databuffer[data_len++] = 0x7E; // 结束符
		
		// 从 g_remote_databuffer[13] 开始复制 64 字节到 flash_temp_prc0h2[441]
		memcpy(&flash_temp_prc0h2[441], &g_remote_databuffer[13], 64);
		
    // 发送 AT 命令
    at_len += sprintf(g_remote_atbuffer, "AT+MIPSEND=0,%d,\"", data_len); // 改为 HEX 格式
    for (uint16_t i = 0; i < data_len; i++) 
    {
        at_len += sprintf(g_remote_atbuffer + at_len, "%02X", g_remote_databuffer[i]);
    }
    at_len += sprintf(g_remote_atbuffer + at_len, "%s", "\"\r\n");
//    printf("%s\r\n", g_remote_atbuffer); // 打印压力气体电压数据

    if (sendCmd_4G_3(g_remote_atbuffer, "OK", "+MIPSEND: 0,73" , 6, 2)) 
    {
//			printf("MIPSEND_Pressure_CO_H2_Data_OK\r\n");
        return 0;
    } 
    else 
    {
			printf("MIPSEND_Pressure_CO_H2_Data_fail\r\n");
      return 1;
    }
}

/*

注册平台的应答：
+MIPURC: "rtcp",0,26,7E8100000B202412040001000000000020241204000100008A7E

心跳平台的应答:
+MIPURC: "rtcp",0,20,7E8001000520241204000100520052000200957E

设置终端参数：
+MIPURC: "rtcp",0,56,7E81030029202412040001000109F1010101F102013CF1030164F1040164F105010AF106010AF1070101F108011EF109010167DFC4051B7E

*/

