256dpi / arduino-mqtt

MQTT library for Arduino
MIT License
1.01k stars 232 forks source link

Error code -3 when using client with private key #263

Closed myrcutio closed 3 years ago

myrcutio commented 3 years ago

I've been following this guide and hit a snag when trying to establish a connection with the MQTT server. I'm fairly certain all my parameters are correct, and openssl confirmed that my certificates are valid, but it fails with a generic -3 error on the device itself.

Here's my code:


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

#include "env.h"

// The MQTT topics that this device should publish/subscribe
#define AWS_IOT_PUBLISH_TOPIC   "gardener"
#define AWS_IOT_SUBSCRIBE_TOPIC "gardener"

WiFiClientSecure net = WiFiClientSecure();
MQTTClient client = MQTTClient(256);

void setup() {
  Serial.begin(9600);
  Serial.println("Booting...");
  setupNetworking();
}

void setupNetworking() {
  connectToWiFi();
  connectToMQTT();
  registerIoTListeners();
}

void connectToMQTT() {
  net.setCACert((const uint8_t*)IOT_ROOT_CA, sizeof(IOT_ROOT_CA) - 1);
  net.setCertificate((const uint8_t*)IOT_CERTIFICATE, sizeof(IOT_CERTIFICATE) - 1);
  net.setPrivateKey((const uint8_t*)IOT_PRIVATE_KEY, sizeof(IOT_PRIVATE_KEY) - 1);
}

void registerIoTListeners() {
  client.begin(MQTT_HOST, MQTT_PORT, net);

  // Create a message handler
  client.onMessage(messageHandler);

  Serial.print("Connecting to AWS IOT");

  while (!client.connect(IOT_MY_THING_NAME)) {
    Serial.println(client.lastError());
    delay(500);
  }

  if(!client.connected()){
    Serial.println("AWS IoT Timeout!");
    return;
  }

  // Subscribe to a topic
  client.subscribe(AWS_IOT_SUBSCRIBE_TOPIC);

  Serial.println("AWS IoT Connected!");
}

void messageHandler(String &topic, String &payload) {
  Serial.println("incoming: " + topic + " - " + payload);
}

void connectToWiFi() {
  Serial.println("Connecting to wifi");

  WiFi.begin(WIFI_SSID, WIFI_PASS);
  if (WiFi.waitForConnectResult() == WL_CONNECTED) {
    printWifiData();
  } else {
    Serial.println("Connection Failed!");
  }
}

void loop() {
  client.loop();
  delay(1000);
  printWifiData();
}

void printWifiData() {
  Serial.println("Connected!");
}

This is what I get out:

⸮⸮Booting...
Connecting to wifi
Connected!
Connecting to AWS IOT-3
-3
-3
-3
...forever

Is there some way I can get a bit more detail or logging regarding the response from the server? Or some clue as to what I might be missing here?

edit: For context, I'm running an ESP8266 12F NodeMCU chip

myrcutio commented 3 years ago

did some troubleshooting and narrowed it down to some TLS misconfiguration. Adding net.setInsecure(); lets it connect, but obviously that's not a great long term solution.

This is probably a bug in https://github.com/esp8266/Arduino, not in MQTT. Sorry for the trouble