0

I am trying to connect a esp8266(esp-12e node mcu 1.0) to azure iot hub with code written in arduino. I've created a iot hub and a device using symmetric key authentication. Using the PubSubClient along with WifiClientSecure library to provide a secure mqtt connection(port 8883). generated a SAS token for the device. can't seem to connect to azure and keep getting mqtt disconnected error (-1). Oh and have the azure Baltimore CyberTrust Root CA downloaded and added

#define AZURE
//#define AWS

#ifdef AZURE
#include "secretsAzure.h"
#elif defined(AWS)
#include "secretsAws.h"
#endif

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

BearSSL::WiFiClientSecure net;
BearSSL::X509List cert(cacert);
PubSubClient client(net);

void connectToWiFi()
{
    Serial.print("connecting to wifi");
    while (WiFi.status() != WL_CONNECTED)
    {
        Serial.print(".");
        delay(1000);
    }
    Serial.println("ok!");
}


void connectToMqtt()
{
    Serial.print("MQTT connecting ");
    while (!client.connected())
    {
        if (client.connect(THINGNAME, USER, SAS_TOKEN))
        {
            Serial.println("connected!");
            if (!client.subscribe(MQTT_SUB_TOPIC))
                Serial.println(client.state());
        }
        else
        {
            Serial.print("failed ");
            Serial.println(client.state());
            delay(5000);
        }
    }
}

void setup()
{
    pinMode(MYPIN, OUTPUT);
    Serial.begin(115200);

    WiFi.hostname(THINGNAME);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, pass);
    connectToWiFi();

    net.setTrustAnchors(&cert);

    client.setServer(MQTT_HOST, MQTT_PORT);
    delay(5000);

    connectToMqtt();
}

unsigned long lastMillis = 0;
void loop()
{
    if (!client.connected())
        connectToMqtt();
    else
    {
        client.loop();
        if (millis() - lastMillis > 5000)
        {
            lastMillis = millis();
            //sendData();
        }
    }
}
Utsab
  • 1
  • 1
  • 1
    Edit the question to show your code, we can't debug what we can't see. – hardillb Feb 16 '20 at 18:13
  • added, thanks.. @hardillb – Utsab Feb 16 '20 at 19:09
  • I tried to do something similar a year ago and failed because the esp8266 couldn't handle the token size required by azure. I don't know if this is the same situation but I would look into that. – Dennis Apr 25 '21 at 10:24
  • Is there any solution. Because I get similar problem. The client secret is not the problem because the example provided by the ms team worker. At my point I think the client can't resolve the end name but I set the dns to the Google one – Sascha Mar 06 '22 at 12:21

0 Answers0