Search code examples
c++arduinomqttpublish-subscribe

how to send TWO strings with arduino pubsubclient library - getting invalid operand error


probably a simple enough thing - so much so I thought it would be worth asking.

I'm familiar with the pubsub mqtt client library from the hirotasker port for Spark/Particle devices. I am trying to use it now on an arduino and hitting a bit of a stumbing block. I'm trying to do this:

client.publish("telemetry", String1 + "confidence=" + String2);

I can't send a string like I can with for example the arduino-mqtt library, I get errors about 'no known conversion' or candidate expects 3 arguments and only 2 povided etc.

So I modify it to:

client.publish("telemetry", String1.c_str() + "confidence=" + String2.c_str());

but that's a no go either

error: invalid operands of types 'const char*' and 'const char [12]' to binary 'operator+' client.publish("telemetry", String1.c_str() + "confidence=" + String2.c_str));


Solution

  • Have a look at the API-Documentation of the publish-function:

    https://pubsubclient.knolleary.net/api#publish

    It expects a char[] for the topic and a char[] for the message. As your error message states, you are trying to concatenate three char[] with the +-operator, which is not possible. One way is to use a temporary String-Object for the character array "confidence=".

    String tmp = String1 + String("confidence=") + String2;
    

    To get the char[] behind the String-Object you can use tmp.c_str().