Setting a Value From a Cloud Action
This topic describes how to set a value from a cloud action.
There are many use cases where you might want to make a change at the edge as a result of a Cloud Action.
To accomplish this, the Cloud Action's script simply needs to write an Event to the :command Stream of the Octave edge device. An Event can be used to change multiple Resources and Virtual Resources at the edge.
The following steps use the example of setting the LCD value on the LCD screen included with the mangOH Red. In this example we will update line 1 of the LCD screen with a message when the brightness detected by the device's light sensor exceeds an arbitrary threshold of 1500.
- Create a Sensor Resource for the mangOH Red's LCD screen and ensure its period is set to few seconds (e.g., 5 seconds).
- Create an Observation to send the light readings to a cloud stream. As a result, once the configuration is applied on the device, you will see the stream updated every 5 seconds with a new reading from the light sensor. In this example the stream is named light_direct.
- Create a Cloud Action and configure its Source stream or tag to Stream.
- Select the Stream: //devices//:command.
- Enter the following code:
function(event) {
var output = {};
var deviceId = event.path.split("/")[3];
var companyId = event.path.split("/")[1];
var command_path = "/" + companyId.toLowerCase() + "/devices/" + deviceId.toLowerCase() + "/:command";
var light_reading = event.elems.redSensor.light;
if (light_reading > 1500) {
output[command_path] = [{
"elems": {
"lcd": {
"txt1": "too Much Light!"
}
}
}];
}
return output;
}
- Click Save.
If you provide light to the light sensor of the mangOH Red, you will see the message too Much Light showing on the screen.
- Verify that the Event has been added to the :command stream of your device.
You can identify if the command has been processed on the device or if an error occurred, by looking for COMMAND_START / COMMAND_COMPLETE
or COMMAND_FAULT
in the :inbox Stream of your device; they also appear in the Recent changes regions on the Device > Details screen.
Resource Path
Most of the time you will need to change the sub resource
value
of a Resource. To do this, addvalue
to the resource path:/app/NAME/value
.The following is an example of an Event to send, that updates a Virtual Resource named lightThreshold :
{ "elems": { "virtual/lightThreshold/value": 1200 } }
You can also add a timeout or ttl: time to live parameter to the Event you are sending to the :command Stream of an Octave edge device. When this parameter is set, Octave will attempt to deliver the command to the device until it succeeds, or the timeout is exceeded. Timeout and TTL are defined as optional attributes of the Event metadata field (in milliseconds).
In the example below the command will timeout after one minute:
{
"elems": {
"lcd/txt1": "too Much Light !"
},
"metadata": {
"ttl": 60000
}
}
Updated about 4 years ago