knolleary / pubsubclient

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

client.connect return rc = -2 with connected Azure IoT Hub #933

Open TiedtTech opened 2 years ago

TiedtTech commented 2 years ago

Hello, 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.

My code is:

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

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

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=106471970490";
const char* topico = "devices/esp-quarto/messages/events/";

WiFiClientSecure espClient;
PubSubClient client(espClient);

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

  client.setBufferSize(256);
  client.setServer(broker, 8883);
  client.setCallback(callback);

}

void callback(char* topic, byte* payload, unsigned int length) {
  // print message to serial for debugging
  Serial.print("Message arrived: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println('---');
}

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");

  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 publicar(String campo, int valor) {
  String json = "{ \"DeviceId\":\"esp-quarto\", \"" + campo + "\":" + valor + " } ";
  client.publish(topico, json.c_str());  
}

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

  publicar("chuva", random(1, 100));
  delay(10000);
}
JayateerthDambal commented 2 years ago

Heyy, Have you solved this error, I am getting the same error??

cruonline commented 2 years ago

Just got the same error, after updating device with new SAS token. Probably something changed in dependencies... :( Anyone has some ideas how to solve it?

cjacky475 commented 2 years ago

@TiedtTech @JayateerthDambal, have you guys solved the problem with rc = -2? Thanks.