Read your first OPC UA variable
Run a Lua server on your computer, then read its Temperature variable from
a second process. You need Mako Server with
either OPC UA profile, two terminals, and a free local TCP port 4850.
The client connects to localhost using an anonymous session and the None
security policy. Run this example on a trusted development network. The BAS
listener can accept connections on other interfaces. For a network
deployment, see Secure Policy and Configuration table.
1. Start the temperature server
Create a directory named temperature_server. Save the
server source in it as
.preload (including the leading dot). In a source checkout, both
examples are already under doc/source/examples/tutorial.
From the directory containing temperature_server, run:
mako -l::temperature_server
Leave this process running. When it prints
Temperature available at opc.tcp://localhost:4850, the listener is ready.
The server creates a variable under Objects → Tutorial → Temperature.
Its NodeId is ns=1;i=6001 and its value is a double-precision number.
-- Give the measurement a stable NodeId that the client can read.
local editor = server.model:edit()
local folder = editor:objectsFolder():addFolder("Tutorial")
folder:addVariable("Temperature", {
Type = ua.VariantType.Double,
Value = 21.5
}, nil, "ns=1;i=6001")
editor:save()
2. Read the value
Save the client source as
06_client_read.lua. Open the second terminal in the directory containing
that file and run:
mako 06_client_read.lua
The client connects to port 4850, opens a channel, creates and activates a
session, and reads the Value attribute. It checks for 21.5 before printing
Client read Temperature from the learning server.
resp, err = client:read({
NodesToRead = {
{
NodeId = temperatureId,
AttributeId = ua.AttributeId.Value
}
}
})
assert(err == nil, tostring(err))
assert(resp.Results[1].Value == 21.5)
Stop the server with Ctrl+C when finished. If the client cannot connect,
check the first terminal for the ready message and confirm the port in both
files. If the read returns BadNodeIdUnknown, browse from Objects and
compare the variable’s NodeId with the one in the request.
Next, connect a variable to device data or write a value from Lua. The learning examples include a writable setpoint and a callable method.