I read the value from the opcu server using the C# program and show the value in the listview

33 views Asked by At

Question

I read the value from the OPCU server using my C# program and show the value in the listview,

But it is not working well. I am sharing the contents developed by Visual Studio below, so please let me know if there is anything wrong. Thank you.

  1. Program.cs
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinFormsApp5;

namespace WinFormsAppXWeb
{
    static class Program
    {
        [STAThread]
        static async Task Main() 
        { 
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Form1 form1 = new Form1();await Task.Run(() => application.Run(form1));
        }
    }
}

2.Form1.cs

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using Opc.Ua;using Opc.Ua.Client;

namespace WinFormsApp5
{
    public partial class Form1 : Form
    {
        private Subscription _subscription = null;
        private Session _session = null; // listView1 필드를 추가하지 않습니다.

        public Form1()
        {
            InitializeComponent(); // InitializeComponent 메서드 호출 추가
            ConnectToOpcServer();
        }
    
        private async Task ConnectToOpcServer()
        {
            try
            {
                DebugLog("Connecting to OPC UA server...");
    
                string endpointUrl = "opc.tcp://Peter:49320";
    
                Opc.Ua.ApplicationConfiguration config = new Opc.Ua.ApplicationConfiguration()
                {
                    ApplicationName = "OPCClientTest",
                    ApplicationUri = Utils.Format(@"urn:{0}:OPCClientTest", System.Net.Dns.GetHostName()),
                    ApplicationType = ApplicationType.Client,
                    SecurityConfiguration = new SecurityConfiguration
                    {
                        ApplicationCertificate = new CertificateIdentifier(),
                        TrustedPeerCertificates = new CertificateTrustList(),
                        RejectedCertificateStore = new CertificateStoreIdentifier(),
                        AutoAcceptUntrustedCertificates = true,
                        RejectSHA1SignedCertificates = false
                    },
                    TransportConfigurations = new TransportConfigurationCollection(),
                    TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },
                    ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 },
                    TraceConfiguration = new Opc.Ua.TraceConfiguration(),
                };
    
                var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointUrl, useSecurity: false);
                DebugLog($"Selected Endpoint: {selectedEndpoint.EndpointUrl}");
    
                var endconf = new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(config));
                _session = await Session.Create(config, endconf, true, "session", 1000, null, null);
    
                _subscription = new Subscription(_session.DefaultSubscription)
                {
                    PublishingEnabled = true,
                    PublishingInterval = 500,
                };
    
                var monitoredItem = new MonitoredItem()
                {
                    DisplayName = "Tag1",
                    StartNodeId = "ns=2;s=Channel.Device1.Tag1"
                };
    
                monitoredItem.Notification += OnNotification;
    
                _subscription.AddItems(new List<MonitoredItem> { monitoredItem });
    
                _session.AddSubscription(_subscription);
    
                _subscription.Create();
    
                DebugLog("Connected to OPC UA server successfully.");
            }
            catch (Exception ex)
            {
                DebugLog($"Error connecting to OPC UA server: {ex.Message}");
            }
        }
    
        private void DebugLog(string message)
        {
            System.Diagnostics.Debug.WriteLine("[DEBUG] " + message);
        }
    
        private void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                if (InvokeRequired)
                {
                    Invoke(new MethodInvoker(() => OnNotification(item, e)));
                    return;
                }
    
                foreach (var value in item.DequeueValues())
                {
                    if (listView1.Items.Count > 100)
                        listView1.Items.RemoveAt(listView1.Items.Count - 1);
                    listView1.Items.Insert(0, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    listView1.Items[0].SubItems.Add(StatusCode.IsGood(value.StatusCode)
                        ? "[Value] : " + value.Value.ToString() + ", ID:" + item.DisplayName
                        : "[STATUS] : " + value.StatusCode.ToString() + ", ID:" + item.DisplayName);
                }
            }
            catch (Exception ex)
            {
                DebugLog($"Error handling notification: {ex.Message}");
            }
        }
    }
}
  1. Form1.Design.cs
namespace WinFormsApp5
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>     
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            { 
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
         // listView1의 선택이 변경될 때 실행되는 코드
          if (listView1.SelectedItems.Count > 0)
         {
            ListViewItem selectedItem = listView1.SelectedItems[0];
             string selectedValue = selectedItem.SubItems[0].Text;
 // 첫 번째 서브아이템의 텍스트 값 가져오기
             Console.WriteLine("Selected Value: " + selectedValue);
         }
     }
     #region Windows Form Designer generated code
      /// <summary>
     /// Required method for Designer support - do not modify
     /// the contents of this method with the code editor.
     /// </summary>
     private void InitializeComponent()
     {
         this.listView1 = new System.Windows.Forms.ListView();
         this.SuspendLayout();
        // 
         // listView1
         //
          this.listView1.Location = new System.Drawing.Point(73, 87);
         this.listView1.Name = "listView1";
         this.listView1.Size = new System.Drawing.Size(292, 142);
         this.listView1.TabIndex = 0;
         this.listView1.UseCompatibleStateImageBehavior = false;         this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
 // listView1_SelectedIndexChanged 이벤트 핸들러 추가
         //
          // Form1
         //
          this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
         this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
         this.ClientSize = new System.Drawing.Size(800, 450);         this.Controls.Add(this.listView1);
         this.Name = "Form1";
         this.Text = "Form1";
         this.ResumeLayout(false);
      }
      #endregion
      private System.Windows.Forms.ListView listView1; 
   }
}

Form

OPCU endpoints

your text Question

I read the value from the OPCU server using the C# program and show the value in the listview,

but it is not working well. I am sharing the contents developed by Visual Studio below, so please let me know if there is anything wrong. Thank you.

enter image description here

0

There are 0 answers