Spark Core MDNS and DNS Service Discovery

Posted by Mark Hornsby on 22/01/2015

Over the last few weeks I've been developing a library for the Spark Core that allows you to use MDNS to register your device on the local network and then exposes a service running on the core using DNS Service Discovery.

The example code below shows how to register the spark core under the name core-1.local and then registers an http service running over tcp on port 80.

#include "MDNS/MDNS.h"

#define HTTP_PORT 80

MDNS mdns;

TCPServer server = TCPServer(HTTP_PORT);

void setup() {
    server.begin();

    bool success = mdns.setHostname("core-1");

    if (success) {
        success = mdns.setService("tcp", "http", HTTP_PORT, "Core 1");
    }

    if (success) {
        success = mdns.addTXTEntry("coreid", "1") & mdns.addTXTEntry("extra", "1234");
    }

    if (success) {
        success = mdns.begin();
    }

    if (success) {
        Spark.publish("mdns/setup", "success");
    } else {
        Spark.publish("mdns/setup", "error");
    }
}

void loop() {
    mdns.processQueries();

    TCPClient client = server.available();

    if (client){
        client.println("<html><body><h1>Ok!</h1></body></html>\n\n");
        client.flush();
        client.stop();
    }
}

Using a Bonjour (Zero conf) browser you should be able to now see the core and the details published in the additional TXT records associated with the Core:

Bonjour explorer screenshot

You can now include the library via the Spark Core Web IDE (MDNS v1.0.0) or download the source code here.