XRayMachine.XRay.cs 15.5 KB
using Asa;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DeviceLibrary
{
    using crc = OnlineStore.CodeResourceControl;
    partial class XRayMachine
    {
        const string xraydir = @"\Image\Xray";
        Task GetResultTask = null;
        void WorkProcess()
        {
            if (CheckWait(MoveInfo))
                return;

            switch (MoveInfo.MoveStep)
            {
                case MoveStep.XRay_01_LocationDown:
                    MoveInfo.StopwatchReset();
                    MoveInfo.NextMoveStep(MoveStep.XRay_02_RunIn);
                    RobotManage.ProductivityCount++;
                    MoveInfo.log($"定位气缸下降,打开点料机入口门");
                    CylinderMove(MoveInfo, IO_XRay_Type.Location_Cylinder_Down, IO_XRay_Type.Location_Cylinder_Up, IO_VALUE.LOW);
                    CylinderMove(null, IO_XRay_Type.Entry_Close, IO_XRay_Type.Entry_Open, IO_VALUE.HIGH);
                    break;
                case MoveStep.XRay_02_RunIn:
                    MoveInfo.NextMoveStep(MoveStep.XRay_03_CloseDoor);
                    MoveInfo.log($"入料伺服相对运转");
                    //Line_Entry_Axis.RelMove(ResetMoveInfo, Config.Line_Entry_Relative, Config.Line_Entry_Relative_speed);
                    Line_Entry_Axis.SpeedMove(Config.Line_Entry_Relative_speed);
                    Line_In_Axis.RelMove(MoveInfo, Config.Line_In_Relative, Config.Line_In_Relative_speed);
                    MoveInfo.WaitList.Add(WaitResultInfo.WaitTime(1000));
                    //MoveInfo.WaitList.Add(WaitResultInfo.WaitIO(IO_XRay_Type.Tray_Inside_Check, IO_VALUE.HIGH));
                    break;
                case MoveStep.XRay_03_CloseDoor:
                    MoveInfo.NextMoveStep(MoveStep.XRay_04_OpenXray);
                    MoveInfo.log($"关闭点料机入口门");
                    Line_Entry_Axis.SuddenStop();
                    CylinderMove(MoveInfo, IO_XRay_Type.Entry_Close, IO_XRay_Type.Entry_Open, IO_VALUE.LOW);
                    CylinderMove(MoveInfo, IO_XRay_Type.Location_Cylinder_Down, IO_XRay_Type.Location_Cylinder_Up, IO_VALUE.HIGH);
                    IOMove(IO_XRay_Type.Xray_Lock, IO_VALUE.HIGH);
                    MoveInfo.WaitList.Add(WaitResultInfo.WaitTime(100));
                    break;
                case MoveStep.XRay_04_OpenXray:
                    MoveInfo.NextMoveStep(MoveStep.XRay_05_GetImage);
                    RobotManage.XRay.Start();
                    MoveInfo.log($"打开X光");
                    MoveInfo.WaitList.Add(WaitResultInfo.WaitTime(1000));
                    break;
                case MoveStep.XRay_05_GetImage:
                    if (GrabImage())
                    {
                        MoveInfo.NextMoveStep(MoveStep.XRay_08_OpenOutDoor);
                        MoveInfo.log($"获取图像,开始点料 IsRayOpen:{RobotManage.XRay.IsRayOpen}");
                        GetResultTask = Task.Run(()=> { GetCountResult(); });
                    }
                    else {
                        MoveInfo.NextMoveStep(MoveStep.XRay_08_OpenOutDoor);
                        //Msg.add("图像平板获取图像失败",MsgLevel.warning);
                        MoveInfo.ReelParam.IsNg = true;
                        MoveInfo.ReelParam.NgMsg = "获取图像失败";
                        MoveInfo.ReelParam.logresult();
                    }
                    MoveInfo.log($"关闭X光");
                    RobotManage.XRay.Stop();
                    IOMove(IO_XRay_Type.Xray_Lock, IO_VALUE.LOW);
                    MoveInfo.StopwatchLog(false, "准备送出");                    
                    //MoveInfo.WaitList.Add(WaitResultInfo.WaitTime(500));
                    break;
                case MoveStep.XRay_08_OpenOutDoor:
                    MoveInfo.NextMoveStep(MoveStep.XRay_09_SentToLabelStop);
                    CylinderMove(MoveInfo, IO_XRay_Type.Exit_Close, IO_XRay_Type.Exit_Open, IO_VALUE.HIGH);
                    MoveInfo.log($"打开出口门");                    
                    break;
                case MoveStep.XRay_09_SentToLabelStop:
                    if (RobotManage.labelMachine.TrayCanIN())
                    {
                        MoveInfo.NextMoveStep(MoveStep.XRay_10_CloseOutDoor);
                        MoveInfo.log($"打开出口门,送出到贴标机构");                        
                        Line_In_Axis.SpeedMove(Config.Line_In_Relative_speed*2);
                        RobotManage.Line1.LineRun("xray", 999, "XRay_09_SentToLabelStop");
                        MoveInfo.StopwatchLog(false, "开始送出");

                    }
                    else if (MoveInfo.IsTimeOut(30)) {
                        Msg.add(crc.GetString("wait_xx_free", "等待{0}空闲", RobotManage.labelMachine.DeviceNameShow), MsgLevel.warning);
                        MoveInfo.log("等待贴标机构入口空闲");
                    }
                    break;
                case MoveStep.XRay_10_CloseOutDoor:
                    if (RobotManage.labelMachine.Tray_Check.Equals(IO_VALUE.HIGH))
                    {
                        //RobotManage.labelMachine.InLineRunControl(IO_VALUE.LOW);
                        RobotManage.Line1.LineStop("xray", "XRay_10_CloseOutDoor");
                        MoveInfo.NextMoveStep(MoveStep.XRay_11_GetCoutResult);
                        MoveInfo.log($"关闭出口门,停止X光机内线体");
                        Line_In_Axis.SuddenStop();
                        CylinderMove(null, IO_XRay_Type.Exit_Close, IO_XRay_Type.Exit_Open, IO_VALUE.LOW);
                        MoveInfo.StopwatchLog(false, "到达阻挡");
                    }
                    else if (MoveInfo.IsTimeOut(10))
                    {
                        Msg.add(crc.GetString("wait_goto_xx", "等待料盘到达{0}",RobotManage.labelMachine.DeviceNameShow), MsgLevel.warning);
                        MoveInfo.log("等待料盘到达贴标线入口");
                    }
                    break;
                case MoveStep.XRay_11_GetCoutResult:
                    if (GetResultTask == null || GetResultTask.IsCompleted)
                    {
                        RobotManage.labelMachine.preReelParam = MoveInfo.ReelParam;
                        MoveInfo.NextMoveStep(MoveStep.XRay_End);
                        MoveInfo.log($"获得点料结果 QTY:{MoveInfo.ReelParam.QTY}");
                        MoveInfo.StopwatchLog(false, "获得点料结果");
                    }
                    else if (MoveInfo.IsTimeOut(30)) {
                        MoveInfo.NextMoveStep(MoveStep.XRay_End);
                        MoveInfo.log("获取点料结果超时");
                        MoveInfo.ReelParam.IsNg = true;
                        MoveInfo.ReelParam.NgMsg = "获取点料结果超时";
                        MoveInfo.ReelParam.logresult();
                        RobotManage.labelMachine.preReelParam = MoveInfo.ReelParam;
                    }
                    break;
                case MoveStep.XRay_End:
                    MoveInfo.log($"送出到贴标机构");
                    MoveInfo.StopwatchLog();
                    MoveInfo.EndMove();
                    break;
            }
        }
        public string xrayImagePath;
        [HandleProcessCorruptedStateExceptions]
        public bool GrabImage()
        {
            Bitmap bmp = null;

            try
            {
                int xplate_getimage_retry_times = ConfigHelper.Config.Get("xplate_getimage_retry_times",5);
                int xplate_open_retry_times = ConfigHelper.Config.Get("xplate_open_retry_times", 3);
                for (int ii = 1; ii <= xplate_getimage_retry_times; ii++) {
                    bool rtn = RobotManage.xrayImage.GetImage(1);
                    if (!rtn)
                    {
                        if (ii == xplate_getimage_retry_times)
                            return false;

                        for (int jj = 1; jj <= xplate_open_retry_times; jj++)
                        {
                            bool closeR = RobotManage.xrayImage.Close();
                            if (!closeR)
                                MoveInfo.log($"xray plate Close ii={ii}, times={jj}, result={closeR}");

                            Thread.Sleep(500 * jj + (jj - 1) * 1000);
                            rtn = RobotManage.xrayImage.Open();
                            Thread.Sleep(500);
                            if (!rtn)
                            {
                                MoveInfo.log($"xray plate open failed ii={ii}, times={jj}");

                                if (jj == xplate_open_retry_times)
                                    return false;

                                continue;
                            }
                            else
                                break;
                        }
                        Thread.Sleep(1000 * ii+(ii-1)*2000);
                    }
                    else
                        break;
                }
                MoveInfo.log("get image from plate scusses");
                //RobotManage.xrayImage.WindowWidth = 30000;
                //RobotManage.xrayImage.WindowLevel = 15000;
                bmp = RobotManage.xrayImage.Get48bImage();

                Directory.CreateDirectory(xraydir);
                var n = DateTime.Now;
                string backDir = Path.Combine(xraydir, "back", n.Year.ToString() + "-" + n.Month.ToString(), n.Day.ToString(), n.Hour.ToString());
                Directory.CreateDirectory(backDir);
                xrayImagePath = Path.Combine(backDir, MoveInfo.ReelParam.GetImgName());

                bmp.Save(xrayImagePath, System.Drawing.Imaging.ImageFormat.Png);
               // File.Copy(xrayImagePath, backDir);
                MoveInfo.log($"save xray pic success. current file:{xrayImagePath}");
                return true;
            }
            catch (Exception ex)
            {
                MoveInfo.log(ex.ToString());
                return false;
            }
            finally
            {
                if (bmp != null)
                    bmp.Dispose();
                bmp = null;
                //StepImage?.Invoke(bmp);
            }
        }
        [HandleProcessCorruptedStateExceptions]
        public void GetCountResult()
        {
            //返回的数量是string类型,count = "4000,3000,3500,2000"
            int count = 0;
            //resfile = "";
            //tpDstImg = new API.EyemImage();
            try
            {
                int[] countStr =  new int[4];
                int result = 0;
                int ShrinkOffset = ConfigHelper.Config.Get<int>("ShrinkOffset",100);
                var pps = MoveInfo.ReelParam.PN.Split('-');
                var type = Pn_Algo_Match.MatchPN(pps[0],out _,out double? finetuning);
                MoveInfo.log($"匹配到算法.{pps[0]}={type}, finetuning={finetuning}");
                if (finetuning != null)
                {
                    XrayImage.setFineTuning = finetuning.Value;
                }
                else
                {
                    XrayImage.setFineTuning = ConfigHelper.Config.Get("setFineTuningDefault", 0.7);
                }
                if (type.StartsWith("IP_Template_PARTS"))
                {
                    if (!File.Exists(type.Substring(17 + 1)))
                    {
                        MoveInfo.log($"模版文件丢失.{type.Substring(17 + 1)}");
                        type = "auto";
                    }
                }
                Bitmap dst=null;
                if (type == "auto")
                {
                    result = XrayImage.GetLocalCount(xrayImagePath, ShrinkOffset, out countStr, out dst);
                    MoveInfo.log("GetCountResult " + type + " 调用 GetLocalCount 【" + xrayImagePath + "】,返回【" + result + "】,结果【" + string.Join(",",countStr) + "】");
                }
                else if (type.StartsWith("IP_Template_PARTS"))
                {
                    string template = "";
                    if (type.Length > 18)
                    {
                        template = type.Substring(17 + 1);
                    }
                    result = XrayImage.GetLocalCountTemplate(xrayImagePath, ShrinkOffset, template, out countStr, out dst);
                    MoveInfo.log("GetCountResult " + template + " 调用 GetLocalCountTemplate 【" + xrayImagePath + "】,返回【" + result + "】,结果【" + string.Join(",", countStr) + "】");

                }
                else
                {
                    result = XrayImage.GetLocalCountIrregular(xrayImagePath, ShrinkOffset, type.ToString(), out countStr, out dst);
                    MoveInfo.log("GetCountResult " + type + " 调用 GetLocalCountIrregular 【" + xrayImagePath + "】,返回【" + result + "】,结果【" + string.Join(",", countStr) + "】");
                }
                if (dst != null)
                {
                    dst.Save("ResOut\\" + Path.GetFileNameWithoutExtension(xrayImagePath) + "-Mark.png");
                    dst.Dispose();
                }
                if (result != 0)
                {
                    MoveInfo.ReelParam.IsNg = true;
                    MoveInfo.ReelParam.NgMsg = "点料失败";
                    MoveInfo.ReelParam.logresult();
                    return;
                }

                if (countStr != null)
                {
                   //string[] array = countStr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    count = (from a in countStr where a > 0 select a).FirstOrDefault();
                }
                else
                {
                    count = 0;
                }
                if (result == 0 && count > 0)
                {
                    MoveInfo.ReelParam.QTY = count;
                    string resfilename = Path.GetFileNameWithoutExtension(xrayImagePath) + "-Mark.png";
                    string root = Path.Combine(Application.StartupPath, "ResOut");
                    var n = DateTime.Now;
                    string destdir = Path.Combine(root, n.Year.ToString() + "-" + n.Month.ToString(), n.Day.ToString(), n.Hour.ToString());
                    Directory.CreateDirectory(destdir);
                    string resfile = Path.Combine(destdir, resfilename);
                    if (File.Exists(resfile))
                        File.Delete(resfile);
                    Directory.Move(Path.Combine(root, resfilename), resfile);
                    if (!RobotManage.offlinemode)
                    {
                        var cl = ServerConn.inputCounterDataByXRayMachine(MoveInfo.ReelParam.WareCode, count);
                        if (cl == null)
                        {
                            MoveInfo.ReelParam.IsNg = true;
                            MoveInfo.ReelParam.NgMsg = "点料数量上传失败";
                            MoveInfo.ReelParam.logresult();
                        }
                    }
                }
                else {
                    MoveInfo.ReelParam.IsNg = true;
                    MoveInfo.ReelParam.NgMsg = "点料结果为0";
                    MoveInfo.ReelParam.logresult();
                }
            }
            catch (Exception ex)
            {
                MoveInfo.log("GetCountResult 出错: " + ex.ToString());
            }
        }
    }
    
}