I have written code in the Arduino IDE to send messages to an NCP MQTT using an ESP32.
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#define root_ca
"-----BEGIN CERTIFICATE-----n"
"MIIDuT**********************************************************n"
"-----END CERTIFICATE-----n"
#define client_cert
"-----BEGIN CERTIFICATE-----n"
"MIIESj**********************************************************n"
"-----END CERTIFICATE-----n"
#define private_key
"-----BEGIN PRIVATE KEY-----n"
"MIIEow**********************************************************n"
"-----END PRIVATE KEY-----n"
const char* ssid = "5021";
const char* password = "12345678";
const char* mqtt_server = "ssl://msg01.cloudiot.ntruss.com";
const int mqtt_port = 8883;
There are discussions addressing the issue of mqtt_port, so I have checked both 8883 and 1883.
WiFiClientSecure espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[256];
int msgCount = 0;
void setup_wifi() {
delay(10);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
}
I have confirmed that WiFi is connected properly.
void reconnect() {
if (!client.connected()) {
Serial.print("Attempting MQTT connection...");
unsigned long startTime = millis();
if (client.connect("arduinoClient")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
delay(5000);
}
Serial.print("Connection attempt took ");
Serial.print(millis() - startTime);
Serial.println(" ms");
}
}
The continuous occurrence of the rc=-2 error at this point suggests that there might be an issue with the key files or potentially with the communication protocol itself.
void setup() {
Serial.begin(115200);
setup_wifi();
char *dest3;
char *dest1;
char *dest2;
dest1 = (char *)malloc(sizeof(char) * (strlen(root_ca) + 1));
strcpy(dest1, root_ca);
dest2 = (char *)malloc(sizeof(char) * (strlen(client_cert) + 1));
strcpy(dest2, client_cert);
dest3 = (char *)malloc(sizeof(char) * (strlen(private_key) + 1));
strcpy(dest3, private_key);
espClient.setCACert(dest1);
espClient.setCertificate(dest2);
espClient.setPrivateKey(dest3);
client.setServer(mqtt_server, mqtt_port);
}
void loop() {
if (!client.connected()) {
reconnect();
}
if(client.connected() ) {
Serial.print("Client connected");
}
}
“I’ve been modifying my code based on various sources, and I’ve confirmed that WiFi is connected properly, but I keep encountering rc=-2 error. I’m unsure whether I need to adjust settings in the Arduino IDE or change settings in Windows. Please help.”
김민석 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.