Leveraging the PubSubClient.h - Thanks to knolleary
I'm able to get temperature readings from my device to a cloud service.
I'm also able to get subscription work (a hello from PC makes it onto the IoT Device)
My questions are, if someone could help.
-
Does client.loop() call the callback function?
If I don’t have the client.loop() then my sketch doesn’t work, I expect it does, but I would have thought with previous subscribe and connect messages it would work without.
client.subscribe(TopicSwitch);
client.loop();// This will check the callback function to see if there is a message - Breaks if not here…..
If I issue the following command, will it stay subscribed to this topic as long as my MQTT connection is alive
client.subscribe(TopicSwitch);
It again, seems like I must use this subscribe just before the client.loop() to get any data returned.
If I wanted to subscribe and print messages from two topics, would I have to subscribe AND run the client.loop for this?
client.subscribe(TopicSwitch1);
client.loop()
client.subscribe(TopicSwitch2);
client.loop()
I’ve seen people use
client.subscribe("2177800/1206/arduinoin");
In their Setup() but I would like to subscribe to a few topics
and then client.loop() with separate topics
for example
client.loop() — Check Topic 1 for Alert
client.loop() - Check Topic 2 for Alert
- Note, this does seem to work if I subscribe to a topic just before running client.loop() but wonder if there is a better way
How can I get the value of the cstring out of the callback function into my loop()
I would like to use the value to turn off/on a switch?
Tried to “return cstring” but that didn’t work.
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
Serial.println();
Serial.println("Attempting Print entire Payload");
char *cstring = (char *) payload;
cstring[length] = '\0'; // Adds a terminate terminate to end of string based on length of current payload
Serial.println(cstring);
Serial.println();
// return cstring;
}
Serial.println("Testing TopicSwitch");
client.subscribe(TopicSwitch);
client.loop();// This will check the callback function to see if there is a message"