当前位置: 首页 > news >正文

用 OPC UA C# WinForm 的单节点订阅方法

调用 OPC UA C# WinForm 的单节点订阅方法

SingleNodeIdDatasSubscription 方法用于订阅单个 OPC UA 节点的数据变化。以下是调用这个方法的完整示例:

基本调用示例

// 1. 定义订阅的关键字(必须唯一)
string subscriptionKey = "MySingleSubscription_Temperature";// 2. 准备要订阅的节点ID
string nodeId = "ns=2;s=Device1/Temperature";// 3. 定义回调方法
Action<string, MonitoredItem, MonitoredItemNotificationEventArgs> callback = (key, monitoredItem, args) =>
{// 处理订阅到的数据var notification = args.NotificationValue as MonitoredItemNotification;if (notification != null){// 获取节点值var value = notification.Value.Value;// 在UI线程上更新界面(如果是WinForm应用)this.Invoke((MethodInvoker)delegate {// 显示接收到的数据textBoxLog.AppendText($"[单节点订阅] Key: {key}, NodeId: {monitoredItem.StartNodeId}, " +$"Value: {value}, Timestamp: {notification.Value.SourceTimestamp}\r\n");// 也可以更新特定的控件,如温度显示lblTemperature.Text = $"{value} °C";});}
};// 4. 调用单节点订阅方法
SingleNodeIdDatasSubscription(subscriptionKey, nodeId, callback);

实际应用中的增强用法

1. 封装订阅方法

public void SubscribeTemperature()
{string key = "TemperatureSubscription_001";string nodeId = "ns=2;s=Device1/Temperature";SingleNodeIdDatasSubscription(key, nodeId, (k, item, args) => {var notification = args.NotificationValue as MonitoredItemNotification;if (notification != null){this.Invoke((MethodInvoker)delegate {lblTemperature.Text = $"{notification.Value.Value} °C";chartTemperature.AddDataPoint(DateTime.Now, Convert.ToDouble(notification.Value.Value));});}});
}

2. 带错误处理的订阅

public bool TrySubscribeSingleNode(string key, string nodeId, out string errorMessage)
{errorMessage = string.Empty;if (!ConnectStatus){errorMessage = "OPC UA客户端未连接";return false;}try{SingleNodeIdDatasSubscription(key, nodeId, (k, item, args) => {// 回调处理逻辑});return true;}catch (Exception ex){errorMessage = $"订阅节点 {nodeId} 失败: {ex.Message}";return false;}
}// 调用示例
if (!TrySubscribeSingleNode("PressureSub_001", "ns=2;s=Device1/Pressure", out var error))
{MessageBox.Show(error);
}

3. 取消订阅

public void UnsubscribeSingleNode(string key)
{if (ConnectStatus){try{opcUaClient.RemoveSubscription(key);}catch (Exception ex){string str = $"取消订阅 {key} 失败";ClientUtils.HandleException(str, ex);}}
}// 调用示例
UnsubscribeSingleNode("MySingleSubscription_Temperature");

回调方法的更多处理示例

// 更复杂的回调处理
Action<string, MonitoredItem, MonitoredItemNotificationEventArgs> advancedCallback = (key, monitoredItem, args) =>
{var notification = args.NotificationValue as MonitoredItemNotification;if (notification == null) return;var value = notification.Value.Value;var statusCode = notification.Value.StatusCode;var timestamp = notification.Value.SourceTimestamp;this.Invoke((MethodInvoker)delegate {// 记录原始数据textBoxRawData.AppendText($"{DateTime.Now}: {key} - {value}\r\n");// 根据节点ID进行不同处理if (monitoredItem.StartNodeId.ToString().Contains("Temperature")){double temp = Convert.ToDouble(value);UpdateTemperatureGauge(temp);CheckTemperatureAlarm(temp);}else if (monitoredItem.StartNodeId.ToString().Contains("Pressure")){UpdatePressureChart(Convert.ToDouble(value), timestamp);}});
};

调用单节点订阅方法时,关键是要确保:

  1. 订阅键(key)的唯一性
  2. 节点ID(nodeId)的正确性
  3. 回调方法正确处理数据并在需要时跨线程更新UI
  4. 适当的错误处理和资源清理
http://www.dtcms.com/a/329883.html

相关文章:

  • 【个人项目】跑者天地—测试用例
  • AI搜索的极限优化、新兴技术、硬件加速、特定行业解决方案
  • [QtADS]解析demo.pro
  • 利用 Makefile 高效启动 VIVADO 软件:深入解析与实践
  • 十,算法-动态规划
  • 深入理解 Cookie 与 Session —— Web 状态保持详解与实战
  • 目标检测公开数据集全解析:从经典到前沿
  • Linux软件编程3.(文件IO和目录IO)
  • windows设置相对路径的快捷方式
  • 想要PDF翻译保留格式?用对工具是关键
  • h5bench(4)
  • MySQL——binlog刷盘机制
  • django name ‘QueryDict‘ is not defined
  • POST 请求内容类型
  • 移动应用渗透测试:API 接口漏洞的识别与利用技巧
  • Oracle归档日志的查询和定时删除
  • elasticsearch基础概念与集群部署
  • 【16】Transformers快速入门:Token Embedding
  • JavaSE高级-01
  • cuDNN详解,从什么是cuDNN到实际应用过程
  • 肖臻《区块链技术与应用》第十二讲:比特币是匿名的吗?—— 深入解析匿名性、隐私风险与增强技术
  • 区块链DApp:颠覆未来的去中心化应用
  • 【Redis笔记】Redis 的通用命令
  • 字符串匹配算法
  • 认知系统的架构: 认知残余三角形、认知主体意识 和认知演进金字塔
  • UniApp开发常见问题及解决办法
  • 摆脱例行 SQL 报表的隐性成本:用 n8n 构建四节点自动化报告流程
  • 锂电池自动化生产线:智能制造重塑能源产业格局
  • ECCV-2018《Variational Wasserstein Clustering》
  • 【HTML】在页面中画一条0.5px的线