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.

@startuml
skinparam backgroundColor transparent
package "root/.../script" {
    [owner.scripts] as trigger
    [callback.ospp] as callback
}

package "root/.../variable" {
    [output.scripts] as output
    [owner.variables] as variable
}
        node ospscripts as "osp-scripts"
        node ospvariables as "osp-variables"

ospscripts -[#black]> trigger : <size:11><color:black>**executes**
trigger .[#grey]> callback : <size:11><color:grey>**random integer**
callback -[#dodgerblue]-> output :<size:11><color:#dodgerblue>**root...script**
output .[#grey]> variable : <size:11><color:grey>**root...script** content
variable -[#black]> ospvariables : <size:11><color:black>**updates**
@enduml

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