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

Full source

The returned value ‘ua’ is a table with functions that may be used for creating an OPC-UA server and/or client.

To create a server, start by creating a Lua table with configuration parameters. See the section Configuration table for additional details.

local config = {
   -- Endpoint URL is used by clients to establish secure channel.
   -- By default listen address and port are taken from endpoint URL
   endpointUrl = "opc.tcp://localhost:4843",

   securePolicies = {
    -- Secure polcy None required to discover server certificate
    -- with GetEndpointsRequest
    { -- #1
      securityPolicyUri = ua.Types.SecurityPolicy.None,
    },
  },
}

Full source

An OPC-UA server instance is created by passing the configuration table into the ‘newServer’ function as shown in the following example:

local server = ua.newServer(config)

Full source

The Lua function “newServer” returns an OPC-UA server instance. The server instance must first be initialized before it can be started.

server:initialize()

Full source

Adding Nodes on server

Once the server is initialized, you can customize the server by adding new nodes.

-- 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 = {
  boolean = true
}

local arrBooleanId = "i=1000001"
-- Initial boolean array value
local arrBoolean = {
  boolean = {true, false, true, false}
}

local request = {
    nodesToAdd = {
    ua.newVariableParams(ObjectsFolder, {name="scalar", ns=0},
                         "boolean", scalarBoolean, scalarBooleanId),
    ua.newVariableParams(ObjectsFolder, {name="array", ns=0},
                         "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

Full source

Starting the Server

You may connect to the OPC-UA server instance using any OPC-UA client after calling the ‘run’ method. See the Third Party Clients for details.

server:run()

Full source

Stopping the Server

The server can be stopped and the server’s listening socket can be closed by calling the ‘shutdown’ method.

server:shutdown()

Full source