ESP32(DOIT DevKit)如何通过 mDNS 在同一局域网中找到另一台主机?

How is the ESP32 (DOIT DevKit) finding another host in the same LAN via mDNS?

我有一个 Raspberry Pi 连接到我的 Wifi LAN,它响应 mDNS 为 mqtt-broker.local

我可以使用以下命令在笔记本电脑上找到它:

$ avahi-resolve-host-name -4 mqtt-broker.local
mqtt-broker.local   192.168.XXX.YYY

我有一个 ESP32 DOIT DevKit 设备,如果我使用 IP 地址 192.168.XXX.YYY,它可以通过 Wifi 向 Raspberry Pi 发送消息,但是我希望我的 ESP32 使用 mDNS 解析主机。

我无法让 mDNS 工作,底部的代码打印:

Finding the mDNS details...
No services found...
Done finding the mDNS details...

这是我使用的代码:

// import the headers
#include <ESPmDNS.h>

void findMyPi() {
  Serial.println("Finding the mDNS details...");

  // make sure we are connected to the Wifi
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.println("Not yet connected to Wifi...");
  }

  if (!MDNS.begin("whatever_this_could_be_anything")) {
    Serial.println("Error setting up MDNS responder!");
  }

  // what should I put in here as "service"?
  int n = MDNS.queryService("mqtt-broker", "tcp");
  if (n == 0) {
    Serial.println("No services found...");
  }
  else {
    for (int i = 0; i < n; ++i) {
      // Print details for each service found
      Serial.print("  ");
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(MDNS.hostname(i)); // "mqtt-broker" ??? How can I find it???
      Serial.print(" (");
      Serial.print(MDNS.IP(i));
      Serial.print(":");
      Serial.print(MDNS.port(i));
      Serial.println(")");
    }
  }
  Serial.println("Done finding the mDNS details...");
}

这个函数的灵感来自这个例子:

https://github.com/espressif/arduino-esp32/blob/master/libraries/ESPmDNS/examples/mDNS-SD_Extended/mDNS-SD_Extended.ino

最终在 Espressif (ESPmDNS.h) 提供的 mDNS 库上使用了与 class 不同的方法,结合了:

  • IPAddress serverIp = MDNS.queryHost(mDnsHost);
  • while 在此检查上循环 serverIp.toString() == "0.0.0.0"

这是将所有内容粘合在一起的代码:

// on my laptop (Ubuntu) the equivalent command is: `avahi-resolve-host-name -4 mqtt-broker.local`
String findMDNS(String mDnsHost) { 
  // the input mDnsHost is e.g. "mqtt-broker" from "mqtt-broker.local"
  Serial.println("Finding the mDNS details...");
  // Need to make sure that we're connected to the wifi first
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.print(".");
  }
  if (!MDNS.begin("esp32whatever")) {
    Serial.println("Error setting up MDNS responder!");
  } else {
    Serial.println("Finished intitializing the MDNS client...");
  }

  Serial.println("mDNS responder started");
  IPAddress serverIp = MDNS.queryHost(mDnsHost);
  while (serverIp.toString() == "0.0.0.0") {
    Serial.println("Trying again to resolve mDNS");
    delay(250);
    serverIp = MDNS.queryHost(mDnsHost);
  }
  Serial.print("IP address of server: ");
  Serial.println(serverIp.toString());
  Serial.println("Done finding the mDNS details...");
  return serverIp.toString();
}