using SKMC.Api.Common; using SKMC.Api.Common.Tcp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SKMC.Api.Device.Adapter.Vision { /// /// 视觉客户端通用基类 /// public class SKVisionClientBase { protected static readonly ILogger log = LogFactory.Get(); public string Address { get; set; } = "127.0.0.1"; public int Port { get; set; } public int TIMEOUT { get; set; } = 5000; // 测试模式(空跑模式)下, 不等待接收响应 public bool TestMode { get; set; } = false; // 是否开启 public bool Enabled { get; set; } = true; // 是否运行中, 结束运行可放弃等待服务端响应数据 public bool Running { get; set; } private TCPClient client; public SKVisionClientBase(int port, int timeout) { //Enabled = Process_Vision_Enabled == 1; //Address = Vision_Address; TIMEOUT = timeout; Port = port; client = new TCPClient(Address, Port) { KeepAlived = true }; } /// /// 保持连接, 如果连接已中断则重新连接 /// /// 验证连接的超时时间(ms) /// public TCPClient Connect(int mills) { if (!Enabled) return null; if (!client.IsConnected(mills)) { client.Connect(); } return client; } /// /// 连接新的连接 /// /// public TCPClient Connect() { if (!Enabled) return null; if (client != null) client.Connect(); return client; } public void Reset(int index) { if (client != null) client.Clear(); Running = false; } /// /// 请求并获取结果 /// 请求后阻塞获取确认消息 /// /// 请求消息 /// 响应结果解析 /// public void Request(string requestMsg, Action responseAction = null) { try { client = Connect(100); Reset(0); } catch (Exception e) { throw new VisionException { Type = VisionException.Conn_Fail, Source = e.Message }; } try { client.Send(requestMsg); } catch (Exception e) { log.Error("send failed", e); client = Connect(); client.Send(requestMsg); } string response = null; try { response = client.Recevie(); } catch (Exception e) { log.Error(e.Message); throw new VisionException { Type = VisionException.Receive_Timeout, Source = e.Message }; } try { responseAction?.Invoke(response); } catch (Exception e) { log.Error(e.Message); throw new VisionException { Type = VisionException.Parse_Error, Source = e.Message }; } } /// /// 请求不获取结果 /// 请求后不阻塞获取确认消息 /// /// 请求消息 /// public void Request(string requestMsg, bool isOnlySend = true) { try { client = Connect(100); Reset(0); } catch (Exception e) { log.Error(e.Message); throw new VisionException { Type = VisionException.Conn_Fail, Source = e.Message }; } try { client.Send(requestMsg); } catch (Exception e) { log.Error("send failed", e); client = Connect(); client.Send(requestMsg); } } public string GetResult() { try { return client.Recevie(); } catch (Exception e) { log.Error(e.Message); throw new VisionException { Type = VisionException.Receive_Timeout, Source = e.Message }; } } } }