patrick.xu
2021-05-24 c585dd8ddbbdc5dece1033bd6a1201493ed610a0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
using System;
using System.Collections.Generic;
using System.Drawing.Text;
using System.Linq;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms.VisualStyles;
using HalconDotNet;
 
namespace M423project
{
 
 
    //上料检测类
    public class UnLoadDetection
    {
        #region 上料检测相关私有成员
        private ConfigStruct opcConfig;
        private TcpListener robotServer;
        private Thread unloadProcesser;
        private VisionDetect vd = new VisionDetect();
        private List<ProductMeasureResult> productTestCollection;
        private DateTime unloadTime = DateTime.MaxValue;
        private OPC _opc;
        #endregion
        /// <summary>
        /// 上料检类构造函数
        /// </summary>
        /// <param name="_opcConfig">OPC配置对象引用</param>
        /// <param name="_ipImage">图象处理对象引用</param>
        public UnLoadDetection(OPC opc, ConfigStruct _opcConfig, List<ProductMeasureResult> _productTestCollection)
        {
            _opc = opc;
            opcConfig = _opcConfig;
            robotServer = new TcpListener(IPAddress.Parse(opcConfig.unloadRobotConfig.localIpAddress), opcConfig.unloadRobotConfig.port);
            productTestCollection = _productTestCollection;
        }
 
        /// <summary>
        /// 启动检测线程
        /// </summary>
        public void Start()
        {
            unloadProcesser = new Thread(Execute);
            unloadProcesser.Start();
        }
 
        public void Stop()
        {
            if (unloadProcesser != null && unloadProcesser.IsAlive)
            {
                unloadProcesser.Abort();
                unloadProcesser.Join();
            }
            unloadProcesser = null;
        }
 
        /// <summary>
        /// 启动对机械手臂监听
        /// </summary>
        /// <returns>是否正常启动</returns>
        public bool OpenListener()
        {
            try
            {
                robotServer.Start();
                CommonUtil.WriteLog(LogType.Inf, string.Format("下料机械手臂监听服务已启动,绑定地址:{0},端口:{1}", opcConfig.unloadRobotConfig.localIpAddress,
                    opcConfig.unloadRobotConfig.port));
                return true;
            }
            catch (Exception e)
            {
                CommonUtil.WriteLog(LogType.Exc, string.Format("下料机械手臂监听服务启动失败:{0}", e.Message));
                return false;
            }
        }
 
        public void CloseListener()
        {
            robotServer.Stop();
            CommonUtil.WriteLog(LogType.Inf, string.Format("下料机械手臂监听服务已关闭"));
        }
 
        /// <summary>
        /// 执行和机械手臂会话,处理上料检测结果。
        /// </summary>
        public void Execute()
        {
            TcpClient robortClient = null;
            NetworkStream netStream = null;
            byte[] recvBuf = new byte[1024];
            byte[] sendBuf;
            string sendMsg = string.Empty;
            int detectID = 0;
 
            while (true)
            {
                try
                {
                    while (!robotServer.Pending())
                        Thread.Sleep(10);
 
                    robortClient = robotServer.AcceptTcpClient();
                    string timeStr = DateTime.Now.ToString("hh:mm:ss fff");
                    CommonUtil.WriteLog(LogType.Inf, string.Format("下料机械手臂已连接:{0}, {1}", robortClient.Client.RemoteEndPoint, timeStr));
                    sendMsg = string.Empty;
                    netStream = robortClient.GetStream();
 
                    //while (robortClient.Connected && !netStream.DataAvailable)
                    //    Thread.Sleep(10);
 
                    while (robortClient.Connected)
                    {
                        if (!netStream.DataAvailable)
                        {
                            Thread.Sleep(10);
                            continue;
 
                        }
 
                        #region data trans
                        //每次一个,完成断开 
                        int n = netStream.Read(recvBuf, 0, 1024);
                        while (n > 0)
                        {
                            string receivedMsg = System.Text.Encoding.ASCII.GetString(recvBuf, 0, n);
                            CommonUtil.WriteLog(LogType.Inf, string.Format("接收到下料机械手臂发来的消息:{0}, {1}", receivedMsg, CommonUtil.StepControl.ToString()));
                            // 处理接收到的数据。
                            if (receivedMsg.Contains("xlrate"))
                            {
                                sendMsg = opcConfig.unloadRbtSpeed.ToString();
                            }
                            if (receivedMsg.Contains("result"))
                            {
                                bool isOk = false;
                                detectID = CommonUtil.StepControl.GetUnloadStepID();
                                if (detectID > 0)
                                {
                                    var x = (from t in productTestCollection
                                             where t.DetectID == detectID
                                             select t
                                            ).FirstOrDefault();
                                    if (x != default(ProductMeasureResult))
                                    {
                                        if (x.ProductResult == MeasureState.OK.ToString())
                                        {
                                            isOk = true;
                                        }
                                    }
                                }
                                sendMsg = isOk ? "ok" : "ng";
 
                                //_opc.Write(OPCOutputTag.TurnDiskReadyConfirm, false);
 
                                CommonUtil.mainForm.Invoke(new Action(() => CommonUtil.mainForm.RemoveDetectedItem(detectID)));
                                CommonUtil.WriteLog(LogType.Inf, string.Format("{0}, {1}", detectID, sendMsg));
 
                                #region add by Patrick 2018-07-13
                                if (!isOk)
                                {
                                    CommonUtil.StepControl.RemoveById(detectID);
                                }
                                #endregion
                            }
                            if (sendMsg != string.Empty)
                            {
                                sendBuf = System.Text.Encoding.ASCII.GetBytes(sendMsg);
                                netStream.Write(sendBuf, 0, sendBuf.Length);
                                CommonUtil.WriteLog(LogType.Inf, string.Format("向下料机械手臂发送的消息:{0}", sendMsg));
 
                                if (unloadTime != DateTime.MaxValue)
                                {
                                    TimeSpan ts = DateTime.Now - unloadTime;
                                    CommonUtil.mainForm.Invoke(new Action(() => CommonUtil.mainForm.DisplayCycleTime((int)Math.Round(ts.TotalMilliseconds))));
                                }
                                unloadTime = DateTime.Now;
                            }
                            n = netStream.Read(recvBuf, 0, 1024);
                        }
 
                        #endregion
                    }
 
 
                    /*
                    if (netStream != null)
                        netStream.Close();
 
                    if (robortClient != null)
                        robortClient.Close();
                        */
 
                    CommonUtil.WriteLog(LogType.Inf, string.Format("下料机械连接断开"));
 
                    Thread.Sleep(10);
                }
                catch (ThreadAbortException)
                {
                    break;
                }
                catch (Exception e)
                {
                    CommonUtil.WriteLog(LogType.Exc, string.Format("与下料通信过程出现异常:{0}", e.Message));//;
                }
                Thread.Sleep(10);
            }
        }
    }
}