marvinroger / async-mqtt-client

📶 An Arduino for ESP8266 asynchronous MQTT client implementation
MIT License
838 stars 268 forks source link

User + Password will not work #210

Open PhetonGH opened 3 years ago

PhetonGH commented 3 years ago

Hi there, I would like to use your code for my SmarthHome, runs great so far, unfortunately I can't get a connection to the broker when I use User + Password. Here is my sketch `

include "DHT.h"

include

include

include

define WIFI_SSID "xxxx"

define WIFI_PASSWORD "xxxxxxx"

// Raspberri Pi Mosquitto MQTT Broker //#define MQTT_HOST IPAddress(xxx,xxx,xxx,xxx) // For a cloud MQTT broker, type the domain name

define MQTT_HOST "xxxxxxx"

define MQTT_PORT 1883

define MQTT_USER "xxxxx"

define MQTT_PWD "xxxxxx"

// Temperature MQTT Topics

define MQTT_PUB_TEMP "Ardu01/Klima/AusT"

define MQTT_PUB_HUM "Ardu01/Klima/AusH"

// Digital pin connected to the DHT sensor

define DHTPIN 5

// Uncomment whatever DHT sensor type you're using

define DHTTYPE DHT11 // DHT 11

//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 //#define DHTTYPE DHT21 // DHT 21 (AM2301)

// Initialize DHT sensor DHT dht(DHTPIN, DHTTYPE);

// Variables to hold sensor readings float temp; float hum;

AsyncMqttClient mqttClient; Ticker mqttReconnectTimer;

WiFiEventHandler wifiConnectHandler; WiFiEventHandler wifiDisconnectHandler; Ticker wifiReconnectTimer;

unsigned long previousMillis = 0; // Stores last time temperature was published const long interval = 15000; // Interval at which to publish sensor readings

void connectToWifi() { Serial.println("Connecting to Wi-Fi..."); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); }

void onWifiConnect(const WiFiEventStationModeGotIP& event) { Serial.println("Connected to Wi-Fi."); connectToMqtt(); }

void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { Serial.println("Disconnected from Wi-Fi."); mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi wifiReconnectTimer.once(2, connectToWifi); }

void connectToMqtt() { Serial.println("Connecting to MQTT..."); mqttClient.connect(); }

void onMqttConnect(bool sessionPresent) { Serial.println("Connected to MQTT."); Serial.print("Session present: "); Serial.println(sessionPresent); }

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { Serial.println("Disconnected from MQTT.");

if (WiFi.isConnected()) { mqttReconnectTimer.once(2, connectToMqtt); } }

/*void onMqttSubscribe(uint16_t packetId, uint8_t qos) { Serial.println("Subscribe acknowledged."); Serial.print(" packetId: "); Serial.println(packetId); Serial.print(" qos: "); Serial.println(qos); }

void onMqttUnsubscribe(uint16_t packetId) { Serial.println("Unsubscribe acknowledged."); Serial.print(" packetId: "); Serial.println(packetId); }*/

void onMqttPublish(uint16_t packetId) { Serial.print("Publish acknowledged."); Serial.print(" packetId: "); Serial.println(packetId); }

void setup() { Serial.begin(115200); Serial.println();

dht.begin();

wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);

mqttClient.onConnect(onMqttConnect); mqttClient.onDisconnect(onMqttDisconnect); //mqttClient.onSubscribe(onMqttSubscribe); //mqttClient.onUnsubscribe(onMqttUnsubscribe); mqttClient.onPublish(onMqttPublish); mqttClient.setServer(MQTT_HOST, MQTT_PORT); // If your broker requires authentication (username and password), set them below mqttClient.setCredentials(MQTT_USER, MQTT_PWD).setClientId("Ardu01");

connectToWifi(); }

void loop() { unsigned long currentMillis = millis(); // Every X number of seconds (interval = 10 seconds) // it publishes a new MQTT message if (currentMillis - previousMillis >= interval) { // Save the last time a new reading was published previousMillis = currentMillis; // New DHT sensor readings hum = dht.readHumidity(); // Read temperature as Celsius (the default) temp = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true) //temp = dht.readTemperature(true);

// Publish an MQTT message on topic Ardu01/Klima/AusT
uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());                            
Serial.printf("Publishing on topic %s at QoS 1, packetId: %i ", MQTT_PUB_TEMP, packetIdPub1);
Serial.printf("Message: %.2f \n", temp);

// Publish an MQTT message on topic Ardu01/Klima/AusH
uint16_t packetIdPub2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());                            
Serial.printf("Publishing on topic %s at QoS 1, packetId: %i ", MQTT_PUB_HUM, packetIdPub2);
Serial.printf("Message: %.2f \n", hum);

} }` My broker log

... New connection from 192.168.169.43 on port 1883. Socket error on client , disconnecting. New connection from 192.168.169.43 on port 1883. Socket error on client , disconnecting. ...

and the output of the serial monitor ... Connecting to MQTT... Disconnected from MQTT. Connecting to MQTT... Disconnected from MQTT. Connecting to MQTT... Disconnected from MQTT. ...

If i comment out

mqttClient.setCredentials(MQTT_USER, MQTT_PWD).setClientId("Ardu01"); like //mqttClient.setCredentials(MQTT_USER, MQTT_PWD).setClientId("Ardu01");

it works fine (need to allow ananymos on my Mosquitto)

I checked the user + password twice, I am using a special character in the password "!" Could that be the cause? thank you ever for your help

CU JP

vladimirko commented 3 years ago

You must use static variables for the const char varibles, as the API simply uses a ponter and does NOT copy the value. You're using temporary stack variables, that get destroyed upon exiting the function.

static const char mqttUser[] = "userName"; static const char mqttPassword[] = "passWord"; static AsyncMqttClient asyncMqttClient;

asyncMqttClient.setCredentials(mqttUser, mqttPassword);

bertmelis commented 3 years ago

Please try again with the develop branch and print out the returned disconnection code.

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.printf("Disconnected from MQTT: %u\n", static_cast<std::underlying_type<AsyncMqttClientDisconnectReason>::type>(reason));

  if (WiFi.isConnected()) {
    mqttReconnectTimer.once(2, connectToMqtt);
  }
}
Bustead commented 1 year ago

I'm not even sure the setClientID is necessary? Here's what is working for me. I came across this thread having very similar issues but I seem to have resolved them on the server side by restarting Mosquitto

mqttClient.setCredentials(SECRET_MQTTNAME, SECRET_MQTTPASSWORD);