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

27 ビュー (過去 30 日間)
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
#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.
// 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";
#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";
#include <WiFiClientSecure.h>
#define mqttPort 8883
WiFiClientSecure client;
#define mqttPort 1883
WiFiClient client;
const char* server = "";
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("] ");
for (int i = 0; i < length; i++) {
// 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
// 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 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.
// Connect to Wi-Fi network.
// Configure the MQTT client
mqttClient.setServer( server, mqttPort );
// Set the MQTT message handler function.
mqttClient.setCallback( mqttSubscriptionCallback );
// 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 );
// Use secure MQTT connections if defined.
// Handle functionality differences of WiFiClientSecure library for different boards.
#ifdef ESP8266BOARD
// Transmitter is connected to again 0 pin that translates to D3 on the D1 R2 Wemos
// Optional set protocol (default is 1, will work for most outlets)
// Optional set pulse length.
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) {
// Connect if MQTT client is not connected and resubscribe to channel updates.
if (!mqttClient.connected()) {
mqttSubscribe( channelID );
Serial.println("MTQQ subscribed...");
//Serial.println("2222222222222... serverloop");
// Call the loop to maintain connection to the server.
// 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.......");
Connecting to Wi-Fi...77Connected to Wi-Fi!!!!!
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


Christopher Stapels
Christopher Stapels 2022 年 7 月 28 日
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.
  2 件のコメント
Christopher Stapels
Christopher Stapels 2022 年 7 月 28 日
I appreciate you letting us know that worked, and reporting the original problem. Hopefully this will help other users in a similar situation.


その他の回答 (0 件)


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



Community Treasure Hunt

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

Start Hunting!

Translated by