knolleary / pubsubclient

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

esp32 Not connecting to mqtt server - odd IP after assignment #905

Open skiminnetonka opened 2 years ago

skiminnetonka commented 2 years ago

I have a simple program that connects to wifi, then mqtt and then sends out some mqtt messages. The connections work fine when I point at broker.hive.com as the mqttServer, but when I try to point at my personal mosquitto broker I get the dreaded -2 status. I have searched high and low and tried the fixes suggested in the Issues here and elsewhere on the internet to no avail. I have tried using different wifi connections (hotspot and in-home) no change. The most disturbing clue that I can not seem to figure out is the serial output for mqttServer "Connecting MQTT to: 82.0.0.0" when I am using the direct IP address of the server as the input. when I use the domain the serial output prints correct as the input domain mqtt.getmetheinfo.com, but the connection also status is -2.

I appreciate the help as I have spent two days chasing this down and I can not figure out why it works with other servers and my broker works with other clients but not together.

Here is the code sorry for odd formating

``

include

include

include

include

include

include

include

include

static BLEAddress *pServerAddress; //known

const int ledPin = 2; const char ssid = "test"; const char password = "test1234"; //const char mqttServer = "mqtt.getmetheinfo.com"; //original try //#define mqttServer "mqtt.getmetheinfo.com" //another option did not work const char mqttuser = "*"; const char mqttpass = ""; const int mqttPort = 1883; const int maxDevices = 10; const int bluetoothScanDuration = 3; String mqttRegTopic = "kt/registration/"; String mqttTopic = "kt/presence/bt/";

String knownAddresses[] = { "ff:ff:44:50:88:58", "ff:ff:44:50:8c:4e"};

IPAddress mqttServer = (173,29,66,82); //set direct IP of broaker - works fine on other mqtt clients

WiFiClient wifiClient;

PubSubClient client(mqttServer, mqttPort, wifiClient); //fully setup client early

BLEScan* pBLEScan;

const int capacity = JSON_ARRAY_SIZE(maxDevices) + (maxDevices * JSON_OBJECT_SIZE(3)); StaticJsonDocument btDevices; char jsonOutput[128];

void mqttCallback(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();

}

void reconnect() { const String bluetoothMac = BLEDevice::getAddress().toString().c_str(); String clientId = "KounterTop-"; clientId += bluetoothMac; clientId += String(random(0xffff), HEX); //random client // Loop until we're reconnected while (!client.connected()) { Serial.println(clientId); Serial.print("Connecting MQTT to: ");

**Serial.println(mqttServer); //gives very odd 82.0.0.0 result in serial output** 
// Attempt to connect
  if (client.connect(clientId.c_str(),mqttuser,mqttpass)) {
  Serial.println("MQTT connected");
  client.publish(mqttRegTopic.c_str(), "hello world");
  //client.subscribe("inTopic");mqttServermqttServermqttServermqttServermqttServer
} else {
  Serial.print("failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 5 seconds");
  // Wait 5 seconds before retrying
  setup_wifi();
  delay(5000);
}

} }

void setup_bluetooth() { Serial.println("Setting up Bluetooth");

BLEDevice::init("KounterTop");

pBLEScan = BLEDevice::getScan(); //create new scan pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster pBLEScan->setInterval(1000); pBLEScan->setWindow(999); // less or equal setInterval value

const String bluetoothMac = BLEDevice::getAddress().toString().c_str(); // Create full MQTT topic mqttTopic += bluetoothMac;

Serial.print("Bluetooth ready. MAC: "); Serial.println(bluetoothMac); }

void setup_wifi() { Serial.print("Connecting WiFi to "); Serial.println(ssid); WiFi.mode(WIFI_STA);

while (WiFi.status() != WL_CONNECTED) { WiFi.begin(ssid,password); delay(5000); Serial.print("."); }

randomSeed(micros());

Serial.print("WiFi connected IP: "); Serial.println(WiFi.localIP()); }

void setup_mqtt() { //client.setServer(mqttServer, mqttPort); //orginal mqtt server setup did not work so moved up and that did not work either client.setCallback(mqttCallback); reconnect(); }

void setup() { pinMode(ledPin, OUTPUT); Serial.begin(115200); delay(10);

// Set up devices JSON object int i = 0; while(i < maxDevices) { btDevices.createNestedObject(); i++; }

setup_bluetooth(); setup_wifi(); setup_mqtt();

Serial.print("MQTT Topic: "); Serial.println(mqttTopic.c_str()); }

void loop() { // Make sure MQTT is connected Serial.println(mqttServer); if (!client.connected()) { reconnect(); } client.loop();

// Scan for BLE devices digitalWrite(ledPin, HIGH); BLEScanResults foundDevices = pBLEScan->start(bluetoothScanDuration, false); digitalWrite(ledPin, LOW); Serial.print("Scan complete. Devices:");

// Go over found devices and generate JSON payload int i = 0;

Serial.println(foundDevices.getCount());

while(i < foundDevices.getCount()) { bool known = false; //add for known BLEAdvertisedDevice device = foundDevices.getDevice(i); String deviceAddress = device.getAddress().toString().c_str(); String deviceName = device.getName().c_str(); const int deviceRssi = device.getRSSI(); Serial.print("Device #"); Serial.print(i); Serial.print(" "); Serial.print(deviceAddress); Serial.print(": "); Serial.println(deviceRssi);

for (int x = 0; x < (sizeof(knownAddresses) / sizeof(knownAddresses[0])); x++) {
  //Serial.println(device.getAddress().toString().c_str());

// Serial.println(knownAddresses[x].c_str());

  if (deviceRssi > -90 && strcmp(deviceAddress.c_str(), knownAddresses[x].c_str()) == 0) known = true;

  //add for known

}   
if (known) { //add for known
Serial.print("Known device #");
Serial.print(i);
Serial.print(" ");
Serial.print(deviceAddress);
Serial.print(": ");
Serial.println(deviceRssi);

JsonObject btDevice = btDevices[i];
btDevice["D"] = deviceAddress;

btDevice["S"] = "Top";
btDevice["R"] = deviceRssi;

serializeJson(btDevice, jsonOutput);

//client.publish((mqttTopic).c_str(), jsonOutput);

client.publish((mqttTopic + "/" + deviceAddress).c_str(), jsonOutput);
}

i++;

}

// Clear scan results to free buffer pBLEScan->clearResults(); //delete pServerAddress; delay(2000); }``

skiminnetonka commented 2 years ago

Well, nothing like finally posting to lead you to the real issue on the next try. My broker server IP is IPv6 set by dynamic DNS. The PubSubClient can not handle that. I figured this out by making a new CNAME pointed a the IPv4 and using it for the broker. That made the connection work. So, I am not sure if the client is deficient or the way it uses DNS or ... the odd 82.0.0.0 issue remains but is not an issue because I can use the full new domain and make the connection.