Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# opc

作者:寒江映月   发布日期:2025-11-08   浏览:130

using System;
using Opc.Da; // 引用 OPC DA 库

class Program
{
    static void Main(string[] args)
    {
        try
        {
            // 创建 OPC 服务器对象
            Opc.URL url = new Opc.URL("opcda://localhost/Matrikon.OPC.Simulation.1");
            OpcCom.Factory factory = new OpcCom.Factory();
            IOpcServer server = (IOpcServer)factory.Create(url);

            // 连接到 OPC 服务器
            server.Connect(url, null);

            // 获取 OPC 组
            IOpcGroup group = server.OPCGroups.Add("Group1", 1000, 1000, true, 0, 0, out short transactionID);

            // 添加 OPC 项
            string[] itemIDs = { "Random.Int4", "Random.Real8" };
            group.OPCItems.AddItem(itemIDs[0], 1, out short clientHandle);
            group.OPCItems.AddItem(itemIDs[1], 2, out clientHandle);

            // 读取 OPC 项的值
            object[] values = new object[itemIDs.Length];
            group.SyncRead(Opc.Da.OPCDataSource.OPCDevice, itemIDs.Length, itemIDs, out int[] qualities, out DateTime[] timestamps, out values);

            // 输出读取到的值
            for (int i = 0; i < values.Length; i++)
            {
                Console.WriteLine($"Item ID: {itemIDs[i]}, Value: {values[i]}, Quality: {qualities[i]}, Timestamp: {timestamps[i]}");
            }

            // 断开连接
            server.Disconnect();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

解释说明:

  1. 引用 OPC DA 库:代码使用了 Opc.Da 命名空间,这是用于与 OPC DA 服务器通信的库。
  2. 创建 OPC 服务器对象:通过 Opc.URL 指定 OPC 服务器的 URL,并使用 OpcCom.Factory 创建 OPC 服务器对象。
  3. 连接到 OPC 服务器:调用 Connect 方法连接到指定的 OPC 服务器。
  4. 获取 OPC 组:通过 OPCGroups.Add 方法添加一个 OPC 组,用于管理 OPC 项。
  5. 添加 OPC 项:使用 AddItem 方法向组中添加 OPC 项。
  6. 读取 OPC 项的值:通过 SyncRead 方法同步读取 OPC 项的值,并输出结果。
  7. 断开连接:完成操作后,调用 Disconnect 方法断开与 OPC 服务器的连接。

请注意,实际使用时需要确保已安装并配置好相应的 OPC DA 服务器和客户端库。

上一篇:c# 字符串转byte

下一篇:c# int 最大值

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站