On my Node MCU board I have it working:
Subscribed to one MQTT channel.
Looking at other posts I see it can subscribe to multiple MQTT topics.
Multiple MQTT subscriptions
This is an exert from the code I have:
void callback(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();
Which is interesting looking at part of the example from the link:
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
char receivedChar = (char)payload[i];
Serial.print(receivedChar);
//TOPIC 1
if (topic == "Charts/PS") {
Serial.print("Reception LED is ");
if ("Charts/PS" == "1") {
digitalWrite(chartsPin, HIGH);
Serial.print("On");
}
Reading it how I do, that means ALL topics come through to this part.
So, if I sent a message with the topic "TEST", I should get to see it if I modify my code thus:
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
if (topic == "TEST/")
{
header(3);
}
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
Where header() is:
void header(byte x)
{
if (x == 0)
Serial.println("=================================================");
//
if (x == 1)
Serial.println("-------------------------------------------------");
if (x == 2)
Serial.println("=-=-=-=-=-=- Main loop -=-=-=-=-=-=-=-=-=-=-=-=");
if (x == 3)
Serial.println("*************************************************");
}
So, I set up an injection to TEST topic and watch what happens.
Nothing.
I don't get to see the row of *'s which is "header(3)"
Shortly after the post:
PaulS replied:
You do not compare strings using ==. You compare them using strcmp().
I'm lost.
I know that originally I was always messing up the = and ==.
= Assign value to variable.
== Logical compare (not sure of exact words) but used in lines like:
if (x == 3)
I have since discovered there is also a ===, but I don't want to think about that too much.
Else where in my code there is this part:
void reconnect()
{
// Loop until we're reconnected
Serial.println("Reconnecting");
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(mqtt_server, willTopic, willQoS, willRetain, willMessage))
{
which doesn't have a topic specified.
I guess at some level every message has to be received and only after it is "filtered" do the subscribed messages get through to the program.
So I kind of get the thinking behind the first part, but as it doesn't seem to work, I'm stuck.