using ConnectionUtil; using LT.Utils.Json; using Newtonsoft.Json; using SuperSocketServer.Common; using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace OPCConnection { public class OPCClient : SCADAApi { private Socket ClientSocket = null; /// /// 连接超时事件ms /// public int _ConnectTimeout = 20000; private int Size = 0x989680; private Dictionary paraMPairs = new Dictionary(); /// /// IP连接Scada服务器 /// /// MES服务器IP /// MES服务器Port口 /// 本地连接IP /// 本地连接端口 /// public bool Connect(string IP, int Port, string LocalIP, int LocalPort) { try { this.ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress address = IPAddress.Parse(IP); IPEndPoint point = new IPEndPoint(IPAddress.Parse(LocalIP), LocalPort); IPEndPoint remoteEP = new IPEndPoint(address, Port); this.ClientSocket.Connect(remoteEP); return true; } catch (Exception) { return false; } } /// /// 连接Scada管理服务器 /// /// Scada服务器IP /// ScadPort口 /// 本地连接端口 /// /// /// public bool Connect2(string IP, int Port, int LocalPort, out string errMsg, Socket socket = null) { try { errMsg = string.Empty; if (!this.TcpPing(IP, Port, out errMsg)) { throw new Exception(errMsg); } if (socket != null) { this.ClientSocket = socket; } else { this.ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } IPAddress address = IPAddress.Parse(IP); this.ClientSocket.Connect(address, Port); if (!this.DoLogin("admin", "LT123456", out string str)) { throw new Exception(str); } return true; } catch (Exception exception) { errMsg = "连接SCADA服务失败:" + exception.Message; return false; } } /// /// 连接Scada管理服务器 /// /// ScadaManagerIP /// ScadaManagerPort口 /// 本地连接端口 /// /// public bool ConnectManager(string IP, int Port, int LocalPort, out string errMsg) { try { errMsg = string.Empty; if (!this.TcpPing(IP, Port, out errMsg)) { throw new Exception(errMsg); } this.ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress address = IPAddress.Parse(IP); this.ClientSocket.Connect(address, Port); return true; } catch (Exception exception) { errMsg = "连接SCADA服务失败:" + exception.Message; return false; } } /// /// 断开服务器连接 /// public void DisConnect() { try { if (this.ClientSocket != null) { //this.ClientSocket.Shutdown(SocketShutdown.Both); this.ClientSocket.Close(); } } catch (Exception exception) { throw new Exception("断开SCADA服务器失败:" + exception.Message); } } /// /// 释放资源 /// public void Dispose() { if (this.ClientSocket != null) { this.ClientSocket.Dispose(); } } /// /// 批量写增加参数 /// /// /// /// public bool DoAddParWriteMultiple(int id, string par) { if (this.paraMPairs.ContainsKey(id)) { return false; } this.paraMPairs.Add(id, par); return true; } /// /// 换型 /// /// /// /// /// /// public bool DoDoChangeModel(string _ProductLineName, string _ProductName, out string errMsg, string _WorkStationName = null) { try { var type = new { command = 7, ProductLineName = _ProductLineName, ProductName = _ProductName, WorkStationName = _WorkStationName }; string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false)); return this.ResquestResult(resquestStr, out _, out errMsg); } catch (Exception exception) { errMsg = exception.Message; return false; } } /// /// 批量读值 /// /// /// public string[,] DoFctReadMultiple(int[] _Id) { string[,] strArray2; try { var type = new { command = 2, comefrom = 1, paraM = _Id }; string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false)); if (this.ResquestResult(resquestStr, out Result result, out _)) { Dictionary dictionary = JsonUtil.ToObject>(result.result.ToString()); string[,] strArray = new string[dictionary.Count, 2]; int num = 0; foreach (KeyValuePair pair in dictionary) { strArray[num, 0] = pair.Key; strArray[num, 1] = pair.Value; num++; } return strArray; } strArray2 = null; } catch (Exception exception) { throw new Exception(exception.Message); } return strArray2; } /// /// 单一读值 /// /// /// /// /// public bool DoFctReadSingle(string _name, out string result, out string errMsg) { result = string.Empty; try { var type = new { command = 0x31, id = _name, comefrom = 1 }; string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false)); if (this.ResquestResult(resquestStr, out Result result2, out errMsg)) { result = result2.result?.ToString(); return true; } return false; } catch (Exception exception) { errMsg = exception.Message; return false; } finally { GC.Collect(); } } /// /// 单一写值 /// /// /// public bool DoFctWriteMultiple(out string errMsg) { bool flag2; errMsg = string.Empty; try { if (this.ToFctWriteMultiple(this.paraMPairs, out errMsg)) { return true; } flag2 = false; } catch (Exception exception) { errMsg = exception.Message; flag2 = false; } finally { this.InitParWriteMultiple(); } return flag2; } /// /// 写单一值 /// /// /// /// /// public bool DoFctWriteSingle(string _name, string _value, out string errMsg) { try { var type = new { command = 5, id = _name, value = _value }; string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false)); return this.ResquestResult(resquestStr, out _, out errMsg); } catch (Exception exception) { errMsg = exception.Message; return false; } } /// /// mqtt发布消息 /// /// 主题 /// 值 /// 错误信息> /// public bool DoMqttPublish(string topic, string _value, out string errMsg) { try { var type = new { command = 12, Tag = topic, value = _value }; string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false)); return this.ResquestResult(resquestStr, out _, out errMsg); } catch (Exception exception) { errMsg = exception.Message; return false; } } /// /// /// /// /// /// /// public bool DoLogin(string _user, string _password, out string errMsg) { try { var type = new { command = 11, user = _user, password = _password }; string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false)); return this.ResquestResult(resquestStr, out _, out errMsg); } catch (Exception exception) { errMsg = exception.Message; return false; } } /// /// 重启DataServer服务器 /// /// /// public bool DoReSETDataServer(out string errMsg) { try { var type = new { command = 10 }; string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false)); return this.ResquestResult(resquestStr, out _, out errMsg); } catch (Exception exception) { errMsg = exception.Message; return false; } } /// /// 获取动态IP /// /// public string getLocalIP() { string str2 = null; IPHostEntry hostByName = Dns.GetHostByName(Dns.GetHostName()); int length = hostByName.AddressList.Length; for (int i = 0; i < length; i++) { IPAddress address = hostByName.AddressList[i]; str2 = Convert.ToString(address); if (str2.Substring(0, 5) == "10.10") { return str2; } } return str2; } /// /// /// /// /// /// public short[,] GetLowerComputerStatus(short[] _paraMPairs, out string errMsg) { try { var type = new { command = 9, paraM = _paraMPairs }; string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false)); if (this.ResquestResult(resquestStr, out Result result, out errMsg)) { Dictionary dictionary = JsonUtil.ToObject>(result.result.ToString()); short[,] numArray = new short[dictionary.Count, 2]; int num = 0; foreach (KeyValuePair pair in dictionary) { numArray[num, 0] = pair.Key; numArray[num, 1] = pair.Value; num++; } return numArray; } return null; } catch (Exception exception) { errMsg = exception.Message; return null; } } /// /// 初始化批量写参数 /// public void InitParWriteMultiple() { this.paraMPairs.Clear(); } /// /// 检查与LTSCADA是否断开连接了 /// /// /// public bool IsConnected(out string errMsg) { try { var type = new { command = 6 }; string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false)); return this.ResquestResult(resquestStr, out _, out errMsg); } catch (Exception exception) { errMsg = exception.Message; return false; } } /// /// /// /// /// /// private static string ParsToString(T Pars) => null; /// /// 返回请求信息 /// /// /// /// /// private bool ResquestResult(string ResquestStr, out Result JResult, out string errMsg) { errMsg = string.Empty; JResult = null; try { JResult = JsonConvert.DeserializeObject(ResquestStr); if (!JResult.success) { errMsg = "请求失败:" + JResult.message; return false; } return true; } catch (Exception exception) { errMsg = JResult?.message + " --- " + exception.Message; return false; } } /// /// 接收数据超时时间 /// public uint TimeRecOut { set; get; } = 20000; /// /// 线程锁 /// private readonly object objLock = new object(); /// /// 发送请求信息 /// /// /// private string SendSocketMessage(string Cmd) { string str2; try { string str = ""; byte[] bytes = Encoding.UTF8.GetBytes(Cmd + "\r\n"); lock (objLock) { int available = this.ClientSocket.Available; if (available > 0) { byte[] buffer2 = new byte[available]; this.ClientSocket.Receive(buffer2, 0, available, SocketFlags.None); } this.ClientSocket.Send(bytes); bool flag = false; int tickCount = Environment.TickCount; int size = this.ClientSocket.Available; bool flag2 = false; while (((size < this.Size) && !flag) && !(flag2 = str.Contains("\r\n"))) { Thread.Sleep(2); size = this.ClientSocket.Available; if ((size > this.Size) || (str.Length > this.Size)) { throw new Exception($"接收数据超过设定值{this.Size}BYTE!"); } flag = (Environment.TickCount - tickCount) > TimeRecOut; if (flag) { if (size > 0) { byte[] buffer3 = new byte[size]; this.ClientSocket.Receive(buffer3, 0, size, SocketFlags.None); } throw new Exception("接收数据超时!"); } if (!flag && (size > 0)) { byte[] buffer4 = new byte[size]; this.ClientSocket.Receive(buffer4, 0, size, SocketFlags.None); str = str + Encoding.UTF8.GetString(buffer4); } } } str2 = str; } catch (Exception exception) { throw new Exception(exception.Message); } return str2; } /// /// TcpPing /// /// /// /// /// private bool TcpPing(string Host, int Port, out string errMsg) { bool flag = false; errMsg = string.Empty; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { bool flag2 = socket.BeginConnect(Host, Port, null, null).AsyncWaitHandle.WaitOne(this._ConnectTimeout, true); if (!flag2) { errMsg = "errTCPConnectionFailed"; } flag = flag2; } catch { errMsg = "errTCPConnectionFailed"; flag = false; } socket.Close(); return flag; } /// /// 批量写 /// /// 参数列表 /// 错误信息 /// 处理结果 public bool ToFctWriteMultiple(Dictionary _paraMPairs, out string errMsg) { try { var type = new { command = 15, paraM = _paraMPairs }; string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false)); return this.ResquestResult(resquestStr, out _, out errMsg); } catch (Exception exception) { errMsg = exception.Message; return false; } } public bool Connect(object config, out string errMsg) { errMsg = null; return false; } } }