Update variable from callback
Description
In this tutorial you will learn how to create a script that periodically updates the content of a variable using a callback.
The script will be executed every second and generates a random integer that will be bound to the script’s value. Once the value is updated, the callback will be triggered and forwards the value content to the linked variable.
Note
The script value used to trigger the callback in this example could be replaced by any other kind of value.
Steps
1. Create a value script that will be executed every second
root/examples/variables/update-variable-from-callback/script/value.ospp
{
"name": "Periodic script",
"description": "Script that executes periodically",
"type": "INTEGER"
}
*root/examples/variables/update-variable-from-callback/script/owner.scripts*
{
"moduleId": "modules.scripts.scripts-1",
"scheduledExecutions": ["* * * ? * * *"],
"accessedValues": [],
"sourceFile": "root/variables/update-variable-from-callback/script/script.js"
}
2. Write a script that generates a random number and returns it
root/examples/variables/update-variable-from-callback/script/script.js
main();
function main() {
let value = Math.floor(Math.random() * 100);
log.info("Generating value [{}]", value)
return value;
}
3. Create an integer variable
root/examples/variables/update-variable-from-callback/variable/value.ospp
{
"name": "Integer variable",
"description": "Variable updated from a callback",
"type": "INTEGER"
}
root/examples/variables/update-variable-from-callback/variable/owner.variables
{
"moduleId": "modules.variables.variables-1"
}
4. Create an output to the previously created variable so one can write its content
root/examples/variables/update-variable-from-callback/variable/output.variables
{
"variableId": "root.variables.update-variable-from-callback.variable"
}
5. Create a callback next to the value script to link it to the previously created variable output
root/examples/variables/update-variable-from-callback/script/callback.ospp
{
"linkedOutputs": [
{"outputId": "root.variables.update-variable-from-callback.variable"}
]
}