Server - Getting Started
Creating a Server
The OPC-UA stack is provided as a Lua module and must be loaded as follows:
local ua = require("opcua.api")
The returned value ‘ua’ is a table with functions that may be used to create an OPC-UA server and client.
To create a server you need to call ‘ua.newServer’ function. The Lua function “newServer” returns an OPC-UA server instance. Before it can be started, the server instance must be initialized.
-- Create new OPC UA server instance.
-- Pass configuration table to server.
local server = ua.newServer()
-- Initialize server.
server:initialize()
It is possible to pass a Lua table with configuration parameters into function ‘newServer’. See the section Configuration table for additional details
local config = {
endpoints = {
{
endpointUrl = "opc.tcp://localhost:4845",
}
},
securePolicies = {
{ -- #1
securityPolicyUri = ua.Types.SecurityPolicy.None,
},
},
}
local server = ua.newServer(config)
server:initialize()
Adding Nodes on server
Once the server is initialized, you can customize the server by adding new nodes.
local ObjectsFolder = "i=85"
-- Add two variables:
-- 1. Boolean scalar value
-- 2. Boolean array value
-- required Node ID for variable
local scalarBooleanId = "i=1000000"
-- Initial boolean scalar value
local scalarBoolean = {
Value = {Boolean = true}
}
local arrBooleanId = "i=1000001"
-- Initial boolean array value
local arrBoolean = {
Value = {
Boolean = {true, false, true, false}
}
}
local request = {
NodesToAdd = {
ua.newVariableParams(ObjectsFolder, "boolean", scalarBoolean, scalarBooleanId),
ua.newVariableParams(ObjectsFolder, "boolean_array", arrBoolean, arrBooleanId),
}
}
local resp = server:addNodes(request)
for _,res in ipairs(resp.Results) do
if res.StatusCode ~= ua.StatusCode.Good and res.StatusCode ~= ua.StatusCode.BadNodeIdExists then
error(res.StatusCode)
end
end
Starting the Server
After calling the ‘ run ‘ method, you may connect to the OPC-UA server instance using any OPC-UA client . See the How to Connect Third-Party Clients for details.
-- Start listening and dispatch incomming messages.
server:run()
Stopping the Server
The server can be stopped, and the server’s listening socket can be closed by calling the ‘shutdown’ method.
-- Stop server.
server:shutdown()