knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.78k stars 1.46k forks source link

PubSubClient cannot connect to MQTT broker (-2) #968

Open cjacky475 opened 1 year ago

cjacky475 commented 1 year ago

Hello, I am trying to connect to AWS IoT on my ESP8266, but it's not connecting. I've checked the credentials, everything is fine. I see no logs in AWS IoT. I can connect with same credentials from my ESP32, but I use MQTTClient.h on ESP32 and I set credentials differently there via setCertificate, setPrivateKey and etc. which is not available on ESP8266

Logs:

Connecting to mywifinameConnecting to WiFi...
, WiFi connected, IP address: 192.168.1.216
MQTT keep alive found MQTT status 0 WiFi status 3

Connecting to mywifinameConnecting to WiFi...
, WiFi connected, IP address: 192.168.1.216
PubSubClient connecting to: xxxxxxxxxxxxxxx-ats.iot.us-east-2.amazonaws.com.-1
.-2
.-2
.-2
.-2
.-2

Code:

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>

const char *ssid = "mywifiname";
const char *password = "mywifipass";

const char *awsEndpoint = "xxxxxxxxxxxxxxx-ats.iot.us-east-2.amazonaws.com";

// xxxxxxxxxx-certificate.pem.crt
const char *certificate_pem_crt =

    "-----BEGIN CERTIFICATE-----\n"
    "MIIDWTCCAkGgAwIBAgIUJ1gT+uvYaUrsqYAuKDGCCY+exfEwDQYJKoZIhvcNAQEL\n"
    "-----END CERTIFICATE-----\n";

// xxxxxxxxxx-private.pem.key
const char *private_pem_key =

    "-----BEGIN RSA PRIVATE KEY-----\n"
    "MIIEpAIBAAKCAQEA3mf0dUwoQY47sL1DL9yKlwoafBpRwgXLqo6bb+ZFKyqmSmU0\n"
    "-----END RSA PRIVATE KEY-----\n";

/* root CA can be downloaded in:
  https://www.symantec.com/content/en/us/enterprise/verisign/roots/VeriSign-Class%203-Public-Primary-Certification-Authority-G5.pem
*/
const char *rootCA =
    "-----BEGIN CERTIFICATE-----\n"
    "MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB\n"
    "-----END CERTIFICATE-----\n";

BearSSL::X509List CERT_CA(rootCA);
BearSSL::X509List CERT_CRT(certificate_pem_crt);
BearSSL::PrivateKey CERT_PRIVATE(private_pem_key);

WiFiClientSecure wiFiClient;
void msgReceived(char *topic, byte *payload, unsigned int len);
PubSubClient pubSubClient(awsEndpoint, 8883, msgReceived, wiFiClient);

void connectToMQTT();
void connectToWiFi();

void setup()
{
    Serial.begin(9600);
    delay(50);
    Serial.println();
    Serial.println("ESP8266 AWS IoT Example");
    Serial.printf("SDK version: %s\n", ESP.getSdkVersion());

    connectToWiFi();
}

unsigned long lastPublish;
int msgCount;

void loop()
{
    if ((wiFiClient.connected()) && (WiFi.status() == WL_CONNECTED))
    {
        pubSubClient.loop();

        if (millis() - lastPublish > 10000)
        {
            if (!pubSubClient.connected())
            {
                connectToMQTT();
            }

            String msg = String("Hello from ESP8266: ") + ++msgCount;
            //boolean rc = pubSubClient.publish("outTopic", msg.c_str());
            //Serial.print("Published, rc=");
            //Serial.print((rc ? "OK: " : "FAILED: "));
            Serial.println(msg);
            lastPublish = millis();
        }
    }
    else
    {
        Serial.print("MQTT keep alive found MQTT status ");
        Serial.print(String(wiFiClient.connected()));
        Serial.print(" WiFi status ");
        Serial.print(String(WiFi.status()));
        Serial.print("\n\n");

        if (!(wiFiClient.connected()) || !(WiFi.status() == WL_CONNECTED))
        {
            connectToWiFi();
        }

        connectToMQTT();
    }
}

void msgReceived(char *topic, byte *payload, unsigned int length)
{
    Serial.print("Message received on ");
    Serial.print(topic);
    Serial.println();
}

void connectToWiFi()
{
    Serial.print("Connecting to ");
    Serial.print(ssid);

    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    WiFi.waitForConnectResult();
    Serial.println("Connecting to WiFi...");

    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.print(".");
    }

    Serial.print(", WiFi connected, IP address: ");
    Serial.println(WiFi.localIP());

    wiFiClient.setTrustAnchors(&CERT_CA);
    wiFiClient.setClientRSACert(&CERT_CRT, &CERT_PRIVATE);
}

void connectToMQTT()
{
    if (WiFi.status() != WL_CONNECTED)
    {
        connectToWiFi();
    }

    if (!pubSubClient.connected())
    {
        Serial.print("PubSubClient connecting to: ");
        Serial.print(awsEndpoint);
        while (!pubSubClient.connected())
        {
            Serial.print(".");
            Serial.println(pubSubClient.state());
            pubSubClient.connect("thingname");
            delay(100);
        }
        Serial.println(" connected");
        pubSubClient.subscribe("inTopic");
    }

    pubSubClient.loop();
}
Rainbrony commented 1 year ago

I'm having the same problem... it only started this week, it worked perfectly before this week. image

boolean mqreconnect()
{
  digitalWrite(LED, 0);
  Serial.printf("Client %s connecting to EMQX\n", client_id.c_str());
  digitalWrite(LED, 1);
  if (client.connect(client_id.c_str(), mqttu.c_str(), mqttk.c_str(), lwt.c_str(), 0, true, lwm.c_str()))
  {
    // Once connected, publish an announcement...
    Serial.println("EMQX connected");
    client.publish(topic.c_str(), "{\"DevID\": \"MakeS\", }");
    // ... and resubscribe
    client.subscribe(topic.c_str());
  }
  else
  {
    Serial.print("EMQX connection failed with state ");
    Serial.print(client.state());
    Serial.println();
  }
  return client.connected();
}

And it's still failing while I type.

Rainbrony commented 1 year ago

Sorry, my problem was caused by bad power supply, the problem was gone after I changed to a better power supply.

Rainbrony commented 1 year ago

Nope, it started failing again, I even load my program to a new board, and got the same result.

cjacky475 commented 1 year ago

@Rainbrony, did you solve it?

Rainbrony commented 1 year ago

I changed to RTOS SDK, it still cannot connect to EMQX with my computer's USB, but work great with my power bank, 充电宝。

tonykambo commented 1 year ago

I have the same issue, any progress on this @cjacky475?

cjacky475 commented 1 year ago

@tonykambo, I couldn't find anything that would make my code connect to AWS IoT Core. Not sure what to do.