Publishing interval-based observable data

Let us begin publishing sensor data. This is done in a similar way to the HTTP case, by adding resources to our endpoint. There are two additions we must consider. First, we want to support observable resources. This means we need to store a reference to the resource we create, so that we can tell it when values change. These reference variables will be of CoapResource type. We also specify what messaging service to use when updating values to subscribers. For our ambient light sensor, we will choose the unacknowledged service.

We will also add some metadata about the resources we create, for interoperability. We will discuss this more in the next chapter. For now, it's sufficient to know that we give a human-readable title to our resource, as well as specify the content formats our resource supports:

this.lightResource = this.coapEndpoint.Register("/Light", 
   (req, resp) => 
   { 
         string s; 
 
         if (this.lastLight.HasValue) 
               s = ToString(this.lastLight.Value, 2) + " %"; 
         else 
               s = "-"; 
 
         resp.Respond(CoapCode.Content, s, 64); 
   }, Notifications.Unacknowledged, "Light, in %.", null, null, 
   new int[] { PlainText.ContentFormatCode }); 
Classes for common content formats are available in the Waher.Networking.CoAP.ContentFormats namespace.

To let the resource know it should update any subscribers using a regular time interval, we call the TriggerAll() method on the resource, with the time interval we want to define:

this.lightResource?.TriggerAll(new TimeSpan(0, 0, 5)); 

In this case, subscribers will be updated every five seconds about changes to the light value. We don't have to worry more about this; the CoAP library takes care of the rest.

The ?. operator executes the method, but only if the object reference is not null. This avoids exceptions during the initialization or termination phases of an application.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.9.115