using OPC_Client;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Xml.Linq;
namespace EBRDemo
{
class SCADA
{
private OPC_Client.Client client = new OPC_Client.Client();
///
/// 第一个string代表唯一设备编码,第二个string代表批次信息
///
private Dictionary BatchNums = new Dictionary();
//每10s在屏幕显示一次值
private static System.Timers.Timer timer = new System.Timers.Timer(10000);
// private string _opcServerName = "Studio.Scada.OPC.5";//现场服务器名称
private string _opcServerName = "Kepware.KEPServerEX.V6";//测试服务器名称
///
/// 添加采集点位
///
public void AddItems()
{
string path = @"采集点位.csv";//采集点位item,需要与实际一致
DataTable table = ReadCSV(path);
if (table.Columns.Count == 3)
{
foreach (DataRow row in table.Rows)
{
client.itemIDs.Add(row[0].ToString());
client.descritions.Add(row[1].ToString());
client.equipMentCodes.Add(row[2].ToString());
}
//建立连接
client._opcServerName = _opcServerName;
client.Connect();
if (client.isConnected)
{
//MessageBox.Show("未连接成功");
Console.WriteLine("连接成功");
}
else
{
Console.WriteLine("未连接成功");
}
//数据变化时
client.Data_Change += Client_DataChange;
//异步写入多个值的回调方法
client.Async_WriteMuchComplete += AsyncWriteMuchComplete;
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
}
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("每10s输出一次值");
//WriteSingleValue("数据类型示例.8 位设备.S 寄存器.String4", "demossss");
//WriteMuchValue();
foreach (OPC_Client.Data data in client.dataCenter.Values)
{
Console.WriteLine(data.itemID + ":" + data.value.ToString());
}
}
///
/// 写入值回调方法
/// TransactionID,人为设置规定的标识ID
///
///
///
///
///
private void AsyncWriteMuchComplete(int TransactionID, int NumItems, ref Array ClientHandles, ref Array Errors)
{
}
///
/// NumItems 变化的数据数目
/// ClientHandles clientID
///
///
///
private void Client_DataChange(int NumItems, ref Array ClientHandles)
{
}
#region 数据更改
///
/// 刷新所有数据,不需要高频使用
///
private void AsyncRefreshAll()
{
client.AsyncRefreshAll();
}
///
/// 更新批次号
///
private void UpdateBatchNum()
{
foreach (Data data in client.dataCenter.Values)
{
string batchNum = "";
//根据设备编码获取当前批次信息
if (BatchNums.TryGetValue(data.equipMentCode, out batchNum))
data.batchNum = batchNum;
}
}
///
/// 写单个值
///
private void WriteSingleValue(string item,object obj_value)
{
try
{
//根据item值,更新值
//如果数据类型不对,可能导致错误
client.WriteOneValue(item, obj_value);
}
catch(Exception err)
{
Console.WriteLine(err.Message);
}
}
///
/// 写多个值
///
private void WriteMuchValue()
{
try
{
List itemIds = new List();
itemIds.Add("通道 1.设备 1.标记 1");
itemIds.Add("通道 1.设备 1.标记 2");
itemIds.Add("通道 1.设备 1.标记 3");
itemIds.Add("数据类型示例.8 位设备.S 寄存器.String1");
List