using PLCHelper.Entity; using System.Collections.Generic; namespace PLCHelper { public class NXI_5010Helper { private static Dictionary cache = new Dictionary(); internal static RestTcpClient GetClient(string ip, int port) { var key = $"{ip}:{port};"; if (!cache.ContainsKey(key)) { var client = new RestTcpClient(ip, port); client.ReceiveTimeout = 500; client.ConnectServer(); if (client.Request("*RST", out string res, out string errMsg) && res == "RST") { if (client.Request("*TSS", out res, out errMsg)) { } } cache[key] = client; } return cache[key]; } internal static bool ParseConfig(string address, out string ip, out int port, out string slot, out string com, out string chn) { try { var arr = address.Split(','); ip = arr[0]; port = int.Parse(arr[1]); slot = arr[2]; com = arr[3]; chn = arr[4]; return true; } catch { ip = null; port = -1; slot = null; com = null; chn = null; return false; } } internal static bool ReadData(PLCTagData data, string name, out object val) { val = null; string address = data.Address; if (!ParseConfig(address, out string ip, out int port, out string slot, out string com, out string chn)) { return false; } var api = GetClient(ip, port); if (data.Type == PLCTagType.BOOL) { var send = $"MULT::SLOT {slot}:GET G{com}C{chn}"; var res = api.ReadBool(send); val = res.Content; return res.IsSuccess; } return false; } internal static bool WriteData(PLCTagData data, string name, object val) { val = null; string address = data.Address; if (!ParseConfig(address, out string ip, out int port, out string slot, out string com, out string chn)) { return false; } var api = GetClient(ip, port); if (data.Type == PLCTagType.BOOL) { string send = string.Empty; if ((bool)val == true) { send = $"MULT::SLOT {slot}:SET G{com}C{chn}"; var res = api.Write(send, true); return res.IsSuccess; } else { send = $"MULT::SLOT {slot}:RESE"; var res = api.Write(send, true); return res.IsSuccess; } } return false; } internal static void Release() { foreach (var client in cache.Values) { client.Dispose(); } cache.Clear(); } } }