opcua

package module
v0.1.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 12, 2026 License: MIT Imports: 28 Imported by: 0

README

otfabric/opcua — OPC-UA library for Go

Go License Go Report Card CI Release

A pure Go implementation of the OPC-UA Binary Protocol, providing both client and server capabilities. No C dependencies, no CGo — just Go.

go get github.com/otfabric/opcua

Requires Go 1.23 or later.

Overview

otfabric/opcua gives you everything needed to interact with OPC-UA servers or build your own:

  • Client — connect, browse, read, write, subscribe, call methods, read history
  • Server — host namespaces, expose variables, handle methods, emit events
  • Security — six encryption policies, certificate and username/password authentication, server certificate validation with TrustedCertificates() and InsecureSkipVerify() options
  • Subscriptions — data-change and event monitoring with automatic publishing
  • Retry & Reconnect — exponential backoff and automatic session recovery
  • Metrics — pluggable instrumentation for request/response/error tracking
  • Logging — structured logging via slog or any custom Logger interface

For full API details see API.md.

Documentation

Guide Description
Client Guide Connecting, reading, writing, browsing, subscriptions, methods, history
Server Guide Building servers, namespaces, custom nodes, methods, events, access control
Security Guide Certificates, encryption policies, authentication, security checklist
Architecture Package layering, message flow, concurrency patterns, internals
API Reference Complete reference for all public types and functions

Quickstart

Read a value
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/otfabric/opcua"
    "github.com/otfabric/opcua/ua"
)

func main() {
    ctx := context.Background()

    c, err := opcua.NewClient("opc.tcp://localhost:4840")
    if err != nil {
        log.Fatal(err)
    }
    if err := c.Connect(ctx); err != nil {
        log.Fatal(err)
    }
    defer c.Close(ctx)

    v, err := c.Node(ua.MustParseNodeID("i=2258")).Value(ctx) // or opcua.StandardNodeID("CurrentTime") for symbolic name
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Server time:", v.Value())
}
Subscribe to changes
sub, notifs, err := c.NewSubscription().
    Interval(500 * time.Millisecond).
    Monitor(ua.MustParseNodeID("ns=2;s=Temperature")).
    Start(ctx)
if err != nil {
    log.Fatal(err)
}
defer sub.Cancel(ctx)

for msg := range notifs {
    if msg.Error != nil {
        log.Println("error:", msg.Error)
        continue
    }
    for _, item := range msg.Value.(*ua.DataChangeNotification).MonitoredItems {
        fmt.Printf("Value: %v\n", item.Value.Value.Value())
    }
}
Browse the address space
node := c.Node(ua.MustParseNodeID("ns=0;i=85")) // Objects folder
refs, err := node.References(ctx, 0, ua.BrowseDirectionForward, ua.NodeClassAll, true)
if err != nil {
    log.Fatal(err)
}
for _, ref := range refs {
    fmt.Printf("  %s: %s\n", ref.BrowseName.Name, ref.NodeID.NodeID)
}
Run a server
package main

import (
    "context"
    "log"

    "github.com/otfabric/opcua/server"
    "github.com/otfabric/opcua/ua"
)

func main() {
    srv := server.New(
        server.EndPoint("localhost", 4840),
        server.EnableSecurity("None", ua.MessageSecurityModeNone),
        server.EnableAuthMode(ua.UserTokenTypeAnonymous),
    )

    ns := server.NewNodeNameSpace(srv, "example")
    idx := srv.AddNamespace(ns)
    _ = idx

    n := ns.AddNewVariableStringNode("temperature", float64(21.5))
    ns.Objects().AddRef(n, 47, true) // HasComponent

    if err := srv.Start(context.Background()); err != nil {
        log.Fatal(err)
    }
    defer srv.Close()

    select {} // run until killed
}

Client Features

Area Capabilities
Connection Secure channel, session management, auto-reconnect, connection state callbacks, SkipNamespaceUpdate
Reading Single/batch reads, all attributes, Node.Value(), Node.Summary(), ReadMulti (chunked batch N×attributes)
Writing Single/batch writes, any attribute, WriteValue, WriteAttribute
Browsing Forward/inverse/both, continuation points, BrowseAll, Walk / WalkLimit (depth-limited), WalkLimitDedup, BrowseWithDepth (client-side recursive, returns slice)
Path resolution NodeFromPath, NodeFromPathInNamespace, NodeFromQualifiedPath (ns:name), Node.TranslateBrowsePathInNamespaceToNodeID (TranslateBrowsePathsToNodeIDs). Symbolic node names: StandardNodeID("CurrentTime"), id.NodeIDByName(name)
Subscriptions Data-change, events, modify/cancel, SetTriggering, SetPublishingMode, builder API
Methods Call, CallMethod (auto-wrap args), MethodArguments introspection
History Read: raw/modified, events, processed, at-time. Update: data, events. Delete: raw/modified, at-time, events
Node Management AddNodes, DeleteNodes, AddReferences, DeleteReferences
Query QueryFirst, QueryNext
Discovery FindServers, GetEndpoints, SelectEndpoint
Security None, Basic128Rsa15, Basic256, Basic256Sha256, Aes128Sha256RsaOaep, Aes256Sha256RsaPss
Authentication Anonymous, username/password, X.509 certificate, issued token
Retry Pluggable RetryPolicy, exponential backoff with jitter
Metrics Pluggable ClientMetrics interface for request/response/error/timeout tracking

Server Features

Area Capabilities
Namespaces Custom NameSpace interface, NodeNameSpace in-memory implementation
Services Read, Write, Browse, BrowseNext, TranslateBrowsePaths, Call, HistoryRead, HistoryUpdate
Node Management AddNodes, DeleteNodes, AddReferences, DeleteReferences
Subscriptions Create, Modify, Delete, Publish, Republish, TransferSubscriptions, SetPublishingMode
MonitoredItems Create, Modify, Delete, SetMonitoringMode, SetTriggering
View RegisterNodes, UnregisterNodes, QueryFirst, QueryNext
Session Create, Activate, Close (with DeleteSubscriptions), Cancel
Methods Register handlers via RegisterMethod, argument introspection
Events EmitEvent to push event notifications to subscribers
Access Control Pluggable AccessController interface for per-operation authorization
NodeSet2 Import Load standard or custom NodeSet2 XML files
Security Same encryption policies as client (server-side)
Authentication Anonymous, username/password, X.509, issued token identity tokens

Service Support Matrix

Service Set Service Client Server
Discovery FindServers Yes Yes
FindServersOnNetwork Yes Yes
GetEndpoints Yes Yes
Secure Channel OpenSecureChannel Yes Yes
CloseSecureChannel Yes Yes
Session CreateSession Yes Yes
ActivateSession Yes Yes
CloseSession Yes Yes
Cancel Yes
Attribute Read Yes Yes
Write Yes Yes
HistoryRead Yes Yes
HistoryUpdate Yes Yes
View Browse Yes Yes
BrowseNext Yes Yes
TranslateBrowsePathsToNodeIDs Yes Yes
RegisterNodes Yes Yes
UnregisterNodes Yes Yes
Query QueryFirst Yes Yes
QueryNext Yes Yes
Method Call Yes Yes
Node Management AddNodes Yes Yes
DeleteNodes Yes Yes
AddReferences Yes Yes
DeleteReferences Yes Yes
MonitoredItems CreateMonitoredItems Yes Yes
DeleteMonitoredItems Yes Yes
ModifyMonitoredItems Yes Yes
SetMonitoringMode Yes Yes
SetTriggering Yes Yes
Subscription CreateSubscription Yes Yes
ModifySubscription Yes Yes
SetPublishingMode Yes Yes
Publish Yes Yes
Republish Yes
TransferSubscriptions Yes
DeleteSubscriptions Yes Yes

Package Structure

Package Purpose
opcua Client, Node, Subscription, configuration options, retry, metrics
ua All OPC-UA types: Variant, DataValue, NodeID, StatusCode, enums, codec
server Server, NameSpace, AccessController, service implementations
monitor High-level NodeMonitor with callback and channel-based subscriptions
errors Sentinel errors for errors.Is() checking
id Well-known NodeID constants (generated from OPC-UA schema)
uacp OPC-UA Connection Protocol (TCP transport)
uasc OPC-UA Secure Conversation (secure channel)
uapolicy Security policy implementations (encryption, signing)
stats Expvar-based statistics collection
logger Logger interface with slog and stdlib adapters

Examples

The examples/ directory contains runnable programs:

