1) Set up avahi-daemon.
sudo apt-get install avahi-daemon
2) Create an avahi configuration file /etc/avahi/services/mosquitto.service
<?xml version="1.0" standalone='no'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
<name replace-wildcards="yes">Mosquitto MQTT server on %h</name>
<service>
<type>_mcmqtt._tcp</type>
<port>1883</port>
<txt-record>info=A MQTT PubSub service! mqtt.org</txt-record>
</service>
</service-group>
3) Use this piece of code to get the ipaddress of the mqtt server
_mqttServer is the ip address of the mqtt server.char hostString[16] = { 0 };sprintf(hostString, "ESP_%06X", ESP.getChipId());Serial.print("Hostname: ");Serial.println(hostString);WiFi.hostname(hostString);if (!MDNS.begin(hostString)) {Serial.println("Error setting up MDNS responder!");}Serial.println("MC: Sending mDNS query");int n = MDNS.queryService("mcmqtt", "tcp"); // Send out query for esp tcp servicesSerial.println("MC: mDNS query done");if (n == 0) {Serial.println("MC: no services found");}else {Serial.print(n);
Serial.println(" service(s) found");
for (int i = 0; i < n; ++i) {DNS.port(i));MDNS.IP(i).toString().toCharArray(_mqttServer, 51);_mqttPort = MDNS.port(i);}
_mqttPort is the port number of the mqtt server.
4) set the mqtt server and use it.
mqttClient.setServer(_mqttServer, _mqttPort);
5) That's all. =)
Thanks for sharing!
ReplyDeletegmail.com sign in