工作中经常需要了解plcdb块的数据!由于工作使用OPC类库进行通讯,开发,配置,使用都比较麻烦,

特在网上找到一个名为PLCcom.dll的类库,可以实现PLC读写操作,下面演示C#如何使用PLCcom.dll类库

首先看一下封装对PLCcom调用的帮助类:

using System;
using PLCcom;
using System.Data;
//using System.Windows.Forms; namespace GetPlcInfo
{
/// <summary>
/// Description of PLCReadWriteHelper.
/// </summary>
public class PLCReadWriteHelper
{ #region 变量定义
private static PLCReadWriteHelper instance=null;//当前类实例
private ePLCType cpu = ePLCType.S7_300_400_compatibel;//cpu类型
private string ip = "192.168.150.201";//CpuIP
private short rack = ;//机架号
private short slot = ;//插槽号
public TCP_ISO_Device plc = null;//Plc对象
private const string user = "";//用户
private const string serial = "51135-21193-754111-1111111";//系列号
public delegate void OnErrorHandler(OnErrorEventArgs e);//发生错误委托
public event OnErrorHandler OnError;//发生错误事件
public delegate void SuccessHandler(SuccessedEventArgs e);//成功委托
public event SuccessHandler success;//成功事件
#endregion
#region 构造函数
public PLCReadWriteHelper(ePLCType type,string plcip,string plcRack,string plcsolt)
{
this.cpu=ePLCType.S7_300_400_compatibel;
this.ip=plcip;
this.rack=short.Parse( plcRack );
this.slot=short.Parse( plcsolt );
plc=new TCP_ISO_Device(ip,rack,slot,cpu); authentication.User=user;
authentication.Serial =serial ; }
#endregion
#region 连接
public void TestConnect()
{
try
{
if (instance!=null)
{
ConnectResult cr=plc.Connect();
//连接失败
if (!cr.HasConnected)
{
if (OnError!=null)
{
OnError (new OnErrorEventArgs(string.Format("连接到PLC:{0}时,发生错误!{1}",this.ip,cr.Message)));
}
}
//成功!
else
{
if(success!=null)
{
success(new SuccessedEventArgs("PLC"+this.ip+"连接成功!"+cr.Message));
}
}
}
}
catch(Exception ex)
{
WriteError("连接失败:"+ex.Message);
}
}
public void disconnect()
{
plc.DisConnect();
}
#endregion
#region 获取时间 public DateTime GetCpuTime()
{
if (instance == null)
{
instance = GetInstance(ePLCType.Other,"192.168.0.4", "", "");
instance.plc.Connect();
}
ReadRequest[] request = new ReadRequest[];
request[] = new ReadRequest();
request[].Region = eRegion.DataBlock;
request[].StartByte = ;
request[].Len = ;
request[].DB = ; ReadResult[] res = plc.read(request); if (!res[].HasWorked)
{
WriteError("读取CPU时间失败:" + res[].Message);
return DateTime.MinValue;
}
else
{
return res[].get_DATE_AND_TIME();
} }
#endregion
#region 获得当前类的实例
/// <summary>
/// 静态方法获得此帮助类的实例
/// </summary>
/// <param name="type">cpu类型</param>
/// <param name="plcip">ip地址</param>
/// <param name="plcRack">机架号</param>
/// <param name="plcsolt">插槽号</param>
/// <returns></returns>
public static PLCReadWriteHelper GetInstance(ePLCType type,string plcip,string plcRack,string plcsolt)//此处偷了个懒写了最简单的单例,此处线程不安全!
{
lock (typeof(PLCReadWriteHelper))
{
if (instance == null)
{
instance = new PLCReadWriteHelper(type,plcip,plcRack,plcsolt );
return instance;
}
else
{
return instance;
}
}
}
#endregion
#region 读PLC信息
public byte[] ReadPLC(int db,int Start,int Length)
{
byte[]readbytes=null; try{
if (this.plc==null)
{
plc=new TCP_ISO_Device (ip,rack,slot,cpu);
plc.Connect();
}
ReadRequest[]request=new ReadRequest[] ;
request[]=new ReadRequest ();
request[].Region=eRegion.DataBlock;
request[].DB=db;
request[].StartByte=Start;
request[].Len=Length;
ReadResult[]res=plc.read(request);
if (!res[].HasWorked)
{
this.plc=null; }
readbytes=new byte[res[].getBufferLen()];
int index=;
while (res[].dataAvailable())
{
readbytes[index++]+=res[].get_Byte(); }
plc.DisConnect(); if (success !=null)
{
success(new SuccessedEventArgs("读取CPU信息成功!"));
string result = null;
foreach(var n in readbytes)
{
result+=n.ToString()+"|";
}
if(result!=null)
{
success(new SuccessedEventArgs(result));
}
}
return readbytes;
}
catch(NullReferenceException) { return null; }
catch(Exception ex)
{ WriteError("读取指定信息错误:"+ex.Message);
return null;
}
} #endregion
#region 写信息到DB块
public WriteResult WritePLC(int db,int Start,byte[]wValue)
{
try
{
if (plc==null)
{
plc=new TCP_ISO_Device (ip,rack,slot,cpu);
plc.Connect();
} WriteRequest[]writes=new WriteRequest[];
writes[]=new WriteRequest ();
writes[].Region=eRegion.DataBlock;
writes[].DB=db;
writes[].StartByte=Start;
writes[].addByte(wValue);
WriteResult[]wrs=plc.write(writes );
if (wrs[].HasWorked != true)
{
this.plc = null;
} return wrs[]; }
catch (Exception ex)
{
WriteError("写入信息错误:"+ex.Message);
return new WriteResult ();
}
} #endregion
#region 抛出异常
void WriteError(string errmsg)
{
if (OnError!=null)
{
OnError(new OnErrorEventArgs (errmsg));
}
}
#endregion
#region byte数组转换为字
public int[]ConvertToints(byte[]bt)
{
try
{
int []result = new int[(bt.Length / )];
for (int ii = ; ii < result.Length; ii++)
{
result[ii] = Convert.ToInt16(bt[ii * ]) * + Convert.ToInt16(bt[ii * + ]); }
return result; }
catch(Exception ex)
{
WriteError("字节数组转换成int数组失败:"+ex.Message);
return null;
}
} #endregion
#region 自定义事件类
/// <summary>
/// 发生错误
/// </summary>
public class OnErrorEventArgs
{
string errMsg=string.Empty;
public OnErrorEventArgs(string errmsg)
{
this.errMsg=errmsg;
}
public string ErrMsg
{get{return this. errMsg;}
} }
/// <summary>
/// 成功
/// </summary>
public class SuccessedEventArgs
{
string errMsg=string.Empty;
public SuccessedEventArgs(string errmsg)
{
this.errMsg=errmsg;
}
public string ErrMsg
{
get{return this. errMsg;}
}
}
#endregion
#region 读取IO public DateTime GetTime()
{
ReadResult rs= plc.GetPLCTime();
DateTime dt= rs.get_DATE_AND_TIME(); return dt;
} public void readIO()
{
ReadRequest[] re = new ReadRequest[];
re[].Region = eRegion.Input;
re[].Bit = ;
re[].StartByte = ;
re[].Len = ;
ReadResult []rr= plc.read(re); if ( rr[].isBit)
{
// MessageBox.Show(rr[0].Buffer.ToString());
} } #endregion
public LEDInfoResult GetLEDINFO()
{
return plc.GetLEDInfo();
}
} }

