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);

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

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

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

        if (token != NULL)

            Particle.publish(variable, token, PRIVATE);
    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)