Hello,
I have made some progresses using the PubSubClient library for MQTT from Nick O’Leary, available on Github : GitHub - knolleary/pubsubclient: A client library for the Arduino Ethernet Shield that provides support for MQTT..
My arduino gets rejected by the Cayenne server with an MQTT Return Code 2, i.e. “Connection refused, identifier rejected”.
I’m using the credentials provided on the cayenne webpage.
The sketch is below:
/*
Basic MQTT example
This sketch demonstrates the basic capabilities of the library.
It connects to an MQTT server then:
- publishes “hello world” to the topic “outTopic”
- subscribes to the topic “inTopic”, printing out any messages
it receives. NB - it assumes the received payloads are strings not binary
It will reconnect to the server if the connection is lost using a blocking
reconnect function. See the ‘mqtt_reconnect_nonblocking’ example for how to
achieve the same result without blocking the main loop.
*/
#include <PubSubClient.h>
#include <WiFi.h>
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(“Message arrived [”);
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
const char* mqtt_server = “mqtt.mydevices.com”;
WiFiClient ethClient;
PubSubClient client(ethClient);
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(“Attempting MQTT connection…”);
// Attempt to connect
//Client ID, MQTT Username, MQTT Password
if (client.connect(“a5a72834-3244-11e7-85a7-c34806d4e04d”,“ae8d97b0-f7680-11e6-81d7-ad79ee868075”,“f6fb0e6176dbb2527617a2333f14859b3e9fdaf8”)) {
Serial.println(“connected”);
// Once connected, publish an announcement…
client.publish(“outTopic”,“hello world”);
// … and resubscribe
client.subscribe(“inTopic”);
} else {
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(9600);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
// Allow the hardware to sort itself out
delay(1500);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
I get the following error:
Attempting MQTT connection…failed, rc=-2 try again in 5 seconds
Any help identifying why my device gets rejected would be appreciated
Thanks