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 = {
   listenPort = 4843,
   listenAddress = "localhost", -- Use '*' for listening on all interfaces
   endpointUrl = "opc.tcp://localhost:4843", -- Endpoint URL is used by clients to establish secure channel.

   logging = {
    socket = {
      dbgOn = true,
      infOn = true,
      errOn = true,
    },
    binary = {
      dbgOn = true,
      infOn = true,
      errOn = true,
    },
    services = {
      dbgOn = false,
      infOn = true,
      errOn = true,
    }
  }
}

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.

-- Initialize server.
server:initialize()

Full source

Adding Nodes

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

-- Start listening and dispatch incomming messages.
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.

-- Stop server.
server:shutdown()

Full source