using System;
using System.Threading.Tasks;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Configuration;

class Program
{
    static async Task Main()
    {
        try
        {
            // 1️⃣ Application 설정
            var config = new ApplicationConfiguration
            {
                ApplicationName = "OpcUaMinimalClient",
                ApplicationType = ApplicationType.Client,
                SecurityConfiguration = new SecurityConfiguration
                {
                    AutoAcceptUntrustedCertificates = true, // 테스트용
                    RejectSHA1SignedCertificates = false
                },
                TransportQuotas = new TransportQuotas
                {
                    OperationTimeout = 15000
                },
                ClientConfiguration = new ClientConfiguration
                {
                    DefaultSessionTimeout = 60000
                }
            };

            await config.Validate(ApplicationType.Client);

            // 2️⃣ Endpoint 설정
            var endpointUrl = "opc.tcp://192.168.0.20:4840"; // Experion 서버
            var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointUrl, useSecurity: true);
            var endpoint = new ConfiguredEndpoint(null, selectedEndpoint);

            // 3️⃣ Session 생성
            var userIdentity = new UserIdentity("mngr", "mngr");
            var session = await Session.Create(
                config,
                endpoint,
                false,
                "MinimalClientSession",
                60000,
                userIdentity,
                null
            );

            Console.WriteLine("✅ OPC UA 서버 연결 성공!");

            // 4️⃣ Node 읽기 (예제 NodeId)
            var nodeId = new NodeId("ns=1;s=shinam:p-6102.hzset.fieldvalue");
            DataValue value = session.ReadValue(nodeId);
            Console.WriteLine($"Node Value: {value.Value}");

            // 5️⃣ 세션 종료
            session.Close();
            Console.WriteLine("세션 종료");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"❌ 오류: {ex.Message}");
        }
    }
}
