Update variable from script

Description

In this tutorial you will learn how to create a script that periodically directly updates the content of a variable.

The script will be executed every second and generates a random integer that will be sent directly to the variable.

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

package "root/.../variable" {
    [owner.variables] as variable
}

        node ospscripts as "osp-scripts"
        node ospvariables as "osp-variables"

ospscripts -[#black]> trigger : <size:11><color:black>**executes**
trigger -[#black]d-> variable : <size:11><color:black>**values.update(...)**
variable -[#black]> ospvariables : <size:11><color:black>**updates**
@enduml

Steps

1. Create a detached script that will be executed every second

root/examples/variables/update-variable-from-script/script/detached.scripts

{
    "moduleId": "modules.scripts.scripts-1",
    "scheduledExecutions": ["* * * ? * * *"],
    "accessedValues": [],
    "sourceFile": "root/variables/update-variable-from-script/script/script.js"
}

2. Create an integer variable

root/examples/variables/update-variable-from-script/variable/value.ospp

{
    "name": "Integer variable",
    "description": "Variable updated from a script",
    "type": "INTEGER"
}

root/examples/variables/update-variable-from-script/variable/owner.variables

{
  "moduleId": "modules.variables.variables-1"
}

3. Write a script that generates a random number and updates the variable

root/examples/variables/update-variable-from-script/script/script.js

main();

function main() {
    let number = Math.floor(Math.random() * 100);
    values.update("root.variables.update-variable-from-script.variable", number);
}

4. Visualize the value change

The example Visualize current state of values show how to display a value.