device.on
You can also attach a listener to device meta data. For example you can subscribe to updates on device name to automatically receive update whenever the name of device will be updated.
This method accepts the following arguments
Name | Type | Description |
---|---|---|
path | string | an be name of key, like you can use 'status' to subscribe to status updates of device |
callback | function | a valid JS function which will be called whenever the subscribed event gets fired |
This method returns the following codes in the response to the promise
TOPIC-SUBSCRIBED
event has been subscribed
DEVICE-NOT-PAIRED
device is not paired to the account
DEVICE-ID-INVALID
device is not registered with this id
DATA-INVALID
device id is required
It is important to note that the update will be directly sent without a response code. So for example if a client updates the name of device to New Name then it will be received as it is in the argument of callback.
The call to this method also returns reference to a clear method with which you can unsubscribe to the event. It don't accept anything in the argument and returns the following code as a response to promise
TOPIC-UNSUBSCRIBED
event has been unsubscribed and update won't trigger the callback provided earlier
The use of this method has been illustrated in the example below
// Variable to store clear method of subscribed event
var listener = null;
// Function to be passed as a callback
var onUpdate = (update) {
// Will be called whenever the
// event will be fired
console.log(update);
};
// Subscribe to the device meta data update event of a device
device.on("name", onUpdate).then((res) => {
// Call to onDeviceSummary returns the
// clear method as a response to promise
switch(res.code) {
case "TOPIC-SUBSCRIBED":
// Event has been subscribed
listener = res;
}
});
// Then in our code we can clear the event
// listener whenever required with the clear method
listener.clear().then((res) => {
// Got the response
switch(res.code) {
case "TOPIC-UNSUBSCRIBED":
// Event has been unsubscribed
}
});