using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using S7.Net; using logtxtWrite; using System.Threading; namespace iWareSda_QQJF.OPCService { public class SS7 : PlcS7 { public string heartAdd = "";//心跳DB地址 int oldHeart = 10;//记录前一秒心跳值(也不知道为啥默认是10) int lostHeartTimes = 10;//掉线次数(一开始让它掉线直接重连) static CpuType plcType = (CpuType)Enum.Parse(typeof(CpuType), "S71200"); public SS7(string ip, short rack, short slot,string HeartDb, string name = "", object tag = null) : base(plcType, ip, rack, slot) { this.OpenReadHeart(HeartDb); } ///// 初始化S7连接 ///// ///// ///// //public static SS7 s7Init(string IP,string add) //{ // try // { // SS7 newPLC = new SS7(IP, Convert.ToInt16("0"), Convert.ToInt16("1"), add); // //var code = newPLC.Open(); // return newPLC; // } // catch (Exception ) // { // logtxt.txtWrite("类名:FormMain/函数名:deviceOpcInit/ OPC初始化失败:"+IP+"初始化异常", 2); // } // return null; //} /// /// S7写入(暂时写这里) /// /// /// /// /// public bool WriteValuePoint(string add, object value) { if (this.IsConnected) { object o = new object(); //bool var t = value.GetType(); if (value.GetType() == typeof(bool)) { //byte MyData = Convert.ToByte(value); int myData = Convert.ToInt32(value); o = this.Write(add, myData); } //浮点 if (value.GetType() == typeof(double) || value.GetType() == typeof(float)) { double MyData = Convert.ToDouble(value); o = this.Write(add, MyData.ConvertToUInt()); } //整数 else if (value.GetType() == typeof(Int32) || value.GetType() == typeof(short)) { short MyData = Convert.ToInt16(value); o = this.Write(add, MyData.ConvertToUshort()); } //双整数 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 o.ToString(); } else { return false; } } /// /// S7读取 /// /// /// /// /// public object ReadValuePoint(string add) { object MyPlcData = this.Read(add); return MyPlcData; } /// /// 自检在线 /// public void IsOnline() { while (true) { Thread.Sleep(1000); if (!string.IsNullOrEmpty(heartAdd)) { //int heart = Convert.ToInt32(this.ReadValuePoint(heartAdd)); //if (heart == oldHeart) //{ // //掉线次数+1 // lostHeartTimes++; //} //else //{ // lostHeartTimes = 0; //} if (!this.IsConnected) { //连续掉线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(); } } }