MQTT can't connect with user and psswd

Hi.

I set up a windows 10 eclipse mosquitto broker. My other devices (zigbee2mqtt, tasmota etc) connects fine, but my ESP8266 / ESP32 will not connect with user and password. Authentication error.

If I edit the conf file with "allow_anonymous true" it can connect, but with "allow_anonymous false" it won't.

Like I said, other devices connect just fine with the same username and password.

Any suggestions?

Although bad practice I removed some part of the code to stay within 9000 char.

#define MQTT_KEEPALIVE 60
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>

#define LED 16  

//"**CHANGE**" wifi SSID and password
const char* ssid = "myssid";
const char* password = "mypsswd";

//"**CHANGE**" MQTT server IP address
const char* mqtt_server = "192.168.winpc.ip";  //my windows machine ip
const char* mqtt_user = "user"; // from psswd file in C:/mosquitto directory
const char* mqtt_password = "psswd"; //from psswd file in C:/mosquitto directory

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;


IPAddress server(192, 168, x, xx);
unsigned long heartbeat_millis=0;
int heartbeat_cnt=0;

//"**CHANGE**" debug output
#define MyDebug 0   //0=no debug, 1=deeebug

/*
**CHANGE** mqtt_name[] used as part of topic name
/ble/MQTT_NAME/mac/rssi
/ble/MQTT_NAME/mac/volt
*/

const char mqtt_name[]="2etg";


const int pinHandShake = 4; //handshake pin, esp8266 GPIO4/D2

//buffer for char[] used in mqtt publishes, size at least as big as topic + msg length
char mqtt_buf[120];  // e.g "/ble/esp1/d76dcd1b3720/volt" is 30 chars long

bool conn_status;
// Callback function header
void callback(char* topic, byte* payload, unsigned int length);


const int serialBufSize = 100;      //size for at least the size of incoming JSON string
static char serialbuffer[serialBufSize];  // {"mac":c2f154bb0af9,"rssi":-55,"volt":3.05,"mag":1}
static char mytopic[120];  //MQTT topic string size, must be less than size declared.
//todo: add error checking for mqtt msg lengths


void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  digitalWrite(LED, HIGH);  //off
}

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




  
  char message_buff[60]; //payload string
  // create string for payload
  int i=0;
  for(i=0; i<length; i++)
  {
    message_buff[i] = payload[i];
  }
  message_buff[i] = '\0';  //terminate buffer string class eol
  String msgString = String(message_buff);
  

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client123-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      client.loop();
      // ... and resubscribe
      //client.subscribe("inTopic");
      //client.subscribe("50C51C570B00");   //switched ble
      //client.subscribe("req_door_open");
      //client.subscribe("req_door_close");
      //client.subscribe("mq_snow_red");
      //client.subscribe("mq_snow_green");
      //client.subscribe("mq_snow_blue");
      //client.subscribe("mq_tree_red");
      //client.subscribe("mq_tree_green");
      //client.subscribe("mq_tree_blue");


      
    } 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() {
  pinMode(LED, OUTPUT);     //  BUILTIN_LED pin as an output, actually pin D0 (GPIO16)
  digitalWrite(LED, LOW);  //LED on
  Serial.begin(9600);   //ESP8266 default serial on UART0 is GPIO1 (TX) and GPIO3 (RX)
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  pinMode(pinHandShake, OUTPUT);
  setup_wifi();
  client.setServer(mqtt_server, 1883); 
  client.setCallback(callback);
}



//stealing this code from
//https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/
//non-blocking serial readline routine, very nice.  Allows mqtt loop to run.
int readline(int readch, char *buffer, int len)
{
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\n': // Ignore new-lines
        break;
      case '\r': // Return on CR
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
          buffer[pos++] = readch;   //first buffer[pos]=readch; then pos++;
          buffer[pos] = 0;
        }
    }
  }
  // No end of line has been found, so return -1.
  return -1;
}


//json iterator that parses char* and publish each key-value pair as mqtt data
void localParseJson(char *mybuf)
{

  //JSON parsing
  //JSON object exists in this scope, routine should execute atomatically no interrupts
  //If software serial is used, and parsing is interrupted, json object still be valid?
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& object = jsonBuffer.parseObject(mybuf);
  /*
    Incoming uart:
    mac:c2f154bb0af9,rssi:-55,volt:3.05,mag:1
    
    Iterate and publish as
    /ble/livingroom/c2f154bb0af9/rssi -55
    /ble/livingroom/c2f154bb0af9/volt 3
    /ble/livingroom/c2f154bb0af9/mag 1

  1)  count # fields in after MAC
  2)  concat "ble"/"MAC"/+iterate field
  3)  capture data to publish
   */
  if (object.success())
  {
    // Parsing success, valid json
    //todo:  it's too easy to forget mytopic size, not checking for size when string being assembled.
    //    add error checking and improve readability

    int topic_char_index=0;
    // mytopic[i] = '\0'; make sure null terminate mytopic
  
    //construct the first part of the topic name, which is just /ble/mac
    mytopic[0]='/'; topic_char_index++;
    mytopic[1]='y'; topic_char_index++;
    mytopic[2]='y'; topic_char_index++;
    mytopic[3]='y'; topic_char_index++;
    mytopic[4]='/'; topic_char_index++;  //topic_char_index is 5;

    //add gateway location name, /ble/LIVINGROOM
    int mqtt_name_len = sizeof(mqtt_name);  //returns num of chars + 1 for \0 character
    
    #if MyDebug
    Serial.print("topic_char_index before mqtt_name:  ");
    Serial.println(topic_char_index);
    Serial.print("size of mqtt_name_len should be 16:  ");
    Serial.println(mqtt_name_len);
    #endif

    for (int i=0; i<(mqtt_name_len-1); i++)
    {
      #if MyDebug
      Serial.println(mqtt_name[i]);
      #endif
      mytopic[topic_char_index] = mqtt_name[i];
      topic_char_index++;
    }
    mytopic[topic_char_index] = '/';  topic_char_index++;
    
    #if MyDebug
    Serial.print("topic_char_index after mqtt_name:  ");
    Serial.println(topic_char_index);
    #endif
    
    //set string pointer to JSON Value containing the key "mac"
    // so it's pointing to "mac":c2f154bb0af9
    const char* mac_name = object["mac"];
    
    #if MyDebug
    Serial.println("mac name is");
    Serial.println(mac_name);
    #endif
    
    int sizeofff = strlen(mac_name);    //returns exactly number of characters in mac_name.  Doesn't add 1 like sizeof

    #if MyDebug
    Serial.print("size of macname: ");
    Serial.println(sizeofff);
    #endif

    // /ble/livingroom/c2f154bb0af9/
    //fill mac address into topic name string
    for (int i=0; i<sizeofff; i++)
    {
      mytopic[topic_char_index]= mac_name[i];
      topic_char_index++;
    }
    mytopic[topic_char_index] = '/';
    topic_char_index++;

    #if MyDebug
    Serial.println("mytopic after mac address add");
    Serial.println(mytopic);
    #endif

In the code posted, there's no loop function and no use of mqtt_password.

I removed it because it didn't work and forgot to re-add before posting, sorry :o
I found the mistake I made.

This was my original which didn't work ;

if (client.connect(clientId,mqtt_user,mqtt_password)) {

This line worked however ;

if (client.connect(clientId.c_str(),mqtt_user,mqtt_password)) {

All good, thanks.

1 Like