Example Description
read Read a single node value
write Write a value to a node
browse Browse the server address space
subscribe Subscribe to data changes
monitor High-level monitoring with NodeMonitor
method Call a server method
history-read Read historical data
crypto Connect with encryption and certificates
datetime Read the server's current time
discovery Discover servers on the network
endpoints List available endpoints
translate Translate browse paths to NodeIDs
trigger Set up monitored item triggering
accesslevel Read node access levels
udt Work with user-defined types
server Run a simple OPC-UA server
reconnect Demonstrate auto-reconnection

Run any example:

go run examples/datetime/datetime.go -endpoint opc.tcp://localhost:4840

Testing and production readiness

  • Unit tests: make test (includes race detector).
  • Coverage: make coverage writes coverage.out; make cover opens the report.
  • Integration tests (tag-gated): make integration (Python client vs Go server), make selfintegration (Go client vs in-process server). These are not run by go test ./... by default.
  • Fuzz tests: see ua/fuzz_test.go for Variant and NodeID decoding.
  • Linting: make lint (staticcheck), make lint-ci (golangci-lint).

See CONTRIBUTING.md for development and PR workflow.

Protocol Support

Layer Protocol Supported
Encoding OPC-UA Binary Yes
Transport UA-TCP Yes
Encryption None Yes
Basic128Rsa15 Yes
Basic256 Yes
Basic256Sha256 Yes
Aes128Sha256RsaOaep Yes
Aes256Sha256RsaPss Yes

License

MIT

Documentation

Overview

Package opcua provides a high-level OPC-UA client and server implementation in pure Go.

The root package contains the Client for connecting to OPC-UA servers and performing read, write, browse, subscribe, and method call operations.

Client Usage

Create a client and connect:

c, err := opcua.NewClient("opc.tcp://localhost:4840")
if err != nil {
    log.Fatal(err)
}
if err := c.Connect(ctx); err != nil {
    log.Fatal(err)
}
defer c.Close(ctx)

Read a value:

dv, err := c.ReadValue(ctx, ua.NewNumericNodeID(0, 2258))

Subscribe to changes:

sub, ch, err := c.NewSubscription().
    Interval(100 * time.Millisecond).
    Monitor(nodeID).
    Start(ctx)

Sub-packages

The server package provides the OPC-UA server implementation. The ua package defines all OPC-UA data types and service messages. The uasc package implements the Secure Conversation layer. The uacp package implements the Connection Protocol (TCP transport). The uapolicy package implements the security policies.

Index

Constants

View Source
const (
	DefaultSubscriptionMaxNotificationsPerPublish = 10000
	DefaultSubscriptionLifetimeCount              = 10000
	DefaultSubscriptionMaxKeepAliveCount          = 3000
	DefaultSubscriptionInterval                   = 100 * time.Millisecond
	DefaultSubscriptionPriority                   = 0
)
View Source
const (
	DefaultDialTimeout = 10 * time.Second
)
View Source
const DefaultReadMultiChunkSize = 32

DefaultReadMultiChunkSize is the default max items per Read request when using ReadMulti, to stay under typical server MaxNodesPerRead limits.

Variables

View Source
var NewSlogLogger = logger.NewSlogLogger

NewSlogLogger returns a Logger backed by the given slog.Handler.

View Source
var NewStdLogger = logger.NewStdLogger

NewStdLogger returns a Logger backed by the standard library log.Logger.

View Source
var NopLogger = logger.NopLogger

NopLogger returns a Logger that discards all output.

Functions

func AggregateType

func AggregateType(name string) *ua.NodeID

AggregateType maps a human-readable aggregate name (e.g. "Average", "Count", "Minimum") to its well-known NodeID. The lookup is case-insensitive. Returns nil if the name is not recognized.

func DataTypeDisplayName added in v0.1.10

func DataTypeDisplayName(dataTypeID *ua.NodeID) string

DataTypeDisplayName returns a display string for a DataType NodeID. For well-known DataTypes in namespace 0 (e.g. Float, String, Boolean, UtcTime), it returns the standard name; otherwise it returns the NodeID string. Use when displaying DataType attributes or type columns to normalize type rendering (e.g. "Float" instead of "i=10", "UtcTime" instead of "i=294"). Returns the empty string if dataTypeID is nil.

func DefaultClientConfig

func DefaultClientConfig() *uasc.Config

DefaultClientConfig returns the default configuration for a client to establish a secure channel.

func DefaultDialer

func DefaultDialer() *uacp.Dialer

func DefaultSessionConfig

func DefaultSessionConfig() *uasc.SessionConfig

DefaultSessionConfig returns the default configuration for a client to establish a session.

func FindServers

func FindServers(ctx context.Context, endpoint string, opts ...Option) ([]*ua.ApplicationDescription, error)

FindServers returns the servers known to a server or discovery server.

func FindServersOnNetwork

func FindServersOnNetwork(ctx context.Context, endpoint string, opts ...Option) ([]*ua.ServerOnNetwork, error)

FindServersOnNetwork returns the servers known to a server or discovery server. Unlike FindServers, this service is only implemented by discovery servers.

func GetEndpoints

func GetEndpoints(ctx context.Context, endpoint string, opts ...Option) ([]*ua.EndpointDescription, error)

GetEndpoints returns the available endpoint descriptions for the server.

func NewMonitoredItemCreateRequestWithDefaults

func NewMonitoredItemCreateRequestWithDefaults(nodeID *ua.NodeID, attributeID ua.AttributeID, clientHandle uint32) *ua.MonitoredItemCreateRequest

NewMonitoredItemCreateRequestWithDefaults creates a MonitoredItemCreateRequest with sensible defaults: reporting mode, queue size of 10, discard oldest, and no filter. If attributeID is 0, it defaults to AttributeIDValue.

func ReferenceTypeDisplayName added in v0.1.9

func ReferenceTypeDisplayName(refTypeID *ua.NodeID) string

ReferenceTypeDisplayName returns a display string for a reference type NodeID. For well-known reference types in namespace 0 (e.g. HasComponent, Organizes), it returns the standard name; otherwise it returns the NodeID string. Use when displaying the reference type column in browse refs or similar UIs. Returns the empty string if refTypeID is nil.

func SelectEndpoint

func SelectEndpoint(endpoints []*ua.EndpointDescription, policy string, mode ua.MessageSecurityMode) (*ua.EndpointDescription, error)

SelectEndpoint returns the endpoint with the highest security level which matches security policy and security mode. policy and mode can be omitted so that only one of them has to match.

func StandardNodeID added in v0.1.10

func StandardNodeID(name string) (*ua.NodeID, bool)

StandardNodeID returns the namespace-0 NodeID for a well-known standard node name, if known. Uses id.NodeIDByName and returns ua.NewNumericNodeID(0, id). Names include "Server", "ObjectsFolder", "Server_ServerStatus_CurrentTime", and short aliases "CurrentTime" (→ i=2258), "ServerStatus" (→ i=2256), "Objects" (→ i=85). Use for CLI flags like get value -n CurrentTime instead of -n i=2258.

func TypeDefinitionDisplayName added in v0.1.11

func TypeDefinitionDisplayName(typeDefID *ua.NodeID) string

TypeDefinitionDisplayName returns a display string for a type definition NodeID (VariableType or ObjectType in namespace 0). It tries VariableTypeName then ObjectTypeName; if neither matches, returns the NodeID string. Use when displaying type definition columns (e.g. browse) so "PropertyType" is shown instead of "i=68". Returns the empty string if typeDefID is nil.

Types

type BrowseWithDepthOptions added in v0.1.12

type BrowseWithDepthOptions struct {
	MaxDepth        int    // stop recursing after this depth; -1 = unlimited
	RefType         uint32 // reference type to follow; 0 = HierarchicalReferences
	Direction       ua.BrowseDirection
	NodeClassMask   ua.NodeClass
	IncludeSubtypes bool
}

BrowseWithDepthOptions configures Node.BrowseWithDepth. Zero values use defaults: MaxDepth -1 (unlimited), RefType HierarchicalReferences, Direction Forward, NodeClassMask All, IncludeSubtypes true.

type BrowseWithDepthResult added in v0.1.12

type BrowseWithDepthResult struct {
	Ref   *ua.ReferenceDescription
	Depth int
}

BrowseWithDepthResult is one reference returned by Node.BrowseWithDepth, with the depth at which it was found (0 = direct children of the start node).

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a high-level client for an OPC-UA server.

It manages the full connection lifecycle: establishing a TCP connection via UACP, opening a secure channel (UASC) with encryption and signing, creating and activating a session, and managing subscriptions.

