0

I have a problem using the PubSubClient. I want to create dynamic mqtt-topics based on a predefined prefix and a suffix and my ESP-macaddress.

My problem is that the PubSubClient requires a cost char* and I cant seem to figure out how to do it dynamically.

Below is my current solution and that is not as convenient as I want. The code below is only pseudocode but that are the crucial parts.

// How I get the mac_address
WiFi.macAddress(mac_array);
for (int i = 0; i < sizeof(mac_array); ++i){
     sprintf(mac_address,"%s%02x",mac_address,mac_array[i]);
}

// Current way, where I hard code the topic_in & topic_out
const char* topic_in = "node/18fe34d77ead/from_node_red";
const char* topic_out = "node/18fe34d77ead/to_node_red";

Below is an example of how I would love to do it but I cant figure out how to do it.

// I would love to be able to do like this
const char* topic_in = "node/"+mac_address+"/from_node_red";

Can any one please help me or point me in the right direction.

closed as off-topic by jfpoilpret, rebatoma, Dat Ha, KIIV, sa_leinad Dec 1 '16 at 12:17

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question does not appear to be about Arduino, within the scope defined in the help center." – jfpoilpret, rebatoma, Dat Ha, KIIV, sa_leinad
If this question can be reworded to fit the rules in the help center, please edit the question.

1

It doesn't require const char *, it says "passed string won't be changed inside of call". Externally it can be char * or char [] or Arduino String class with using c_str() method to get const char *.

And as the MAC address won't change a lot, it should be done once in the setup().

0

Try this:

String topicPreFix = "node/";
String mac = "18fe34d77ead";
String topicPostFix = "/from_node_red";
PubSubClient client ... ;

void setup(){
...
}

In your Method:

String myString = topicPreFix + mac + topicPostFix;
const char * msg = myString.c_str();
client.publish(msg ,"0");

Not the answer you're looking for? Browse other questions tagged or ask your own question.