I am having problems using a command payload to define a temperature setpoint. I want to remotely be able to define the temperature my fridge comes on and goes off.
After much trial and error I have a simple short message and payload being delivered.
Losant setup
However I cannot parse the Json file within Arduino on my Adafruit ESP8266. I am a noob with Json.
I have tried all sort of stuff including trying to convert to float but no success
/******************************* Global Variables *****************************/
int8_t humidity;
float temperature;
bool fridgestate;
float ontemp = 16; // Temp to turn on fridge. can be set remotely
float offtemp = 14; // Temp to turn off fridge
int lastUpdate = millis();
int lastPublish = millis();
…
void handleCommand(LosantCommand *command) {
Serial.print("Command received: ");
Serial.println(command->name);
JsonObject& payload = *command->payload;
//print payload
Serial.print("Payload is: ");
payload.printTo(Serial);
Serial.println();
// Perform action specific to the command received.
if (strcmp(command->name, "UpdateSP") == 0) {
ontemp = payload["onSP"];
Serial.print("ontemp = ");
Serial.println(ontemp);
}
}
The serial output is below when the command is received.
Command received: UpdateSP
Payload is: {“OnSP”:27}
ontemp = 0.00
I’m hoping there is a simple answer
I would first try explicitly casting it to float when decoding it:
ontemp = payload["onSP"].asFloat();
You can read a bit more about decoding JSON from the ArduinoJson’s documentation here: https://github.com/bblanchon/ArduinoJson/wiki/Decoding%20JSON
This does not compile. I don’t think Arduino supports .asFloat();
I got it to work.
However I do not know if this is very efficient. I would welcome any feedback;
// Called whenever the device receives a command from the Losant platform.
void handleCommand(LosantCommand *command) {
Serial.print("Command received: ");
Serial.println(command->name);
JsonObject& payload = *command->payload;
//print payload
Serial.print("Payload is: ");
payload.printTo(Serial);
Serial.println();
// create json string
char json[200];
//expecting payload to be
//{"OnSP":16.5,"OffSP":14.3};
//reserve memory space
StaticJsonBuffer<200> jsonBuffer;
payload.printTo(json, sizeof(json));
// Step 2: Deserialize the JSON string
JsonObject& root = jsonBuffer.parseObject(json);
if (!root.success())
{
Serial.println("parseObject() failed");
return;
}
//
// Step 3: Retrieve the values
//const char* sensor = root["sensor"];
float OnSP = root["OnSP"];
ontemp = OnSP;
Serial.print("OnSP: ");
Serial.println(OnSP);
//const char* sensor = root["sensor"];
float OffSP = root["OffSP"];
offtemp = OffSP;
Serial.print("OffSP: ");
Serial.println(OffSP);
}
Note I also had to change the MQTT_MAX_PACKET_SIZE as described here:
https://forums.losant.com/t/sending-commands-with-larger-payloads/?source_topic_id=272