Question: Functions

I’m having problem with displaying first string from a set.
Let say I call this command in myFunction: a_b_c_d

Only “b”, “c” and “d”" gets published. Can’t get “a” to display.

Here is my code. Thank you in advance.

int myFunction(String command);

void setup()
{
    Particle.function("myFunction", myFunction);
}

void loop()
{
}

int myFunction(String command)
{
    int counter = 0;

    char command_lenght[16];
    int string_lenght = 16;
    strncpy(command_lenght, command, size_t(string_lenght));
    string_lenght = (strlen(command_lenght) + 1);
    char command_input[string_lenght];
    Particle.publish(String(command), (String("Size: ") + String(string_lenght)), PRIVATE);
    delay(2000);

    strncpy(command_input, command, size_t(string_lenght));
    char *token = strtok(command_input, "_");

    while (token != NULL)
    {
        counter++;
        token = strtok(NULL, "_");

        String variable = (String("Variable #") + String(counter));

        if (token != NULL)
        {

            Particle.publish(variable, token, PRIVATE);
            delay(2000);
        }
    }
    return 1;
}

I would suggest moving these two lines from the beginning of the while loop to the end of the while loop. Since you are calling strtok twice before your first publish it would make sense that a is skipped.

1 Like

There also seems to be a lot of work that appears superfluous

BTW, why return a non-interesting 1 when your code already produces a more useful value counter?
In addition, avoid delaying your Particle.function() for more than three seconds (if at all) as the cloud would expect to hear back from the call rather quickly before assuming a timeout error.

This would be a more straight forward way to do (pretty much) the same thing

int myFunction(const char* command) {
  char cmd[strlen(command) + 1];
  char msg[128];
  int  count = 0;
  
  strncpy(cmd, command, sizeof(cmd));                       // non-const copy is required for strtok()
  snprintf(msg, sizeof(msg), "{\"size\": %d", strlen(cmd)); // avoid String concatenations wherever possible
  for(char* tok = strtok(cmd, "_"); tok; tok = strtok(NULL, "_")) 
    snprintf(msg, sizeof(msg), "%s, \"var%d\": \"%s\"", msg, ++count, tok);
  strncat(msg, "}", sizeof(msg));                           // close the JSON string
  
  Particle.publish(command, msg, PRIVATE);                  // only one publish for the entire result set
  return count;
}

(this produces a JSON string for easy consumption on the receiving end)

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.