The Client supports automatic reconnection when AutoReconnect is enabled. On connection loss it will attempt progressive recovery: recreating the secure channel, restoring or recreating the session, and transferring subscriptions.

Create a Client with NewClient and connect with Client.Connect. Always call Client.Close when done to release resources.

The Client is safe for concurrent use from multiple goroutines.

func NewClient

func NewClient(endpoint string, opts ...Option) (*Client, error)

NewClient creates a new Client.

When no options are provided the new client is created from DefaultClientConfig() and DefaultSessionConfig(). If no authentication method is configured, a UserIdentityToken for anonymous authentication will be set. See #Client.CreateSession for details.

To modify configuration you can provide any number of Options as opts. See #Option for details.

https://godoc.org/github.com/otfabric/opcua#Option

func (*Client) ActivateSession

func (c *Client) ActivateSession(ctx context.Context, s *Session) error

ActivateSession activates the session and associates it with the client. If the client already has a session it will be closed. To retain the current session call DetachSession.

See Part 4, 5.6.3

func (*Client) AddNodes

func (c *Client) AddNodes(ctx context.Context, req *ua.AddNodesRequest) (*ua.AddNodesResponse, error)

AddNodes adds one or more nodes to the server address space.

Part 4, Section 5.7.2

func (*Client) AddReferences

func (c *Client) AddReferences(ctx context.Context, req *ua.AddReferencesRequest) (*ua.AddReferencesResponse, error)

AddReferences adds one or more references to one or more nodes.

Part 4, Section 5.7.4

func (*Client) Browse

func (c *Client) Browse(ctx context.Context, req *ua.BrowseRequest) (*ua.BrowseResponse, error)

Browse executes a synchronous browse request.

func (*Client) BrowseAll

func (c *Client) BrowseAll(ctx context.Context, nodeID *ua.NodeID) ([]*ua.ReferenceDescription, error)

BrowseAll collects all hierarchical forward references for a node.

It automatically follows continuation points until all references are retrieved. Results are accumulated in memory and returned as a slice.

For streaming results without accumulating in memory, use Node.BrowseAll which returns an iter.Seq2 iterator.

func (*Client) BrowseNext

func (c *Client) BrowseNext(ctx context.Context, req *ua.BrowseNextRequest) (*ua.BrowseNextResponse, error)

BrowseNext executes a synchronous browse request.

func (*Client) Call

Call executes a synchronous call request for a single method.

func (*Client) CallMethod

func (c *Client) CallMethod(ctx context.Context, objectID, methodID *ua.NodeID, args ...any) (*ua.CallMethodResult, error)

CallMethod calls a method on a server object.

This is a convenience wrapper around Client.Call that automatically wraps the variadic args into ua.Variant values. For full control over the request, use Client.Call directly.

objectID is the NodeID of the object that owns the method. methodID is the NodeID of the method to call.

func (*Client) Close

func (c *Client) Close(ctx context.Context) error

Close closes the session, secure channel, and underlying TCP connection.

It attempts to gracefully close the session on the server, then closes the secure channel and connection. Errors during session close are ignored to ensure cleanup completes.

Close is safe to call multiple times. After Close returns, the Client cannot be reused.

func (*Client) CloseSession

func (c *Client) CloseSession(ctx context.Context) error

CloseSession closes the current session.

See Part 4, 5.6.4

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect establishes a secure channel and creates a new session.

It performs the full OPC-UA connection sequence:

  1. Opens a TCP connection to the server (UACP)
  2. Opens a secure channel with the configured security policy
  3. Creates a session with the configured parameters
  4. Activates the session with the configured authentication

If AutoReconnect is enabled, Connect also starts a background goroutine that monitors the connection and attempts recovery on failure.

Connect must be called exactly once. Call Client.Close to disconnect.

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, cfg *uasc.SessionConfig) (*Session, error)

CreateSession creates a new session which is not yet activated and not associated with the client. Call ActivateSession to both activate and associate the session with the client.

If no UserIdentityToken is given explicitly before calling CreateSesion, it automatically sets anonymous identity token with the same PolicyID that the server sent in Create Session Response. The default PolicyID "Anonymous" wii be set if it's missing in response.

See Part 4, 5.6.2

func (*Client) DeleteNodes

func (c *Client) DeleteNodes(ctx context.Context, req *ua.DeleteNodesRequest) (*ua.DeleteNodesResponse, error)

DeleteNodes deletes one or more nodes from the server address space.

Part 4, Section 5.7.3

func (*Client) DeleteReferences

func (c *Client) DeleteReferences(ctx context.Context, req *ua.DeleteReferencesRequest) (*ua.DeleteReferencesResponse, error)

DeleteReferences deletes one or more references from one or more nodes.

Part 4, Section 5.7.5

func (*Client) DetachSession

func (c *Client) DetachSession(ctx context.Context) (*Session, error)

DetachSession removes the session from the client without closing it. The caller is responsible to close or re-activate the session. If the client does not have an active session the function returns no error.

func (*Client) Dial

func (c *Client) Dial(ctx context.Context) error

Dial establishes a secure channel.

func (*Client) FindNamespace

func (c *Client) FindNamespace(ctx context.Context, name string) (uint16, error)

FindNamespace returns the id of the namespace with the given name.

func (*Client) FindServers

func (c *Client) FindServers(ctx context.Context) (*ua.FindServersResponse, error)

FindServers finds the servers available at an endpoint

func (*Client) FindServersOnNetwork

func (c *Client) FindServersOnNetwork(ctx context.Context) (*ua.FindServersOnNetworkResponse, error)

FindServersOnNetwork finds the servers available at an endpoint

func (*Client) GetEndpoints

func (c *Client) GetEndpoints(ctx context.Context) (*ua.GetEndpointsResponse, error)

GetEndpoints returns the list of available endpoints of the server.

func (*Client) HistoryDeleteAtTime

func (c *Client) HistoryDeleteAtTime(ctx context.Context, details ...*ua.DeleteAtTimeDetails) (*ua.HistoryUpdateResponse, error)

HistoryDeleteAtTime deletes historical data values at specific timestamps.

Part 4, Section 5.10.5 / Part 11, Section 6.8.6

func (*Client) HistoryDeleteEvents

func (c *Client) HistoryDeleteEvents(ctx context.Context, details ...*ua.DeleteEventDetails) (*ua.HistoryUpdateResponse, error)

HistoryDeleteEvents deletes historical events matching specific event IDs.

Part 4, Section 5.10.5 / Part 11, Section 6.8.7

func (*Client) HistoryDeleteRawModified

func (c *Client) HistoryDeleteRawModified(ctx context.Context, details ...*ua.DeleteRawModifiedDetails) (*ua.HistoryUpdateResponse, error)

HistoryDeleteRawModified deletes raw or modified historical data within a time range.

Part 4, Section 5.10.5 / Part 11, Section 6.8.5

func (*Client) HistoryReadAtTime

func (c *Client) HistoryReadAtTime(ctx context.Context, nodes []*ua.HistoryReadValueID, details *ua.ReadAtTimeDetails) (*ua.HistoryReadResponse, error)

func (*Client) HistoryReadEvent

func (c *Client) HistoryReadEvent(ctx context.Context, nodes []*ua.HistoryReadValueID, details *ua.ReadEventDetails) (*ua.HistoryReadResponse, error)

func (*Client) HistoryReadProcessed

func (c *Client) HistoryReadProcessed(ctx context.Context, nodes []*ua.HistoryReadValueID, details *ua.ReadProcessedDetails) (*ua.HistoryReadResponse, error)

func (*Client) HistoryReadRawModified

func (c *Client) HistoryReadRawModified(ctx context.Context, nodes []*ua.HistoryReadValueID, details *ua.ReadRawModifiedDetails) (*ua.HistoryReadResponse, error)

func (*Client) HistoryUpdateData

func (c *Client) HistoryUpdateData(ctx context.Context, details ...*ua.UpdateDataDetails) (*ua.HistoryUpdateResponse, error)

HistoryUpdateData updates historical data values for one or more nodes.

Part 4, Section 5.10.5 / Part 11, Section 6.8.2

func (*Client) HistoryUpdateEvents

func (c *Client) HistoryUpdateEvents(ctx context.Context, details ...*ua.UpdateEventDetails) (*ua.HistoryUpdateResponse, error)

HistoryUpdateEvents updates historical events for one or more nodes.

Part 4, Section 5.10.5 / Part 11, Section 6.8.4

func (*Client) MethodArguments

func (c *Client) MethodArguments(ctx context.Context, objectID, methodID *ua.NodeID) (inputs, outputs []*ua.Argument, err error)

MethodArguments reads the InputArguments and OutputArguments properties of a method node. Returns nil slices for methods without declared arguments.

func (*Client) NamespaceArray

func (c *Client) NamespaceArray(ctx context.Context) ([]string, error)

NamespaceArray returns the list of namespaces registered on the server.

func (*Client) NamespaceURI

func (c *Client) NamespaceURI(ctx context.Context, idx uint16) (string, error)

NamespaceURI returns the namespace URI for the given namespace index. Returns an error if the index is out of bounds.

func (*Client) Namespaces

func (c *Client) Namespaces() []string

Namespaces returns the currently cached list of namespaces.

func (*Client) NewSubscription

func (c *Client) NewSubscription() *SubscriptionBuilder

NewSubscription returns a SubscriptionBuilder for configuring a new subscription. Call Start to create the subscription on the server.

func (*Client) Node

func (c *Client) Node(id *ua.NodeID) *Node

Node returns a node object which accesses its attributes through this client connection.

func (*Client) NodeFromExpandedNodeID

func (c *Client) NodeFromExpandedNodeID(id *ua.ExpandedNodeID) *Node

NodeFromExpandedNodeID returns a node object which accesses its attributes through this client connection. This is usually needed when working with node ids returned from browse responses by the server.

func (*Client) NodeFromPath added in v0.1.1

func (c *Client) NodeFromPath(ctx context.Context, path string) (*Node, error)

NodeFromPath resolves a dot-separated browse path to a Node.

Start node: server's Objects folder (i=85). Namespace: all path segments are interpreted in namespace 0. Path format: dot-separated browse names (e.g. "Server.ServerStatus"). Error behavior: returns (nil, err) if the path does not resolve, the TranslateBrowsePathsToNodeIDs service fails, or the client is not connected. Use NodeFromPathInNamespace for a different namespace; use Node().TranslateBrowsePathInNamespaceToNodeID when starting from a custom node.

Example: NodeFromPath(ctx, "Server.ServerStatus") returns the ServerStatus node.

func (*Client) NodeFromPathInNamespace added in v0.1.1

func (c *Client) NodeFromPathInNamespace(ctx context.Context, ns uint16, path string) (*Node, error)

NodeFromPathInNamespace resolves a dot-separated browse path to a Node using a single namespace for all segments.

Start node: server's Objects folder (i=85). Namespace: all path segments use the given namespace index ns. Path format: dot-separated browse names (e.g. "MyFolder.Sensor1.Temperature"). Error behavior: returns (nil, err) if the path does not resolve, the service fails, or the client is not connected. For paths in namespace 0 from Objects folder, NodeFromPath is equivalent. For a custom start node, use Node().TranslateBrowsePathInNamespaceToNodeID.

Example: NodeFromPathInNamespace(ctx, 1, "Objects.IntVar") for a custom namespace 1.

func (*Client) NodeFromQualifiedPath added in v0.1.10

func (c *Client) NodeFromQualifiedPath(ctx context.Context, path string) (*Node, error)

NodeFromQualifiedPath resolves a namespace-qualified path to a Node.

Path format: dot-separated segments, each of the form "ns:name" where ns is a decimal namespace index (0-65535) and name is the browse name (e.g. "0:Server.0:ServerStatus" or "2:DeviceSet.4:PLC_Name"). Parsing is protocol-level and uses TranslateBrowsePathsToNodeIDs with per-segment namespace indices.

Start node: server's Objects folder (i=85). Namespace: each segment specifies its own namespace via the "ns:" prefix. Error behavior: returns (nil, err) if the path is invalid (e.g. segment missing "ns:" or ns not numeric), the path does not resolve, the service fails, or the client is not connected.

func (*Client) QueryFirst

func (c *Client) QueryFirst(ctx context.Context, req *ua.QueryFirstRequest) (*ua.QueryFirstResponse, error)

QueryFirst executes a QueryFirst service call.

func (*Client) QueryNext

func (c *Client) QueryNext(ctx context.Context, req *ua.QueryNextRequest) (*ua.QueryNextResponse, error)

QueryNext executes a QueryNext service call to continue a previous query.

func (*Client) Read

func (c *Client) Read(ctx context.Context, req *ua.ReadRequest) (*ua.ReadResponse, error)

Read executes a synchronous read request.

By default, the function requests the value of the nodes in the default encoding of the server.

func (*Client) ReadHistory

func (c *Client) ReadHistory(ctx context.Context, nodeID *ua.NodeID, start, end time.Time, maxValues uint32) ([]*ua.DataValue, error)

ReadHistory reads raw historical values for a single node within a time range. It returns up to maxValues results. Use maxValues=0 for all values in the range.

func (*Client) ReadHistoryAll

func (c *Client) ReadHistoryAll(ctx context.Context, nodeID *ua.NodeID, start, end time.Time) iter.Seq2[*ua.DataValue, error]

ReadHistoryAll returns an iterator that reads all historical data values for a node within the given time range, automatically following continuation points.

func (*Client) ReadMulti added in v0.1.12

func (c *Client) ReadMulti(ctx context.Context, items []ReadItem, opts ...ReadMultiOption) ([]ReadResult, error)

ReadMulti performs a batch read of N nodes × attributes in one or more OPC UA Read calls, chunking by DefaultReadMultiChunkSize (or chunkSize if provided via ReadMultiWithChunkSize). Results are in the same order as items. Each result's StatusCode reflects the server's status for that item; a failed overall request returns (nil, err).

func (*Client) ReadValue

func (c *Client) ReadValue(ctx context.Context, nodeID *ua.NodeID) (*ua.DataValue, error)

ReadValue reads the Value attribute of a single node.

This is a convenience wrapper around Client.Read for the common case of reading one node's value. It returns timestamps from both source and server.

For reading multiple nodes in one round-trip, use Client.ReadValues. For reading attributes other than Value, use Client.Read directly.

func (*Client) ReadValues

func (c *Client) ReadValues(ctx context.Context, nodeIDs ...*ua.NodeID) ([]*ua.DataValue, error)

ReadValues reads the Value attribute of multiple nodes in a single request.

This is more efficient than calling Client.ReadValue in a loop because all nodes are read in a single OPC-UA Read service call. Results are returned in the same order as the input node IDs.

func (*Client) RegisterNodes

func (c *Client) RegisterNodes(ctx context.Context, req *ua.RegisterNodesRequest) (*ua.RegisterNodesResponse, error)

RegisterNodes registers node ids for more efficient reads.

Part 4, Section 5.8.5

func (*Client) SecureChannel

func (c *Client) SecureChannel() *uasc.SecureChannel

SecureChannel returns the active secure channel. During reconnect this value can change. Make sure to capture the value in a method before using it.

func (*Client) SecurityMode

func (c *Client) SecurityMode() ua.MessageSecurityMode

SecurityMode returns the message security mode of the active secure channel.

func (*Client) SecurityPolicy

func (c *Client) SecurityPolicy() string

SecurityPolicy returns the security policy URI of the active secure channel.

func (*Client) Send

func (c *Client) Send(ctx context.Context, req ua.Request, h func(ua.Response) error) error

Send sends the request via the secure channel and registers a handler for the response. If the client has an active session it injects the authentication token.

When a RetryPolicy is configured via WithRetryPolicy, failed requests are retried according to the policy. Between retries the method sleeps for the policy-specified delay while respecting context cancellation.

func (*Client) ServerStatus

func (c *Client) ServerStatus(ctx context.Context) (*ua.ServerStatusDataType, error)

ServerStatus reads the server's ServerStatusDataType from node i=2256.

func (*Client) Session

func (c *Client) Session() *Session

Session returns the active session. During reconnect this value can change. Make sure to capture the value in a method before using it.

func (*Client) SetPublishingMode

func (c *Client) SetPublishingMode(ctx context.Context, publishingEnabled bool, subscriptionIDs ...uint32) (*ua.SetPublishingModeResponse, error)

SetPublishingMode enables or disables publishing of notification messages for one or more subscriptions.

Part 4, Section 5.13.4

func (*Client) State

func (c *Client) State() ConnState

State returns the current connection state.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, params *SubscriptionParameters, notifyCh chan<- *PublishNotificationData) (*Subscription, error)

Subscribe creates a new OPC-UA subscription with the given parameters.

The subscription receives data change and event notifications from the server. Notifications are delivered to notifyCh. If the channel is full, the notification is dropped and counted in stats.

Parameters that have not been set use their defaults:

  • Interval: 100ms
  • LifetimeCount: 10000
  • MaxKeepAliveCount: 3000
  • MaxNotificationsPerPublish: 10000

