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();
}
}
}