Home > Software design >  mqtt subscribe to change relay state json
mqtt subscribe to change relay state json

Time:05-11

what the data should be sent if the code like this

void mqttCallback(char *topic, byte *payload, unsigned int length)
{
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i  )
  {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  if (strcmp(topic, DeviceConfig.MqttSub) == 0) // topic = /command
  {
    Serial.print("Recvd relay command parse code: ");
    StaticJsonDocument<100> doc;
    DeserializationError error = deserializeJson(doc, (char *)payload);
    Serial.println(error.code());
    if (error == DeserializationError::Ok)
    {
      if (doc.containsKey("state") && doc["state"].is<int>())
      {
        DeviceConfig.RelayOn = (doc["state"].as<int>() == 1);
        Serial.print("Changing state: ");
        Serial.print(DeviceConfig.RelayOn );
        Serial.println();
      }
    }
  }
}

i tried ON : OFF and 0 : 1, but it doesn't work to control the relay

CodePudding user response:

It looks like the MQTT message payload needs to be a JSON object with at least the following:

{
   "state": 1
}
  • Related