/** ****************************************************************************** * @file cmd.c * @author He Fahong * @version V1 * @date 1/3/2012 * @brief 封装的用于通讯具体处理的函数命令。 ****************************************************************************** * @note * @copy * */ enum CMDTYPE {CMDTYPE_SETTING, CMDTYPE_POLLING, CMDTYPE_SAVING, CMDTYPE_CHANGING, CMDTYPE_ERROR}; //inputcmdlength是实际经过rs232传输的命令字节的个数, 从命令开始到结束符'\r'结束, 长度包含结束符在内 uint8_t Cmd_CheckRS232Cmd(char * inputcmdstr, uint8_t inputcmdstrlength) { char modulestr[MaxComStrLength] = "\0"; char paramstr[MaxComStrLength] = "\0"; char valuestr[MaxComStrLength] = "\0"; uint8_t addr = 0; uint8_t syntaxlevel = 0; enum CMDTYPE cmdtype = ProtocolAnalysis(inputcmdstr, inputcmdstrlength, modulestr, paramstr, valuestr, &addr, &syntaxlevel); if(cmdtype == CMDTYPE_SETTING) //设置 { //这里写入自己的处理程序 } else if(cmdtype == CMDTYPE_POLLING) //查询 { //这里写入自己的处理程序 } else if(cmdtype == CMDTYPE_SAVING) //保存 { //这里写入自己的处理程序 } else if(cmdtype == CMDTYPE_CHANGING) //改变 { //这里写入自己的处理程序 } else { //这里写入自己的处理程序 } return 1; } //通用的完善协议解析程序 //赋值三个字符串,地址,syntaxlevel(0,最简模式;1,带地址,2,带校验) //返回,cmd_type enum CMDTYPE ProtocolAnalysis(uint8_t * comstr, int comstrlength, uint8_t* modulestr, uint8_t* paramstr, uint8_t* valuestr, uint8_t * addr, uint8_t *syntaxlevel) { int16_t ix; //有符号数,防止负数变成正数,导致长度或定位计算错误 uint8_t colonflag = 0; //是否有冒号的标志 uint8_t modulelength = 0; uint8_t paramlength = 0; uint8_t valuelength = 0; uint8_t addrstartpos = 0; //地址字符串起始位置,@符号的下一个字符位置 uint8_t checkstartpos = 0; //校验字符串起始位置,#符号的下一个字符位置 *syntaxlevel = 0; enum CMDTYPE cmdtype = CMDTYPE_ERROR; //首先判断最后一位是否是'\r' if(comstr[comstrlength - 1] != '\r') return CMDTYPE_ERROR; else comstr[comstrlength - 1] = '\0'; //格式分析 for (ix=0; ix= 1) //有地址 { *addr = atoi(comstr + addrstartpos); //遇到#符号或者\0或者\r都会停止转换,strtol同atoi if(*syntaxlevel >= 2) //不仅有目标地址,还有校验 { //进行校验 if(CheckSum(comstr, checkstartpos) != strtol(comstr + checkstartpos, NULL, 16)) //校验不正确 return CMDTYPE_ERROR; } //获取参数字符串的长度 valuelength = addrstartpos - paramlength - 2; paramlength = paramlength - modulelength - 1; } else //无地址 { //获取参数字符串的长度 valuelength = (comstrlength - 1) - paramlength - 1; paramlength = paramlength - modulelength - 1; } //根据字符串长度来赋值,是否可以改成字符串拷贝函数 for (ix=0;ix