1、C#通过OPC连接PLC读写功能案例最简单、最有效的PLC连接程序,里面包含了各种类型的读写功能,绝对是拷贝过去,直接把地址替换就可以使用。功能简介:本程序主要是针对 PLC 发送请求信号,收到信号执行调用,例如:由 PLC 发送请求信号 1,程序自动去调用,当调用结束,信号恢复为 0,直到下一次变为 1,再次进行调用;1、手工下载一个Interop.OPCAutomation.dll2、手工创建一个类 PublicOPC_PLC3、直接调用即可,调用方法:PublicOPC_PLC Plc = new PublicOPC_PLC();Plc.InitConnect();Plc.CH160Cr
2、eateGroup(“PLC地址“);/此处的 PLC地址必须为 PLC中 DB块对应的 BOOL型的地址例如:C1.S7.DB35.DBX544.0using System;using System.Collections.Generic;using System.Linq;using System.Text;using OPCAutomation;using System.Net;using System.Threading;namespace OPCServicepublic class PublicOPC_PLC#region 私有变量/ / OPCServer Object / pu
3、blic static OPCServer MyServer;/ / OPCGroups Object / public static OPCGroups MyGroups;/ / OPCGroup Object / public static OPCGroup MyGroupMA;public static OPCGroup MyGroupMA2;/ / OPCItems Object / OPCItems MyItemsMA;/ / OPCItem Object / OPCItem MyItemMA;/ / 主机IP / public static string strHostIP = “
4、;/ / 主机名称 / public static string strHostName = “;/ / 连接状态 / public static bool opc_connected = false;/ / 客户端句柄 / int itmHandleClient = 0;/ / 服务端句柄 / int itmHandleServer = 0;public OPCGroup GroupMAget return MyGroupMA; #endregion/ / 初始化连接对应的状态,包括连接服务器,需要读取的初始值/ public void InitConnect()/初始化OPC服务配置Get
5、LocalServer();ConnectRemoteServer();/连接OPC服务器MyGroups = MyServer.OPCGroups;/枚举本地OPC服务器 public void GetLocalServer()/获取本地计算机IP,计算机名称 strHostName = Dns.GetHostName();/或者通过局域网内计算机名称 /获取本地计算机IP,计算机名称IPHostEntry IPHost = Dns.Resolve(Environment.MachineName);if (IPHost.AddressList.Length 0)IPHostEntry ipH
6、ostEntry = Dns.GetHostByAddress(IPHost.AddressList0.ToString();strHostName = ipHostEntry.HostName.ToString();/获取本地计算机上的OPCServerName tryMyServer = new OPCServer();object serverList = MyServer.GetOPCServers(strHostName);foreach (string server in (Array)serverList)/cmbServerName.Items.Add(turn); Conso
7、le.WriteLine(“本地OPC服务器:0“, server);catch (Exception err)Console.WriteLine(“枚举本地OPC服务器出错:0“, err.Message);/连接OPC服务器 / OPCServerIP / OPCServer名称 public bool ConnectRemoteServer()trystring remoteServerIP = “, remoteServerName = “KEPware.KEPServerEx.V4“;MyServer.Connect(remoteServerName, remoteServerIP)
8、;/连接本地服务器:服务器名+主机名或IP if (MyServer.ServerState = (int)OPCServerState.OPCRunning)/MessageBox.Show(“已连接到:0“, MyServer.ServerName);/WriteLog_Station(“网络连接成功“);else/这里你可以根据返回的状态来自定义显示信息,请查看自动化接口API文档 /MessageBox.Show(“状态:0“, MyServer.ServerState.ToString();/WriteLog_Station(“网络连接失败“);MyServer.ServerShut
9、Down += ServerShutDown;/服务器断开事件 catch (Exception err)/MessageBox.Show(“连接远程服务器出现错误:0“ + err.Message);return false;return true;public void ServerShutDown(string Reason)/服务器先行断开 /WriteLog_Station(“服务器已经先行断开!“);MyServer.Disconnect();public void RemoveGroup(string Name)MyServer.OPCGroups.Remove(Name);vo
10、id GroupAsyncWriteComplete(int TransactionID, int NumItems, ref Array ClientHandles, ref Array Errors)Console.WriteLine(“%AsyncWriteComplete%“);/*for (int i = 1; i / 读取byte转ASCII值/ public string ReadData(string Add)string result = “;try/初始化item数组 /GetLocalServer();AddGroupItems(Add);Thread.Sleep(200
11、);/暂停线程以让DataChange反映,否则下面的同步读可能读不到 /以下同步读 object ItemValues; object Qualities; object TimeStamps;/同步读的临时变量:值、质量、时间戳 MyItemMA0.Read(1, out ItemValues, out Qualities, out TimeStamps);/同步读,第一个参数只能为1或2 /int q0 = Convert.ToInt32(ItemValues);/转换后获取item值 Byte bytTemp = ItemValues as Byte;/将byte数组转为字符串+res
12、ult = System.Text.ASCIIEncoding.ASCII.GetString(bytTemp);/OK/MessageBox.Show(result, “结果“);return result;catch (Exception ex)/异常处理return result;finally/ / 读取boolean值,需要先创建group/ / / public Boolean ReadData_Boolean(string Add)Boolean result = false;try/初始化item数组 /GetLocalServer();AddGroupItems(Add);T
13、hread.Sleep(200);/暂停线程以让DataChange反映,否则下面的同步读可能读不到 /以下同步读 object ItemValues; object Qualities; object TimeStamps;/同步读的临时变量:值、质量、时间戳 MyItemMA0.Read(1, out ItemValues, out Qualities, out TimeStamps);/同步读,第一个参数只能为1或2 /int q0 = Convert.ToInt32(ItemValues);/转换后获取item值 Boolean result1 = (Boolean)ItemValue
14、s;result = result1;return result;catch (Exception ex)/异常处理return result;finally/ / 读取Object值,需要先创建group/ / / public object ReadData_Object(string Add)tryCreateGroup(Add);catch (Exception ex)object result = null;tryAddGroupItems(Add);Thread.Sleep(200);/暂停线程以让DataChange反映,否则下面的同步读可能读不到 /以下同步读 object I
15、temValues; object Qualities; object TimeStamps;/同步读的临时变量:值、质量、时间戳 MyItemMA0.Read(1, out ItemValues, out Qualities, out TimeStamps);/同步读,第一个参数只能为1或2 /int q0 = Convert.ToInt32(ItemValues);/转换后获取item值 result = ItemValues;if (result != null)if (result.ToString() = “)return “;elseresult = result.ToString
16、().Replace(“0“, “);result = result.ToString().Replace(“n“, “);result = result.ToString().Replace(“r“, “);result = result.ToString().Replace(“t“, “);return result;catch (Exception ex)/异常处理result = “;return result;finally/RemoveGroup(Add);public bool CreateGroup(string Address)tryMyGroupMA = MyServer.
17、OPCGroups.Add(Address);/添加组 /以下设置组属性 MyServer.OPCGroups.DefaultGroupIsActive = true;/激活组。 MyServer.OPCGroups.DefaultGroupDeadband = 0;/ 死区值,设为0时,服务器端该组内任何数据变化都通知组。 MyServer.OPCGroups.DefaultGroupUpdateRate = 200;/默认组群的刷新频率为200ms MyGroupMA.UpdateRate = 100;/刷新频率为1秒。 MyGroupMA.IsSubscribed = true;/使用订
18、阅功能,即可以异步,默认false /MyGroupMA.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(GroupDataChange_Heart);MyGroupMA.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(GroupAsyncWriteComplete);MyGroupMA.AsyncReadComplete += new DIOPCGroupEvent_AsyncReadCompleteEventHandler(Gr
19、oupAsyncReadComplete);catch (Exception err)/this.WriteLog_Station(“过点创建组出现错误:“ + err.Message);return false;return true;#endregion#region 写入功能/ / 写入方法ascII/ / public void WriteFa(string Value)int temp;temp = new int 0, MyItemMA0.ServerHandle ;/机型string typecode = Value;byte arrValue = System.Text.Enc
20、oding.Default.GetBytes(typecode);/将string转为 byte Array serverHandles = (Array)temp;object valueTemp = new object2 “, arrValue ;/item数量为2Array values = (Array)valueTemp;Array Errors;int cancelID;MyGroupMA.AsyncWrite(1, ref serverHandles, ref values, out Errors, 1, out cancelID);/第一参数为item数量/ / 写入obje
21、ct/ / public void WritecharFa(string Value)int temp = new int 0, MyItemMA0.ServerHandle ;/写入数据Item数量2Array serverHandles = (Array)temp;object valueTemp = new object2 “, Value ;/item数量为2Array values = (Array)valueTemp;Array Errors;int cancelID;MyGroupMA.AsyncWrite(1, ref serverHandles, ref values, ou
22、t Errors, 1, out cancelID);/第一参数为item数量private void WriteByteFa(byte Value)int temp = new int 0, MyItemMA0.ServerHandle ;/写入数据Item数量2Array serverHandles = (Array)temp;object valueTemp = new object2 “, Value ;/item数量为2Array values = (Array)valueTemp;Array Errors;int cancelID;MyGroupMA.AsyncWrite(1, r
23、ef serverHandles, ref values, out Errors, 1, out cancelID);/第一参数为item数量#endregion#region CH160/ / 创建组/ / / / OPCGroups MyGroupsStationCH160;/ / OPCGroup Object / OPCGroup MyGroupStationCH160;/ / OPCItems Object / OPCItems MyItemsStationCH160;/ / OPCItem Object / OPCItem MyItemStationCH160;public OPC
24、Group GroupStationCH160get return MyGroupStationCH160; public bool CH160CreateGroup(string Address)tryMyGroupStationCH160 = MyServer.OPCGroups.Add(Address);/添加组 /以下设置组属性 MyServer.OPCGroups.DefaultGroupIsActive = true;/激活组。 MyServer.OPCGroups.DefaultGroupDeadband = 0;/ 死区值,设为0时,服务器端该组内任何数据变化都通知组。 MyS
25、erver.OPCGroups.DefaultGroupUpdateRate = 200;/默认组群的刷新频率为200ms MyGroupStationCH160.UpdateRate = 100;/刷新频率为1秒。 MyGroupStationCH160.IsSubscribed = true;/使用订阅功能,即可以异步,默认false MyGroupStationCH160.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(GroupDataChange_CH160Heart);MyGroupStationCH160.Asyn
26、cWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(GroupAsyncWriteComplete);MyGroupStationCH160.AsyncReadComplete += new DIOPCGroupEvent_AsyncReadCompleteEventHandler(GroupAsyncReadComplete);AddGroupItemsCH160(Address);catch (Exception err)return false;return true;void GroupDataChange_CH160Heart(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)tryfor (int i = 1; i = 1; i+)if (ItemValues.GetValue(i) != null)object bb = ItemValues.GetValue(i);string s = bb.ToString();