0
\$\begingroup\$

I have been trying to connect them but it seems like the MQTT connection is not working. That is the only part that is not, I followed this tutorial (https://www.instructables.com/id/How-to-Use-MQTT-With-the-Raspberry-Pi-and-ESP8266/) on how to install MQTT to the raspberry and then used my own code for the next part because I am using a different sensor.

Maybe what I am doing wrong is adding the wrong Pi IP address? I have tried both already but doesnt work.

With all of the printlines I can see that the connection to the MQTT broker is not ocurring, I do not know what the error is but I know that the MQTT connection is not happening

attached is all of my code:

To get the Pi IP Address I do:

hostname -I

and the response is: 169.254.137.114 192.168.86.58

The following is the code on my Raspberry pi:

mosquitto_sub -d -u jmontalv -P Jolumofe1 -t esp32/bme280/temperature

The following is the code on my ESP.

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <WiFi.h>
extern "C" {
  #include "freertos/FreeRTOS.h"
  #include "freertos/timers.h"
}
#include <AsyncMqttClient.h>

#define WIFI_SSID "CASA"
#define WIFI_PASSWORD "Jolumofe1"

// Raspberry Pi Mosquitto MQTT Broker
#define MQTT_HOST IPAddress(169, 254, 137, 114)
// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST "example.com"
#define MQTT_PORT 1883

// Temperature MQTT Topics
#define MQTT_PUB_TEMP "esp32/bme280/temperature"
#define MQTT_PUB_HUM "esp32/bme280/humidity"
#define MQTT_PUB_PRES "esp32/bme280/pressure"

// BME280 I2C
Adafruit_BME280 bme;
// Variables to hold sensor readings
float temp;
float hum;
float pres;

AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;

unsigned long previousMillis = 0;   // Stores last time temperature was published
const long interval = 10000;        // Interval at which to publish sensor readings

void connectToWifi() {
  Serial.println("Connecting to Wi-Fi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}

void connectToMqtt() {
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
}

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
  switch(event) {
    case SYSTEM_EVENT_STA_GOT_IP:
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      connectToMqtt();
      break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
      Serial.println("WiFi lost connection");
      xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
      xTimerStart(wifiReconnectTimer, 0);
      break;
  }
}

void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");
  if (WiFi.isConnected()) {
    xTimerStart(mqttReconnectTimer, 0);
  }
}

/*void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.println("Subscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
  Serial.print("  qos: ");
  Serial.println(qos);
}
void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("Unsubscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}*/

void onMqttPublish(uint16_t packetId) {
  Serial.print("Publish acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

void setup() {
  Serial.begin(115200);
  Serial.println();

  // Initialize BME280 sensor 
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }

  mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
  wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

  WiFi.onEvent(WiFiEvent);

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  //mqttClient.onSubscribe(onMqttSubscribe);
  //mqttClient.onUnsubscribe(onMqttUnsubscribe);
  mqttClient.onPublish(onMqttPublish);
  mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  // If your broker requires authentication (username and password), set them below
  mqttClient.setCredentials("jmontalv", "Jolumofe1");
  connectToWifi();
}

void loop() {
  unsigned long currentMillis = millis();
  // Every X number of seconds (interval = 10 seconds) 
  // it publishes a new MQTT message
  if (currentMillis - previousMillis >= interval) {
    // Save the last time a new reading was published
    previousMillis = currentMillis;
    // New BME280 sensor readings
    temp = bme.readTemperature();
    //temp = 1.8*bme.readTemperature() + 32;
    hum = bme.readHumidity();
    pres = bme.readPressure()/100.0F;

    // Publish an MQTT message on topic esp32/BME2800/temperature
    uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());                            
    Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", MQTT_PUB_TEMP, packetIdPub1);
    Serial.printf("Message: %.2f \n", temp);

    // Publish an MQTT message on topic esp32/BME2800/humidity
    uint16_t packetIdPub2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());                            
    Serial.printf("Publishing on topic %s at QoS 1, packetId %i: ", MQTT_PUB_HUM, packetIdPub2);
    Serial.printf("Message: %.2f \n", hum);

    // Publish an MQTT message on topic esp32/BME2800/pressure
    uint16_t packetIdPub3 = mqttClient.publish(MQTT_PUB_PRES, 1, true, String(pres).c_str());                            
    Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", MQTT_PUB_PRES, packetIdPub3);
    Serial.printf("Message: %.3f \n", pres);
  }
}
\$\endgroup\$
2
  • \$\begingroup\$ your code has a lot of Serial.print() functions and all you can say is it doesn't work? ... to that i say change the code so that it works .... please describe clearly what you observe when you run the code \$\endgroup\$
    – jsotola
    May 7, 2020 at 14:28
  • \$\begingroup\$ With all of the printlines I can see that the connection to the MQTT broker is not ocurring, I do not know what the error is but I know that the MQTT connection is not happening \$\endgroup\$ May 7, 2020 at 14:37

1 Answer 1

1
\$\begingroup\$

The IP address of your MQTT host as defined in your code is probably wrong. The 169.254.x.x that you refer to in your code is a kind of "emergency" link-local address, from a range also called "APIPA" (Automatic Private IP Address).

Such an address is assigned by the Operating System to a network interface, configured to work with a dynamic IP address (DHCP), that is physically connected but cannot get an IP address from a DHCP server. Chances are that this interface on the Pi cannot communicate with other devices on your network.

I assume that the second IP address you mentioned as the output of hostname -I is the correct address as that is in the 192.168.x.x range commonly used in small private LANs.

So, you should change the line beginning with #define MQTT_HOST to the following:

#define MQTT_HOST IPAddress(192, 168, 86, 58)

If that does not help, you can use the mosquitto_pub and mosquitto_sub commands on the Pi to test local connectivity to your Mosquitto broker.

\$\endgroup\$
5
  • \$\begingroup\$ Hey! I trued that but still unable to connect. Thanks for the thorough answer tho. I have used those commands in the Pi (mosquitto_pub and mosquitto_sub) and it works when I have 2 terminal windows open... \$\endgroup\$ May 7, 2020 at 15:05
  • \$\begingroup\$ @Ish Montalvo, Do you have a firewall or a port filter running? Can you ping the IP address of the ESP32 from the Pi? And what IP address (in what range) does the ESP32 get? \$\endgroup\$
    – StarCat
    May 7, 2020 at 15:07
  • \$\begingroup\$ no firewall or a port filter running! I cannot get the IP address of the ESP32 from the Pi. \$\endgroup\$ May 7, 2020 at 15:17
  • \$\begingroup\$ You should be able to ping the ESP from the Pi. The fact that you can't tells me you have a network related problem. Are the ESP and Pi in the same network? If they're on Wifi, are you sure you have enabled your router to allow internal Wifi devices to communicate? \$\endgroup\$
    – StarCat
    May 7, 2020 at 15:24
  • \$\begingroup\$ Thank you so much! that was the issue I had them connected to 2 different wifi networks without realizing it. as well as the MQTT_HOST you stated up there! so helpful thank you so much \$\endgroup\$ May 7, 2020 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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