Search code examples
arduinomqttesp8266node-red

Why Node-red Debug node doesn't show my mqtt message?


I'm trying to send data from my Wemos to Node-red via MQTT. I created a nested object I want to send to MQTT. From the serial of Arduino IDE the output is this (and that's what I want):

[{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1}]

It seems all correct but the debug node show nothing. what am I missing?

Here's the code:

//LIBRARY
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#include<Wire.h>

//JSON Array and mqtt data
#include <ArduinoJson.h>
#define MQTT_BUFFER 512


//MPU
const int MPU = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ;

// IP adress Raspberry Pi
const char* mqttServer = "raspi-hyperink";
const int mqttPort = 1883;

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;



WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  //MPU
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);

  //SERIAL
  Serial.begin(115200);
  
  // WiFiManager
  // Local intialization.
  WiFiManager wifiManager;
  
  // Uncomment and run it once, if you want to erase all the stored information
  //wifiManager.resetSettings();
  
  // set custom ip for portal
  //wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

  // fetches ssid and pass from eeprom and tries to connect
  // if it does not connect it starts an access point with the specified name
  // here  "AutoConnectAP"
  // and goes into a blocking loop awaiting configuration
  wifiManager.autoConnect("AutoConnectAP");
  // if you get here you have connected to the WiFi
  Serial.println("Connected.");
  //server.begin();

  //CLIENT
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
  server.begin();
}

void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  Serial.println("-----------------------"); 
}

//RECONNECT FUNCTION
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("esp8266")) {
        Serial.println("connected");
        // Once connected, publish an announcement...
        //client.publish("outTopic", "hello world");
        // ... and resubscribe
        //client.subscribe("inTopic");
    } else {
        Serial.print("failed, rc=");
        Serial.print(client.state());
        Serial.println(" try again in 5 seconds");
        // Wait 5 seconds before retrying
        delay(5000);
      }
  }
}

void loop(){
  WiFiClient(espClient) = server.available();   // Listen for incoming clients

  if (espClient) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (espClient.connected()) {            // loop while the client's connected
      if (espClient.available()) {             // if there's bytes to read from the client,
        char c = espClient.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
           
            // Web Page Heading
            client.println("<body><h1>ESP8266 Web Server</h1>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }  
    }
    // Clear the header variable
    header = "";
    // Close the connection
    espClient.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }

  if (!client.connected()) {
          reconnect();
        }
  client.loop();      

         //compute the required size
         const size_t CAPACITY = JSON_ARRAY_SIZE(5) + 5*JSON_OBJECT_SIZE(3);
         //allocate the memory for the document
         StaticJsonDocument<CAPACITY> doc;
         
        //Create an empty array
        JsonArray arr = doc.to<JsonArray>();
        
        //definiamo quanti campioni registrare prima di inviarli tramite mqtt
        for (int i=0; i<5; i++){
          
            //MPU reading
            Wire.beginTransmission(MPU);
            Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
            Wire.endTransmission(false);
            Wire.requestFrom(MPU, 14, true); // request a total of 14 registers
            AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
            AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
            AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)

            //Create JSON Array
            JsonObject obj = doc.createNestedObject();
            obj["AcX"] = AcX;
            obj["AcY"] = AcY;
            obj["AcZ"] = AcZ;

            delay(3000);
        }

       //MQTT PUBLISHING JSON PACKAGE 
       char mqttData[MQTT_BUFFER];
       serializeJson(doc, mqttData);
       Serial.println(mqttData);
       client.publish("esp8266", mqttData);
       //client.subscribe("esp8266");
       client.subscribe("esp8266");
       delay(10000);

      //Inserire un ciclo WHILE dove
      //mentre il wifi è connesso invia i dati all'mqtt
      //altrimenti li salva e basta

       
}

This is the mqtt node
enter image description here

Node-red debug
enter image description here


Solution

  • Normally debug should show you what you are publishing to your MQTT broker. As simple troubleshooting I would start moving backwards:

    • Replace the NodeRED client by any other one. Is the problem still there? Very likely it will be meaning that the problem is not on the MQTT client.

    So we move a step "backwards"

    • Replace the MQTT Broker, use another one from the internet, one that you know works fine. The problem, is it still there? If it's not there, voilà, you found the problem (the broker), if it's still there, it means that the issue is on client publishing your msgs. It might be the msg itself.

    So we move a step "backwards"

    • Replace you msg by another one, much simpler. Does it work ?

    You get the idea :)