我有一个树莓派连接到我的WiFi网络,响应的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发送消息给树莓派,但是我想我的ESP32解析使用的mDNS主机。
我无法得到的mDNS工作,在底部打印的代码:
Finding the mDNS details...
No services found...
Done finding the mDNS details...
service
在MDNS.queryService("mqtt-broker", "tcp")
?我曾尝试即使没有运气的服务mqtt
,但是这并不重要,不管的mDNS东西应该工作什么从树莓派暴露(HTTP服务器,MQTT,FTP什么...)这是我使用的代码:
// 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...");
}
此功能已被启发这个例子:
结束了使用不同的方法从由Espressif(ESPmDNS.h
)的组合,条件是库的mDNS类:
IPAddress serverIp = MDNS.queryHost(mDnsHost);
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();
}