Hi all,
I would appreciate your support guys with my code as I’ve done all needed to connect the ESP32 device with the cloud HiveMQ to send data but failed. I’m still having the same error with no hope to get it solved.
Can you please help or suggest anything I can do to solve this issue?
Credit to @Mike post:
Error message:
Attempting MQTT connection…failed, rc=-2 try again in 5 seconds
Attempting MQTT connection…failed, rc=-2 try again in 5 seconds
Attempting MQTT connection…failed, rc=-2 try again in 5 seconds
Attempting MQTT connection…failed, rc=-2 try again in 5 seconds
Attempting MQTT connection…failed, rc=-2 try again in 5 seconds
Code:
#define LED 2
#define PIR 4
#include <Arduino.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ESP_Mail_Client.h>
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
//---- WiFi settings
const char* ssid = "wifi-ssid";
const char* password = "wifi-password";
//---- MQTT Broker settings
const char* mqtt_server = "my-broker-id.hivemq.cloud"; // replace with your broker url
const char* mqtt_username = "uname";
const char* mqtt_password = "pwd";
const int mqtt_port =8883;
WiFiClientSecure espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
const char* sensor1_topic= "testing";
const char* root_ca =
"-----BEGIN CERTIFICATE-----\n" \
"MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n" \
"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n" \
"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n" \
"WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n" \
"ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n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8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n" \
"NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n" \
"ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n" \
"TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n" \
"jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n" \
"oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n" \
"4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n" \
"mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n" \
"emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n" \
"-----END CERTIFICATE-----\n";
bool msgSent = false;
Adafruit_BME280 bme; // BME280 connect to ESP32 I2C (GPIO 21 = SDA, GPIO 22 = SCL)
const int voltPin = 34;
float temperature, humidity, pressure, voltage;
int voltValue = 0;
String myTemp, myHum, myPress, temp18B20;
char msgBuf[100];
unsigned long previousMillis = 0;
unsigned long interval = 30000;
unsigned long period = 10 * 60 * 1000; // 10 minute delay
unsigned long time_now = 0;
// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
// Init BME280
void initBME(){
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
}
// Get BME280, DS18B20 & Voltage values
void getValues(){
// Get BME280 values
myTemp = String(bme.readTemperature());
myPress = String((bme.readPressure())/100);
myHum = String(bme.readHumidity());
// Get 18B20 values
sensors.requestTemperatures();
float temperatureC = sensors.getTempCByIndex(0);
temp18B20 = String(temperatureC);
// Get the voltage
voltValue = analogRead(voltPin);
// 4.946245734 = correction based on the Potential Div
// 0.78 = correction based on results
voltage = ((voltValue * (3.3 / 4096)) * 4.946245734) + 0.78;
String fullMsg = "Temp = ";
fullMsg += myTemp;
fullMsg += " ºC,";
fullMsg += "\tPress = ";
fullMsg += myPress;
fullMsg += " hPa,";
fullMsg += "\tHum = ";
fullMsg += myHum;
fullMsg += " %,";
fullMsg += "\tInt_T = ";
fullMsg += temp18B20;
fullMsg += " ºC,";
fullMsg += "\tVin = ";
fullMsg += voltage;
fullMsg += " V";
//fullMsg = ("Temp = \t%s\tPress = \t%s\tHum = \t%s", myTemp, myPress, myHum);
Serial.println(fullMsg);
fullMsg.toCharArray(msgBuf, 100);
//temperatureC = 0; //This is a test, reset the 18B20 value.
}
void setup() {
delay(5000);
Serial.begin(115200);
Serial.print("\nConnecting to ");
Serial.println(ssid);
sensors.begin();
//WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("\nWiFi connected\nIP address: ");
Serial.println(WiFi.localIP());
while (!Serial) delay(1);
espClient.setCACert(root_ca);
espClient.setCertificate(root_ca); // for client verification
initBME();
//PubSubClient client(espClient);
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void loop() {
Serial.println("entering the loop");
unsigned long currentMillis = millis();
// if WiFi is down, try reconnecting every CHECK_WIFI_TIME seconds
if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=interval)) {
Serial.print(millis());
Serial.println("Reconnecting to WiFi...");
WiFi.disconnect();
WiFi.reconnect();
previousMillis = currentMillis;
}
Serial.println("Getting Values ");
getValues();
char *msg = msgBuf;
Serial.println("Checking MQTT Server Connection");
if (!client.connected()) reconnect();
client.loop();
Serial.println("Publishing Message ");
publishMessage(sensor1_topic,msg,true);
//Delay
while(millis() < time_now + period){
//wait approx. [period] ms
}
time_now = millis();
}
//=======================================================================Function=================================================================================
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection…");
String clientId = "esp-client-"; // Create a random client ID
boolean cleanSession = true;
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {//, "testing",1,false,"no",false)) {
// boolean PubSubClient::connect(const char *id, const char *user, const char *pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage, boolean cleanSession)
Serial.println("connected");
//client.subscribe(sensor1_topic); // subscribe the topics here
//client.subscribe(command2_topic); // subscribe the topics here
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying
delay(5000);
}
}
}
//=======================================
// This void is called every time we have a message from the broker
void callback(char* topic, byte* payload, unsigned int length) {
String incommingMessage = "";
for (int i = 0; i < length; i++) incommingMessage+=(char)payload[i];
Serial.println("Message arrived ["+String(topic)+"]"+incommingMessage);
// check for other commands
/* else if( strcmp(topic,command2_topic) == 0){
if (incommingMessage.equals("1")) { } // do something else
}
*/
}
//======================================= publising as string
void publishMessage(const char* topic, String payload , boolean retained){
if (client.publish(topic, payload.c_str(), true))
Serial.println("Message publised ["+String(topic)+"]: "+payload);
}