Distributed Publish & Subscribe for IoT
Building a DPS network


The Hello world tutorial showed how to build a simple multicast publisher and subscriber network. This tutorial will show how to use the link functionality of DPS to create more complex networks that can span subnets.

As before, we need to create nodes for the publisher and subscriber using DPS_CreateNode() . But this time we will create a third type of node that is neither a publisher or subscriber that will forward publications and subscriptions between the publisher and subscriber nodes.

Note that a third node is not strictly necessary. It is possible to use the same mechanisms described below to link the publisher and subscriber nodes.

Starting a node

int mcastPub = DPS_MCAST_PUB_DISABLED;
if (!listenAddr) {
goto Exit;
}
snprintf(addrText, sizeof(addrText), "[::]:%d", port);
DPS_SetAddress(listenAddr, addrText);
ret = DPS_StartNode(node, mcastPub, listenAddr);
if (ret != DPS_OK) {
goto Exit;
}

The first thing we will do is disable multicast sending and receiving for our three nodes by using DPS_MCAST_PUB_DISABLED for the mcastPub parameter of DPS_StartNode(). All publications and subscriptions will go through the forwarding node.

The second thing we do is specify the listenAddr parameter to DPS_StartNode(). In this instance we bind the node to all available interfaces at the port provided. A port value of zero lets DPS assign an ephemeral listening port. A value of non-zero requests a specific port.

The last thing we do is get the port DPS has chosen with DPS_GetListenAddress(). This will be used by the subscriber and publisher to link to the forwarding node.

Linking to a node

char addrText[24];
snprintf(addrText, sizeof(addrText), "127.0.0.1:%d", linkPort);
ret = DPS_Link(node, addrText, LinkComplete, NULL);
if (ret != DPS_OK) {
goto Exit;
}

Now that we know the host (localhost in this example) and listening port of the forwarding node, we can call DPS_Link() to create the link from the subscriber and publisher to the forwarding node.

static void LinkComplete(DPS_Node* node, const DPS_NodeAddress* addr, DPS_Status status, void* data)
{
DPS_PRINT("Node is linked to %s\n", DPS_NodeAddrToString(addr));
}

The link is now complete and we can proceed with subscribing or publishing as before.

Note
The link complete callback is dispatched from the DPS_Node's thread.
See also
DPS_Unlink(), DPS_LinkTo(), DPS_UnlinkFrom()