Daemon Services

A Daemon Service is a software service that runs continuously to handle requests. Within ClearBlade Platform or Edge, a Daemon Service will listen to a particular MQTT Topic, and handle requests that come in the form of MQTT Messages from Devices.

Configuration

See Code Service Configuration.

Shared Subscriptions

Shared subscriptions allows for multiple messages to be queued in the message broker and processed through a daemon service. Multiple versions of the same service can be ran and can process many messages from devices.

Example

function SharedTopicLRS(req, resp) {
  ClearBlade.init({ request: req });
  var messaging = ClearBlade.Messaging();
  
  var sharedTopic = "$share/SharedTopicName/device/+";
  var deviceCollection = ClearBlade.Collection({
    collectionName: "some_collection"
  });

  messaging.publish("success", "Service Started");
  messaging.subscribe(sharedTopic, function(err, errMsg) {
    if (err) {
      messaging.publish("error", "Subscribe failed: " + errMsg);
      resp.error();
    }
    messaging.publish("success", "Subscribed to Shared Topic");
    WaitLoop();
  });

  function WaitLoop() {
    messaging.publish("success", "Starting the Loop");
    while (true) {
      messaging.waitForMessage([sharedTopic], function(err, msg, topic) {
        if (err) {
          messaging.publish("error", "Failed to wait for message: " + err + " " + msg + "  " + topic);
          resp.error("Failed to wait for message: " + err + " " + msg + "    " + topic);
        } else {
          // any action
          addCollectionRow(msg);
        }
      });
    }
  }

  function addCollectionRow(msg) {
    try {
      var parseMsg = JSON.parse(msg);
    } catch (e) {
      messaging.publish("error","Problem with parsing: " + e);
      resp.error("Problem with parsing: " + e);
    }
    var data = {
      column_1_name: "column_1_data",
      column_2_name: "column_2_data"
    };
    //debugging
    deviceCollection.create(data, function(err, result) {
      if (err) {
        messaging.publish("error", "failed to create: " + result);
        resp.error("create failed: " + result);
      } else {
        //no op
      }
    });
  }

}