### OpcSharp Client Builder Example Source: https://patdhlk.com/OpcSharp/docs/architecture Demonstrates how to use the OpcSharpClientBuilder to fluently configure and build an OPC UA client instance. This includes setting the endpoint, session name, security policies, user identity, and certificate acceptance behavior. ```csharp var client = new OpcSharpClientBuilder() .WithEndpoint("opc.tcp://localhost:4840") .WithSessionName("MySession") .WithSecurity(SecurityPolicyUris.Basic256Sha256, MessageSecurityMode.SignAndEncrypt) .WithUserIdentity(new UserNameIdentity("user", "pass")) .WithAutoAcceptUntrustedCertificates(true) .Build(); ``` -------------------------------- ### Browse Address Space and Translate Paths with OpcSharp Source: https://patdhlk.com/OpcSharp/docs/services Covers navigating the server address space and resolving node identifiers from paths. Includes examples for batch browsing and path translation. ```csharp // Browse children of the Objects folder var browseResults = await client.BrowseAsync(new[] { new BrowseDescription { NodeId = ObjectIds.ObjectsFolder, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All } }); foreach (var reference in browseResults[0].References) { Console.WriteLine($"{reference.DisplayName} ({reference.NodeId})"); } // Translate paths var result = await client.TranslateBrowsePathAsync( ObjectIds.ObjectsFolder, "Server/ServerStatus/CurrentTime"); ``` -------------------------------- ### Initialize OPC UA Client Source: https://patdhlk.com/OpcSharp/docs/cli-tool Demonstrates how to initialize the opcsharp client with specific security parameters or save the configuration to a file. ```bash opcsharp init --endpoint opc.tcp://192.168.1.100:4840 --security-policy Basic256Sha256 --security-mode SignAndEncrypt --auth Username opcsharp init --output MyClient.cs ``` -------------------------------- ### Configure Credentials via .env Source: https://patdhlk.com/OpcSharp/docs/cli-tool Shows how to define credentials in a .env file to avoid passing them as command-line arguments, followed by executing operations. ```bash # .env file content OPCUA_USERNAME=myuser OPCUA_PASSWORD=mypassword # Execution opcsharp browse opc.tcp://192.168.1.100:4840 opcsharp read opc.tcp://192.168.1.100:4840 "ns=4;s=MAIN.counter" opcsharp check opc.tcp://192.168.1.100:4840 ``` -------------------------------- ### Access CLI Help Source: https://patdhlk.com/OpcSharp/docs/cli-tool Commands to display general help information or specific guidance for individual subcommands. ```bash opcsharp --help opcsharp discover --help opcsharp browse --help ``` -------------------------------- ### Connect and Read Data with OpcSharp Source: https://patdhlk.com/OpcSharp/docs Demonstrates how to initialize an OPC UA client using the builder pattern, connect to a server, perform a read operation on a specific NodeId, and disconnect. This snippet requires the OpcSharp NuGet package and assumes a running OPC UA server at the specified endpoint. ```csharp var client = new OpcSharpClientBuilder() .WithEndpoint("opc.tcp://localhost:4840") .Build(); await client.ConnectAsync(); var results = await client.ReadAsync(new[] { new ReadValueId { NodeId = new NodeId(0, 2258), AttributeId = AttributeIds.Value } }); Console.WriteLine(results[0].Value); await client.DisconnectAsync(); ``` -------------------------------- ### Configure Credentials via Environment Variables Source: https://patdhlk.com/OpcSharp/docs/cli-tool Demonstrates exporting credentials as shell environment variables for authentication during CLI operations. ```bash export OPCUA_USERNAME=myuser export OPCUA_PASSWORD='mypassword' opcsharp browse opc.tcp://192.168.1.100:4840 ``` -------------------------------- ### Invoke Server Methods with OpcSharp Source: https://patdhlk.com/OpcSharp/docs/services Shows how to execute methods on an OPC UA server by providing the Object ID, Method ID, and required input arguments. ```csharp var results = await client.CallAsync(new[] { new CallMethodRequest { ObjectId = new NodeId(2, "MyObject"), MethodId = new NodeId(2, "MyMethod"), InputArguments = new Variant[] { new Variant(42), new Variant("hello") } } }); ``` -------------------------------- ### Manage Subscriptions and Monitored Items with OpcSharp Source: https://patdhlk.com/OpcSharp/docs/services Demonstrates creating subscriptions and managing monitored items for real-time data change reporting. Includes lifecycle management and event handling. ```csharp // Create a subscription var subscription = await client.CreateSubscriptionAsync(publishingInterval: 1000); // Create monitored items var items = await client.CreateMonitoredItemsAsync(subscription.SubscriptionId, new[] { new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = new NodeId(0, 2258), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting } }); // Handle data changes client.DataChanged += (sender, args) => Console.WriteLine($"Node {args.NodeId}: {args.Value}"); ``` -------------------------------- ### Troubleshoot Authentication and NodeId Parsing Source: https://patdhlk.com/OpcSharp/docs/cli-tool Provides commands to diagnose authentication issues and correct shell-related parsing errors for NodeIds containing semicolons. ```bash # Authenticate explicitly opcsharp browse opc.tcp://server:4840 --username myuser --password "mypass" # Discover authentication types opcsharp discover opc.tcp://server:4840 # Correctly quote NodeIds opcsharp read opc.tcp://server:4840 "ns=4;s=MAIN.counter" ``` -------------------------------- ### Browse Service Source: https://patdhlk.com/OpcSharp/docs/services Endpoints for navigating the server's address space and resolving paths to NodeIds. ```APIDOC ## [POST] /BrowseService ### Description Allows navigation of the server address space and translation of human-readable paths to NodeIds. ### Method POST ### Endpoint client.BrowseAsync / client.TranslateBrowsePathsToNodeIdsAsync ### Parameters #### Request Body - **BrowseDescription[]** (array) - Required - Parameters defining the browse operation (NodeId, Direction, etc.). - **requestedMaxReferencesPerNode** (int) - Optional - Limit for pagination. ### Response #### Success Response (200) - **BrowseResult[]** (array) - References found at the specified node. ``` -------------------------------- ### Configure OPC UA Client Security with SecurityOptions Action Source: https://patdhlk.com/OpcSharp/docs/security Configures an OpcSharp OPC UA client's security settings using an Action delegate that modifies a SecurityOptions object. This provides a flexible way to set the policy URI and message security mode, along with the application certificate. ```csharp var client = new OpcSharpClientBuilder() .WithEndpoint("opc.tcp://localhost:4840") .WithSecurity(options => { options.PolicyUri = SecurityPolicyUris.Basic256Sha256; options.Mode = MessageSecurityMode.SignAndEncrypt; }) .WithApplicationCertificate("certs/client.pfx", "password") .Build(); ``` -------------------------------- ### Read and Write Node Attributes with OpcSharp Source: https://patdhlk.com/OpcSharp/docs/services Demonstrates how to perform batch read and write operations on OPC UA node attributes using the Attribute Service. Inputs include NodeId and AttributeId, returning DataValue or status codes. ```csharp // Read multiple values var results = await client.ReadAsync(new[] { new ReadValueId { NodeId = new NodeId(0, 2258), AttributeId = AttributeIds.Value }, new ReadValueId { NodeId = new NodeId(0, 2259), AttributeId = AttributeIds.Value } }); // Write a value var statusCodes = await client.WriteAsync(new[] { new WriteValue { NodeId = new NodeId(2, "MyVar"), AttributeId = AttributeIds.Value, Value = new DataValue(new Variant(42)) } }); ``` -------------------------------- ### Configure OPC UA Client with X.509 Certificate Identity Source: https://patdhlk.com/OpcSharp/docs/security Configures an OpcSharp OPC UA client to use an X.509 certificate for authentication. The activation request is signed with the client certificate's private key. ```csharp var cert = new X509Certificate2("user-cert.pfx", "password"); var client = new OpcSharpClientBuilder() .WithEndpoint("opc.tcp://localhost:4840") .WithUserIdentity(new X509Identity(cert)) .Build(); ``` -------------------------------- ### Subscription and MonitoredItem Service Source: https://patdhlk.com/OpcSharp/docs/services Manages real-time data subscriptions and monitors specific items for changes. ```APIDOC ## [POST] /SubscriptionService ### Description Creates and manages subscriptions for real-time data monitoring. ### Method POST ### Endpoint client.CreateSubscriptionAsync / client.CreateMonitoredItemsAsync ### Parameters #### Request Body - **publishingInterval** (int) - Required - Interval in milliseconds. - **MonitoredItemCreateRequest[]** (array) - Required - Items to monitor within the subscription. ### Response #### Success Response (200) - **Subscription** (object) - The created subscription instance. - **MonitoredItem[]** (array) - The created monitored items. ``` -------------------------------- ### Discover Server Endpoints with OpcSharp Source: https://patdhlk.com/OpcSharp/docs/services Retrieves available endpoints from an OPC UA server to determine security policies and connection settings. ```csharp var endpoints = await client.GetEndpointsAsync(); foreach (var ep in endpoints) { Console.WriteLine($"{ep.EndpointUrl} — {ep.SecurityPolicyUri} [{ep.SecurityMode}]"); } ``` -------------------------------- ### Discovery Service Source: https://patdhlk.com/OpcSharp/docs/services Retrieves available endpoints from an OPC UA server. ```APIDOC ## [GET] /DiscoveryService ### Description Retrieves a list of available endpoints and security policies from the server. ### Method GET ### Endpoint client.GetEndpointsAsync ### Response #### Success Response (200) - **EndpointDescription[]** (array) - List of available server endpoints. ``` -------------------------------- ### Configure OPC UA Client Security with Explicit Policy and Mode Source: https://patdhlk.com/OpcSharp/docs/security Configures an OpcSharp OPC UA client with a specific security policy URI and message security mode. It also sets the application certificate for secure communication. This method is suitable when the exact security configuration is known. ```csharp var client = new OpcSharpClientBuilder() .WithEndpoint("opc.tcp://localhost:4840") .WithSecurity(SecurityPolicyUris.Basic256Sha256, MessageSecurityMode.SignAndEncrypt) .WithApplicationCertificate("certs/client.pfx", "password") .Build(); ``` -------------------------------- ### Configure OPC UA Client to Auto-Accept Untrusted Certificates Source: https://patdhlk.com/OpcSharp/docs/security Configures an OpcSharp OPC UA client to automatically accept untrusted certificates. This is intended for development environments only due to security risks. It bypasses manual certificate validation. ```csharp var client = new OpcSharpClientBuilder() .WithEndpoint("opc.tcp://localhost:4840") .WithSecurity(SecurityPolicyUris.Basic256Sha256, MessageSecurityMode.SignAndEncrypt) .WithAutoAcceptUntrustedCertificates(true) // WARNING: insecure, use only in development .Build(); ``` -------------------------------- ### Configure OPC UA Client with UserName/Password Identity Source: https://patdhlk.com/OpcSharp/docs/security Configures an OpcSharp OPC UA client to use a username and password for authentication. The password is RSA-encrypted using the server's public key, with padding dependent on the security policy. ```csharp var client = new OpcSharpClientBuilder() .WithEndpoint("opc.tcp://localhost:4840") .WithUserIdentity(new UserNameIdentity("user", "password")) .Build(); ``` -------------------------------- ### Configure OPC UA Client with Issued Token Identity (SAML/JWT) Source: https://patdhlk.com/OpcSharp/docs/security Configures an OpcSharp OPC UA client to use an issued token (SAML or JWT) for authentication. The token data is RSA-encrypted for secure transport. ```csharp // tokenBytes contains the SAML assertion or JWT token as a byte array byte[] tokenBytes = GetTokenFromIdentityProvider(); var client = new OpcSharpClientBuilder() .WithEndpoint("opc.tcp://localhost:4840") .WithUserIdentity(new IssuedTokenIdentity(tokenBytes)) .Build(); ``` -------------------------------- ### Attribute Service Source: https://patdhlk.com/OpcSharp/docs/services Methods for reading and writing node attributes within an OPC UA server. ```APIDOC ## [POST] /AttributeService ### Description Provides functionality to read and write values for specific node attributes. ### Method POST ### Endpoint client.ReadAsync / client.WriteAsync ### Parameters #### Request Body - **ReadValueId[]** (array) - Required - Collection of NodeIds and AttributeIds to read. - **WriteValue[]** (array) - Required - Collection of values to write to specific nodes. ### Request Example { "NodeId": "ns=2;s=MyVar", "AttributeId": 13, "Value": 42 } ### Response #### Success Response (200) - **DataValue[]** (array) - The values read from the server. - **StatusCode[]** (array) - The result status of write operations. ``` -------------------------------- ### Configure OPC UA Client with Anonymous User Identity Source: https://patdhlk.com/OpcSharp/docs/security Configures an OpcSharp OPC UA client to use anonymous user identity. This is the default behavior and does not require any specific credentials to be provided. ```csharp // Default — no credentials required var client = new OpcSharpClientBuilder() .WithEndpoint("opc.tcp://localhost:4840") .Build(); ```