#include "main.h"
#include "CatOneTask.h"
#include "RS485Task.h"
#include "Public.h"
#include <stdlib.h>
#include "spiflash.h"
#include "LoraTask.h"

#define	DBG_RX_LEN_MAX				128
//#define	DBG_LOG(...)									rt_kprintf(__VA_ARGS__)
#define DEBUG_CMD_CNT					22
#define	DEBUG_BUFF_SIZE_MAX		512

#define DEBUG_BUFSIZE 						200
#define	DEBUG_BUFF_MAX				1024

void Debug_Printf(char *format, ...);

#define	DBG_LOG(...)									Debug_Printf(__VA_ARGS__)

typedef void (*DebugExec)(int argc, char *argv[]);

typedef struct{
	char *DBGCmd;
	DebugExec   DBGExec;
}DBGFunType;

const DBGFunType DebugFun[DEBUG_CMD_CNT];

static GateWayPara GateWay;
static char buff[DBG_RX_LEN_MAX];
static uint8_t DebugRxLen;
static uint8_t DebugRxBuff[DBG_RX_LEN_MAX];
static uint8_t DebugRxTimeOut1mSCnt;
static rt_sem_t DebugRev_Sem;
static uint16_t ir=0;  /* buffer read index*/
static char tempBuff[DEBUG_BUFF_MAX];

void vcom_Print(uint8_t sLen)
{
	char* CurChar;
	ir = 0;
  while(ir < sLen)
  {
    CurChar = &buff[ir++];
		if(GateWay->ConfigPara.DebugChannel == DEBUG_CH_RS485_1)
			RS485Ch1UartSend((uint8_t*)CurChar, 1);
		else if(GateWay->ConfigPara.DebugChannel == DEBUG_CH_RS485_2)
			RS485Ch2UartSend((uint8_t*)CurChar, 1);
  }
}

/*****************************************************************************************
* 函数名称: Debug_Printf
* 功能描述: RS485通道1任务函数
* 参    数: 任务参数入口
* 返 回 值: 无
*****************************************************************************************/
void Debug_Printf(char *format, ...)
{
	va_list args;
	va_start(args, format);
	uint16_t len;
	//uint32_t primask_bit;
	uint16_t offset = 0;
	//primask_bit = __get_PRIMASK();
	//__disable_irq();
	
	/*convert into string at buff[0] of length iw*/
	len = vsprintf(&tempBuff[0], format, args);
	if(GateWay->ConfigPara.DebugChannel == DEBUG_CH_DBG) {
		rt_kprintf(tempBuff);
	}
	else {
		while(offset < len) {
			if((len - offset) < DEBUG_BUFSIZE) {
				memcpy(&buff[0], &tempBuff[offset], len - offset);
				vcom_Print(len - offset);
				offset = len;
			}
			else {
				memcpy(&buff[0], &tempBuff[offset], DEBUG_BUFSIZE);
				offset += DEBUG_BUFSIZE;
				vcom_Print(DEBUG_BUFSIZE);
			}
		}
	}
	//__set_PRIMASK(primask_bit);
	//__enable_irq();
	
	va_end(args);
}
/*****************************************************************************************
* 函数名称: RS485Ch2_Thread_Entry
* 功能描述: RS485通道1任务函数
* 参    数: 任务参数入口
* 返 回 值: 无
*****************************************************************************************/
void Debug_Thread_Entry(void *parameter)
{
	GateWay = (GateWayPara)parameter;
	rt_err_t result;
	
	DebugRev_Sem  = rt_sem_create("debug_sem",	0, RT_IPC_FLAG_FIFO);
	if(DebugRev_Sem == RT_NULL) {
		rt_kprintf("DebugRev Sem Create Failed!\r\n");
	}
	rt_kprintf("DebugRev Thread is running！\r\n");
	
	while(1) {
		result = rt_sem_take(DebugRev_Sem, RT_WAITING_FOREVER);
		if(result == RT_EOK) {
			DebugAnalyze(GateWay, DebugRxBuff, DebugRxLen);
			DebugRxTimeOut1mSCnt = 0;
			DebugRxLen = 0;
		}
	}
}

/*****************************************************************************************
* 函数名称: RS485Ch2RxIrqCallback
* 功能描述: RS485通道1中断处理回调函数
* 参    数: rData 接收到的数据
* 返 回 值: 无
*****************************************************************************************/
void DbgRxIrqCallback(uint8_t rData)
{
	if(DebugRxTimeOut1mSCnt == 0) 
		DebugRxLen = 0;
	
	DebugRxTimeOut1mSCnt = 3;
	if(DebugRxLen < DBG_RX_LEN_MAX) {
		DebugRxBuff[DebugRxLen++] = rData;
	}
}


void DebugRxOverhandler(void)
{
	if(DebugRxTimeOut1mSCnt > 0)
		DebugRxTimeOut1mSCnt--;
	
	if(DebugRxLen > 2 && DebugRxTimeOut1mSCnt == 0) {
		DebugRxTimeOut1mSCnt = 20;
		rt_sem_release(DebugRev_Sem);
	}
}

/*****************************************************************************************
* 函数名称: DebugAnalyze
* 功能描述: 调试指令解析
* 参    数: GateWay, 网关参数句柄
						rData,输入数据
            rLen, 输入数据长度
* 返 回 值: 无
*****************************************************************************************/
void DebugAnalyze(GateWayPara GateWay, uint8_t *rData, uint16_t rLen)
{
	int argc = 0;
	char *argv[10], *argp;
	
	for(int i = 0; i < 10; i++) {
		argv[i] = 0;
	}
	if(rLen == 0) 
		return;
	//for(argv[argc] = strtok(RxBuff, " "); argv[argc] != NULL; argv[++argc] = strtok(NULL, " "));
	argp = strtok((char *)rData, " ");
	for(int i = 0; i < 10; i++) {
		if(argp != NULL) {
			argv[argc++] = argp;
			argp = strtok(NULL, " ");
		}
		else if(argc > 0){
			argc--;
			break;
		}
	}

	argp = strtok(argv[argc], "'\r'");
	if(argp != NULL) {
		argv[argc++] = argp;
	}
	
	for(int i = 0; i < DEBUG_CMD_CNT; i++) {
		if(strcmp(argv[0], DebugFun[i].DBGCmd) == 0)
			DebugFun[i].DBGExec(argc, argv);
	}
	memset(rData, 0x00, rLen);
}

