mrdunk / esp8266_mdns

mDNS queries and responses on esp8266
MIT License
77 stars 16 forks source link

mDNS doesn't work with WiFiManager library #15

Open FilipBelohlavek opened 4 years ago

FilipBelohlavek commented 4 years ago

Hi, I'm trying to find an IP address of a HomeAssistant gateway on the subnet. Here's the problem. If I hard code my ssid and password it all works fine. Once I start using the WiFiManager library it suddenly stops working. I get no answers or bunch of different hostnames that aren't the one I queried for. I made sure that this library is the cause, without including it in the code, the query gets answered properly. Btw majority of this code is from here https://hackaday.io/project/12482-garage-door-opener/log/46150-an-mdns-library . When I upload only his code, it works. With the WiFiManager modification, it doesn't. Here's my code:

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiManager.h>
#include "mdns.h"

#define QUERY_NAME "hassio.local" // not used

void answerCallback(const mdns::Answer* answer);
void query(const char *name);
void setupDevice();

mdns::MDns my_mdns(NULL, NULL, answerCallback);

void setup() {

    Serial.begin(115200);

   //this function connects to WiFi using WiFiManager
    setupDevice();

// with this "hard coded credentials" approach it all works

 /* WiFi.begin("[ssid]", "[pass]");

  Serial.print("Connecting to WiFi");
  // Wait for connect to AP
  int tries = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    tries++;
    if (tries > 50) {
      Serial.println("Connection failed");
      break;
    }
  }
  Serial.println();*/
  Serial.println("Ending setup...");
}

int send = 0;
void loop() {
  if(send == 0) {  
    Serial.println("Sending query...");
    query("hassio.local");  
    send = 1;
  }
  my_mdns.loop(); 
}

void answerCallback(const mdns::Answer* answer){
  if(strcmp(answer->name_buffer, "hassio.local") == 0) {
    Serial.print("Name: ");
    Serial.println(answer->name_buffer);
    Serial.print("Answer: ");
    Serial.println(answer->rdata_buffer);
    Serial.print("TTL: ");
    Serial.println(answer->rrttl);    
  }
  else{
    Serial.print("Wrong name: ");
    Serial.println(answer->name_buffer);
    send = 0;
    delay(1000);
  }
}
//setup a query here
void query(const char *name) {
  mdns::Query q;

  int len = strlen(name);

  for(int i = 0; i < len; i++) {
    q.qname_buffer[i] = name[i];
  }
  q.qname_buffer[len] = '\0';

  q.qtype = 0x01;
  q.qclass = 0x01;
  q.unicast_response = 0;
  q.valid = 0;

  my_mdns.Clear();
  my_mdns.AddQuery(q);
  my_mdns.Send();
}

void setupDevice(){

  WiFiManager wifiManager;

  wifiManager.autoConnect("ILS - setup");

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

  delay(5000);
}

If some more info is needed, I'll be more than happy to provide all you need. Thanks!