Tiedt Tech
Tiedt Tech

Reputation: 717

ESP8266 not connected in Azure Iot Hub, return state -2

I'm trying to connect my ESP8266 to Azure Hub IoT, but I'm not getting it. I've already followed examples and I get the return rc = -2.

I use https://github.com/knolleary/pubsubclient libary.

I used the library example and other examples and nothing being able to connect to Azure Hub IoT.

Error this line

client.connect(dispositivo, usuario_mqtt, senha_mqtt)

My code

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

const char* nome_wifi = "M11";
const char* senha_wifi = "035954159";

const char* broker = "tiedt-tech-iot-hub.azure-devices.net";
const char* dispositivo = "esp-quarto";
const char* usuario_mqtt = "tiedt-tech-iot-hub.azure-devices.net/esp-quarto";
const char* senha_mqtt = "SharedAccessSignature sr=tiedt-tech-iot-hub.azure-devices.net%2Fdevices%2Fesp-quarto&sig=uM6iZTBylAcNHa4%2F4GYxPcAwMUfMAljCx5zvHyx3m%2BE%3D&se=1647197049";
const char* topico = "devices/esp-quarto/messages/events/";

WiFiClientSecure espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);
  conectarWifi();
}

void conectarWifi(){
  Serial.print("Conectando na rede");
  WiFi.begin(nome_wifi, senha_wifi);

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

  Serial.println("");
  Serial.println("WiFi Conectado");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());  
}

void conectarMQTT() {
  Serial.println("Conectando no broker");
  client.setServer(broker, 8883);

  while(!client.connected()) {
    if (client.connect(dispositivo, usuario_mqtt, senha_mqtt)){
      Serial.println("Conectado no broker");  
    }
    else {
      Serial.print("Falha na conexão com o broker, rc= ");
      Serial.print(client.state());            
      Serial.println("");            
      delay(5000);
    }
  }  
}

void loop(){
  if (!client.connected()){
    conectarMQTT();  
  }
}

Upvotes: 1

Views: 184

Answers (1)

Matthijs van der Veer
Matthijs van der Veer

Reputation: 4095

Since late last year, there is an official Arduino SDK for ESP8266 boards. You can find it here, it comes with an example that I can confirm works.

It takes care of some of the heavy lifting, and uses the same WifiClientSecure and PubSubClient classes of your implementation.

Upvotes: 0

Related Questions