Update variable from callback

🟢 Beginner

variable

This example shows how to update a variable at regular intervals by executing a script through a callback and writing the result via an output.

  • Create a script value with owner.scripts to trigger a JS script on each value change.

  • Write a JavaScript function that generates a random number and returns it as the new value.

  • Declare an integer variable with owner.variables and a writable output.variables.

  • Wire the script result to the variable output using a callback.ospp.

git checkout origin/osp-scripts-configuration .
git checkout origin/osp-variables-configuration .
git checkout origin/example-variables-update-from-callback .

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"
}