In depth analysis based on C language instruction

  • 2020-04-02 00:45:36
  • OfStack

This is only part of the instruction parsing, but this is the most The core part of the . The full instruction is: AT+REG[admin][2][00:0c :29:AA:0B:A7].

 

#include <stdio.h>
#include <string.h>
//Saves the structure of the parameter
typedef struct parameters
{
 char str1[20];  //First parameter
 char str2[20];  //Second parameter
 char str3[20];  //Third parameter
}parameters_t;
 

//The return value is the number of parameters obtained, and -1 indicates an instruction error
int Getparams(char* data, parameters_t* pparam)
{
 int len = 0;
 memset(pparam, 0, sizeof(parameters_t));

 //First parameter
 {
  //If null or newline, there is no parameter 
  if( 0 == *data || 'n' == *data)
  {
   _ERROR("no parameter!");
   return 0;
  } 
  //If it is a '[' character, then there is an argument 
  if( strncmp(data, "[", 1) )
  {
   _ERROR("first parameter err:  can't find '['");
   return -1;
  }
  data += 1;
  //If the '[' is followed by a ']' ending character, the argument is valid 
  if( !strstr(data, "]") )
  {
   _ERROR("first parameter err:  can't find ']'");
   return -1;
  }
  // get First parameter The length of the 
  len = strstr(data, "]") - data;
  if(20 <= len)
  {
   _ERROR("param one is too long!");
   return -1;
  }
  // get First parameter
  strncpy(pparam->str1, data, len);
  //printf("str1 : %sn", pparam->str1);
 }

 //Second parameter
 {
  data += (len + 1);
  //If null, there is only one parameter 
  if( 0 == *data || 'n' == *data)
  {
   //printf("only one parameter!n");
   return 1;
  } 
  //If it is a '[' character, then there is an argument 
  if( strncmp(data, "[", 1) )
  {
   _ERROR("second parameter err:  can't find '['");
   return -1;
  }
  data += 1;
  //If the '[' is followed by a ']' ending character, the argument is valid 
  if( !strstr(data, "]") )
  {
   _ERROR("second parameter err:  can't find ']'"); 
   return -1;
  }
  len = strstr(data, "]") - data;
  if(20 <= len)
  {
   _ERROR("param two is too long!");
   return -1;
  }  
  // get Second parameter
  strncpy(pparam->str2, data, len);
  //printf("str2 : %sn", pparam->str2);
 }

 //Third parameter
 {
  data += (len + 1);
  if( 0 == *data || 'n' == *data)
  {
   //printf("only two parameter!n");
   return 2;
  } 
  if( strncmp(data, "[", 1) )
  {
   _ERROR("third parameter err:  can't find '['");
   return -1;
  }
  data += 1;
  if( !strstr(data, "]") )
  {
   _ERROR("third parameter err:  can't find ']'"); 
   return -1;
  }
  len = strstr(data, "]") - data;
  if(20 <= len)
  {
   _ERROR("param three is too long!");
   return -1;
  }  
  strncpy(pparam->str3, data, len);
  //printf("str3 : %sn", pparam->str3); 
 }

 data += (len + 1);
 if( 0 != *data && 'n' != *data)
 {
  _ERROR("too much parameter!");
  return -1;
 }  

 return 3;
}
 

This is the instruction (string) parsing to get the parameters.

Related articles: