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
- Variables
- func AggregateType(name string) *ua.NodeID
- func DataTypeDisplayName(dataTypeID *ua.NodeID) string
- func DefaultClientConfig() *uasc.Config
- func DefaultDialer() *uacp.Dialer
- func DefaultSessionConfig() *uasc.SessionConfig
- func FindServers(ctx context.Context, endpoint string, opts ...Option) ([]*ua.ApplicationDescription, error)
- func FindServersOnNetwork(ctx context.Context, endpoint string, opts ...Option) ([]*ua.ServerOnNetwork, error)
- func GetEndpoints(ctx context.Context, endpoint string, opts ...Option) ([]*ua.EndpointDescription, error)
- func NewMonitoredItemCreateRequestWithDefaults(nodeID *ua.NodeID, attributeID ua.AttributeID, clientHandle uint32) *ua.MonitoredItemCreateRequest
- func ReferenceTypeDisplayName(refTypeID *ua.NodeID) string
- func SelectEndpoint(endpoints []*ua.EndpointDescription, policy string, ...) (*ua.EndpointDescription, error)
- func StandardNodeID(name string) (*ua.NodeID, bool)
- func TypeDefinitionDisplayName(typeDefID *ua.NodeID) string
- type BrowseWithDepthOptions
- type BrowseWithDepthResult
- type Client
- func (c *Client) ActivateSession(ctx context.Context, s *Session) error
- func (c *Client) AddNodes(ctx context.Context, req *ua.AddNodesRequest) (*ua.AddNodesResponse, error)
- func (c *Client) AddReferences(ctx context.Context, req *ua.AddReferencesRequest) (*ua.AddReferencesResponse, error)
- func (c *Client) Browse(ctx context.Context, req *ua.BrowseRequest) (*ua.BrowseResponse, error)
- func (c *Client) BrowseAll(ctx context.Context, nodeID *ua.NodeID) ([]*ua.ReferenceDescription, error)
- func (c *Client) BrowseNext(ctx context.Context, req *ua.BrowseNextRequest) (*ua.BrowseNextResponse, error)
- func (c *Client) Call(ctx context.Context, req *ua.CallMethodRequest) (*ua.CallMethodResult, error)
- func (c *Client) CallMethod(ctx context.Context, objectID, methodID *ua.NodeID, args ...any) (*ua.CallMethodResult, error)
- func (c *Client) Close(ctx context.Context) error
- func (c *Client) CloseSession(ctx context.Context) error
- func (c *Client) Connect(ctx context.Context) error
- func (c *Client) CreateSession(ctx context.Context, cfg *uasc.SessionConfig) (*Session, error)
- func (c *Client) DeleteNodes(ctx context.Context, req *ua.DeleteNodesRequest) (*ua.DeleteNodesResponse, error)
- func (c *Client) DeleteReferences(ctx context.Context, req *ua.DeleteReferencesRequest) (*ua.DeleteReferencesResponse, error)
- func (c *Client) DetachSession(ctx context.Context) (*Session, error)
- func (c *Client) Dial(ctx context.Context) error
- func (c *Client) FindNamespace(ctx context.Context, name string) (uint16, error)
- func (c *Client) FindServers(ctx context.Context) (*ua.FindServersResponse, error)
- func (c *Client) FindServersOnNetwork(ctx context.Context) (*ua.FindServersOnNetworkResponse, error)
- func (c *Client) GetEndpoints(ctx context.Context) (*ua.GetEndpointsResponse, error)
- func (c *Client) HistoryDeleteAtTime(ctx context.Context, details ...*ua.DeleteAtTimeDetails) (*ua.HistoryUpdateResponse, error)
- func (c *Client) HistoryDeleteEvents(ctx context.Context, details ...*ua.DeleteEventDetails) (*ua.HistoryUpdateResponse, error)
- func (c *Client) HistoryDeleteRawModified(ctx context.Context, details ...*ua.DeleteRawModifiedDetails) (*ua.HistoryUpdateResponse, error)
- func (c *Client) HistoryReadAtTime(ctx context.Context, nodes []*ua.HistoryReadValueID, ...) (*ua.HistoryReadResponse, error)
- func (c *Client) HistoryReadEvent(ctx context.Context, nodes []*ua.HistoryReadValueID, ...) (*ua.HistoryReadResponse, error)
- func (c *Client) HistoryReadProcessed(ctx context.Context, nodes []*ua.HistoryReadValueID, ...) (*ua.HistoryReadResponse, error)
- func (c *Client) HistoryReadRawModified(ctx context.Context, nodes []*ua.HistoryReadValueID, ...) (*ua.HistoryReadResponse, error)
- func (c *Client) HistoryUpdateData(ctx context.Context, details ...*ua.UpdateDataDetails) (*ua.HistoryUpdateResponse, error)
- func (c *Client) HistoryUpdateEvents(ctx context.Context, details ...*ua.UpdateEventDetails) (*ua.HistoryUpdateResponse, error)
- func (c *Client) MethodArguments(ctx context.Context, objectID, methodID *ua.NodeID) (inputs, outputs []*ua.Argument, err error)
- func (c *Client) NamespaceArray(ctx context.Context) ([]string, error)
- func (c *Client) NamespaceURI(ctx context.Context, idx uint16) (string, error)
- func (c *Client) Namespaces() []string
- func (c *Client) NewSubscription() *SubscriptionBuilder
- func (c *Client) Node(id *ua.NodeID) *Node
- func (c *Client) NodeFromExpandedNodeID(id *ua.ExpandedNodeID) *Node
- func (c *Client) NodeFromPath(ctx context.Context, path string) (*Node, error)
- func (c *Client) NodeFromPathInNamespace(ctx context.Context, ns uint16, path string) (*Node, error)
- func (c *Client) NodeFromQualifiedPath(ctx context.Context, path string) (*Node, error)
- func (c *Client) QueryFirst(ctx context.Context, req *ua.QueryFirstRequest) (*ua.QueryFirstResponse, error)
- func (c *Client) QueryNext(ctx context.Context, req *ua.QueryNextRequest) (*ua.QueryNextResponse, error)
- func (c *Client) Read(ctx context.Context, req *ua.ReadRequest) (*ua.ReadResponse, error)
- func (c *Client) ReadHistory(ctx context.Context, nodeID *ua.NodeID, start, end time.Time, maxValues uint32) ([]*ua.DataValue, error)
- func (c *Client) ReadHistoryAll(ctx context.Context, nodeID *ua.NodeID, start, end time.Time) iter.Seq2[*ua.DataValue, error]
- func (c *Client) ReadMulti(ctx context.Context, items []ReadItem, opts ...ReadMultiOption) ([]ReadResult, error)
- func (c *Client) ReadValue(ctx context.Context, nodeID *ua.NodeID) (*ua.DataValue, error)
- func (c *Client) ReadValues(ctx context.Context, nodeIDs ...*ua.NodeID) ([]*ua.DataValue, error)
- func (c *Client) RegisterNodes(ctx context.Context, req *ua.RegisterNodesRequest) (*ua.RegisterNodesResponse, error)
- func (c *Client) SecureChannel() *uasc.SecureChannel
- func (c *Client) SecurityMode() ua.MessageSecurityMode
- func (c *Client) SecurityPolicy() string
- func (c *Client) Send(ctx context.Context, req ua.Request, h func(ua.Response) error) error
- func (c *Client) ServerStatus(ctx context.Context) (*ua.ServerStatusDataType, error)
- func (c *Client) Session() *Session
- func (c *Client) SetPublishingMode(ctx context.Context, publishingEnabled bool, subscriptionIDs ...uint32) (*ua.SetPublishingModeResponse, error)
- func (c *Client) State() ConnState
- func (c *Client) Subscribe(ctx context.Context, params *SubscriptionParameters, ...) (*Subscription, error)
- func (c *Client) SubscriptionIDs() []uint32
- func (c *Client) UnregisterNodes(ctx context.Context, req *ua.UnregisterNodesRequest) (*ua.UnregisterNodesResponse, error)
- func (c *Client) UpdateNamespaces(ctx context.Context) error
- func (c *Client) Write(ctx context.Context, req *ua.WriteRequest) (*ua.WriteResponse, error)
- func (c *Client) WriteAttribute(ctx context.Context, nodeID *ua.NodeID, attrID ua.AttributeID, ...) (ua.StatusCode, error)
- func (c *Client) WriteNodeValue(ctx context.Context, nodeID *ua.NodeID, value any) (ua.StatusCode, error)
- func (c *Client) WriteValue(ctx context.Context, nodeID *ua.NodeID, value *ua.DataValue) (ua.StatusCode, error)
- func (c *Client) WriteValues(ctx context.Context, writes ...*ua.WriteValue) ([]ua.StatusCode, error)
- type ClientMetrics
- type Config
- type ConnState
- type ExponentialBackoffConfig
- type InvalidResponseTypeError
- type Logger
- type Node
- func (n *Node) AccessLevel(ctx context.Context) (ua.AccessLevelType, error)
- func (n *Node) Attribute(ctx context.Context, attrID ua.AttributeID) (*ua.Variant, error)
- func (n *Node) Attributes(ctx context.Context, attrID ...ua.AttributeID) ([]*ua.DataValue, error)
- func (n *Node) BrowseAll(ctx context.Context, refType uint32, dir ua.BrowseDirection, mask ua.NodeClass, ...) iter.Seq2[*ua.ReferenceDescription, error]
- func (n *Node) BrowseName(ctx context.Context) (*ua.QualifiedName, error)
- func (n *Node) BrowseWithDepth(ctx context.Context, opts BrowseWithDepthOptions) ([]BrowseWithDepthResult, error)
- func (n *Node) Children(ctx context.Context, refs uint32, mask ua.NodeClass) ([]*Node, error)
- func (n *Node) DataType(ctx context.Context) (*ua.NodeID, error)
- func (n *Node) Description(ctx context.Context) (*ua.LocalizedText, error)
- func (n *Node) DisplayName(ctx context.Context) (*ua.LocalizedText, error)
- func (n *Node) HasAccessLevel(ctx context.Context, mask ua.AccessLevelType) (bool, error)
- func (n *Node) HasUserAccessLevel(ctx context.Context, mask ua.AccessLevelType) (bool, error)
- func (n *Node) NodeClass(ctx context.Context) (ua.NodeClass, error)
- func (n *Node) ReferencedNodes(ctx context.Context, refs uint32, dir ua.BrowseDirection, mask ua.NodeClass, ...) ([]*Node, error)
- func (n *Node) References(ctx context.Context, refType uint32, dir ua.BrowseDirection, mask ua.NodeClass, ...) ([]*ua.ReferenceDescription, error)
- func (n *Node) String() string
- func (n *Node) Summary(ctx context.Context) (*NodeSummary, error)
- func (n *Node) TranslateBrowsePathInNamespaceToNodeID(ctx context.Context, ns uint16, browsePath string) (*ua.NodeID, error)
- func (n *Node) TranslateBrowsePathsToNodeIDs(ctx context.Context, pathNames []*ua.QualifiedName) (*ua.NodeID, error)
- func (n *Node) TypeDefinition(ctx context.Context) (*ua.NodeID, error)
- func (n *Node) UserAccessLevel(ctx context.Context) (ua.AccessLevelType, error)
- func (n *Node) Value(ctx context.Context) (*ua.Variant, error)
- func (n *Node) Walk(ctx context.Context) iter.Seq2[WalkResult, error]
- func (n *Node) WalkLimit(ctx context.Context, maxDepth int) iter.Seq2[WalkResult, error]
- func (n *Node) WalkLimitDedup(ctx context.Context, maxDepth int) iter.Seq2[WalkResult, error]
- type NodeSummary
- type Option
- func ApplicationName(s string) Option
- func ApplicationURI(s string) Option
- func AuthAnonymous() Option
- func AuthCertificate(cert []byte) Option
- func AuthIssuedToken(tokenData []byte) Option
- func AuthPolicyID(policy string) Option
- func AuthPrivateKey(key *rsa.PrivateKey) Option
- func AuthUsername(user, pass string) Option
- func AutoReconnect(b bool) Option
- func Certificate(cert []byte) Option
- func CertificateFile(filename string) Option
- func DialTimeout(d time.Duration) Option
- func Dialer(d *uacp.Dialer) Option
- func InsecureSkipVerify() Option
- func Lifetime(d time.Duration) Option
- func Locales(locale ...string) Option
- func MaxChunkCount(n uint32) Option
- func MaxMessageSize(n uint32) Option
- func PrivateKey(key *rsa.PrivateKey) Option
- func PrivateKeyFile(filename string) Option
- func ProductURI(s string) Option
- func RandomRequestID() Option
- func ReceiveBufferSize(n uint32) Option
- func ReconnectInterval(d time.Duration) Option
- func RemoteCertificate(cert []byte) Option
- func RemoteCertificateFile(filename string) Option
- func RequestTimeout(t time.Duration) Option
- func SecurityFromEndpoint(ep *ua.EndpointDescription, authType ua.UserTokenType) Option
- func SecurityMode(m ua.MessageSecurityMode) Option
- func SecurityModeString(s string) Option
- func SecurityPolicy(s string) Option
- func SendBufferSize(n uint32) Option
- func SessionName(s string) Option
- func SessionTimeout(d time.Duration) Option
- func SkipNamespaceUpdate() Option
- func StateChangedCh(ch chan<- ConnState) Optiondeprecated
- func StateChangedFunc(f func(ConnState)) Optiondeprecated
- func TrustedCertificates(certs ...*x509.Certificate) Option
- func WithConnStateHandler(h func(ConnState)) Option
- func WithLogger(l Logger) Option
- func WithMetrics(m ClientMetrics) Option
- func WithRetryPolicy(p RetryPolicy) Option
- type PublishNotificationData
- type ReadItem
- type ReadMultiOption
- type ReadResult
- type RetryPolicy
- type Session
- type Subscription
- func (s *Subscription) Cancel(ctx context.Context) error
- func (s *Subscription) ModifyMonitoredItems(ctx context.Context, ts ua.TimestampsToReturn, ...) (*ua.ModifyMonitoredItemsResponse, error)
- func (s *Subscription) ModifySubscription(ctx context.Context, params SubscriptionParameters) (*ua.ModifySubscriptionResponse, error)
- func (s *Subscription) Monitor(ctx context.Context, ts ua.TimestampsToReturn, ...) (*ua.CreateMonitoredItemsResponse, error)
- func (s *Subscription) SetMonitoringMode(ctx context.Context, monitoringMode ua.MonitoringMode, ...) (*ua.SetMonitoringModeResponse, error)
- func (s *Subscription) SetPublishingMode(ctx context.Context, publishingEnabled bool) (*ua.SetPublishingModeResponse, error)
- func (s *Subscription) SetTriggering(ctx context.Context, triggeringItemID uint32, add, remove []uint32) (*ua.SetTriggeringResponse, error)
- func (s *Subscription) Stats(ctx context.Context) (*ua.SubscriptionDiagnosticsDataType, error)
- func (s *Subscription) Unmonitor(ctx context.Context, monitoredItemIDs ...uint32) (*ua.DeleteMonitoredItemsResponse, error)
- type SubscriptionBuilder
- func (b *SubscriptionBuilder) Interval(d time.Duration) *SubscriptionBuilder
- func (b *SubscriptionBuilder) LifetimeCount(n uint32) *SubscriptionBuilder
- func (b *SubscriptionBuilder) MaxKeepAliveCount(n uint32) *SubscriptionBuilder
- func (b *SubscriptionBuilder) MaxNotificationsPerPublish(n uint32) *SubscriptionBuilder
- func (b *SubscriptionBuilder) Monitor(nodeIDs ...*ua.NodeID) *SubscriptionBuilder
- func (b *SubscriptionBuilder) MonitorEvents(filter *ua.EventFilter, nodeIDs ...*ua.NodeID) *SubscriptionBuilder
- func (b *SubscriptionBuilder) MonitorItems(items ...*ua.MonitoredItemCreateRequest) *SubscriptionBuilder
- func (b *SubscriptionBuilder) NotifyChannel(ch chan *PublishNotificationData) *SubscriptionBuilder
- func (b *SubscriptionBuilder) Priority(p uint8) *SubscriptionBuilder
- func (b *SubscriptionBuilder) SamplingInterval(d time.Duration) *SubscriptionBuilder
- func (b *SubscriptionBuilder) Start(ctx context.Context) (*Subscription, chan *PublishNotificationData, error)
- func (b *SubscriptionBuilder) Timestamps(ts ua.TimestampsToReturn) *SubscriptionBuilder
- type SubscriptionParameters
- type WalkResult
Constants ¶
const ( DefaultSubscriptionMaxNotificationsPerPublish = 10000 DefaultSubscriptionLifetimeCount = 10000 DefaultSubscriptionMaxKeepAliveCount = 3000 DefaultSubscriptionInterval = 100 * time.Millisecond DefaultSubscriptionPriority = 0 )
const (
DefaultDialTimeout = 10 * time.Second
)
const DefaultReadMultiChunkSize = 32
DefaultReadMultiChunkSize is the default max items per Read request when using ReadMulti, to stay under typical server MaxNodesPerRead limits.
Variables ¶
var NewSlogLogger = logger.NewSlogLogger
NewSlogLogger returns a Logger backed by the given slog.Handler.
var NewStdLogger = logger.NewStdLogger
NewStdLogger returns a Logger backed by the standard library log.Logger.
var NopLogger = logger.NopLogger
NopLogger returns a Logger that discards all output.
Functions ¶
func AggregateType ¶
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
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 ¶
DefaultClientConfig returns the default configuration for a client to establish a secure channel.
func DefaultDialer ¶
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
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
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
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 ¶
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.
func (*Client) ActivateSession ¶
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 ¶
func (c *Client) Call(ctx context.Context, req *ua.CallMethodRequest) (*ua.CallMethodResult, error)
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 ¶
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) Connect ¶
Connect establishes a secure channel and creates a new session.
It performs the full OPC-UA connection sequence:
- Opens a TCP connection to the server (UACP)
- Opens a secure channel with the configured security policy
- Creates a session with the configured parameters
- 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 ¶
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 ¶
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) FindNamespace ¶
FindNamespace returns the id of the namespace with the given name.
func (*Client) FindServers ¶
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 ¶
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 ¶
NamespaceArray returns the list of namespaces registered on the server.
func (*Client) NamespaceURI ¶
NamespaceURI returns the namespace URI for the given namespace index. Returns an error if the index is out of bounds.
func (*Client) Namespaces ¶
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 ¶
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
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
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 ¶
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 ¶
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 ¶
SecurityPolicy returns the security policy URI of the active secure channel.
func (*Client) Send ¶
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 ¶
ServerStatus reads the server's ServerStatusDataType from node i=2256.
func (*Client) 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) 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 ¶
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 ¶
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 ¶
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 )
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 ¶
func (*InvalidResponseTypeError) Error ¶
func (e *InvalidResponseTypeError) Error() string
func (*InvalidResponseTypeError) Is ¶
func (e *InvalidResponseTypeError) Is(target error) bool
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 ¶
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) Attributes ¶
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 ¶
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) Description ¶
Description returns the description of the node.
func (*Node) DisplayName ¶
DisplayName returns the display name of the node.
func (*Node) HasAccessLevel ¶
HasAccessLevel returns true if all bits from mask are set in the access level mask of the node.
func (*Node) HasUserAccessLevel ¶
HasUserAccessLevel returns true if all bits from mask are set in the user access level mask of the node.
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) 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 ¶
TypeDefinition returns the NodeID of the type definition for this node by following the HasTypeDefinition reference.
func (*Node) UserAccessLevel ¶
UserAccessLevel returns the access level of the node.
func (*Node) Walk ¶
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
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
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 ¶
Option is an option function type to modify the configuration.
func ApplicationName ¶
ApplicationName sets the application name in the session configuration.
func ApplicationURI ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
AutoReconnect sets the auto reconnect state of the secure channel.
func Certificate ¶
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 ¶
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 ¶
DialTimeout sets the timeout for establishing the UACP connection. Defaults to DefaultDialTimeout. Set to zero for no timeout.
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 MaxChunkCount ¶
MaxChunkCount sets the maximum chunk count for the UACP handshake.
func MaxMessageSize ¶
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 ¶
PrivateKeyFile sets the RSA private key in the secure channel configuration from a PEM or DER encoded file.
func ProductURI ¶
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 ¶
ReceiveBufferSize sets the receive buffer size for the UACP handshake.
func ReconnectInterval ¶
ReconnectInterval is interval duration between each reconnection attempt.
func RemoteCertificate ¶
RemoteCertificate sets the server certificate.
func RemoteCertificateFile ¶
RemoteCertificateFile sets the server certificate from the file in PEM or DER encoding.
func RequestTimeout ¶
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 ¶
SecurityModeString sets the security mode for the secure channel. Valid values are "None", "Sign", and "SignAndEncrypt".
func SecurityPolicy ¶
SecurityPolicy sets the security policy uri for the secure channel.
func SendBufferSize ¶
SendBufferSize sets the send buffer size for the UACP handshake.
func SessionName ¶
SessionName sets the name in the session configuration.
func SessionTimeout ¶
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 StateChangedFunc
deprecated
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 ¶
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 ¶
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 ¶
MaxRequestMessageSize returns the maximum request message size negotiated during session creation.
func (*Session) RevisedTimeout ¶
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.
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 (s *Subscription) ModifyMonitoredItems(ctx context.Context, ts ua.TimestampsToReturn, items ...*ua.MonitoredItemModifyRequest) (*ua.ModifyMonitoredItemsResponse, error)
func (*Subscription) ModifySubscription ¶
func (s *Subscription) ModifySubscription(ctx context.Context, params SubscriptionParameters) (*ua.ModifySubscriptionResponse, error)
func (*Subscription) Monitor ¶
func (s *Subscription) Monitor(ctx context.Context, ts ua.TimestampsToReturn, items ...*ua.MonitoredItemCreateRequest) (*ua.CreateMonitoredItemsResponse, error)
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 ¶
func (s *Subscription) Stats(ctx context.Context) (*ua.SubscriptionDiagnosticsDataType, error)
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 ¶
func (b *SubscriptionBuilder) Interval(d time.Duration) *SubscriptionBuilder
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 ¶
func (b *SubscriptionBuilder) MonitorItems(items ...*ua.MonitoredItemCreateRequest) *SubscriptionBuilder
MonitorItems adds custom monitored item create requests.
func (*SubscriptionBuilder) NotifyChannel ¶
func (b *SubscriptionBuilder) NotifyChannel(ch chan *PublishNotificationData) *SubscriptionBuilder
NotifyChannel sets the channel for receiving notifications. If not set, Start creates a buffered channel with capacity 256.
func (*SubscriptionBuilder) Priority ¶
func (b *SubscriptionBuilder) Priority(p uint8) *SubscriptionBuilder
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 ¶
func (b *SubscriptionBuilder) Start(ctx context.Context) (*Subscription, chan *PublishNotificationData, error)
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 ¶
func (b *SubscriptionBuilder) Timestamps(ts ua.TimestampsToReturn) *SubscriptionBuilder
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.
Source Files
¶
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/NodeSet2_server
command
|
|
|
server/map_server
command
|
|
|
server/node_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
|
|
|
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. |