/*****************************************************************************************
* 函数名称: DebugCmdMainOnOff
* 功能描述: 主调试信息开关
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdMainOnOff(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: main arg1\r\n");
		DBG_LOG("  brief --> Turn the Main_DBG on or off.\r\n");
		DBG_LOG("  arg1  --> on/off\r\n\r\n");
		return;
	}

	if(strcmp(argv[1], "on") == 0) {
		MainDBGOnOff(true);
	}
	else if(strcmp(argv[1], "off") == 0) {
		MainDBGOnOff(false);
	}
}

/*****************************************************************************************
* 函数名称: DebugCmdCat1OnOff
* 功能描述: CAT1调试信息开关
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdCat1OnOff(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: cat1 arg1\r\n");
		DBG_LOG("  brief --> Turn the Cat1_DBG on or off.\r\n");
		DBG_LOG("  arg1  --> on/off\r\n\r\n");
 		return;
	}

	if(strcmp(argv[1], "on") == 0) {
		Cat1DBGOnOff(true);
	}
	else if(strcmp(argv[1], "off") == 0) {
		Cat1DBGOnOff(false);
	}
}

/*****************************************************************************************
* 函数名称: DebugCmdCat1OnOff
* 功能描述: CAT1调试信息开关
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdRS485Ctrl(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: rs485 arg1 arg2 arg3 arg4\r\n");
		DBG_LOG("  brief --> RS485 control command.\r\n");
		DBG_LOG("  arg1  --> idx: (1, 2) RS485 channel selection.\r\n");
		DBG_LOG("  arg2  --> scmd:(o, c, v, b)Rs485 subcommand.\r\n");
		DBG_LOG("            scmd = o, arg3 = (on, off) RS485 Channel On-OFF.\r\n");
		DBG_LOG("            scmd = c, arg3 = (on, off) Enable the internal communication unit function.\r\n");
		DBG_LOG("            scmd = v, arg3 = (on, off) Set output voltage.\r\n");
		DBG_LOG("            scmd = b, arg3 = (2400~500000) Set baud rate.\r\n\r\n");
		DBG_LOG("            scmd = u, arg4 = (on, off) Set Upgrade symbol.\r\n\r\n");
		return;
	}
	
	int idx = atoi(argv[1]);
	if(idx < 1 || idx > 2) {
		DBG_LOG("RS485 Cmd Para Error!\r\n");
		return;
	}
	
	char scmd = argv[2][0];
	switch(scmd) {
		case 'o':
			if(strstr(argv[3], "on") != NULL) {
				if(idx == 1)
					GateWay->ConfigPara.Rs485Ch1.Enable = true;
				else if(idx == 2)
					GateWay->ConfigPara.Rs485Ch2.Enable = true;
				DBG_LOG("RS485Ch%d Enable!\r\n", idx);
			}
			else if(strstr(argv[3], "off") != NULL){
				if(idx == 1)
					GateWay->ConfigPara.Rs485Ch1.Enable = false;
				else if(idx == 2)
					GateWay->ConfigPara.Rs485Ch2.Enable = false;
				DBG_LOG("RS485Ch%d Disable!\r\n", idx);
			}
			break;	
			
		case 'c':
			if(strstr(argv[3], "on") != NULL) {
				if(idx == 1) {
					GateWay->ConfigPara.Rs485Ch1.CommUnitEnable = true;
					GateWay->ConfigPara.Rs485Ch1.QuerySensorFlag = true;
					GateWay->ConfigPara.Rs485Ch1.CUData.Para.SensorN = 0;
					memset(GateWay->ConfigPara.Rs485Ch1.CUData.Para.SensorType, 0x00, SENSOR_NUM_MAX * 2);
					GateWay->ConfigPara.Rs485Ch1.CUData.Para.CommStatus = true;
					RS485Ch1_Config(9600);
					GateWay->ConfigPara.Rs485Ch1.BaudRate = 9600;
					SComm1Para.SensorCnt = 0;
				}
				else if(idx == 2) {
					GateWay->ConfigPara.Rs485Ch2.CommUnitEnable = true;
					GateWay->ConfigPara.Rs485Ch2.QuerySensorFlag = true;
					GateWay->ConfigPara.Rs485Ch2.CUData.Para.SensorN = 0;
					memset(GateWay->ConfigPara.Rs485Ch2.CUData.Para.SensorType, 0x00, SENSOR_NUM_MAX * 2);
					GateWay->ConfigPara.Rs485Ch2.CUData.Para.CommStatus = true;
					RS485Ch2_Config(9600);
					GateWay->ConfigPara.Rs485Ch2.BaudRate = 9600;
					SComm2Para.SensorCnt = 0;
				}
				DBG_LOG("RS485Ch%d Enable!\r\n", idx);
			}
			else if(strstr(argv[3], "off") != NULL){
				if(idx == 1) {
					GateWay->ConfigPara.Rs485Ch1.CommUnitEnable = false;
					GateWay->ConfigPara.Rs485Ch1.CUData.Para.CommStatus = false;
				}
				else if(idx == 2) {
					GateWay->ConfigPara.Rs485Ch2.CommUnitEnable = false;
					GateWay->ConfigPara.Rs485Ch2.CUData.Para.CommStatus = false;
				}
				DBG_LOG("RS485Ch%d Disable!\r\n", idx);
			}
			break;	
			
		case 'v': 
			if(strstr(argv[3], "on") != NULL) {
				if(idx == 1) {
					GateWay->ConfigPara.Rs485Ch1.Power = 1;
					RS485_CH1_POW_ON();
					DBG_LOG("RS485Ch%d Power On!\r\n", idx);
				}
				else if(idx == 2) {
					GateWay->ConfigPara.Rs485Ch2.Power = 1;
					RS485_CH2_POW_ON();
					DBG_LOG("RS485Ch%d Power On!\r\n", idx);
				}
			}
			else if(strstr(argv[3], "off") != NULL) {
				if(idx == 1) {
					GateWay->ConfigPara.Rs485Ch1.Power = 0;
					RS485_CH1_POW_OFF();
					DBG_LOG("RS485Ch%d Power Off!\r\n", idx);
				}
				else if(idx == 2) {
					GateWay->ConfigPara.Rs485Ch2.Power = 0;
					RS485_CH2_POW_OFF();
					DBG_LOG("RS485Ch%d Power Off!\r\n", idx);
				}
			}				
		break;
		
		case 'b': {
			int BaudRate = atoi(argv[3]);
			if(idx == 1) {
				GateWay->ConfigPara.Rs485Ch1.BaudRate = BaudRate;
				RS485Ch1_Config(BaudRate);
				DBG_LOG("RS485Ch%d Set BaudRate %d!\r\n", idx, GateWay->ConfigPara.Rs485Ch1.BaudRate);
			}
			else if(idx == 2) {
				GateWay->ConfigPara.Rs485Ch2.BaudRate = BaudRate;
				RS485Ch2_Config(BaudRate);
				DBG_LOG("RS485Ch%d Set BaudRate %d!\r\n", idx, GateWay->ConfigPara.Rs485Ch2.BaudRate);
			}
		}
		break;	
		
		case 'u':
			if(strstr(argv[3], "on") != NULL) {
				if(idx == 1) {
					GateWay->ConfigPara.Rs485Ch1.UpgradeEnable = true;
					DBG_LOG("RS485Ch%d Upgrade On!\r\n", idx);
				}
				else if(idx == 2) {
					GateWay->ConfigPara.Rs485Ch2.UpgradeEnable = true;
					DBG_LOG("RS485Ch%d Upgrade On!\r\n", idx);
				}
			}
			else if(strstr(argv[3], "off") != NULL){
				if(idx == 1) {
					GateWay->ConfigPara.Rs485Ch2.UpgradeEnable = false;
					DBG_LOG("RS485Ch%d Upgrade Off!\r\n", idx);
				}
				else if(idx == 2) {
					GateWay->ConfigPara.Rs485Ch2.UpgradeEnable = false;
					DBG_LOG("RS485Ch%d Upgrade Off!\r\n", idx);
				}
			}
		break;
		
		default:
			DBG_LOG("RS485 Cmd Para Error!\r\n");
			return;
	}
	WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
}

/*****************************************************************************************
* 函数名称: DebugCmdDelCommUnit
* 功能描述: 删除已注册的通讯单元
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdDelCommUnit(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	uint8_t mac[6];
	
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: cudel arg1\r\n");
		DBG_LOG("  brief --> Delete communication unit.\r\n");
		DBG_LOG("  arg1  --> mac: communication unit Mac address.\r\n");
		DBG_LOG("            mac = (XX-XX-XX-XX-XX-XX), Delete specified MAC communication unit.\r\n");
		DBG_LOG("            mac = (all), Delete all communication units.\r\n\r\n");
		return;
	}
	
	if(strcmp(argv[1], "all") == 0) {
		for(uint8_t i = 0; i < COMMUNIT_NUM_MAX; i++)
		{
			GateWay->ConfigPara.CommUnitArray[i].RegFlag = false;
		}
		DBG_LOG("All devices have been deleted!\r\n");
		WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
		return;
	}
		
	int ret = sscanf(argv[1], "%x-%x-%x-%x-%x-%x", 
									(int *)&mac[0], (int *)&mac[1], (int *)&mac[2], (int *)&mac[3], (int *)&mac[4], (int *)&mac[5]);
	if(ret != 6) {
		DBG_LOG("cudel Cmd Para Error!\r\n");
		return;
	}
	
	ret = CheckCommUnitReg(GateWay, mac);
	if(ret < 0) {
		DBG_LOG("The device is not registered with this gateway!\r\n");
		return;
	}
	GateWay->ConfigPara.CommUnitArray[ret].RegFlag = false;
	//memset(&GateWay->ConfigPara.CommUnitArray[ret], 0x00, sizeof(CommUnitData_t));
	DBG_LOG("Device has been deleted!\r\n");
	WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
}

/*****************************************************************************************
* 函数名称: DebugCmdLsCommUnit
* 功能描述: 查看通讯单元信息
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdLsCommUnit(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: culs\r\n\
  brief --> Viewing Communication Unit Information.\r\n\r\n");
		return;
	}
	
	if(GateWay->ConfigPara.Rs485Ch1.CommUnitEnable == true) {
		DBG_LOG("DevType: 8001\r\n");
		DBG_LOG("DevMac: 01-80-02-00-00-01\r\n");
		DBG_LOG("SensorNum: %d\r\n", GateWay->ConfigPara.Rs485Ch1.CUData.Para.SensorN);
		DBG_LOG("SensorType: ");
		for(int i = 0; i < GateWay->ConfigPara.Rs485Ch1.CUData.Para.SensorN; i++) {
			DBG_LOG("%04X ", GateWay->ConfigPara.Rs485Ch1.CUData.Para.SensorType[i]);
		}
		DBG_LOG("\r\n\r\n");
	}
	
	if(GateWay->ConfigPara.Rs485Ch2.CommUnitEnable == true) {
		DBG_LOG("DevType: 8002\r\n");
		DBG_LOG("DevMac: 01-80-02-00-00-02\r\n");
		DBG_LOG("SensorNum: %d\r\n", GateWay->ConfigPara.Rs485Ch2.CUData.Para.SensorN);
		DBG_LOG("SensorType: ");
		for(int i = 0; i < GateWay->ConfigPara.Rs485Ch2.CUData.Para.SensorN; i++) {
			DBG_LOG("%04X ", GateWay->ConfigPara.Rs485Ch2.CUData.Para.SensorType[i]);
		}
		DBG_LOG("\r\n\r\n");
	}
	
	int CUCnt = 0;
	for(int i = 0; i < COMMUNIT_NUM_MAX; i++) {
		if(GateWay->ConfigPara.CommUnitArray[i].RegFlag == true) {
			CUCnt++;
			CommUnitPara_t CU;
			memcpy(&CU, &GateWay->ConfigPara.CommUnitArray[i], sizeof(CommUnitPara_t));
			DBG_LOG("DevType: %04X\r\n", GateWay->ConfigPara.CommUnitArray[i].CUType);
			DBG_LOG("DevMac: %02X-%02X-%02X-%02X-%02X-%02X\r\n", 
							GateWay->ConfigPara.CommUnitArray[i].Mac[0][0], 
							GateWay->ConfigPara.CommUnitArray[i].Mac[0][1], 
							GateWay->ConfigPara.CommUnitArray[i].Mac[0][2],
							GateWay->ConfigPara.CommUnitArray[i].Mac[0][3], 
							GateWay->ConfigPara.CommUnitArray[i].Mac[0][4], 
							GateWay->ConfigPara.CommUnitArray[i].Mac[0][5]);
			DBG_LOG("SensorNum: %d\r\n", GateWay->ConfigPara.CommUnitArray[i].SensorN);
			DBG_LOG("SensorType: ");
			for(int j = 0; j < GateWay->ConfigPara.CommUnitArray[i].SensorN; j++) {
				DBG_LOG("%04X ", GateWay->ConfigPara.CommUnitArray[i].SensorType[j]);
			}
			DBG_LOG("\r\n\r\n");
		}
	}
	if(CUCnt ==0) {
		DBG_LOG("No device is registered.\r\n");
	}
}

/*****************************************************************************************
* 函数名称: DebugCmdSetComm
* 功能描述: 设置网关与服务通讯方式
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdSetComm(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: comm	arg1\r\n");
		DBG_LOG("  brief --> Set gateway and service communication methods.\r\n");
		DBG_LOG("  arg1  --> para: (cat1, eth),Cat1 or ETH communication.\r\n\r\n");
		return;
	}
	
	if(strcmp(argv[1], "cat1") == 0) {
		GateWay->ConfigPara.Comm = CATONE_COMM;
		CAT1_ON();
		CatOneReset();
		DBG_LOG("Set the communication method to Cat1.\r\n");
		WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
	}
	else if(strcmp(argv[1], "eth") == 0) {
		DBG_LOG("Set the communication method to Eth.\r\n");
		if(GateWay->ConfigPara.Comm == CATONE_COMM) {
			CAT1_PWR_KEY_CLR();
			CatOneStop();
			rt_thread_delay(3000);
			CAT1_PWR_KEY_SET();
		}
	
		GateWay->ConfigPara.Comm = ETH_COMM;
		ETH_ON();
		WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
	}
	
}

/*****************************************************************************************
* 函数名称: DebugCmdSetCollTime
* 功能描述: 设置数据采集间隔
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdSetCollTime(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: sct para\r\n");
		DBG_LOG("  brief --> Set the data collection interval.\r\n");
		DBG_LOG("  arg1  --> para: (10~3600),Set the range from 10 to 3600 seconds.\r\n\r\n");
		return;
	}
	
	int time = atoi(argv[1]);
	if(time < 10 && time > 7200) {
		DBG_LOG("RS485 Cmd Para Error!\r\n");
		return;
	}
	GateWay->ConfigPara.CommUnitReadInterval = time;
	DBG_LOG("Set the collection time interval to %d seconds.\r\n", time);
	WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
}

/*****************************************************************************************
* 函数名称: DebugCmdReadHisData
* 功能描述: 读取历史数据
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdReadHisData(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	int StartIdx;
	int ReadNum;
	LogHeader_t Header;
	uint8_t *Data;
	char *AsciiData;
	int ret;
	int LogIdx;
	
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: his arg1 arg2\r\n");
		DBG_LOG("  brief --> Read historical data.\r\n");
		DBG_LOG("  arg1  --> start_num: The starting number of historical data.\r\n");
		DBG_LOG("            start_num = (all),Read all historical data.\r\n");
		DBG_LOG("  arg2  --> read_num: The number of historical data.\r\n\r\n");
		return;
	}
	
	if(strcmp(argv[1], "all") == 0) {
		StartIdx = 1;
		ReadNum = 0xffffffff;
	}
	StartIdx = atoi(argv[1]);
	ReadNum = atoi(argv[2]);
	if(StartIdx <= 0 || ReadNum <= 0) {
		DBG_LOG("His Cmd Para Error!\r\n");
		return;
	}
	
	if(StartIdx > 1) {
		ret = ReadLog(&Header, &Data, 1);
		if(ret == 0) {
			DBG_LOG("His Cmd Read Error!\r\n");
			return;
		}
		rt_free(Data);
		if(Header.LogIdx > StartIdx) {
			DBG_LOG("His Cmd StartIdx Error, Read First Log, StartIdx = %d!\r\n, Header.LogIdx");
			LogIdx = Header.LogIdx;
		}
		else {
			if(Header.LogIdx == StartIdx) {
				Header.LogEndAddr = 0;
			}
			LogIdx = StartIdx;
		}
		
	}
	else {
		LogIdx = 1;
	}
	while(ReadNum > 0) {
		ret = ReadLog(&Header, &Data, LogIdx);
		if(ret == 0)
			return;
		
		LogIdx++;
		ReadNum--;
		AsciiData = rt_malloc(ret * 2 + 2);
		HexToAscii(Data, AsciiData, ret);
		AsciiData[2 * ret] = 0;
		DBG_LOG("LogIdx: %d, Data %s\r\n", Header.LogIdx, AsciiData);
		rt_free(AsciiData);
		rt_free(Data);
	}
}

/*****************************************************************************************
* 函数名称: DebugCmdDelHisData
* 功能描述: 删除历史数据
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdDelHisData(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: fmt\r\n\
  brief --> Delete historical data.\r\n\r\n");
		return;
	}
	
	SavLogNum(0);
	DBG_LOG("The historical data has been deleted.\r\n");
}

/*****************************************************************************************
* 函数名称: DebugCmdGetHisInfo
* 功能描述: 获取历史数据信息
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdGetHisInfo(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	uint32_t LogN;
	LogHeader_t Header;
	uint8_t *Data;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: hinf\r\n\
  brief --> Obtain historical data information.\r\n\r\n");
		return;
	}
	
	LogN = ReadLogNum();
	if(LogN == 0) {
		DBG_LOG("LogN: 0\r\n");
		DBG_LOG("FirstLogIdx: 0\r\n");
		DBG_LOG("FirstLogAddr: %d\r\n", ReadFirstLogStartAddr());
		DBG_LOG("LastLogEndAddr: %d\r\n", ReadLastLogEndAddr());
		return;
	}
	Header.LogEndAddr = 0;
	int ret = ReadLog(&Header, &Data, 0);
	if(ret == 0) {
		DBG_LOG("Read log information error.\r\n");
		return;
	}
	rt_free(Data);
	DBG_LOG("LogN: %d\r\n", LogN - Header.LogIdx + 1);
	DBG_LOG("FirstLogIdx: %d\r\n", Header.LogIdx);
	DBG_LOG("FirstLogAddr: %d\r\n", ReadFirstLogStartAddr());
	DBG_LOG("LastLogEndAddr: %d\r\n", ReadLastLogEndAddr());
}

/*****************************************************************************************
* 函数名称: DebugCmdRestoreFactory
* 功能描述: 恢复出厂设置
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdRestoreFactory(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: res\r\n\
  brief --> Restore to factory.\r\n\r\n");
		return;
	}
	
	memset((uint8_t *)&GateWay->ConfigPara, 0x00, sizeof(GWConfigPara_t));
	WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
	DBG_LOG("Restore factory settings, GateWay Restart...\r\n");
	rt_thread_delay(1000);
	NVIC_SystemReset();
	while(1);
}

/*****************************************************************************************
* 函数名称: DebugCmdRestoreFactory
* 功能描述: 恢复出厂设置
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdReboot(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: reboot\r\n\
  brief --> System Reboot.\r\n\r\n");
		return;
	}
	
	DBG_LOG("GateWay Reboot...\r\n");
	rt_thread_delay(1000);
	NVIC_SystemReset();
	while(1);
}

/*****************************************************************************************
* 函数名称: DebugCmdSetSensorCollectTime
* 功能描述: 设置采集时间
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdSetCollectTime(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	uint8_t sData[50];
	uint8_t sLen;
	
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: sct arg1 arg2\r\n");
		DBG_LOG("  brief --> Set the sensor collection time.\r\n");
		DBG_LOG("  arg1  --> (cu, se)cu: CommUnit, Se: Sensor\r\n");
		DBG_LOG("  arg1  --> (10--7200)Second.\r\n\r\n");
		return;
	}
	
	int IntervalTime = atoi(argv[2]);
	
	if(IntervalTime < 10 && IntervalTime > 7200) {
		DBG_LOG("SCT Cmd Para Error!\r\n");
		return;
	}
	
	if(strcmp(argv[1], "cu") == 0) { 
		GateWay->ConfigPara.CommUnitReadInterval = IntervalTime;
		DBG_LOG(" Set the CommUnit collect time to %d seconds\r\n", IntervalTime);
		WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
	}
	else if(strcmp(argv[1], "se") == 0) {
		FrameHeader Header = (FrameHeader)sData;
		Header->Header = 0x7C;
		Header->SlvAddr = 00;
		Header->Cmd = RS485_SENSOR_CMD_SET_INV_TIME;
		//Header->DevType = 0;
		Header->PayloadLen = 2;
		
		sLen = sizeof(FrameHeader_t);
		
		sData[sLen++] = IntervalTime & 0x00ff;
		sData[sLen++] = (IntervalTime >> 8) & 0x00ff;
		
		uint16_t Check = CRC_Modbus(0xA001, sData, sLen);
		
		sData[sLen++] = Check & 0xff;
		sData[sLen++] = (Check >> 0x08) & 0x00ff;
		
		if(GateWay->ConfigPara.Rs485Ch1.Enable == true && GateWay->ConfigPara.Rs485Ch1.CommUnitEnable == true)
			GateWay->ConfigPara.Rs485Ch1.RS485Send(sData, sLen);
		if(GateWay->ConfigPara.Rs485Ch2.Enable == true && GateWay->ConfigPara.Rs485Ch2.CommUnitEnable == true)
			GateWay->ConfigPara.Rs485Ch2.RS485Send(sData, sLen);
		
		DBG_LOG("Set the Sensor collect time to %d seconds\r\n", IntervalTime);
	}
	else {
		DBG_LOG("SCT Cmd Para Error!\r\n");
	}
}

/*****************************************************************************************
* 函数名称: DebugCmdTimeSync
* 功能描述: 时间同步
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdTimeSync(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	uint32_t year, month, day, hour, min, sec;
	uint8_t ret;
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: time\r\n");
		DBG_LOG("  brief --> Time synchronization.\r\n");
		DBG_LOG("  args  --> (time YYYY-MM-DD,hh:mm:ss)Set system time.\r\n\r\n");
		return;
	}

	ret = sscanf(argv[1], "%d-%d-%d,%d:%d:%d\r\n", &year, &month, &day, &hour, &min, &sec);
	if(ret != 6 || year < 2022 || year > 2099 || month > 12 || day > 31 || hour > 60 || min > 60 || sec > 60) {
		DBG_LOG("Parameter error.\r\n");
		return;
	}
	else
		TimeSync2(year - 2000, month, day, hour, min, sec);
	
	DBG_LOG("Time Sync: ");
	uint32_t ctime = TimeTs(); 
	struct tm *stime;
  stime = localtime(&ctime);
  DBG_LOG("%d/",stime->tm_year + 1900);
  DBG_LOG("%d/",stime->tm_mon + 1);
  DBG_LOG("%d-",stime->tm_mday);
  DBG_LOG("%d:",stime->tm_hour);
  DBG_LOG("%d:",stime->tm_min);
  DBG_LOG("%d\r\n",stime->tm_sec);
}

/*****************************************************************************************
* 函数名称: DebugCmdTimeSync
* 功能描述: 查询内置通讯单元传感器
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
extern SensorCommPara_t SComm1Para;
extern SensorCommPara_t SComm2Para;
void DebugCmdQuerySensor(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: qs\r\n");
		DBG_LOG("  brief --> Query the sensors of the internal CommUnit.\r\n\r\n");
		return;
	}

	if(GateWay->ConfigPara.Rs485Ch1.Enable == true && GateWay->ConfigPara.Rs485Ch1.CommUnitEnable == true) {
		DBG_LOG("Query Rs485Ch1...\r\n");
		GateWay->ConfigPara.Rs485Ch1.QuerySensorFlag = true;
		GateWay->ConfigPara.Rs485Ch1.CUData.Para.SensorN = 0;
		memset(GateWay->ConfigPara.Rs485Ch1.CUData.Para.SensorType, 0x00, sizeof(GateWay->ConfigPara.Rs485Ch1.CUData.Para.SensorType));
		SComm1Para.SensorCnt = 0;
	}
	if(GateWay->ConfigPara.Rs485Ch2.Enable == true && GateWay->ConfigPara.Rs485Ch2.CommUnitEnable == true) {
		DBG_LOG("Query Rs485Ch2...\r\n");
		GateWay->ConfigPara.Rs485Ch2.QuerySensorFlag = true;
		GateWay->ConfigPara.Rs485Ch2.CUData.Para.SensorN = 0;
		memset(GateWay->ConfigPara.Rs485Ch2.CUData.Para.SensorType, 0x00, sizeof(GateWay->ConfigPara.Rs485Ch2.CUData.Para.SensorType));
		SComm2Para.SensorCnt = 0;
	}
}


/*****************************************************************************************
* 函数名称: DebugCmdSelDebugChannel
* 功能描述: 选择调试信息输出通道，
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdSelDebugChannel(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: dch\r\n");
		DBG_LOG("  brief --> Debug information output channel selection.\r\n");
		DBG_LOG("  args  --> (dbg|ch1|ch2) default: dbg\r\n");
		DBG_LOG("            dbg: On board debugging serial port.\r\n");
		DBG_LOG("            ch1: RS485 channel 1 serial port.\r\n");
		DBG_LOG("            ch2: RS485 channel 2 serial port.\r\n");
		DBG_LOG("  note  --> When selecting ch1 or ch2, the channel must enable an disable internal CommUnit function before it can be used.\r\n\r\n");
		return;
	}

	if(strcmp(argv[1], "dbg") == 0) {
		DBG_LOG("Select Debug Channel is dbg\r\n");
		GateWay->ConfigPara.DebugChannel = DEBUG_CH_DBG;
		WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
	}
	else if(strcmp(argv[1], "ch1") == 0) {
		if (GateWay->ConfigPara.Rs485Ch1.CommUnitEnable == true){
			DBG_LOG("RS485 channel 1 CommUnit function is not disabled\r\n");
			return;
		}
		DBG_LOG("Select Debug Channel is RS485_CH1\r\n");
		GateWay->ConfigPara.Rs485Ch1.BaudRate = 500000;
		GateWay->ConfigPara.Rs485Ch1.Enable = true;
		RS485Ch1_Config(GateWay->ConfigPara.Rs485Ch1.BaudRate);
		GateWay->ConfigPara.DebugChannel = DEBUG_CH_RS485_1;
		WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
	}
	
	else if(strcmp(argv[1], "ch2") == 0) {
		if (GateWay->ConfigPara.Rs485Ch2.CommUnitEnable == true){
			DBG_LOG("RS485 channel 2 CommUnit function is not disabled\r\n");
			return;
		}
		DBG_LOG("Select Debug Channel is RS485_CH2\r\n");
		GateWay->ConfigPara.Rs485Ch2.BaudRate = 500000;
		GateWay->ConfigPara.Rs485Ch2.Enable = true;
		RS485Ch2_Config(GateWay->ConfigPara.Rs485Ch2.BaudRate);
		GateWay->ConfigPara.DebugChannel = DEBUG_CH_RS485_2;
		WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
	}
}

/*****************************************************************************************
* 函数名称: DebugCmdSetSvr
* 功能描述: 设置服务器地址、端口
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
static void DebugCmdSetSvr(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	int IP[4];
	int port;
	
	if(argc < 3)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: arg1 arg2\r\n");
		DBG_LOG("  brief --> Set the server IP address and port for 4G communication.\r\n");
		DBG_LOG("  arg1  --> (xx.xx.xx.xx) ip\r\n");
		DBG_LOG("  arg2  --> port\r\n\r\n");
		return;
	}
	
	char *IpStr = argv[1];

	int ret = sscanf(IpStr, "%d.%d.%d.%d", &IP[0], &IP[1], &IP[2], &IP[3]);
	if(ret != 4)
		return;
	if(IP[0] > 0xff || IP[1] > 0xff || IP[2] > 0xff || IP[3] > 0xff)
		return;
	
	port = atoi(argv[2]);
	if(port > 0xffff)
		return;
	
	GateWay->ConfigPara.SvrAddr[0] = IP[0];
	GateWay->ConfigPara.SvrAddr[1] = IP[1];
	GateWay->ConfigPara.SvrAddr[2] = IP[2];
	GateWay->ConfigPara.SvrAddr[3] = IP[3];
	GateWay->ConfigPara.SvrPort = port;

	WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
	DBG_LOG("Set server ip and port completed.\r\n");
}

/*****************************************************************************************
* 函数名称: DebugCmdSetMac
* 功能描述: 设置MAC地址
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
static void DebugCmdSetMac(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	uint8_t mac[6];
	
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: mac arg1 arg2\r\n");
		DBG_LOG("  brief --> Set the server IP address and port for 4G communication.\r\n");
		DBG_LOG("  arg1  --> psw\r\n");
		DBG_LOG("  arg2  --> mac(xx-xx-xx-xx-xx-xx)\r\n\r\n");
		return;
	}
	
	if(strcmp(argv[1], "gxjt") != 0) {
		DBG_LOG("Password Error\r\n");
		return;
	}

	int ret = sscanf(argv[2], "%02X-%02X-%02X-%02X-%02X-%02X", 
									(int *)&mac[0], (int *)&mac[1], (int *)&mac[2], (int *)&mac[3], (int *)&mac[4], (int *)&mac[5]);
	if(ret != 6)
		return;
	
	memcpy(GateWay->ConfigPara.GwMac, mac, 6);
//	GateWay->ConfigPara.Rs485Ch1.CUData.Para.Mac[0][3] = GateWay->ConfigPara.GwMac[4];
//	GateWay->ConfigPara.Rs485Ch1.CUData.Para.Mac[0][4] = GateWay->ConfigPara.GwMac[5];
//	GateWay->ConfigPara.Rs485Ch2.CUData.Para.Mac[0][3] = GateWay->ConfigPara.GwMac[4];
//	GateWay->ConfigPara.Rs485Ch2.CUData.Para.Mac[0][4] = GateWay->ConfigPara.GwMac[5];
	WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
	DBG_LOG("Set gateway mac Address completed.\r\n");
}


/*****************************************************************************************
* 函数名称: DebugCmdGetPara
* 功能描述: 查看参数
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
static void DebugCmdGetPara(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(argc > 1) {
		if(strcmp(argv[1], "?") == 0) {
			DBG_LOG("Debug Cmd: para\r\n");
			DBG_LOG("  brief --> View gateway parameters.\r\n\r\n");
			return;
		}
	}
	DBG_LOG("\r\n**********************************************************\r\n");
	DBG_LOG("SoftWare V:%d.%d, HardWare V:%d.%d\r\n", SOFTWARE_VERSION / 10, SOFTWARE_VERSION % 10, HARDWARE_VERSION / 10, HARDWARE_VERSION % 10);
	DBG_LOG("GateWay MAC: %02X-%02X-%02X-%02X-%02X-%02X\r\n", 
					GateWay->ConfigPara.GwMac[0], GateWay->ConfigPara.GwMac[1], GateWay->ConfigPara.GwMac[2], GateWay->ConfigPara.GwMac[3], GateWay->ConfigPara.GwMac[4], GateWay->ConfigPara.GwMac[5]);
	DBG_LOG("Battery: %d%\r\n", GateWay->Battery);
	DBG_LOG("CommInf: %s\r\n", (GateWay->ConfigPara.Comm == CATONE_COMM) ? "Cat1" : "Eth");
	if(GateWay->ConfigPara.Comm == CATONE_COMM) {
		char Imei[20], Sim[32];
		CatReadImeiOrSim(Imei, Sim);
		DBG_LOG("Cat1 IMEI: %s\r\n", Imei);
		DBG_LOG("Cat1 SIM: %s\r\n", Sim); 
	}
	DBG_LOG("CommUnitReadInterval: %d\r\n", GateWay->ConfigPara.CommUnitReadInterval);
	DBG_LOG("Svr MAC: %02X-%02X-%02X-%02X-%02X-%02X\r\n", 
					GateWay->SvrMac[0], GateWay->SvrMac[1], GateWay->SvrMac[2], GateWay->SvrMac[3], GateWay->SvrMac[4], GateWay->SvrMac[5]);
	DBG_LOG("Svr IP: %d.%d.%d.%d\r\n", 
					GateWay->ConfigPara.SvrAddr[0], GateWay->ConfigPara.SvrAddr[1], GateWay->ConfigPara.SvrAddr[2], GateWay->ConfigPara.SvrAddr[3]);
	DBG_LOG("Svr Port: %d\r\n", GateWay->ConfigPara.SvrPort);
	DBG_LOG("Register Status: %d\r\n", GateWay->SvrRegFlag);
	DBG_LOG("RS485Ch1 Mac: %02X-%02X-%02X-%02X-%02X-%02X\r\n",
					GateWay->ConfigPara.Rs485Ch1.CUData.Para.Mac[0][0],GateWay->ConfigPara.Rs485Ch1.CUData.Para.Mac[0][1],
					GateWay->ConfigPara.Rs485Ch1.CUData.Para.Mac[0][2],GateWay->ConfigPara.Rs485Ch1.CUData.Para.Mac[0][3],
					GateWay->ConfigPara.Rs485Ch1.CUData.Para.Mac[0][4],GateWay->ConfigPara.Rs485Ch1.CUData.Para.Mac[0][5]);
	DBG_LOG("RS485Ch1: %s, ", (GateWay->ConfigPara.Rs485Ch1.Enable == true) ? "Enable" : "Disable");
	DBG_LOG("InCommUnit %s, ", (GateWay->ConfigPara.Rs485Ch1.CommUnitEnable == true) ? "Enable" : "Disable");
	DBG_LOG("Vout %s, ", (GateWay->ConfigPara.Rs485Ch1.Power == true) ? "Enable" : "Disable");
	DBG_LOG("Baudrate %d\r\n", GateWay->ConfigPara.Rs485Ch1.BaudRate);
	DBG_LOG("RS485Ch2 Mac: %02X-%02X-%02X-%02X-%02X-%02X\r\n",
					GateWay->ConfigPara.Rs485Ch2.CUData.Para.Mac[0][0],GateWay->ConfigPara.Rs485Ch2.CUData.Para.Mac[0][1],
					GateWay->ConfigPara.Rs485Ch2.CUData.Para.Mac[0][2],GateWay->ConfigPara.Rs485Ch2.CUData.Para.Mac[0][3],
					GateWay->ConfigPara.Rs485Ch2.CUData.Para.Mac[0][4],GateWay->ConfigPara.Rs485Ch2.CUData.Para.Mac[0][5]);
	DBG_LOG("RS485Ch2: %s, ", (GateWay->ConfigPara.Rs485Ch2.Enable == true) ? "Enable" : "Disable");
	DBG_LOG("InCommUnit %s, ", (GateWay->ConfigPara.Rs485Ch2.CommUnitEnable == true) ? "Enable" : "Disable");
	DBG_LOG("Vout %s, ", (GateWay->ConfigPara.Rs485Ch2.Power == true) ? "Enable" : "Disable");
	DBG_LOG("Baudrate %d\r\n", GateWay->ConfigPara.Rs485Ch2.BaudRate);
	
	DBG_LOG("Lora: ch %d, rp %d, fc %d\r\n", GateWay->ConfigPara.Lora.ucChannel, GateWay->ConfigPara.Lora.RegPreamble, GateWay->ConfigPara.Lora.FreqCent);
	
	struct tm *stime;
	uint32_t dwStamp = TimeTs();
  stime = localtime(&dwStamp);
  DBG_LOG("%d/",stime->tm_year + 1900);
  DBG_LOG("%d/",stime->tm_mon + 1);
  DBG_LOG("%d-",stime->tm_mday);
  DBG_LOG("%d:",stime->tm_hour);
  DBG_LOG("%d:",stime->tm_min);
  DBG_LOG("%d\r\n",stime->tm_sec);
	DBG_LOG("**********************************************************\r\n");
}

/*****************************************************************************************
* 函数名称: DebugCmdCali
* 功能描述: 校准传感器
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
static void DebugCmdCali(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	uint8_t mac[6];
	uint8_t Rs485Cmd[8] = {0x7a, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x7d};
	uint8_t CommUnitCmd[20];
	CommUnitFrameHeader CUFrame;
	
	if(argc < 2) 
		return;
	
	if(argc > 1) {
		if(strcmp(argv[1], "?") == 0) {
			DBG_LOG("Debug Cmd: cali\r\n");
			DBG_LOG("  brief --> Calibrate the sensor.\r\n\r\n");
			DBG_LOG("  arg1  --> mac: communication unit Mac address.\r\n");
			DBG_LOG("            mac = (XX-XX-XX-XX-XX-XX), Calibrate specified MAC communication unit.\r\n");
			DBG_LOG("            mac = (all), Calibrate all communication units.\r\n\r\n");
			return;
		}
	}
	
	CUFrame = (CommUnitFrameHeader)CommUnitCmd;
	CUFrame->Header = 0x7B;
	memcpy(CUFrame->GWMac, GateWay->ConfigPara.GwMac, 6);
	memset(CUFrame->DevMac, 0x00, 6);
	CUFrame->Cmd = 0x01;
	//CUFrame->DevType = 0x8002;
	CUFrame->PayloadLen = 0;
	uint16_t crc16 = CRC_Modbus(0xA001, CommUnitCmd, sizeof(CommUnitFrameHeader_t));
	CommUnitCmd[sizeof(CommUnitFrameHeader_t)] = crc16 & 0x00ff;
	CommUnitCmd[sizeof(CommUnitFrameHeader_t) + 1] = (crc16 >> 8) & 0x00ff;
	
	if(strcmp(argv[1], "all") == 0) {
		if(GateWay->ConfigPara.Rs485Ch1.Enable == true) {
			if(GateWay->ConfigPara.Rs485Ch1.CommUnitEnable == true) {
				GateWay->ConfigPara.Rs485Ch1.RS485Send(Rs485Cmd, 8);
			}
			else {
				GateWay->ConfigPara.Rs485Ch1.RS485Send(CommUnitCmd, sizeof(CommUnitFrameHeader_t) + 2);
			}
		}
		if(GateWay->ConfigPara.Rs485Ch2.Enable == true) {
			if(GateWay->ConfigPara.Rs485Ch2.CommUnitEnable == true) {
				GateWay->ConfigPara.Rs485Ch2.RS485Send(Rs485Cmd, 8);
			}
			else {
				GateWay->ConfigPara.Rs485Ch2.RS485Send(CommUnitCmd, sizeof(CommUnitFrameHeader_t) + 2);
			}
		}
		
		for(int i = 0; i < COMMUNIT_NUM_MAX; i++)//参数遍历
		{
			if(GateWay->ConfigPara.CommUnitArray[i].RegFlag == true)
				GateWay->ConfigPara.CommUnitArray[i].CailFlag = true;//校准置位，等待下次此MAC主设备上传数据时下发校准指令（低功耗）
		}
		//Sx1276LoRaSendBuffer(CommUnitCmd, sizeof(CommUnitFrameHeader_t) + 2);//低功耗模式下不用下发
		
		DBG_LOG("Calibrate all communication units.\r\n");
		return;
	}
	
	int ret = sscanf(argv[1], "%x-%x-%x-%x-%x-%x", 
									(int *)&mac[0], (int *)&mac[1], (int *)&mac[2], (int *)&mac[3], (int *)&mac[4], (int *)&mac[5]);
	if(ret != 6) {
		DBG_LOG("Cali Cmd Para Error!\r\n");
		return;
	}
	
	if(memcmp(mac, GateWay->ConfigPara.Rs485Ch1.CUData.Para.Mac[0], 6) == 0) {
		if(!GateWay->ConfigPara.Rs485Ch1.Enable || !GateWay->ConfigPara.Rs485Ch1.CommUnitEnable) {
			DBG_LOG("Internal communication unit 1 is turned off!\r\n");
			return;
		}
		GateWay->ConfigPara.Rs485Ch1.RS485Send(Rs485Cmd, 8);
		DBG_LOG("Calibrate internal communication unit 1!\r\n");
		return;
	}
	
	if(memcmp(mac, GateWay->ConfigPara.Rs485Ch2.CUData.Para.Mac[0], 6) == 0) {
		if(!GateWay->ConfigPara.Rs485Ch2.Enable || !GateWay->ConfigPara.Rs485Ch2.CommUnitEnable) {
			DBG_LOG("Internal communication unit 2 is turned off!\r\n");
			return;
		}
		GateWay->ConfigPara.Rs485Ch2.RS485Send(Rs485Cmd, 8);
		DBG_LOG("Calibrate internal communication unit 2!\r\n");
	}
	
	ret = CheckCommUnitReg(GateWay, mac);
	if(ret < 0) {
		DBG_LOG("The CommUnit was not found!\r\n");
		return;
	}
	
	memcpy(CUFrame->DevMac, mac, 6);
	crc16 = CRC_Modbus(0xA001, CommUnitCmd, sizeof(CommUnitFrameHeader_t));
	CommUnitCmd[sizeof(CommUnitFrameHeader_t)] = crc16 & 0x00ff;
	CommUnitCmd[sizeof(CommUnitFrameHeader_t) + 1] = (crc16 >> 8) & 0x00ff;
	
	if(mac[2] == 0x01) {	//LORA通讯
		if(GateWay->ConfigPara.CommUnitArray[ret].RegFlag == true)
				GateWay->ConfigPara.CommUnitArray[ret].CailFlag = true;//校准置位，等待下次此MAC主设备上传数据时下发校准指令（低功耗）
			DBG_LOG("Wait for the device to respond. Mac:%02X-%02X-%02X-%02X-%02X-%02X\r\n",
			CUFrame->DevMac[0], CUFrame->DevMac[1], CUFrame->DevMac[2], CUFrame->DevMac[3], CUFrame->DevMac[4], CUFrame->DevMac[5]);
		//Sx1276LoRaSendBuffer(CommUnitCmd, sizeof(CommUnitFrameHeader_t) + 2);
	}
	else if(mac[2] == 0x02) { //RS485通讯
		if(GateWay->ConfigPara.Rs485Ch1.Enable == true && !GateWay->ConfigPara.Rs485Ch1.CommUnitEnable) {
			GateWay->ConfigPara.Rs485Ch1.RS485Send(Rs485Cmd, sizeof(CommUnitFrameHeader_t) + 2);
			DBG_LOG("Calibrate CommUnit: %s!\r\n", argv[1]);
		}
		else if(GateWay->ConfigPara.Rs485Ch2.Enable == true && !GateWay->ConfigPara.Rs485Ch2.CommUnitEnable) {
			GateWay->ConfigPara.Rs485Ch2.RS485Send(Rs485Cmd, sizeof(CommUnitFrameHeader_t) + 2);
			DBG_LOG("Calibrate CommUnit: %s!\r\n", argv[1]);
		}
		else {
			DBG_LOG("Communication unit type error.\r\n");
		}
	}
}
/*****************************************************************************************
* 函数名称: DebugLaserConfig
* 功能描述: 激光控制
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
static void DebugLaserConfig(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	uint8_t mac[6];
	uint8_t Rs485Cmd[8] = {0x7a, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x7d};
	uint8_t CommUnitCmd[20];
	uint8_t len;
	uint16_t crc16;
	CommUnitFrameHeader CUFrame;
	
	if(argc < 2) 
		return;
	
	if(argc > 1) {
		if(strcmp(argv[1], "?") == 0) {
			DBG_LOG("Debug Cmd: laser\r\n");
			DBG_LOG("  brief --> Control laser cutting.\r\n\r\n");
			DBG_LOG("  arg1  --> mac: communication unit Mac address.\r\n");
			DBG_LOG("            mac = (XX-XX-XX-XX-XX-XX), Control specified MAC communication unit.\r\n");
			DBG_LOG("  arg2  --> state: on/off, Turn on or off the laser.\r\n\r\n");
			return;
		}
	}
	
	int ret = sscanf(argv[1], "%x-%x-%x-%x-%x-%x", 
									(int *)&mac[0], (int *)&mac[1], (int *)&mac[2], (int *)&mac[3], (int *)&mac[4], (int *)&mac[5]);
	if(ret != 6) {
		DBG_LOG("Control laser Cmd Para Error!\r\n");
		return;
	}
	
	CUFrame = (CommUnitFrameHeader)CommUnitCmd;
	CUFrame->Header = 0x7B;
	memcpy(CUFrame->GWMac, GateWay->ConfigPara.GwMac, 6);
	memcpy(CUFrame->DevMac, mac, 6);
	CUFrame->Cmd = COMM_UNIT_CMD_CONT_LASER;
	//CUFrame->DevType = 0x8002;
	CUFrame->PayloadLen = 1;
	
	if(strcmp(argv[2], "on") == 0 || strcmp(argv[2], "off") == 0)
	{
		if(memcmp(mac, GateWay->ConfigPara.Rs485Ch1.CUData.Para.Mac[0], 6) == 0) {
			if(!GateWay->ConfigPara.Rs485Ch1.Enable || !GateWay->ConfigPara.Rs485Ch1.CommUnitEnable) {
				DBG_LOG("Internal communication unit 1 is turned off!\r\n");
				return;
			}
			GateWay->ConfigPara.Rs485Ch1.RS485Send(Rs485Cmd, 8);
			DBG_LOG("Control internal communication unit 1!\r\n");
			return;
		}
	
		if(memcmp(mac, GateWay->ConfigPara.Rs485Ch2.CUData.Para.Mac[0], 6) == 0) {
			if(!GateWay->ConfigPara.Rs485Ch2.Enable || !GateWay->ConfigPara.Rs485Ch2.CommUnitEnable) {
				DBG_LOG("Internal communication unit 2 is turned off!\r\n");
				return;
			}
			GateWay->ConfigPara.Rs485Ch2.RS485Send(Rs485Cmd, 8);
			DBG_LOG("Control internal communication unit 2!\r\n");
		}
	
		ret = CheckCommUnitReg(GateWay, mac);
		if(ret < 0) {
			DBG_LOG("The CommUnit was not found!\r\n");
			
		}
	}
	else
	{
		DBG_LOG("Parameter error!\r\n");
		return;
	}
		
	
	len = sizeof(CommUnitFrameHeader_t);
	bool onoff;
	if(strcmp(argv[2], "on") == 0)
	{
		onoff = true;
		CommUnitCmd[len++] = onoff;
	}
	else if(strcmp(argv[2], "off") == 0)
	{
		onoff = false;
		CommUnitCmd[len++] = onoff;
	}
	crc16 = CRC_Modbus(0xA001, CommUnitCmd, len);
	CommUnitCmd[len++] = crc16 & 0x00ff;
	CommUnitCmd[len++] = (crc16 >> 8) & 0x00ff;
	
	if(mac[2] == 0x01) {	//LORA通讯，低功耗模式不用主动下发
		if(GateWay->ConfigPara.CommUnitArray[ret].RegFlag == true)
		{
			if(onoff == true)
			{
				GateWay->ConfigPara.CommUnitArray[ret].ContLaser = true;//控制置位，等待下次此MAC主设备上传数据时下发校准指令（低功耗）
				DBG_LOG("Wait for the device to respond. Mac:%02X-%02X-%02X-%02X-%02X-%02X\r\n",
							CUFrame->DevMac[0], CUFrame->DevMac[1], CUFrame->DevMac[2], CUFrame->DevMac[3], CUFrame->DevMac[4], CUFrame->DevMac[5]);
				GateWay->ConfigPara.CommUnitArray[ret].LaserOnOff = onoff;
			}
			else if(onoff == false)
			{
				GateWay->ConfigPara.CommUnitArray[ret].ContLaser = false;
				GateWay->ConfigPara.CommUnitArray[ret].LaserOnOff = onoff;
				Sx1276LoRaSendBuffer(CommUnitCmd, len);//直接发
			}	
		}
	}
	else if(mac[2] == 0x02) { //RS485通讯
		if(GateWay->ConfigPara.Rs485Ch1.Enable == true && !GateWay->ConfigPara.Rs485Ch1.CommUnitEnable) {
			GateWay->ConfigPara.Rs485Ch1.RS485Send(Rs485Cmd, len);
			DBG_LOG("Control RS485 laser CommUnit: %s!\r\n", argv[1]);
		}
		else if(GateWay->ConfigPara.Rs485Ch2.Enable == true && !GateWay->ConfigPara.Rs485Ch2.CommUnitEnable) {
			GateWay->ConfigPara.Rs485Ch2.RS485Send(Rs485Cmd, len);
			DBG_LOG("Control RS485 laser CommUnit: %s!\r\n", argv[1]);
		}
		else {
			DBG_LOG("Communication unit type error.\r\n");
		}
	}
}

/*****************************************************************************************
* 函数名称: DebugCmdLPConfig
* 功能描述: 低功耗参数配置
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
static void DebugCmdLPConfig(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	uint16_t CollectInterval;		//采集时间间隔
	uint16_t ReportInterval;		//上报时间间隔
	uint8_t ERInterval;				//紧急上报时间间隔
	uint8_t ERTime;						//紧急上报时长
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: lpcfg arg1 arg2 arg3 arg4\r\n");
		DBG_LOG("  brief --> Configure low-power device parameters.\r\n");
		DBG_LOG("  arg1  --> Collect interval\r\n");
		DBG_LOG("  arg2  --> Report interval\r\n");
		DBG_LOG("  arg3  --> Emergency reporting interval\r\n");
		DBG_LOG("  arg4  --> Emergency reporting time\r\n\r\n");
		return;
	}
	
	if(argc < 5)
		return;
	
	
	CollectInterval = atoi(argv[1]);
	if(CollectInterval < 30 || CollectInterval > 7200) {
		DBG_LOG("CollectInterval Para Error!\r\n");
		return;
	}
	
	ReportInterval = atoi(argv[2]);
	if(ReportInterval < 5 || ReportInterval > 720) {
		DBG_LOG("ReportInterval Para Error!\r\n");
		return;
	}
	
	ERInterval = atoi(argv[3]);
	if(ERInterval < 1 || ERInterval > 5) {
		DBG_LOG("ERInterval Para Error!\r\n");
		return;
	}
	
	ERTime = atoi(argv[4]);
	if(ERTime < 10 || ERTime > 120) {
		DBG_LOG("ERTime Para Error!\r\n");
		return;
	}
	
	for(int i = 0; i < COMMUNIT_NUM_MAX; i++) {
		if(GateWay->ConfigPara.CommUnitArray[i].RegFlag) {
			GateWay->ConfigPara.CommUnitArray[i].CollectInterval = CollectInterval;
			GateWay->ConfigPara.CommUnitArray[i].ReportInterval = ReportInterval;
			GateWay->ConfigPara.CommUnitArray[i].ERInterval = ERInterval;
			GateWay->ConfigPara.CommUnitArray[i].ERTime = ERTime;
			GateWay->ConfigPara.CommUnitArray[i].ConfigFlag = true;
		}
	}
	WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
	DBG_LOG("The low-power device is configured.\r\n");
}

/*****************************************************************************************
* 函数名称: DebugCmdLPConfig
* 功能描述: 低功耗参数配置
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
static void DebugLoraConfig(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	if(argc < 2)
		return;
	
	if(strcmp(argv[1], "?") == 0) {
		DBG_LOG("Debug Cmd: Lora arg1 arg2\r\n");
		DBG_LOG("  brief --> Configure Lora parameters.\r\n");
		DBG_LOG("  arg1  --> ch: Channel--para=(0~16)\r\n");
		DBG_LOG("            pw: Power--para=(0~20)\r\n");
		DBG_LOG("            bw: SignalBw--para=(0~9)\r\n");
		DBG_LOG("            sf: SpreadFactor--para=(6~12)\r\n");
		DBG_LOG("            ec: ErrorCoding--para=(1~4)\r\n");
		DBG_LOG("            rp: RegPreamble--para=(1~32)\r\n");
		DBG_LOG("            o: on/off\r\n");
		DBG_LOG("  arg2  --> para\r\n");

		return;
	}
	
	if(strcmp(argv[1], "o") == 0) {
		if(strcmp(argv[2], "on") == 0) {
			GateWay->ConfigPara.Lora.OnOff = true;
			LORA_POW_ON();
			DBG_LOG(" Lora Power On!\r\n");
		}
		else if(strcmp(argv[2], "off") == 0) {
			GateWay->ConfigPara.Lora.OnOff = false;
			LORA_POW_OFF();
			DBG_LOG(" Lora Power Off!\r\n");
		}
	}
	
	if(strcmp(argv[1], "ch") == 0) {
		int ch = atoi(argv[2]);
		if(LoraSetChannel(ch)) {
			GateWay->ConfigPara.Lora.ucChannel = ch;
			DBG_LOG(" Lora Channel is configured successfully!\r\n");
		}
		else {
			DBG_LOG("Lora Para Error!\r\n");
			return;
		}
	}
	
	if(strcmp(argv[1], "pw") == 0) {
		int pow = atoi(argv[2]);
		if(LoraSetPower(pow)) {
			GateWay->ConfigPara.Lora.ucPower = pow;
			DBG_LOG(" Lora Power is configured successfully!\r\n");
		}
		else {
			DBG_LOG("Lora Para Error!\r\n");
			return;
		}
	}
	
	if(strcmp(argv[1], "bw") == 0) {
		int bw = atoi(argv[2]);
		if(LoraSetSignalBw(bw)) {
			GateWay->ConfigPara.Lora.SignalBw = bw;
			DBG_LOG(" Lora SignalBw is configured successfully!\r\n");
		}
		else {
			DBG_LOG("Lora Para Error!\r\n");
			return;
		}
	}
	
	if(strcmp(argv[1], "sf") == 0) {
		int sf = atoi(argv[2]);
		if(LoraSetSpreadFactor(sf)) {
			GateWay->ConfigPara.Lora.SpreadFactor = sf;
			DBG_LOG(" Lora SpreadFactor is configured successfully!\r\n");
		}
		else {
			DBG_LOG("Lora Para Error!\r\n");
			return;
		}
	}

	if(strcmp(argv[1], "ec") == 0) {
		int ec = atoi(argv[2]);
		if(LoraSetErrorCoding(ec)) {
			GateWay->ConfigPara.Lora.ErrorCoding = ec;
			DBG_LOG(" Lora ErrorCoding is configured successfully!\r\n");
		}
		else {
			DBG_LOG("Lora Para Error!\r\n");
			return;
		}
	}
	
	if(strcmp(argv[1], "rp") == 0) {
		int rp = atoi(argv[2]);
		if(LoraSetRegPreamble(rp)) {
			GateWay->ConfigPara.Lora.RegPreamble = rp;
			DBG_LOG(" Lora RegPreamble is configured successfully!\r\n");
		}
		else {
			DBG_LOG("Lora Para Error!\r\n");
			return;
		}
	}
	if(GateWay->ConfigPara.Lora.OnOff)
		LoraInit();
	WritePara((uint8_t *)&GateWay->ConfigPara, sizeof(GWConfigPara_t));
	DBG_LOG("Lora reinitializes.\r\n");
}


/*****************************************************************************************
* 函数名称: DebugCmdHelp
* 功能描述: 调试命令帮助信息
* 参    数: argc, 输入参数数量
						argv, 输入参数
* 返 回 值: 无
*****************************************************************************************/
void DebugCmdHelp(int argc, char *argv[])
{
	DBG_LOG("\r\n");
	uint8_t Data[100];
	uint8_t len;
	
	len = strlen("main ?\r\n");
	memcpy(Data, "main ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("cat1 ?\r\n");
	memcpy(Data, "cat1 ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("rs485 ?\r\n");
	memcpy(Data, "rs485 ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("cudel ?\r\n");
	memcpy(Data, "cudel ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("culs ?\r\n");
	memcpy(Data, "culs ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("comm ?\r\n");
	memcpy(Data, "comm ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("sct ?\r\n");
	memcpy(Data, "sct ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("his ?\r\n");
	memcpy(Data, "his ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("fmt ?\r\n");
	memcpy(Data, "fmt ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("hinf ?\r\n");
	memcpy(Data, "hinf ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
//	len = strlen("res ?\r\n");
//	memcpy(Data, "res ?\r\n", len);
//	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("sct ?\r\n");
	memcpy(Data, "sct ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("time ?\r\n");
	memcpy(Data, "time ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("svr ?\r\n");
	memcpy(Data, "svr ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("qs ?\r\n");
	memcpy(Data, "qs ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("dch ?\r\n");
	memcpy(Data, "dch ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
	
	len = strlen("para ?\r\n");
	memcpy(Data, "para ?\r\n", len);
	DebugAnalyze(GateWay, Data, len);
}

const DBGFunType DebugFun[DEBUG_CMD_CNT] = {
	"help",				DebugCmdHelp,
	"main",				DebugCmdMainOnOff,
	"cat1",				DebugCmdCat1OnOff,
	"rs485",				DebugCmdRS485Ctrl,
	"cudel",				DebugCmdDelCommUnit,
	"culs",				DebugCmdLsCommUnit,
	"comm",				DebugCmdSetComm,
	"sct",				DebugCmdSetCollectTime,
//	"his",				DebugCmdReadHisData,
	"fmt",				DebugCmdDelHisData,
	"hinf",				DebugCmdGetHisInfo,
//	"res",				DebugCmdRestoreFactory,
	"time",				DebugCmdTimeSync,
	"qs",					DebugCmdQuerySensor,
	"dch",				DebugCmdSelDebugChannel,
	"svr",				DebugCmdSetSvr,
	"mac",				DebugCmdSetMac,
	"para",				DebugCmdGetPara,
	"cali",				DebugCmdCali,
	"laser",				DebugLaserConfig,
	"lpcfg",				DebugCmdLPConfig,
	"lora",				DebugLoraConfig,
	"reboot",			DebugCmdReboot,
};