The caller must call Subscription.Cancel when done to clean up resources. For a fluent builder API, see Client.NewSubscription.

See OPC-UA Part 4, Section 5.13.1 for the specification.

func (*Client) SubscriptionIDs

func (c *Client) SubscriptionIDs() []uint32

SubscriptionIDs gets a list of subscriptionIDs

func (*Client) UnregisterNodes

func (c *Client) UnregisterNodes(ctx context.Context, req *ua.UnregisterNodesRequest) (*ua.UnregisterNodesResponse, error)

UnregisterNodes unregisters node ids previously registered with RegisterNodes.

Part 4, Section 5.8.6

func (*Client) UpdateNamespaces

func (c *Client) UpdateNamespaces(ctx context.Context) error

UpdateNamespaces updates the list of cached namespaces from the server.

func (*Client) Write

func (c *Client) Write(ctx context.Context, req *ua.WriteRequest) (*ua.WriteResponse, error)

Write executes a synchronous write request.

func (*Client) WriteAttribute

func (c *Client) WriteAttribute(ctx context.Context, nodeID *ua.NodeID, attrID ua.AttributeID, value *ua.DataValue) (ua.StatusCode, error)

WriteAttribute writes a single attribute value to a node.

func (*Client) WriteNodeValue

func (c *Client) WriteNodeValue(ctx context.Context, nodeID *ua.NodeID, value any) (ua.StatusCode, error)

WriteNodeValue writes a Go value to the Value attribute of a node. The value is wrapped in a Variant using NewVariant, which auto-detects the OPC-UA type from the Go type.

func (*Client) WriteValue

func (c *Client) WriteValue(ctx context.Context, nodeID *ua.NodeID, value *ua.DataValue) (ua.StatusCode, error)

WriteValue writes a DataValue to a single node's Value attribute.

Returns the status code from the server indicating success or failure. For writing multiple nodes in one round-trip, use Client.WriteValues.

func (*Client) WriteValues

func (c *Client) WriteValues(ctx context.Context, writes ...*ua.WriteValue) ([]ua.StatusCode, error)

WriteValues writes multiple values in a single request.

type ClientMetrics

type ClientMetrics interface {
	// OnRequest is called before the request is sent to the server.
	// The service parameter is the OPC-UA service name (e.g. "Read", "Write",
	// "Browse", "Call", "CreateSubscription").
	OnRequest(service string)

	// OnResponse is called after a successful round-trip.
	OnResponse(service string, duration time.Duration)

	// OnError is called when a request fails with a non-timeout error.
	OnError(service string, duration time.Duration, err error)

	// OnTimeout is called when a request fails due to a timeout.
	OnTimeout(service string, duration time.Duration)
}

ClientMetrics receives callbacks for client-side OPC-UA service calls. All methods are called synchronously; implementations must be non-blocking (e.g. increment an atomic counter, send on a buffered channel).

Attach an implementation via WithMetrics.

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config contains all config options.

func ApplyConfig

func ApplyConfig(opts ...Option) (*Config, error)

ApplyConfig applies the config options to the default configuration.

type ConnState

type ConnState uint8

ConnState represents the connection state of an OPC-UA Client.

Monitor state changes by providing a callback via WithConnStateHandler.

const (
	// Closed indicates the client is not connected. This is the initial state
	// and the final state after [Client.Close] or a failed reconnection.
	Closed ConnState = iota
	// Connected indicates the client has an active session and is ready for operations.
	Connected
	// Connecting indicates the client is establishing its first connection.
	Connecting
	// Disconnected indicates the connection was lost. If AutoReconnect is
	// enabled, the client will transition to Reconnecting.
	Disconnected
	// Reconnecting indicates the client is attempting to recover a lost connection.
	// On success it transitions to Connected; on failure to Closed.
	Reconnecting
)

func (ConnState) String

func (i ConnState) String() string

type ExponentialBackoffConfig

type ExponentialBackoffConfig struct {
	BaseDelay      time.Duration // default 100 ms
	MaxDelay       time.Duration // default 30 s
	MaxAttempts    int           // 0 = unlimited (pair with a context deadline)
	RetryOnTimeout bool          // default false: timeouts are not retried
}

ExponentialBackoffConfig provides full control over exponential back-off retry behaviour.

type InvalidResponseTypeError

type InvalidResponseTypeError struct {
	Got  string
	Want string
}

func (*InvalidResponseTypeError) Error

func (e *InvalidResponseTypeError) Error() string

func (*InvalidResponseTypeError) Is

func (e *InvalidResponseTypeError) Is(target error) bool

type Logger

type Logger = logger.Logger

Logger is a printf-style leveled logging interface.

type Node

type Node struct {
	// ID is the node id of the node.
	ID *ua.NodeID
	// contains filtered or unexported fields
}

Node is a high-level object to interact with a node in the address space. It provides common convenience functions to access and manipulate the common attributes of a node.

func (*Node) AccessLevel

func (n *Node) AccessLevel(ctx context.Context) (ua.AccessLevelType, error)

AccessLevel returns the access level of the node. The returned value is a mask where multiple values can be set, e.g. read and write.

func (*Node) Attribute

func (n *Node) Attribute(ctx context.Context, attrID ua.AttributeID) (*ua.Variant, error)

Attribute returns the attribute of the node. with the given id.

func (*Node) Attributes

func (n *Node) Attributes(ctx context.Context, attrID ...ua.AttributeID) ([]*ua.DataValue, error)

Attributes returns the given node attributes.

func (*Node) BrowseAll

func (n *Node) BrowseAll(ctx context.Context, refType uint32, dir ua.BrowseDirection, mask ua.NodeClass, includeSubtypes bool) iter.Seq2[*ua.ReferenceDescription, error]

BrowseAll returns an iterator over all references for the node, automatically following continuation points. Results are streamed without accumulating in memory.

func (*Node) BrowseName

func (n *Node) BrowseName(ctx context.Context) (*ua.QualifiedName, error)

BrowseName returns the browse name of the node.

func (*Node) BrowseWithDepth added in v0.1.12

func (n *Node) BrowseWithDepth(ctx context.Context, opts BrowseWithDepthOptions) ([]BrowseWithDepthResult, error)

BrowseWithDepth performs a client-side recursive browse from this node up to opts.MaxDepth, using the given reference type, direction, and node class filter. It returns a flat slice of references with their depth. Standard OPC UA Browse is single-level; this method implements recursion by issuing multiple Browse calls (same as Node.WalkLimit but returns a slice instead of an iterator).

func (*Node) Children

func (n *Node) Children(ctx context.Context, refs uint32, mask ua.NodeClass) ([]*Node, error)

Children returns the child nodes which match the node class mask.

func (*Node) DataType

func (n *Node) DataType(ctx context.Context) (*ua.NodeID, error)

DataType returns the NodeID of the data type of this node.

func (*Node) Description

func (n *Node) Description(ctx context.Context) (*ua.LocalizedText, error)

Description returns the description of the node.

func (*Node) DisplayName

func (n *Node) DisplayName(ctx context.Context) (*ua.LocalizedText, error)

DisplayName returns the display name of the node.

func (*Node) HasAccessLevel

func (n *Node) HasAccessLevel(ctx context.Context, mask ua.AccessLevelType) (bool, error)

HasAccessLevel returns true if all bits from mask are set in the access level mask of the node.

func (*Node) HasUserAccessLevel

func (n *Node) HasUserAccessLevel(ctx context.Context, mask ua.AccessLevelType) (bool, error)

HasUserAccessLevel returns true if all bits from mask are set in the user access level mask of the node.

func (*Node) NodeClass

func (n *Node) NodeClass(ctx context.Context) (ua.NodeClass, error)

NodeClass returns the node class attribute.

func (*Node) ReferencedNodes

func (n *Node) ReferencedNodes(ctx context.Context, refs uint32, dir ua.BrowseDirection, mask ua.NodeClass, includeSubtypes bool) ([]*Node, error)

ReferencedNodes returns the nodes referenced by this node.

func (*Node) References

func (n *Node) References(ctx context.Context, refType uint32, dir ua.BrowseDirection, mask ua.NodeClass, includeSubtypes bool) ([]*ua.ReferenceDescription, error)

References returns all references for the node, automatically following continuation points for large result sets.

func (*Node) String

func (n *Node) String() string

func (*Node) Summary

func (n *Node) Summary(ctx context.Context) (*NodeSummary, error)

Summary reads the common attributes of the node in a single Read call and follows the HasTypeDefinition reference. This is the most efficient way to gather all display-relevant information about a node.

func (*Node) TranslateBrowsePathInNamespaceToNodeID

func (n *Node) TranslateBrowsePathInNamespaceToNodeID(ctx context.Context, ns uint16, browsePath string) (*ua.NodeID, error)

TranslateBrowsePathInNamespaceToNodeID resolves a dot-separated browse path to a NodeID, with all segments in one namespace.

Start node: the receiver node n. Namespace: every path segment uses the given namespace index ns. Path format: dot-separated browse names (e.g. "Server.ServerStatus" or "Sensors.Temperature"); split on "." and each segment becomes a QualifiedName{NamespaceIndex: ns, Name: segment}. Error behavior: returns (nil, err) if the path does not resolve, the TranslateBrowsePathsToNodeIDs service fails, or the client is not connected. err may be a ua.StatusCode. For paths from the server's Objects folder, Client.NodeFromPath or Client.NodeFromPathInNamespace are simpler. For per-segment namespaces, use TranslateBrowsePathsToNodeIDs with a []*ua.QualifiedName.

func (*Node) TranslateBrowsePathsToNodeIDs

func (n *Node) TranslateBrowsePathsToNodeIDs(ctx context.Context, pathNames []*ua.QualifiedName) (*ua.NodeID, error)

TranslateBrowsePathsToNodeIDs resolves a path of browse name segments to a single NodeID using the TranslateBrowsePathsToNodeIDs service.

Start node: the receiver node n (StartingNode in the request). Namespace: each segment can specify its own namespace via pathNames[i].NamespaceIndex. Path format: slice of QualifiedName; traversal uses HierarchicalReferences. Error behavior: returns (nil, err) if the path does not resolve (no targets or non-OK status), the service fails, or the client is not connected. err may be a ua.StatusCode (e.g. StatusBadNotFound). For a dot-separated path string with one namespace for all segments, use TranslateBrowsePathInNamespaceToNodeID.

func (*Node) TypeDefinition

func (n *Node) TypeDefinition(ctx context.Context) (*ua.NodeID, error)

TypeDefinition returns the NodeID of the type definition for this node by following the HasTypeDefinition reference.

func (*Node) UserAccessLevel

func (n *Node) UserAccessLevel(ctx context.Context) (ua.AccessLevelType, error)

UserAccessLevel returns the access level of the node.

func (*Node) Value

func (n *Node) Value(ctx context.Context) (*ua.Variant, error)

Value returns the value of the node.

func (*Node) Walk

func (n *Node) Walk(ctx context.Context) iter.Seq2[WalkResult, error]

Walk returns an iterator that recursively descends through the node's hierarchical references, yielding each discovered reference along with its depth. The walk uses BrowseAll to automatically follow continuation points. For a depth limit, use WalkLimit.

func (*Node) WalkLimit added in v0.1.5

func (n *Node) WalkLimit(ctx context.Context, maxDepth int) iter.Seq2[WalkResult, error]

WalkLimit is like Walk but stops recursing when depth reaches maxDepth. The node at depth maxDepth is still yielded. If maxDepth < 0, depth is unlimited. Use this for "find node", "find type", or "browse tree" style tools to avoid unbounded traversal (e.g. pass a -depth flag from the CLI).

The same node may be yielded more than once if it is reachable via multiple hierarchical paths. Use WalkLimitDedup to yield each node at most once.

func (*Node) WalkLimitDedup added in v0.1.8

func (n *Node) WalkLimitDedup(ctx context.Context, maxDepth int) iter.Seq2[WalkResult, error]

WalkLimitDedup is like WalkLimit but yields each node at most once, keyed by NodeID. When a node is reachable via multiple hierarchical paths, only the first occurrence (by traversal order) is yielded. Use this to avoid duplicate nodes without implementing a visited set in the caller.

type NodeSummary

type NodeSummary struct {
	NodeID          *ua.NodeID
	NodeClass       ua.NodeClass
	BrowseName      *ua.QualifiedName
	DisplayName     *ua.LocalizedText
	Description     *ua.LocalizedText
	DataType        *ua.NodeID
	Value           *ua.DataValue
	AccessLevel     ua.AccessLevelType
	UserAccessLevel ua.AccessLevelType
	TypeDefinition  *ua.NodeID
}

NodeSummary contains the common attributes of a node, read in a single round-trip via Node.Summary.

type Option

type Option func(*Config) error

Option is an option function type to modify the configuration.

func ApplicationName

func ApplicationName(s string) Option

ApplicationName sets the application name in the session configuration.

func ApplicationURI

func ApplicationURI(s string) Option

ApplicationURI sets the application uri in the session configuration.

func AuthAnonymous

func AuthAnonymous() Option

AuthAnonymous sets the authentication mode to anonymous.

The policy ID is typically set via SecurityFromEndpoint. It can also be set explicitly with AuthPolicyID (in any order).

func AuthCertificate

func AuthCertificate(cert []byte) Option

AuthCertificate sets the authentication mode to X509 certificate.

The policy ID is typically set via SecurityFromEndpoint. It can also be set explicitly with AuthPolicyID (in any order).

func AuthIssuedToken

func AuthIssuedToken(tokenData []byte) Option

AuthIssuedToken sets the authentication mode to an externally-issued token.

tokenData is the opaque token value whose format depends on the token type advertised by the server's UserTokenPolicy (e.g. SAML, JWT, WS-Security). See OPC-UA Part 4, §7.36.6 for details on IssuedIdentityToken encoding.

The policy ID is typically set via SecurityFromEndpoint. It can also be set explicitly with AuthPolicyID (in any order).

func AuthPolicyID

func AuthPolicyID(policy string) Option

AuthPolicyID sets the policy ID of the user identity token.

This can be called before or after an AuthXXX method. If called before, the policy ID is stored and applied once the token type is set.

Most callers should use SecurityFromEndpoint which automatically determines the correct policy ID from the endpoint description.

func AuthPrivateKey

func AuthPrivateKey(key *rsa.PrivateKey) Option

AuthPrivateKey sets the client's authentication RSA private key Note: PolicyID still needs to be set outside of this method, typically through the SecurityFromEndpoint() Option

func AuthUsername

func AuthUsername(user, pass string) Option

AuthUsername sets the authentication mode to username/password.

The policy ID is typically set via SecurityFromEndpoint. It can also be set explicitly with AuthPolicyID (in any order).

func AutoReconnect

func AutoReconnect(b bool) Option

AutoReconnect sets the auto reconnect state of the secure channel.

func Certificate

func Certificate(cert []byte) Option

Certificate sets the client X509 certificate in the secure channel configuration. It also detects and sets the ApplicationURI from the URI within the certificate.

func CertificateFile

func CertificateFile(filename string) Option

CertificateFile sets the client X509 certificate in the secure channel configuration from the PEM or DER encoded file. It also detects and sets the ApplicationURI from the URI within the certificate.

func DialTimeout

func DialTimeout(d time.Duration) Option

DialTimeout sets the timeout for establishing the UACP connection. Defaults to DefaultDialTimeout. Set to zero for no timeout.

func Dialer

func Dialer(d *uacp.Dialer) Option

Dialer sets the uacp.Dialer to establish the connection to the server.

func InsecureSkipVerify added in v0.1.4

func InsecureSkipVerify() Option

InsecureSkipVerify disables server certificate validation. When set, the client still parses the server certificate to extract the public key (required for signing and encryption), but does not verify the trust chain, expiration, or application URI.

This is INSECURE and should only be used for development and testing.

func Lifetime

func Lifetime(d time.Duration) Option

Lifetime sets the lifetime of the secure channel in milliseconds.

func Locales

func Locales(locale ...string) Option

Locales sets the locales in the session configuration.

func MaxChunkCount

func MaxChunkCount(n uint32) Option

MaxChunkCount sets the maximum chunk count for the UACP handshake.

func MaxMessageSize

func MaxMessageSize(n uint32) Option

MaxMessageSize sets the maximum message size for the UACP handshake.

func PrivateKey

func PrivateKey(key *rsa.PrivateKey) Option

PrivateKey sets the RSA private key in the secure channel configuration.

func PrivateKeyFile

func PrivateKeyFile(filename string) Option

PrivateKeyFile sets the RSA private key in the secure channel configuration from a PEM or DER encoded file.

func ProductURI

func ProductURI(s string) Option

ProductURI sets the product uri in the session configuration.

func RandomRequestID

func RandomRequestID() Option

RandomRequestID assigns a random initial request id.

The request id is generated using the 'rand' package and it is the caller's responsibility to initialize the random number generator properly.

func ReceiveBufferSize

func ReceiveBufferSize(n uint32) Option

ReceiveBufferSize sets the receive buffer size for the UACP handshake.

func ReconnectInterval

func ReconnectInterval(d time.Duration) Option

ReconnectInterval is interval duration between each reconnection attempt.

func RemoteCertificate

func RemoteCertificate(cert []byte) Option

RemoteCertificate sets the server certificate.

func RemoteCertificateFile

func RemoteCertificateFile(filename string) Option

RemoteCertificateFile sets the server certificate from the file in PEM or DER encoding.

func RequestTimeout

func RequestTimeout(t time.Duration) Option

RequestTimeout sets the timeout for all requests over SecureChannel

func SecurityFromEndpoint

func SecurityFromEndpoint(ep *ua.EndpointDescription, authType ua.UserTokenType) Option

SecurityFromEndpoint sets the server-related security parameters from a chosen endpoint (received from GetEndpoints())

func SecurityMode

func SecurityMode(m ua.MessageSecurityMode) Option

SecurityMode sets the security mode for the secure channel.

func SecurityModeString

func SecurityModeString(s string) Option

SecurityModeString sets the security mode for the secure channel. Valid values are "None", "Sign", and "SignAndEncrypt".

func SecurityPolicy

func SecurityPolicy(s string) Option

SecurityPolicy sets the security policy uri for the secure channel.

func SendBufferSize

func SendBufferSize(n uint32) Option

SendBufferSize sets the send buffer size for the UACP handshake.

func SessionName

func SessionName(s string) Option

SessionName sets the name in the session configuration.

func SessionTimeout

func SessionTimeout(d time.Duration) Option

SessionTimeout sets the timeout in the session configuration.

func SkipNamespaceUpdate

func SkipNamespaceUpdate() Option

SkipNamespaceUpdate disables automatic namespace table update on connect and reconnect. Use this when the server does not support namespace queries. See https://github.com/otfabric/opcua/pull/512 for discussion.

func StateChangedCh deprecated

func StateChangedCh(ch chan<- ConnState) Option

StateChangedCh sets the channel for receiving client connection state changes.

The caller must either consume the channel immediately or provide a buffer to prevent blocking state changes in the client.

Deprecated: Use WithConnStateHandler instead.

func StateChangedFunc deprecated

func StateChangedFunc(f func(ConnState)) Option

StateChangedFunc sets the function for receiving client connection state changes.

Deprecated: Use WithConnStateHandler instead.

func TrustedCertificates added in v0.1.4

func TrustedCertificates(certs ...*x509.Certificate) Option

TrustedCertificates adds CA or self-signed certificates to the trust pool used to validate the server certificate. The provided certificates are merged with the system CA pool. If the system pool is unavailable, only the provided certificates are trusted.

Use this to trust self-signed server certificates or private CAs without disabling all validation via InsecureSkipVerify.

func WithConnStateHandler

func WithConnStateHandler(h func(ConnState)) Option

WithConnStateHandler sets a callback for receiving client connection state changes. This is the preferred way to observe state transitions. To use a channel instead, wrap it in a function:

ch := make(chan ConnState, 8)
WithConnStateHandler(func(s ConnState) { ch <- s })

func WithLogger

func WithLogger(l Logger) Option

WithLogger sets the logger for the client. By default, the library delegates to slog.Default().

func WithMetrics

func WithMetrics(m ClientMetrics) Option

WithMetrics sets a metrics callback handler for the client. All methods are called synchronously; implementations must be non-blocking.

func WithRetryPolicy

func WithRetryPolicy(p RetryPolicy) Option

WithRetryPolicy sets the retry policy for failed client requests. By default no retries are performed.

Example:

// Retry up to 4 times with exponential back-off.
opcua.WithRetryPolicy(opcua.ExponentialBackoff(200*time.Millisecond, 5*time.Second, 4))

type PublishNotificationData

type PublishNotificationData struct {
	SubscriptionID uint32
	Error          error
	Value          ua.Notification
}

PublishNotificationData contains a notification received from a subscription.

Check Error first — if non-nil, Value will be nil. When Error is nil, Value contains the notification which can be a *ua.DataChangeNotification, *ua.EventNotificationList, or *ua.StatusChangeNotification.

type ReadItem added in v0.1.12

type ReadItem struct {
	NodeID      *ua.NodeID
	AttributeID ua.AttributeID
	IndexRange  string // optional; empty means entire value
}

ReadItem specifies one node/attribute to read in a batch.

type ReadMultiOption added in v0.1.12

type ReadMultiOption struct {
	// contains filtered or unexported fields
}

ReadMultiOption configures Client.ReadMulti.

func ReadMultiWithChunkSize added in v0.1.12

func ReadMultiWithChunkSize(n uint32) ReadMultiOption

ReadMultiWithChunkSize sets the max number of items per Read request. If 0 or unset, DefaultReadMultiChunkSize is used.

type ReadResult added in v0.1.12

type ReadResult struct {
	DataValue  *ua.DataValue
	StatusCode ua.StatusCode
}

ReadResult holds the result of one read in a batch. StatusCode is the per-item status from the server; DataValue may be nil if the read failed.

type RetryPolicy

type RetryPolicy interface {
	// ShouldRetry is called after each failed attempt.
	// attempt is zero-based (0 = first failure).
	// Return (true, delay) to retry after delay, or (false, 0) to stop.
	ShouldRetry(attempt int, err error) (bool, time.Duration)
}

RetryPolicy controls retry behaviour for failed client requests. The policy is consulted after each failed attempt to determine whether to retry and how long to wait before the next attempt.

Attach an implementation via WithRetryPolicy.

func ExponentialBackoff

func ExponentialBackoff(base, maxDelay time.Duration, maxAttempts int) RetryPolicy

ExponentialBackoff returns a RetryPolicy with exponential back-off. delay = base × 2^attempt, capped at maxDelay. Stops after maxAttempts retries. maxAttempts = 0 means unlimited (always pair with a context deadline).

func NewExponentialBackoff

func NewExponentialBackoff(cfg ExponentialBackoffConfig) RetryPolicy

NewExponentialBackoff returns a RetryPolicy with full control over the exponential back-off parameters via ExponentialBackoffConfig.

func NoRetry

func NoRetry() RetryPolicy

NoRetry returns a RetryPolicy that never retries (default behaviour).

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session is a OPC/UA session as described in Part 4, 5.6.

func (*Session) MaxRequestMessageSize

func (s *Session) MaxRequestMessageSize() uint32

MaxRequestMessageSize returns the maximum request message size negotiated during session creation.

func (*Session) RevisedTimeout

func (s *Session) RevisedTimeout() time.Duration

RevisedTimeout return actual maximum time that a Session shall remain open without activity. This value is provided by the server in response to CreateSession.

func (*Session) ServerEndpoints

func (s *Session) ServerEndpoints() []*ua.EndpointDescription

ServerEndpoints returns the endpoints provided by the server during session creation.

func (*Session) SessionID

func (s *Session) SessionID() *ua.NodeID

SessionID returns the server-assigned session identifier.

type Subscription

type Subscription struct {
	SubscriptionID            uint32
	RevisedPublishingInterval time.Duration
	RevisedLifetimeCount      uint32
	RevisedMaxKeepAliveCount  uint32
	Notifs                    chan<- *PublishNotificationData
	// contains filtered or unexported fields
}

Subscription represents an active OPC-UA subscription on the server.

A subscription receives periodic notifications about data changes and events from monitored items. Notifications are delivered to the Notifs channel.

Create a subscription with Client.Subscribe or SubscriptionBuilder.Start. Add monitored items with Subscription.Monitor. Call Subscription.Cancel when done to clean up resources on both client and server.

The RevisedPublishingInterval, RevisedLifetimeCount, and RevisedMaxKeepAliveCount fields contain the values negotiated with the server, which may differ from the requested values.

func (*Subscription) Cancel

func (s *Subscription) Cancel(ctx context.Context) error

Cancel stops the subscription and removes it from the client and the server.

func (*Subscription) ModifyMonitoredItems

func (*Subscription) ModifySubscription

func (s *Subscription) ModifySubscription(ctx context.Context, params SubscriptionParameters) (*ua.ModifySubscriptionResponse, error)

func (*Subscription) Monitor

Monitor creates monitored items on the server for data change or event notifications. If the server closes the connection (e.g. because it does not support event or alarm subscriptions), the returned error wraps io.EOF with a message suggesting that the server may not support event or alarm subscriptions; callers can use errors.Is(err, io.EOF).

