Search code examples
arduinomqttpublish-subscribe

no reaction to incoming MQTT message


I have a simple setup of a wemos d1 mini with a button and some LED's. It can send and receive MQTT messages and should act upon them.

I want that it sends "11" when pressing the button and light the LED's when receiving a specific message - "21" in this case.

It all seems to be working alright, the message is going out and it is reporting that it "sees" "21" when that message comes in. But then it skips the IF statement where I compare the incoming message with a string. They both print out the same, but the IFcomparison seems to say they are not. This is done in the callback loop.

Could anyone point me to where i go wrong?


long lastMsg = 0;
char msg[50];
int value = 0;
char* msgIN;
String msgIN_trigger;
char* msgOUT;
String boxID = "1";
int boxID_len = boxID.length() + 1;
String clientID = "rememberbox " + boxID;
int clientID_len = clientID.length() + 1;

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived: [");
  Serial.print(topic);
  Serial.print("] ");
  String msgIN = "";
  msgIN += (char *)payload;
  String msgString = msgIN;
  Serial.print(msgIN.substring(0,2));
  Serial.println("/");


    if (msgString == msgIN_trigger) {
      Serial.println("message is for me!");
      Serial.println("wake up MP3 player");
      myMP3.wakeUp();
      Serial.println("play track 5");
      myMP3.play(5);
      Serial.println("confetti!!!");
      confetti();
      Serial.println("and fade to black");
      for (int i = 0; i < NUM_LEDS; i++) {
        leds[i] = CRGB::Black;
      }
      FastLED.show();
      delay(7500);
      myMP3.sleep();
      message_out = false;
      Serial.println("message_out = false");
      Serial.println("");
    }

    Serial.println("nothing intended for me");
    Serial.print("only reacting to message: ");
    Serial.print(msgIN_trigger);
    Serial.println("/");
    Serial.println("");
}

Solution

  • You are using an operand to try and compare two Strings...that can lead to flaky operation. Try this

    if (strcmp(msgString, msgIN_trigger) == 0) {
       ...
    }
    

    This is what I use and it seems to work fine.