Skip to content

OPC-UA Sim Lua script tutorial

This tutorial will outline how to write a basic lua script to control the simulator. We will cover how to create a variable node and update its value with the Update function.

Create a new server namespace

tutorial_namespace = Server.addNamespace("Tutorial")

Create a new Folder to store our Node in

This will create a new folder under the Objects folder. We will also need to register this Node with the server.

tutorial_folder = ObjectNode.newRootFolder("Tutorial", tutorial_namespace)
Server.addObjectNode(tutorial_folder)

Create our Variable node

This will create a new node with a string node identifier. The name of the node will be called Counter and it will be placed under the tutorial_folder node as we have set this as the parent node. We have defined the permissions of the node so that it can be read from and written to:

-- create the variable node's nodeid
counter_node_id = NodeId.newString("Counter", tutorial_namespace)

-- create the counter node's value variant and initialise its value
counter_variant = Variant.new(DataType.DOUBLE)
counter_variant:setScalar(0.0)

-- variable node attributes
display_name = "Counter"
parent_node = tutorial_folder:getNodeId()
access_level = AccessLevel.READ | AccessLevel.WRITE --permissions

counter_node = VariableNode.new(counter_node_id, display_name, parent_node, counter_variant, access_level)
Server.addVariableNode(counter_node) --dont forget to register the node with the server

Update the nodes value

We first need to define our Update function, which will be called by the server every 100ms:

function Update()

end

We can then update the value of our variable node each time the function is called by setting the variant's value to its previous value plus one. We then also need to notify the server that the value has changed by calling the variable node's updateValue() method:

function Update()
  counter_variant:setScalar(counter_variant:getScalar() + 1)
  counter_node:updateValue()
end

Full code

tutorial_namespace = Server.addNamespace("Tutorial")

tutorial_folder = ObjectNode.newRootFolder("Tutorial", tutorial_namespace)
Server.addObjectNode(tutorial_folder)

-- create the variable node's nodeid
counter_node_id = NodeId.newString("Counter", tutorial_namespace)

-- create the counter node's value variant
counter_variant = Variant.new(DataType.DOUBLE)
counter_variant:setScalar(0.0)

-- variable node attributes
display_name = "Counter"
parent_node = tutorial_folder:getNodeId()
access_level = AccessLevel.READ | AccessLevel.WRITE --permissions

counter_node = VariableNode.new(counter_node_id, display_name, parent_node, counter_variant, access_level)
Server.addVariableNode(counter_node) --dont forget to register the node with the server

function Update()
  counter_variant:setScalar(counter_variant:getScalar() + 1)
  counter_node:updateValue()
end