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 LoadDetection
{
#region 上料检测相关私有成员
private ConfigStruct opcConfig;
private TcpListener robotServer;
private ImageProcess ipImage;
private Thread loadProcesser;
#endregion
///
/// 上料检类构造函数
///
/// OPC配置对象引用
/// 图象处理对象引用
public LoadDetection(ConfigStruct _opcConfig, ImageProcess _ipImage)
{
opcConfig = _opcConfig;
ipImage = _ipImage;
robotServer = new TcpListener(IPAddress.Any, opcConfig.loadRobotConfig.port);
}
///
/// 启动检测线程
///
public void Start()
{
loadProcesser = new Thread(Execute);
loadProcesser.Start();
}
public void Stop()
{
if (loadProcesser != null && loadProcesser.IsAlive)
{
loadProcesser.Abort();
loadProcesser.Join();
}
loadProcesser = null;
}
///
/// 启动对机械手臂监听
///
/// 是否正常启动
public bool OpenListener()
{
try
{
robotServer.Start();
CommonUtil.WriteLog(LogType.Inf, string.Format("机械手臂监听服务已启动,绑定端口:{0}", opcConfig.loadRobotConfig.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("机械手臂监听服务已关闭"));
}
///
/// 执行和机械手臂会话,处理上料检测结果。
/// 连结是否需要多次建立还 是只建立一次?
///
public void Execute()
{
TcpClient robortClient = null;
NetworkStream netStream = null;
byte[] recvBuf = new byte[1024];
byte[] sendBuf;
while (true)
{
try
{
robortClient = robotServer.AcceptTcpClient();
CommonUtil.WriteLog(LogType.Inf, string.Format("机械手臂已连接:{0}", robortClient.Client.RemoteEndPoint));
netStream = robortClient.GetStream();
while (robortClient.Connected)
{
if (netStream.DataAvailable)
{
int n = netStream.Read(recvBuf, 0, 1024);
string receivedMsg = System.Text.Encoding.ASCII.GetString(recvBuf, 0, n);
CommonUtil.WriteLog(LogType.Inf, string.Format("接收到机械手臂上传数据:{0}", receivedMsg));
if (receivedMsg.Contains("slgrab"))
{
HObject ihImage = null;
HObject ihInterestImage = null;
VisionDetect vd = new VisionDetect();
ipImage.GrapLoad(ref ihImage);
ipImage.GetImageIntrest(ihImage, out ihInterestImage);
//
string resp = ipImage.JudgeLoad(ihInterestImage) ? "ok" : "ng";
CommonUtil.WriteLog(LogType.Inf, string.Format("上料判断结果:{0}", resp));
sendBuf = System.Text.Encoding.ASCII.GetBytes(resp);
netStream.Write(sendBuf, 0, sendBuf.Length);
}
}
Thread.Sleep(20);
}
}
catch (Exception e)
{
if (e is ThreadAbortException) //手动终止则退出,否则继续等待连接
{
CommonUtil.WriteLog(LogType.Inf, "用户手动终止程序, 连接关闭");
break;
}
else
CommonUtil.WriteLog(LogType.Exc, string.Format("处理上料检测过程中出现异常:{0}", e.Message));
}
finally
{
if (robortClient != null)
robortClient.Close();
if (netStream != null)
netStream.Close();
}
Thread.Sleep(10);
}
CommonUtil.WriteLog(LogType.Exc, string.Format("上料检测过程退出"));
}
}
}