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 });
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.