using HslCommunication; using HslCommunication.Profinet.Siemens; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace iWareSda_QQJF.OPCService { public class HSLS7 : SiemensS7Net { public string heartAdd = "";//心跳DB地址 public bool IsConnected=false; int oldHeart = 10;//记录前一秒心跳值(也不知道为啥默认是10) int lostHeartTimes = 10;//掉线次数(一开始让它掉线直接重连) static SiemensPLCS siemensPLCSelected = SiemensPLCS.S1200; public HSLS7(string ip, string HeartDb) : base(siemensPLCSelected, ip) { this.OpenReadHeart(HeartDb); OperateResult operateResult = this.ConnectServer(); } /// /// S7写入(暂时写这里) /// /// /// /// /// public bool WriteValuePoint(string add, object value) { OperateResult o = new OperateResult(); //bool var t = value.GetType(); if (value.GetType() == typeof(bool)) { //byte MyData = Convert.ToByte(value); bool myData = Convert.ToBoolean(value); o = this.Write(add, myData); } //浮点 else if (value.GetType() == typeof(double) || value.GetType() == typeof(float)) { double MyData = Convert.ToDouble(value); o = this.Write(add, MyData); } //整数 else if (value.GetType() == typeof(Int32) || value.GetType() == typeof(Int16)) { short MyData = Convert.ToInt16(value); o = this.Write(add, MyData); } //双整数 else if (value.GetType() == typeof(Int32)) { int myData = Convert.ToInt32(value); o = this.Write(add, myData); } if (o == null) { return false; } //if (o.ToString() == "NoError") //{ // return true; //} //else //{ // return false; //} return true; //return o.ToString(); } /// /// S7读取 /// /// /// /// /// public object ReadValuePoint(string add,string type) { object MyPlcData = null; if (type == "int") { MyPlcData = this.ReadInt16(add).Content; } else if (type == "Dint") { MyPlcData = this.ReadInt32(add).Content; } else if (type == "bool") { MyPlcData = this.ReadBool(add).Content; } else if (type == "byte") { MyPlcData = this.ReadByte(add).Content; } return MyPlcData; } /// /// 自检在线 /// public void IsOnline() { while (true) { Thread.Sleep(1000); if (!string.IsNullOrEmpty(heartAdd)) { int heart =this.ReadInt16(heartAdd).Content; if (heart == oldHeart) { ////掉线次数+1 //lostHeartTimes++; IsConnected = false; } else { IsConnected = true; //lostHeartTimes = 0; } //if (!this.con) //{ // //连续掉线5次以上为掉线 // this.Close(); // //尝试重连 // Thread.Sleep(100); // this.Open(); //} oldHeart = heart; } } } /// /// //开启自检在线线程 /// /// public void OpenReadHeart(string add) { heartAdd = add; Thread IsOnlineThread = new Thread(this.IsOnline); IsOnlineThread.Start(); } } }