REST API arguments - is there a better way?

Late post. I can’t find in the docs if this is resolved or not, though.

I think @ScruffR is onto something with strtok. The following code works dandy for me:

/*
 * This funtion will turn on a selected digital output pin.
 * Usage - "args=ON,7" will enable pin 7
 */
int parseArgs(String command) {
    int    ledPin = -1;
    char * params = new char[command.length() + 1];

    strcpy(params, command.c_str());
    char * param1 = strtok(params, ",");
    char * param2 = strtok(NULL, ",");

    if(param1 != NULL &&  /* Make sure parameters are present */
       param2 != NULL &&
       !strcmp(param1, "ON")) /* strcmp will return 0 if the args match */
    {
      ledPin = atoi(param2);
      if(ledPin >= 0 && ledPin < 8) /* Check for a valid digital pin */
      {
        pinMode(ledPin, OUTPUT);
        digitalWrite(ledPin, HIGH);
        return 0;
      }
    }
    return -1;
}

That code seems cleaner and a bit more flexible to me, but I think that’s just a matter of personal preference. It may even be a bit overkill if you have a small and clearly defined set of commands.

Hope this helps.

1 Like