Tuesday, January 17, 2017

Auto discover Mqtt server using arduino mdns

So I am using MyControllerDevice to connect to MyController, however the default way is to input the ip address of the mqtt server when setting up the arduino. I would like a way to auto discover the mqtt server and register itself to the mqtt server. I searched and found mdns could work. These are the steps i did to get it working:

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
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 services
Serial.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);
}
_mqttServer is the ip address of the mqtt server.
_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. =)

1 comment: