MQTT via esp8266 suddenly stopped connecting giving mqttClient.state() = -2 error!?

27 views (last 30 days)
My project has been running fine. then all of a sudden in the last 2-3weeks my esp8266 has stopped getting information from my Thingspeak channel. I havent changed the code... its all been the same since day one. But its giving me some mqttClient.state() = -2 error, which means MQTT_CONNECT_FAILED - the network connection failed!
BUT... from my mobile I am still able to write stuff to my Thingspeak channel. I double check the channel and the data is always there, that I have sent from my mobile. Its just after it(the channel) receives the data... my esp8266 cant get that information because its no longer able to connect to the channel via MQTT for some reason.
Here is the code and the step by step logs from the serial monitor
CODE
#include "mqtt_secrets.h"
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
char ssid[] = "HUAWEI-ABCD"; // Change to your network SSID (name).
char pass[] = "XXXXXXXXXXXX";
char mqttUserName[] = SECRET_MQTT_USERNAME; // Change to your MQTT device username.
char mqttPass[] = SECRET_MQTT_PASSWORD; // Change to your MQTT device password.
char clientID[] = SECRET_MQTT_CLIENT_ID; // Change to your MQTT device clientID.
#define channelID XXXXX
// It is strongly recommended to use secure connections. However, certain hardware does not work with the WiFiClientSecure library.
// Comment out the following #define to use non-secure MQTT connections to ThingSpeak server.
#define USESECUREMQTT
// Comment the following line if not using an ESP8266.
#define ESP8266BOARD
#include <PubSubClient.h>
#ifdef ESP8266BOARD
#include <ESP8266WiFi.h>
const char* PROGMEM thingspeak_cert_thumbprint = "xxxxxxxxxxxxxxxxxxxxxxxxx";
#else
#include <WiFi.h>
const char * PROGMEM thingspeak_ca_cert = \
"-----BEGIN CERTIFICATE-----\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxxxxxxxxxxxxxxxxxx\n" \
"xxxxxxxxxxx\n" \
"-----END CERTIFICATE-----\n";
#endif
#ifdef USESECUREMQTT
#include <WiFiClientSecure.h>
#define mqttPort 8883
WiFiClientSecure client;
#else
#define mqttPort 1883
WiFiClient client;
#endif
const char* server = "mqtt3.thingspeak.com";
int status = WL_IDLE_STATUS;
long lastPublishMillis = 0;
int connectionDelay = 1;
int updateInterval = 15;
PubSubClient mqttClient( client );
// Function to handle messages from MQTT subscription.
void mqttSubscriptionCallback( char* topic, byte* payload, unsigned int length ) {
// Print the details of the message that was received to the serial monitor.
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
mySwitch.send("xxxxxxxxxxxxxxxx");
Serial.println();
}
// Subscribe to ThingSpeak channel for updates.
void mqttSubscribe( long subChannelID ){
// String myTopic = "channels/"+String( subChannelID )+"/subscribe";//this is all fields of the channel
String myTopic = "channels/"+String( subChannelID )+"/subscribe/fields/field4";//i want only field 4
mqttClient.subscribe(myTopic.c_str());
}
// Publish messages to a ThingSpeak channel.
void mqttPublish(long pubChannelID, String message) {//message already has Field4 concatenated in the beginning
String topicString ="channels/" + String( pubChannelID ) + "/publish";
mqttClient.publish( topicString.c_str(), message.c_str() );
}
// Connect to WiFi.
void connectWifi()
{
Serial.print( "Connecting to Wi-Fi..." );
Serial.print( WiFi.status());
while ( WiFi.waitForConnectResult() != WL_CONNECTED ) {
WiFi.begin( ssid, pass );
delay( connectionDelay*1000 );
Serial.print( WiFi.status());
}
Serial.println( "Connected to Wi-Fi!!!!!" );
}
// Connect to MQTT server.
void mqttConnect() {
Serial.println("MQTT connecting.....");
// Loop until connected.
while ( !mqttClient.connected() )
{
// Connect to the MQTT broker.
if ( mqttClient.connect( clientID, mqttUserName, mqttPass ) ) {
Serial.print( "MQTT to " );
Serial.print( server );
Serial.print (" at port ");
Serial.print( mqttPort );
Serial.println( " successful." );
} else {
Serial.print( "MQTT connection failed, rc = " );
// See https://pubsubclient.knolleary.net/api.html#state for the failure code explanation.
Serial.print( mqttClient.state() );
Serial.println( " Will try again in a few seconds" );
delay( connectionDelay*1000 );
}
}
}
void setup() {
Serial.begin( 115200 );
// Delay to allow serial monitor to come up.
delay(3000);
// Connect to Wi-Fi network.
//WiFi.mode(WIFI_STA);
Serial.println("1x-x-x-x");
connectWifi();
// Configure the MQTT client
Serial.println("2x-x-x-x");
mqttClient.setServer( server, mqttPort );
Serial.println("3x-x-x-x");
// Set the MQTT message handler function.
mqttClient.setCallback( mqttSubscriptionCallback );
Serial.println("4x-x-x-x");
// Set the buffer to handle the returned JSON. NOTE: A buffer overflow of the message buffer will result in your callback not being invoked.
mqttClient.setBufferSize( 2048 );
Serial.println("x-x-x-x");
// Use secure MQTT connections if defined.
#ifdef USESECUREMQTT
// Handle functionality differences of WiFiClientSecure library for different boards.
#ifdef ESP8266BOARD
client.setFingerprint(thingspeak_cert_thumbprint);
#else
client.setCACert(thingspeak_ca_cert);
#endif
#endif
//===============================
// Transmitter is connected to again 0 pin that translates to D3 on the D1 R2 Wemos
mySwitch.enableTransmit(0);
// Optional set protocol (default is 1, will work for most outlets)
mySwitch.setProtocol(11);
// Optional set pulse length.
mySwitch.setPulseLength(415);
Serial.println("x-x-x-x SET UP FINISHED");
}
//Maintain the MQTT connection, and publish data to the channel at regular time intervals in the loop method.
void loop() {
Serial.println("00000000000 LOOP");
// Reconnect to WiFi if it gets disconnected.
if (WiFi.status() != WL_CONNECTED) {
connectWifi();
}
// Connect if MQTT client is not connected and resubscribe to channel updates.
if (!mqttClient.connected()) {
mqttConnect();
mqttSubscribe( channelID );
Serial.println("MTQQ subscribed...");
}
//Serial.println("2222222222222... serverloop");
// Call the loop to maintain connection to the server.
mqttClient.loop();
//Serial.println("3333333333333");
// Update ThingSpeak channel periodically. The update results in the message to the subscriber.
if ( (millis() - lastPublishMillis) > updateInterval*1000) {
//mqttPublish( channelID, (String("field1=")+String(WiFi.RSSI())) );
lastPublishMillis = millis();
Serial.println("... published after 15secs.......");
}
delay(1000);
}
SerialMonitor
1x-x-x-x
Connecting to Wi-Fi...77Connected to Wi-Fi!!!!!
2x-x-x-x
3x-x-x-x
4x-x-x-x
x-x-x-x
x-x-x-x SET UP FINISHED
00000000000 LOOP
MQTT connecting.....
MQTT connection failed, rc = -2 Will try again in a few seconds
MQTT connection failed, rc = -2 Will try again in a few seconds
MQTT connection failed, rc = -2 Will try again in a few seconds
MQTT connection failed, rc = -2 Will try again in a few seconds
MQTT connection failed, rc = -2 Will try again in a few seconds
MQTT connection failed, rc = -2 Will try again in a few seconds

Accepted Answer

Christopher Stapels
Christopher Stapels on 28 Jul 2022
ThingSpeak recently updated the security certificate. Can you try reprogamming with the new cert? The ESP8266 MQTT example code here only uses the fingerprint. The new fingerprint is "9780c25078532fc0fd03dae01bfd8c923fff9878" but I wasnt able to get that working in ESP32 either. Il looking into it. In the meantime, the non-secure versions should work.
  4 Comments
Tibor
Tibor on 29 Jan 2023
Hi Christopher,
I spent 6 hours trying to figure out why the example code provided here does not work and why I get "MQTT connection failed, rc = -2", before I found this conversation and updated the CERT thumbnail in the code to solve the issue. May I suggest that someone updates the linked documentation?
Thank you!
Christopher Stapels
Christopher Stapels on 30 Jan 2023
Sure, thanks for the reminder, we will schedule it if it isnt already scheduled for an update. Glad to hear you got yours working.

Sign in to comment.

More Answers (0)

Categories

Find more on Write Data to Channel in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!