If (topic == "TEST") How do i wright the topics with subtopics

Hello all,

I have a sensor that posts it value to a MQTT topic with a sub topic.
Mean topic is SCD
sub topic is temperature

Now how do i wright dis down in the following part."

 if (topic == "TEST")

Wen i have

void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");

  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }

  if (topic == "SCD/temperature") {
    Serial.println("Received"));
  }

}

I do receive this in the monitor:
23:27:31.092 → Ambient = 20.47C Object = 20.05C

But its not posting “Received”

What do you want to write in? Is this something to do with openHAB, what version? Are you trying to write a rule, a transformation, a binding?

It is for a sensor i want to connect to openhab.
But i have it working.


void callback(char* topic, byte* payload, unsigned int length)
{

  String strTopic = String((char*)topic);


  if (strTopic  == "SCD/temperature") {
    char buffer[6];
    memcpy(buffer, payload, length);  //copy the payload to the buffer
    buffer[length] = '\0';  //terminate the string (NOT a String !
    temp = String((char*)payload).toFloat();
    Serial.print("Message1:");
    Serial.println(temp);

  }


  if (strTopic  == "SCD/humidity") {
    char buffer[6];
    memcpy(buffer, payload, length);  //copy the payload to the buffer
    buffer[length] = '\0';  //terminate the string (NOT a String !
    hum = String((char*)payload).toFloat();
    Serial.print("Message2:");
    Serial.println(hum);

  }
}

You definitely should have mentioned that you are talking about the program that runs on your microprocessor (probably ESP32 or 8266).
I do not want to be rude but that definitely belongs to another community (arduino for example), but asking in the openHAB forum how to code Arduino/C++ would be the same as asking microsoft how to code games in Unity or Unreal engine…

1 Like

fixed it for you :slight_smile:

1 Like

C++ comes also with some string functions, so instead of copying buffers which might be dangerous, you can also use

strcmp()

https://www.cplusplus.com/reference/cstring/strcmp/

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