下面看看如何进行调用:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Gaofajin.LogWrite;
namespace GetPlcInfo
{
class Program
{
static Timer t;
static TimerCallback tc;
static int time = ;
static PLCReadWriteHelper helper;
static string last;
// public static object TxtLog { get; private set; } static void Main(string[] args)
{ if(args.Length<=)
{
Console.WriteLine("必须输入IP地址:");
return;
}
if(args.Length==)
{
int.TryParse(args[],out time);
}
helper=new PLCReadWriteHelper(PLCcom.ePLCType.S7_300_400_compatibel,args[],"","");//此示例演示的PLC为300系列故此处写死槽号2,机架号0
helper.OnError+=new PLCReadWriteHelper.OnErrorHandler(error);
helper.success+=new PLCReadWriteHelper.SuccessHandler(success); tc=new TimerCallback(getContent);
t=new Timer(tc,helper,,time);
Console.WriteLine("后台程序捕获进程运行中!请勿关闭程序!");
Console.ReadLine();
} private static void success(PLCReadWriteHelper.SuccessedEventArgs e)
{
Console.WriteLine(e.ErrMsg);
} private static void error(PLCReadWriteHelper.OnErrorEventArgs e)
{
Console.WriteLine(e.ErrMsg);
} private static void getContent(object obj)
{
try
{
t.Change(-,-);
helper.TestConnect();
byte[]bts= helper.ReadPLC(,,); string str = null; foreach(byte b in bts)
{
str+=byteTostringChar(b).ToString()+"|";
}
if(last!=str)
{
TxtLog.WriteLineToTimeFile(str);
}
last=str; }
catch(Exception ex)
{
// Console.WriteLine("发生错误:"+ex.Message);
}
finally
{
t.Change(,time);
}
} public static char byteTostringChar(byte b)
{
return ((Char)b);
}
}
}

最新文章

  1. 【无私分享:ASP.NET CORE 项目实战(第六章)】读取配置文件(一) appsettings.json
  2. Windows Live Writer代码插件整理
  3. java集合类的学习(二)
  4. jquery实现返回基部案例效果
  5. 使用Html5+C#+微信 开发移动端游戏详细教程 :(二)准备工作&amp;开发环境
  6. [5]Telerik Extensions for ASP.NET MVC 开发问题
  7. Java程序员要注意的10个问题————————好东西就是要拿来分享
  8. Asp.Net验证码2
  9. asp.net中js和jquery调用ashx的不同方法分享
  10. 关于百度地图API的地图坐标转换问题
  11. Splay tree
  12. Android 树形菜单
  13. log4net基础学习
  14. 1025. PAT Ranking (25)
  15. 解决Win10系统下 C# DateTime 出现星期几的问题
  16. Vue(一) 数据绑定和第一个Vue应用
  17. 背水一战 Windows 10 (49) - 控件(集合类): Pivot, Hub
  18. 企业案例--生产环节更改mysql字符集
  19. 哈希表 -数据结构(C语言实现)
  20. 小米路由器设置DMZ主机 并在外网访问

热门文章

  1. NPF
  2. apper
  3. 把git仓库从码云迁到github,及git常用命令
  4. 巴什博奕小结 HDU2188 HDU1846 HDU2149
  5. 14、编写一个通用的Makefile
  6. OC学习篇之---文件的操作
  7. storm原理介绍
  8. centos中的配置文件 分类: B3_LINUX 2015-04-03 22:21 184人阅读 评论(0) 收藏
  9. lv resize
  10. 使用URLConnection获取网页信息的基本流程 分类: H1_ANDROID 2013-10-12 23:51 3646人阅读 评论(0) 收藏