Unable to extract payload of type string shipped to Arduino via Device Command


#1

I am sending a string as payload with device command from Losant to nodemcu. Serial monitor shows nothing.

image

Where it shows curly braces, it should be displaying a string (“Just about anything!”).

I have verified the following:

  1. The device is connected
  2. It receives the command
  3. The device log shows message sent with the string.

Code compiles but doesn’t work as intended.

// Called whenever the device receives a command from the Losant platform.
void handleCommand(LosantCommand *command) {
  Serial.print("Command received: ");
  Serial.println(command->name);
  
  if(strcmp(command->name, "toggle") == 0) {
    toggle();
  }


  // TRY 1: Print payload using printTo
  JsonObject& payload = *command->payload;
  Serial.println("Received payload: ");
  payload.printTo(Serial);    // Gives {}
  Serial.println();

  // TRY 2: Serialize payload and print
  char json[200];  
  StaticJsonBuffer<200> jsonBuffer;
  payload.printTo(json, sizeof(json));
  Serial.print(json);         // Gives {}

}

image


#2

Apologies for the confusion here. Our Arduino client is expecting JSON data within commands. Since that string is not valid JSON, the client is failing to parse the command payload, so nothing is returned.

The fastest workaround would be to make your payload JSON. Something like { "value" : "Just about any thing!" }. You can then access that field using the following:

JsonObject& payload = *command->payload;
Serial.println(payload["value"]);

I created an issue on the repo to add a new field to the command object for the raw string for cases like this.


#3

Also, make sure to increase the max mqtt packet size if you’re sending commands. Instructions here: