### Complete OPC UA Client Configuration Example Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md This example demonstrates a comprehensive client configuration, including connection settings, security, authentication, session parameters, and reconnection options. ```go package main import ( "context" "time" "github.com/gopcua/opcua" "github.com/gopcua/opcua/ua" ) func main() { client, _ := opcua.NewClient( "opc.tcp://localhost:4840", // Connection settings opcua.DialTimeout(30 * time.Second), opcua.MaxMessageSize(4194304), // 4MB // Security opcua.SecurityPolicy("Basic256Sha256"), opcua.SecurityMode(ua.MessageSecurityModeSignAndEncrypt), opcua.CertificateFile("/etc/opcua/client.crt"), opcua.PrivateKeyFile("/etc/opcua/client.key"), // Authentication opcua.AuthUsername("operator", "password"), // Session opcua.SessionName("MyApplication"), opcua.SessionTimeout(30 * time.Minute), opcua.ApplicationName("My OPC UA App"), opcua.Locales("en-us"), // Reconnection opcua.AutoReconnect(true), opcua.ReconnectInterval(5 * time.Second), // Monitoring opcua.StateChangedFunc(func(state opcua.ConnState) { println("Connection state:", state) }), ) client.Connect(context.Background()) defer client.Close(context.Background()) // Use client... } ``` -------------------------------- ### Install gopcua Library Source: https://github.com/gopcua/opcua/blob/main/README.md Installs the gopcua library using the go get command. This is the first step before using the library in your Go projects. ```shell go get -u github.com/gopcua/opcua ``` -------------------------------- ### Crypto Example for Supported Devices Source: https://github.com/gopcua/opcua/wiki/Current-State This example demonstrates crypto and authentication methods tested against various devices and applications. Refer to the wiki for a list of supported devices. ```go package main import ( "log" ) func main() { // Example for crypto and authentication methods. // See https://github.com/gopcua/opcua/wiki/Supported-Devices // Please add your own. See examples/crypto for an example. // This is a placeholder and does not represent actual runnable code from the source. // The actual code would involve setting up crypto configurations and authentication protocols. log.Println("Placeholder for crypto example.") } ``` -------------------------------- ### Complete OPC UA Client Example Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/node.md A full example demonstrating how to connect to an OPC UA server, read node properties (class, browse name, display name), and browse child nodes with their values. ```go package main import ( "context" "fmt" "log" "time" "github.com/gopcua/opcua" "github.com/gopcua/opcua/ua" ) func main() { client, err := opcua.NewClient("opc.tcp://localhost:4840") if err != nil { log.Fatal(err) } if err := client.Connect(context.Background()); err != nil { log.Fatal(err) } defer client.Close(context.Background()) // Get the Server node node := client.Node(ua.NewNumericNodeID(0, 20)) // Read its properties class, _ := node.NodeClass(context.Background()) name, _ := node.BrowseName(context.Background()) displayName, _ := node.DisplayName(context.Background()) fmt.Printf("Node Class: %v\n", class) fmt.Printf("Browse Name: %s\n", name.Name) fmt.Printf("Display Name: %s\n", displayName.Text) // Browse its children children, _ := node.Children(context.Background(), 0, ua.NodeClassVariable) for _, child := range children { childName, _ := child.BrowseName(context.Background()) value, _ := child.Value(context.Background()) fmt.Printf(" %s = %v\n", childName.Name, value.Value()) } } ``` -------------------------------- ### Create and Start a New OPC UA Server Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/server.md Initializes a new OPC UA server with specified endpoint and application name, then starts it. Ensure to handle potential errors during startup. ```go server := server.New( server.Endpoint("opc.tcp://localhost:4840"), server.ApplicationName("My OPC UA Server"), ) if err := server.Start(context.Background()); err != nil { log.Fatal(err) } ``` -------------------------------- ### Start OPC UA Server and Print URLs Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/server.md Starts an OPC UA server configured with a specific endpoint and prints the URLs it is listening on. This is useful for verifying server accessibility. ```go server := server.New(server.Endpoint("opc.tcp://0.0.0.0:4840")) if err := server.Start(context.Background()); err != nil { log.Fatal(err) } fmt.Printf("Server listening on %v\n", server.URLs()) ``` -------------------------------- ### Example Usage of GoOPCUA Client Source: https://github.com/gopcua/opcua/wiki/Current-State This snippet demonstrates the basic usage of the GoOPCUA client. It is intended for use with real-world PLCs and other OPC/UA implementations. ```go package main import ( "context" "log" "time" "github.com/gopcua/opcua" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() // Example usage of the client.go and examples/datetime // This code is not ready for production but we intend to get it there. // We are testing the code against real-world PLCs and other OPC/UA implementations but this needs to be more formalized. // The goal is to have the examples working with real PLCs. Please let us know if they don't. // This is a placeholder and does not represent actual runnable code from the source. // The actual code would involve client connection, secure channel creation, and session establishment. log.Println("Placeholder for client example.") // Example of a potential client connection (not from source): // opts := []opcua.Option{ // opcua.SecurityPolicy("None"), // opcua.AuthAnonymous() // } // client, err := opcua.NewClient("opc.tcp://localhost:4841", opts...) // if err != nil { // log.Fatal(err) // } // if err := client.Connect(ctx); err != nil { // log.Fatal(err) // } // defer client.Close() // log.Println("Client connected") } ``` -------------------------------- ### Build an OPC UA Server Source: https://github.com/gopcua/opcua/blob/main/_autodocs/README.md This snippet demonstrates how to initialize and start a basic OPC UA server with anonymous authentication. It also shows how to add a custom namespace. Ensure necessary imports are present. ```go import "github.com/gopcua/opcua/server" srv := server.New( server.Endpoint("opc.tcp://0.0.0.0:4840"), server.ApplicationName("MyServer"), server.AuthAnonymous(), ) if err := srv.Start(context.Background()); err != nil { log.Fatal(err) } // Add custom namespace ns := server.NewNodeNameSpace("http://example.com/myapp") nsIdx := srv.AddNamespace(ns) // Add nodes and handle client connections... defer srv.Close() ``` -------------------------------- ### Server Start Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/server.md Initializes service handlers, opens listening sockets, and begins accepting client connections. This method sets the server state to Running and spawns goroutines for connection handling. ```APIDOC ## Server Start ### Description Initializes service handlers, opens listening sockets, and starts accepting client connections. Sets server state to Running. Spawns goroutines for connection handling. ### Signature ```go func (s *Server) Start(ctx context.Context) error ``` ### Parameters - **ctx** (context.Context) - Context for shutdown signaling ### Returns - **`error`**: Start error or nil if successful ### Throws - Error if no endpoints are configured - Network errors (port in use, permission denied, etc.) ### Example ```go server := server.New(server.Endpoint("opc.tcp://0.0.0.0:4840")) if err := server.Start(context.Background()); err != nil { log.Fatal(err) } fmt.Printf("Server listening on %v\n", server.URLs()) ``` ``` -------------------------------- ### Complete OPC UA Server Example in Go Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/server.md This snippet shows how to create a self-signed certificate, initialize an OPC UA server with an endpoint, application name, URI, certificate, private key, and anonymous authentication. It also demonstrates adding a custom namespace and a node to the server. ```go package main import ( "context" "crypto/rand" "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "log" "math/big" "time" "github.com/gopcua/opcua/id" "github.com/gopcua/opcua/server" "github.com/gopcua/opcua/ua" ) func main() { // Create self-signed certificate pk, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { log.Fatal(err) } cert := &x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{ CommonName: "MyServer", }, NotBefore: time.Now(), NotAfter: time.Now().AddDate(1, 0, 0), } certDER, err := x509.CreateCertificate(rand.Reader, cert, cert, &pk.PublicKey, pk) if err != nil { log.Fatal(err) } // Create server srv := server.New( server.Endpoint("opc.tcp://0.0.0.0:4840"), server.ApplicationName("Example Server"), server.ApplicationURI("urn:example:server"), server.Certificate(certDER), server.PrivateKey(pk), server.AuthAnonymous(), ) // Start server if err := srv.Start(context.Background()); err != nil { log.Fatal(err) } log.Printf("Server started on %v", srv.URLs()) // Add custom namespace ns := server.NewNodeNameSpace("http://example.com/devices") nsIdx := srv.AddNamespace(ns) // Add a node deviceNode := server.NewNodeWithID( ua.NewNumericNodeID(uint16(nsIdx), 1), server.WithBrowseName("Device1"), server.WithDisplayName("First Device"), ) ns.AddNode(deviceNode) // Cleanup defer srv.Close() // Keep running select {} } ``` -------------------------------- ### New Server Constructor Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/server.md Creates a new OPC/UA server instance with default configuration. It includes namespace 0 with standard nodes and requires `Start()` to be called to begin listening for connections. ```APIDOC ## New Server Constructor ### Description Creates a new server with default configuration. The server includes a pre-loaded namespace 0 with OPC Foundation standard nodes. Call `Start()` to begin listening. ### Signature ```go func New(opts ...Option) *Server ``` ### Parameters - **opts** (*Option) - Variable number of server configuration options ### Returns - **`*Server`**: Initialized server (not yet listening) ### Example ```go server := server.New( server.Endpoint("opc.tcp://localhost:4840"), server.ApplicationName("My OPC UA Server"), ) if err := server.Start(context.Background()); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Connect Method Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Establishes a secure channel, creates a session, and activates it. This is the main connection entry point. The method also updates namespace information and starts internal monitoring goroutines. Returns an error if a secure channel already exists (already connected). ```APIDOC ## Connect Method ### Description Establishes a secure channel, creates a session, and activates it. This is the main connection entry point. The method also updates namespace information and starts internal monitoring goroutines. Returns an error if a secure channel already exists (already connected). ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **ctx** (context.Context) - Required - Context for deadline, cancellation, and timeout ### Returns - `error`: Connection error or nil if successful ### Throws - `StatusBadSecureChannelIDInvalid`: Secure channel rejected by server during reconnection - `StatusBadSessionIDInvalid`: Session rejected by server during reconnection - `error`: Network or protocol errors ### Example ```go ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) def cancel() if err := client.Connect(ctx); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Get Server Endpoint Descriptions Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/server.md Retrieves detailed descriptions for all endpoints exposed by the server. This includes information about security policies and authentication methods. ```go func (s *Server) Endpoints() []*ua.EndpointDescription ``` -------------------------------- ### Get Server Endpoint URLs Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/server.md Returns a list of all configured endpoint URLs that the OPC/UA server is actively listening on. This is useful for clients to discover available connection points. ```go func (s *Server) URLs() []string ``` -------------------------------- ### Get Default Client Configuration Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md The DefaultClientConfig function returns a pointer to a default uasc.Config struct, which includes settings for security, lifetime, request timeout, and reconnection. ```go func DefaultClientConfig() *uasc.Config ``` ```go &uasc.Config{ SecurityPolicyURI: ua.SecurityPolicyURINone, SecurityMode: ua.MessageSecurityModeNone, Lifetime: uint32(time.Hour / time.Millisecond), RequestTimeout: 10 * time.Second, AutoReconnect: true, ReconnectInterval: 5 * time.Second, } ``` -------------------------------- ### GUID Structure Source: https://github.com/gopcua/opcua/blob/main/_autodocs/types.md Represents a Globally Unique Identifier (GUID) conforming to RFC 4122. It includes fields for the different parts of a GUID. ```go type GUID struct { Data1 uint32 Data2 uint16 Data3 uint16 Data4 []byte } ``` -------------------------------- ### Basic Error Handling with Client Source: https://github.com/gopcua/opcua/blob/main/_autodocs/errors.md Demonstrates setting up a client with a timeout and handling initial connection errors. Ensure to defer client closing. ```go ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() client, err := opcua.NewClient("opc.tcp://localhost:4840") if err != nil { log.Fatal(err) } defer client.Close(ctx) if err := client.Connect(ctx); err != nil { log.Fatal(err) } // Use client... ``` -------------------------------- ### AddNamespace Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/server.md Registers a new namespace with the server. Custom namespaces are indexed starting from 1. ```APIDOC ## AddNamespace ### Description Registers a new namespace. Namespace 0 is pre-registered as the OPC Foundation standard namespace. Custom namespaces are indexed starting at 1. ### Method POST (conceptual) ### Endpoint N/A (Method Call) ### Parameters #### Request Body - **ns** (NameSpace) - Required - Namespace implementation to register. ### Request Example ```go ns := server.NewNodeNameSpace("http://example.com/namespace") idx := srv.AddNamespace(ns) fmt.Printf("Namespace registered at index %d\n", idx) ``` ### Response #### Success Response - **index** (int) - The index of the newly added namespace. ### Response Example ```json { "index": 1 } ``` ``` -------------------------------- ### Monitor Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/subscription.md Adds monitored items to the subscription. Each item gets an ID for future reference. ```APIDOC ## Monitor ### Description Adds monitored items to the subscription. Each item gets an ID for future reference. ### Method func (s *Subscription) Monitor(ctx context.Context, ts ua.TimestampsToReturn, items ...*ua.MonitoredItemCreateRequest) (*ua.CreateMonitoredItemsResponse, error) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go req := opcua.NewMonitoredItemCreateRequestWithDefaults( ua.NewNumericNodeID(0, 2258), // Node ID ua.AttributeIDValue, // Attribute 1, // Client handle ) resp, err := sub.Monitor(context.Background(), ua.TimestampsToReturnBoth, req) if err != nil { log.Fatal(err) } for _, result := range resp.Results { if result.StatusCode == ua.StatusOK { fmt.Printf("Monitored item ID: %d\n", result.MonitoredItemID) } } ``` ### Response #### Success Response (200) - `*ua.CreateMonitoredItemsResponse`: Response with monitored item IDs and status #### Response Example None provided in source. ERROR HANDLING: - `error`: Creation error or nil ``` -------------------------------- ### Configure Username Authentication Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md Sets up username and password authentication for the client. ```go client, _ := opcua.NewClient( "opc.tcp://localhost:4840", opcua.AuthUsername("admin", "password123"), ) ``` -------------------------------- ### SubscriptionIDs Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Gets the IDs of all active subscriptions. This method returns a list of active subscription IDs. ```APIDOC ## SubscriptionIDs ### Description Gets the IDs of all active subscriptions. ### Method (Method signature implies a client-side call, not a direct HTTP endpoint) ### Parameters (None) ### Response #### Success Response - **[]uint32** (type) - List of active subscription IDs #### Response Example (Not applicable - Go method signature provided) ``` -------------------------------- ### Get Active Session Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Retrieves the active session object. Returns nil if no session is currently established. ```go func (c *Client) Session() *Session ``` -------------------------------- ### Get Active Subscription IDs Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Retrieves a list of all currently active subscription identifiers managed by the client. ```go func (c *Client) SubscriptionIDs() []uint32 ``` -------------------------------- ### Get OPC UA Endpoints Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Retrieves a list of available endpoints for the connected OPC UA server. ```go resp, err := c.GetEndpoints(ctx) ``` -------------------------------- ### Get Node String Representation Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/node.md Returns the string representation of the node ID. Useful for debugging or logging. ```go fmt.Println(node.String()) // "ns=0;i=2258" ``` -------------------------------- ### Set Client Certificate from File Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md Configures the client certificate using a file path. Supports PEM or DER format. ```go client, _ := opcua.NewClient( "opc.tcp://localhost:4840", opcua.CertificateFile("/path/to/client.crt"), ) ``` -------------------------------- ### Get Secure Channel Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Retrieves the active secure channel associated with the client. Returns nil if the client is not connected. ```go func (c *Client) SecureChannel() *uasc.SecureChannel ``` -------------------------------- ### Set Product URI Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md Use the ProductURI option to specify a unique identifier for the product. The default is 'urn:gopcua'. ```go func ProductURI(s string) Option ``` -------------------------------- ### ReferencedNodes Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/node.md Retrieves nodes at the other end of references, similar to References but returns Node wrappers instead of ReferenceDescriptions. Includes an example. ```APIDOC ## ReferencedNodes ### Description Like References but returns Node wrappers instead of ReferenceDescriptions. ### Method `func (n *Node) ReferencedNodes(ctx context.Context, refs uint32, dir ua.BrowseDirection, mask ua.NodeClass, includeSubtypes bool) ([]*Node, error)` ### Parameters - **ctx** (context.Context) - Context for timeout - **refs** (uint32) - Reference type ID (0 for all references) - **dir** (ua.BrowseDirection) - Direction (Forward, Inverse, Both) - **mask** (ua.NodeClass) - Node class filter (0 for all classes) - **includeSubtypes** (bool) - Include subtypes of refType ### Returns - **`[]*Node`**: Nodes at the other end of references - **`error`**: Browse error ### Example ```go children, err := node.ReferencedNodes( context.Background(), id.HierarchicalReferences, ua.BrowseDirectionForward, ua.NodeClassAll, true, ) for _, child := range children { name, _ := child.BrowseName(context.Background()) fmt.Println(name.Name) } ``` ``` -------------------------------- ### Node.Children Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/node.md Convenience method to get child nodes (forward hierarchical references). Equivalent to calling ReferencedNodes with specific defaults. ```APIDOC ## Node.Children ### Description Convenience method to get child nodes (forward hierarchical references). Equivalent to calling ReferencedNodes with specific defaults. ### Method Go function call ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for timeout - **refs** (uint32) - Required - Reference type (0 for HierarchicalReferences) - **mask** (ua.NodeClass) - Required - Node class filter ### Returns - `[]*Node`: Child nodes - `error`: Browse error ### Example ```go children, err := node.Children(context.Background(), 0, ua.NodeClassAll) if err != nil { log.Fatal(err) } for _, child := range children { fmt.Println(child.String()) } ``` ``` -------------------------------- ### Set Private Key from File Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md Configures the client's private key using a file path. Supports PEM or DER format. ```go client, _ := opcua.NewClient( "opc.tcp://localhost:4840", opcua.CertificateFile("/path/to/client.crt"), opcua.PrivateKeyFile("/path/to/client.key"), ) ``` -------------------------------- ### Get Current Date and Time Source: https://github.com/gopcua/opcua/blob/main/README.md Retrieves the current date and time from an OPC/UA server. Requires the server endpoint to be specified. ```go go run examples/datetime/datetime.go -endpoint opc.tcp://localhost:4840 ``` -------------------------------- ### Create and Connect OPC/UA Client Source: https://github.com/gopcua/opcua/blob/main/_autodocs/README.md Establishes a connection to an OPC/UA server. Ensure the server address is correct and the client can reach it. ```go import "github.com/gopcua/opcua" import "context" import "log" client, err := opcua.NewClient("opc.tcp://localhost:4840") if err != nil { log.Fatal(err) } if err := client.Connect(context.Background()); err != nil { log.Fatal(err) } defer client.Close(context.Background()) ``` -------------------------------- ### Get Cached Namespace URIs Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Returns the currently cached list of namespace URIs. For an updated list, call UpdateNamespaces() first. ```go func (c *Client) Namespaces() []string ``` -------------------------------- ### Go Static File Server Source: https://github.com/gopcua/opcua/wiki/gopcua-in-the-browser A simple Go program to serve static files from disk, required for hosting the WebAssembly application. ```go package main import ( "flag" "log" "net/http" ) var ( listen = flag.String("listen", ":7070", "listen address") dir = flag.String("dir", ".", "directory to serve") ) func main() { flag.Parse() log.Printf("listening on %q...", *listen) log.Fatal(http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir)))) } ``` -------------------------------- ### Get OPC UA Endpoints Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Retrieves a list of available endpoints and their security configurations from an OPC UA server. This is a convenience function. ```go func GetEndpoints(ctx context.Context, endpoint string, opts ...Option) ([]*ua.EndpointDescription, error) ``` ```go endpoints, err := opcua.GetEndpoints(context.Background(), "opc.tcp://localhost:4840") for _, ep := range endpoints { fmt.Printf("Policy: %s, Mode: %s, Level: %d\n", ep.SecurityPolicyURI, ep.SecurityMode, ep.SecurityLevel) } ``` -------------------------------- ### Create and Print QualifiedName Source: https://github.com/gopcua/opcua/blob/main/_autodocs/types.md Demonstrates the creation of a QualifiedName struct and how to format it for printing, showing the namespace index and the name. ```go qn := &ua.QualifiedName{ NamespaceIndex: 1, Name: "Device1", } fmt.Printf("%d:%s", qn.NamespaceIndex, qn.Name) // 1:Device1 ``` -------------------------------- ### Create New OPC UA Client Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Creates a new OPC/UA client instance with default configuration. The client is not yet connected; call Connect() to establish the connection. Anonymous authentication is used if no method is configured. ```go client, err := opcua.NewClient("opc.tcp://localhost:4840") if err != nil { log.Fatal(err) } deffer client.Close(context.Background()) ``` ```go client, err := opcua.NewClient( "opc.tcp://localhost:4840", opcua.SecurityPolicy("Basic256"), opcua.SecurityMode(ua.MessageSecurityModeSignAndEncrypt), opcua.AuthUsername("user", "password"), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Connect OPC UA Client Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Establishes a secure channel, creates a session, and activates it. This is the main connection entry point. Returns an error if a secure channel already exists. ```go ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) deffer cancel() if err := client.Connect(ctx); err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Request Timeout Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Returns the configured timeout duration for client requests. This value dictates how long the client will wait for a response before timing out. ```go func (c *Client) RequestTimeout() time.Duration ``` -------------------------------- ### Create and Use Variants Source: https://github.com/gopcua/opcua/blob/main/_autodocs/types.md Shows how to wrap Go values and arrays into Variants using constructor functions. The Value() method retrieves the wrapped value. ```go v1 := ua.NewVariant(int32(42)) v2 := ua.NewVariant("Hello") v3 := ua.NewVariant([]float64{1.1, 2.2}) fmt.Println(v1.Value()) // 42 fmt.Println(v2.Value()) // Hello ``` -------------------------------- ### Get OPC UA Client Connection State Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Returns the current connection state of the client. Use this to determine if the client is ready to send requests. ```go if client.State() == opcua.Connected { // Can send requests } ``` -------------------------------- ### Set Client Certificate Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md Sets the client X509 certificate for authentication. Extracts the ApplicationURI from the certificate. ```go func Certificate(cert []byte) Option ``` -------------------------------- ### NewClient Constructor Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/client.md Creates a new OPC/UA client with default configuration. The client uses DefaultClientConfig() and DefaultSessionConfig() internally. If no authentication method is configured, anonymous authentication is used. The client is not yet connected; call Connect() to establish the connection. ```APIDOC ## NewClient Constructor ### Description Creates a new OPC/UA client with default configuration. The client uses `DefaultClientConfig()` and `DefaultSessionConfig()` internally. If no authentication method is configured, anonymous authentication is used. The client is not yet connected; call `Connect()` to establish the connection. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **endpoint** (string) - Required - OPC/UA server endpoint URL (e.g., `opc.tcp://localhost:4840`) - **opts** (...Option) - Optional - Variable number of configuration options to customize client behavior ### Returns - `*Client`: A new client instance ready for connection - `error`: Error if configuration is invalid ### Throws - `error` if any option returns an error ### Example ```go client, err := opcua.NewClient("opc.tcp://localhost:4840") if err != nil { log.Fatal(err) } def client.Close(context.Background()) ``` ### With options ```go client, err := opcua.NewClient( "opc.tcp://localhost:4840", opcua.SecurityPolicy("Basic256"), opcua.SecurityMode(ua.MessageSecurityModeSignAndEncrypt), opcua.AuthUsername("user", "password") ) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Get Node Children Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/node.md Convenience method to retrieve child nodes using forward hierarchical references. Equivalent to calling ReferencedNodes with specific defaults. ```go func (n *Node) Children(ctx context.Context, refs uint32, mask ua.NodeClass) ([]*Node, error) ``` ```go children, err := node.Children(context.Background(), 0, ua.NodeClassAll) if err != nil { log.Fatal(err) } for _, child := range children { fmt.Println(child.String()) } ``` -------------------------------- ### Set Security Mode by String Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md Configures the security mode using a string representation. Accepted values are 'None', 'Sign', or 'SignAndEncrypt'. ```go client, _ := opcua.NewClient( "opc.tcp://localhost:4840", opcua.SecurityModeString("SignAndEncrypt"), ) ``` -------------------------------- ### Get Server Status Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/server.md Retrieves the current status of the OPC/UA server, including its state and uptime. Use this to monitor server health and operational details. ```go func (s *Server) Status() *ua.ServerStatusDataType ``` ```go status := server.Status() fmt.Printf("Server state: %v\n", status.State) fmt.Printf("Uptime: %v\n", time.Since(status.StartTime)) ``` -------------------------------- ### Create Node Wrapper Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/node.md Creates a node wrapper. This is typically obtained via Client.Node() rather than calling this constructor directly. ```go func NewNode(id *ua.NodeID, c ClientInterface) *Node ``` -------------------------------- ### Advanced Security and Authentication Source: https://github.com/gopcua/opcua/blob/main/README.md Connects to an OPC/UA server using custom certificates, keys, and specific security policies and modes. This is useful for secure communication setups. ```go go run examples/crypto/*.go -endpoint opc.tcp://localhost:4840 -cert path/to/cert.pem -key path/to/key.pem -sec-policy Basic256 -sec-mode SignAndEncrypt ``` -------------------------------- ### Create LocalizedText Instance Source: https://github.com/gopcua/opcua/blob/main/_autodocs/types.md Demonstrates two ways to create a LocalizedText instance: using a constructor function and direct struct literal initialization. The constructor is typically preferred for simpler cases. ```go text := ua.NewLocalizedText("Device Status") text := &ua.LocalizedText{ Locale: "en-US", Text: "Device Status", } ``` -------------------------------- ### Configure Security from Endpoint Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md Configures security and user token type directly from an endpoint description. This is the recommended approach after calling GetEndpoints. ```go endpoints, _ := opcua.GetEndpoints(ctx, "opc.tcp://localhost:4840") ep, _ := opcua.SelectEndpoint(endpoints, "Basic256", ua.MessageSecurityModeSignAndEncrypt) client, _ := opcua.NewClient( "opc.tcp://localhost:4840", opcua.SecurityFromEndpoint(ep, ua.UserTokenTypeUserName), opcua.AuthUsername("user", "password"), ) ``` -------------------------------- ### Create Monitored Item Request with Defaults Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/subscription.md Creates a monitored item request with sensible defaults, including Reporting mode, a 10-item queue, discard oldest strategy, and 1-second sampling interval. The attribute defaults to Value if 0 is passed. ```go func NewMonitoredItemCreateRequestWithDefaults(nodeID *ua.NodeID, attributeID ua.AttributeID, clientHandle uint32) *ua.MonitoredItemCreateRequest ``` ```go req := opcua.NewMonitoredItemCreateRequestWithDefaults( ua.NewNumericNodeID(0, 2258), ua.AttributeIDValue, 1, ) ``` -------------------------------- ### Get Nodes from References Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/node.md Retrieves Node wrappers for nodes at the other end of references, similar to the References method but returns Node objects directly. Useful for further interaction with referenced nodes. ```go func (n *Node) ReferencedNodes(ctx context.Context, refs uint32, dir ua.BrowseDirection, mask ua.NodeClass, includeSubtypes bool) ([]*Node, error) ``` ```go children, err := node.ReferencedNodes( context.Background(), id.HierarchicalReferences, ua.BrowseDirectionForward, ua.NodeClassAll, tue, ) for _, child := range children { name, _ := child.BrowseName(context.Background()) fmt.Println(name.Name) } ``` -------------------------------- ### Set Server Certificate from File Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md Configures the server certificate for pinning using a file path. Supports PEM or DER format. ```go func RemoteCertificateFile(filename string) Option ``` -------------------------------- ### Retrieve Namespace by Index Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/server.md Fetches a specific namespace implementation from the server using its index. Returns an error if the namespace is not found. ```go func (s *Server) Namespace(id int) (NameSpace, error) ``` -------------------------------- ### Get Default Session Configuration Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md The DefaultSessionConfig function returns a pointer to a default uasc.SessionConfig struct, pre-configured with session timeout, application URI, application name, application type, and locale IDs. ```go func DefaultSessionConfig() *uasc.SessionConfig ``` -------------------------------- ### Certificate File Configuration Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md Options for loading client and server certificates from files. ```APIDOC ## CertificateFile ### Description Sets the client X509 certificate for authentication by loading it from a file. ### Function Signature ```go func CertificateFile(filename string) Option ``` ### Parameters - **filename** (*string*) - Required - Path to certificate file (PEM or DER format) ### Example ```go client, _ := opcua.NewClient( "opc.tcp://localhost:4840", opcua.CertificateFile("/path/to/client.crt") ) ``` --- ## RemoteCertificateFile ### Description Pins the server certificate for verification by loading it from a file. ### Function Signature ```go func RemoteCertificateFile(filename string) Option ``` ### Parameters - **filename** (*string*) - Required - Path to server certificate (PEM or DER) ``` -------------------------------- ### Private Key Configuration Source: https://github.com/gopcua/opcua/blob/main/_autodocs/configuration.md Options for setting the client's private key for authentication. ```APIDOC ## PrivateKey ### Description Sets the client's private key for authentication. ### Function Signature ```go func PrivateKey(key *rsa.PrivateKey) Option ``` ### Parameters - **key** (* *rsa.PrivateKey*) - Required - RSA private key (parsed) --- ## PrivateKeyFile ### Description Sets the client's private key for authentication by loading it from a file. ### Function Signature ```go func PrivateKeyFile(filename string) Option ``` ### Parameters - **filename** (*string*) - Required - Path to private key file (PEM or DER format) ### Example ```go client, _ := opcua.NewClient( "opc.tcp://localhost:4840", opcua.CertificateFile("/path/to/client.crt"), opcua.PrivateKeyFile("/path/to/client.key") ) ``` ``` -------------------------------- ### Access Predefined Node IDs Source: https://github.com/gopcua/opcua/blob/main/_autodocs/README.md This code shows how to import and use predefined node IDs from the `id` package for common OPC UA nodes like Server, RootFolder, and ObjectsFolder. These constants simplify referencing standard nodes. ```go import "github.com/gopcua/opcua/id" id.Server // Node ID 20 - Server node id.ServerNamespaceArray // Node ID 11715 - Namespace array id.RootFolder // Node ID 84 - Root folder id.ObjectsFolder // Node ID 85 - Objects folder id.TypesFolder // Node ID 86 - Types folder id.ViewsFolder // Node ID 87 - Views folder ``` -------------------------------- ### Add Custom Namespace to Server Source: https://github.com/gopcua/opcua/blob/main/_autodocs/api-reference/server.md Registers a new custom namespace with the server. Custom namespaces are indexed starting from 1, while namespace 0 is reserved for the OPC Foundation standard. This is essential for organizing custom data models. ```go func (s *Server) AddNamespace(ns NameSpace) int ``` ```go ns := server.NewNodeNameSpace("http://example.com/namespace") idx := srv.AddNamespace(ns) fmt.Printf("Namespace registered at index %d\n", idx) ``` -------------------------------- ### Create and Manage OPC/UA Subscription Source: https://github.com/gopcua/opcua/blob/main/_autodocs/README.md Sets up a subscription to monitor data changes on OPC/UA nodes. Notifications are received on a provided channel. Ensure the subscription interval is appropriate for the data update frequency. ```go import "context" import "fmt" import "log" import "time" import "github.com/gopcua/opcua" import "github.com/gopcua/opcua/ua" // Assuming 'client' is an established OPC/UA client notifyCh := make(chan *opcua.PublishNotificationData) sub, err := client.Subscribe(context.Background(), &opcua.SubscriptionParameters{ Interval: 500 * time.Millisecond, }, notifyCh, ) if err != nil { log.Fatal(err) } // Add monitored item req := opcua.NewMonitoredItemCreateRequestWithDefaults( ua.NewNumericNodeID(0, 2258), ua.AttributeIDValue, 1, ) sub.Monitor(context.Background(), ua.TimestampsToReturnBoth, req) // Receive notifications go func() { for notif := range notifyCh { fmt.Printf("Value: %v\n", notif.Value) } }() defer sub.Cancel(context.Background()) ``` -------------------------------- ### HTML Interface for WebAssembly Source: https://github.com/gopcua/opcua/wiki/gopcua-in-the-browser An HTML file that loads the WebAssembly JavaScript runtime and instantiates the compiled Go WebAssembly module. It includes a button to trigger a decoding function. ```html