Hi, I'm trying to use an Arduino WiFi Shield with an Arduino Mega ADK to connect to CloudMQTT which serves as my MQTT broker. Initially I can set up the client with the pubsubclient library, and when I do Wifi.Begin(ssid, pass), the link LED lights up. However when I try to use the client to get the state, it always returns -2, meaning not connected and "No Socket available". Can someone tell me what this means and why I can't connect?
Code below:
#include <SPI.h>
#include <PubSubClient.h>
#include <WiFi.h>
byte mac[6];
char ssid[] = "******";
char pass[] = "******";
//Mac of wifi shield is **:**:**:**:**:**
WiFiClient wifiClient;
PubSubClient client(wifiClient);
char* topic = "Topic";
char* User = "Arduino";
char* Pass = "arduino";
void callback(char* topic, byte* payload, unsigned int length){
Serial.print(topic);
Serial.println();
for(int i =0; i < length; i++){
//Or can be not converted for number
Serial.print((char) payload[i]);
}
}
void reconnect(){
while(!client.connected()){
if(client.connect("Arduino",User, Pass)){
client.publish(topic, "connected");
client.subscribe(topic);
Serial.println(client.state());
Serial.println("Connected");
}else{
Serial.println(client.state());
Serial.println("Not Connected");
delay(5000);
}
}
}
void setup() {
Serial.begin(57600);
Serial.println("beginning setup");
client.setServer("m10.cloudmqtt.com",*****);
Serial.println("set server");
client.setCallback(callback);
Serial.println("set callback");
WiFi.begin(ssid);
Serial.println("wifi begun");
client.subscribe("Topic");
Serial.println("setting up");
WiFi.macAddress(mac);
}
void loop() {
// put your main code here, to run repeatedly:
if(!client.connected()){
reconnect();
}else{
Serial.println("connected");
}
client.loop();
}
Thanks