func (*Subscription) SetMonitoringMode

func (s *Subscription) SetMonitoringMode(ctx context.Context, monitoringMode ua.MonitoringMode, monitoredItemIDs ...uint32) (*ua.SetMonitoringModeResponse, error)

func (*Subscription) SetPublishingMode

func (s *Subscription) SetPublishingMode(ctx context.Context, publishingEnabled bool) (*ua.SetPublishingModeResponse, error)

SetPublishingMode enables or disables publishing of notification messages for this subscription.

Part 4, Section 5.13.4

func (*Subscription) SetTriggering

func (s *Subscription) SetTriggering(ctx context.Context, triggeringItemID uint32, add, remove []uint32) (*ua.SetTriggeringResponse, error)

SetTriggering sends a request to the server to add and/or remove triggering links from a triggering item. To add links from a triggering item to an item to report provide the server assigned ID(s) in the `add` argument. To remove links from a triggering item to an item to report provide the server assigned ID(s) in the `remove` argument.

func (*Subscription) Stats

Stats returns a diagnostic struct with metadata about the current subscription.

This reads the full SubscriptionDiagnosticsArray from the server and filters by SubscriptionID. A future optimisation could browse for the specific diagnostics node (e.g. i=2290/<subscription-guid>) and cache its NodeID, but the current approach works with all servers regardless of how they structure the diagnostics address space.

func (*Subscription) Unmonitor

func (s *Subscription) Unmonitor(ctx context.Context, monitoredItemIDs ...uint32) (*ua.DeleteMonitoredItemsResponse, error)

type SubscriptionBuilder

type SubscriptionBuilder struct {
	// contains filtered or unexported fields
}

SubscriptionBuilder provides a fluent API for constructing and starting subscriptions with monitored items.

Create a builder with Client.NewSubscription and chain configuration methods. Call SubscriptionBuilder.Start to create the subscription on the server:

sub, ch, err := c.NewSubscription().
    Interval(100 * time.Millisecond).
    Monitor(nodeID1, nodeID2).
    Start(ctx)

If no notification channel is set via SubscriptionBuilder.NotifyChannel, Start creates a buffered channel with capacity 256.

func (*SubscriptionBuilder) Interval

Interval sets the requested publishing interval.

func (*SubscriptionBuilder) LifetimeCount

func (b *SubscriptionBuilder) LifetimeCount(n uint32) *SubscriptionBuilder

LifetimeCount sets the requested lifetime count.

func (*SubscriptionBuilder) MaxKeepAliveCount

func (b *SubscriptionBuilder) MaxKeepAliveCount(n uint32) *SubscriptionBuilder

MaxKeepAliveCount sets the requested maximum keep-alive count.

func (*SubscriptionBuilder) MaxNotificationsPerPublish

func (b *SubscriptionBuilder) MaxNotificationsPerPublish(n uint32) *SubscriptionBuilder

MaxNotificationsPerPublish sets the maximum notifications per publish response.

func (*SubscriptionBuilder) Monitor

func (b *SubscriptionBuilder) Monitor(nodeIDs ...*ua.NodeID) *SubscriptionBuilder

Monitor adds node IDs to be monitored for data changes.

func (*SubscriptionBuilder) MonitorEvents

func (b *SubscriptionBuilder) MonitorEvents(filter *ua.EventFilter, nodeIDs ...*ua.NodeID) *SubscriptionBuilder

MonitorEvents adds event-monitoring items for the given node IDs using the provided EventFilter. Each node is monitored on AttributeIDEventNotifier.

func (*SubscriptionBuilder) MonitorItems

MonitorItems adds custom monitored item create requests.

func (*SubscriptionBuilder) NotifyChannel

NotifyChannel sets the channel for receiving notifications. If not set, Start creates a buffered channel with capacity 256.

func (*SubscriptionBuilder) Priority

Priority sets the subscription priority.

func (*SubscriptionBuilder) SamplingInterval added in v0.1.8

func (b *SubscriptionBuilder) SamplingInterval(d time.Duration) *SubscriptionBuilder

SamplingInterval sets the requested sampling interval for monitored items added by Monitor or MonitorEvents. The server samples at this rate (in milliseconds); the subscription's publishing interval controls how often notifications are sent to the client. If not set or zero, the server uses the fastest practical rate (0.0 in OPC UA). Call this before Monitor or MonitorEvents to apply to those items.

func (*SubscriptionBuilder) Start

Start creates the subscription and monitored items on the server. It returns the subscription and the notification channel. If the server closes the connection during creation, the error may wrap io.EOF with a message suggesting the server may not support subscriptions or event/alarm monitoring.

func (*SubscriptionBuilder) Timestamps

Timestamps sets the timestamps to return for monitored items.

type SubscriptionParameters

type SubscriptionParameters struct {
	Interval                   time.Duration
	LifetimeCount              uint32
	MaxKeepAliveCount          uint32
	MaxNotificationsPerPublish uint32
	Priority                   uint8
}

SubscriptionParameters configures a subscription's behavior.

Fields that are left at their zero value will use the defaults:

  • Interval: 100ms
  • LifetimeCount: 10000
  • MaxKeepAliveCount: 3000
  • MaxNotificationsPerPublish: 10000
  • Priority: 0

type WalkResult

type WalkResult struct {
	Depth int
	Ref   *ua.ReferenceDescription
}

WalkResult contains a reference description along with its tree depth.

Directories

Path Synopsis
cmd
attrid command
capability command
id command
permissions command
service command
status command
Package errors provides sentinel errors and helpers for the OPC-UA library.
Package errors provides sentinel errors and helpers for the OPC-UA library.
examples
accesslevel command
browse command
Example browse uses Node.WalkLimit to traverse the OPC-UA address space up to a configurable depth and outputs all discovered variable nodes as CSV.
Example browse uses Node.WalkLimit to traverse the OPC-UA address space up to a configurable depth and outputs all discovered variable nodes as CSV.
crypto command
datetime command
discovery command
Example discovery demonstrates the OPC-UA discovery services: FindServers and GetEndpoints.
Example discovery demonstrates the OPC-UA discovery services: FindServers and GetEndpoints.
endpoints command
Package main provides an example to query the available endpoints of a server.
Package main provides an example to query the available endpoints of a server.
history-read command
method command
Example method demonstrates calling a method on an OPC-UA server object.
Example method demonstrates calling a method on an OPC-UA server object.
monitor command
Example monitor demonstrates the high-level monitor package which provides callback-based and channel-based subscription APIs.
Example monitor demonstrates the high-level monitor package which provides callback-based and channel-based subscription APIs.
read command
Example read demonstrates reading a node value from an OPC-UA server.
Example read demonstrates reading a node value from an OPC-UA server.
reconnect command
Example reconnect demonstrates the OPC-UA client's automatic reconnection feature.
Example reconnect demonstrates the OPC-UA client's automatic reconnection feature.
regread command
security command
Example security demonstrates the different OPC-UA security configurations.
Example security demonstrates the different OPC-UA security configurations.
server command
server_test command
subscribe command
Example subscribe demonstrates creating an OPC-UA subscription that monitors a node for data changes or events.
Example subscribe demonstrates creating an OPC-UA subscription that monitors a node for data changes or events.
translate command
trigger command
udt command
write command
Example write demonstrates writing a value to an OPC-UA node.
Example write demonstrates writing a value to an OPC-UA node.
Package stats provides instrumentation for the otfabric/opcua library via expvar.
Package stats provides instrumentation for the otfabric/opcua library via expvar.
tests
go
Package ua defines the structures, decoders and encoder for built-in data types described in Part 6 Section 5 Data encoding and for services in OPC UA Binary Protocol.
Package ua defines the structures, decoders and encoder for built-in data types described in Part 6 Section 5 Data encoding and for services in OPC UA Binary Protocol.
Package uacp provides encoding/decoding and automated connection handling for the OPC UA Connection Protocol.
Package uacp provides encoding/decoding and automated connection handling for the OPC UA Connection Protocol.
Package uapolicy implements the encryption, decryption, signing, and signature verifying algorithms for Security Policy profiles as defined in Part 7 of the OPC-UA specifications (version 1.04)
Package uapolicy implements the encryption, decryption, signing, and signature verifying algorithms for Security Policy profiles as defined in Part 7 of the OPC-UA specifications (version 1.04)
Package uasc provides encoding/decoding and automated secure channel and session handling for OPC UA Secure Conversation.
Package uasc provides encoding/decoding and automated secure channel and session handling for OPC UA Secure Conversation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL