Controller.cs 13.9 KB
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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
using OpenCvSharp;
using OS.Spin.BusinessLayer.MainBusiness;
using OS.Spin.BusinessLayer.SubBusiness;
using OS.Spin.Common;
using OS.Spin.Modle.BusinessLayer;
using OS.Spin.ViewModle.Flaw;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using static OS.Spin.BusinessLayer.MainBusiness.FlawDetectionBl;

namespace OS.Spin.Commands
{
    public class Controller
    {
        private static Controller _cer = null;
        private static object _objLock = new object();
        public delegate void AddNewFlawShot(MFlawInfo flaw);

        public delegate void FlawViewShowDialog(ref MGoodFlaws flaws);

        public FlawViewShowDialog FlawViewShowDialogEvent;
        public delegate void WindowsControl(int cmd);

        public WindowsControl WindowsControlEvent;

        public AddNewFlawShot DoAddFlawShot;

        public RunningEvent Running;

        private int _flawCount = 0;

        [DllImport("user32.dll")]
        public static extern int MessageBoxTimeoutA(IntPtr hWnd, string msg, string Caps, int type, int Id, int time);

        private int _tScore = 0;
        private List<MGreyCloth> _cacheGreyGloths = new List<MGreyCloth>();

        private List<MGoodFlaws> _cacheGoods = new List<MGoodFlaws>();

        public int Scores
        {
            get { return _tScore; }
        }

        public int FlawCount
        {
            get { return _flawCount; }
        }

        //public Dictionary<string, List<MFlawInfo>> 

        public delegate void ViewZeroing();
        public ViewZeroing DoViewZeroing;

        private const int CAMERA_COUNT = 3;

        private List<MFlawInfo> _flaws = new List<MFlawInfo>();

        private ObservableCollection<MFlawRow> _viewFlaws = new ObservableCollection<MFlawRow>();

        public List<MFlawInfo> Flaws
        {
            get { return _flaws; }
        }
        private FlawDetectionBl _flawBl;
        public static Controller GetInstance()
        {
            lock (_objLock)
            {
                return _cer ?? (_cer = new Controller());
            }
        }

        /// <summary>
        /// 改变布匹种类
        /// </summary>
        /// <param name="kind"></param>
        public void ChangedClokdKind(int kind)
        {
            _flawBl.UploadClothsKind(kind);
        }

        public void DoTrigger(int type, double meter)
        {
            _flawBl.TimerRecived(type, meter);
        }

        /// <summary>
        /// 瑕疵误报
        /// </summary>
        public void MisReport()
        {
            if (ImageSavingBl.Getinstance().lstManMade == null || ImageSavingBl.Getinstance().lstManMade.Count == 0)
            {
                MessageBoxTimeoutA((IntPtr)0, "未检测到瑕疵!", "瑕疵忽略", 0, 0, 1500);
            }
            else
            {
                Thread _th = new Thread(new ParameterizedThreadStart(ImageCopy));
                _th.Start(ImageSavingBl.Getinstance().lstManMade);
            }

        }
        /// <summary>
        /// 将要忽略的瑕疵图片复制到新目录并删除原文件
        /// </summary>
        /// <param name="lst"></param>
        private void ImageCopy(object lst)
        {
            try
            {
                foreach (string imgPath in (lst as List<string>))
                {
                    string newPath = imgPath.Replace(@"Flaws\AutoMade", "MissReport");
                    if (!Directory.Exists(Path.GetDirectoryName(newPath)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(newPath));
                    }
                    if (File.Exists(imgPath))
                    {
                        File.Copy(imgPath, newPath, true);
                    }
                    File.Delete(imgPath);//删除旧图
                }
                MessageBoxTimeoutA((IntPtr)0, "当前瑕疵已忽略!", "瑕疵忽略", 0, 0, 1500);
            }
            catch (Exception ex)
            {
                LogisTrac.WriteLog(string.Format("MisReport:{0}", ex.Message));
            }
        }

        /// <summary>
        /// 单次拍照
        /// </summary>
        public void SnapShoting()
        {
            try
            {
                while (!_flawBl.CanTrigger)
                {
                    System.Threading.Thread.Sleep(5);
                }
                //var last = OS.Spin.Running.Cache.GetInstance().AutoFlaw;
                //OS.Spin.Running.Cache.GetInstance().AutoFlaw = false;
                var meter = OS.Spin.Running.Cache.GetInstance().CMeter;
                _flawBl.CameraTrigger(meter);
                while (!_flawBl.CanTrigger)
                {
                    System.Threading.Thread.Sleep(5);
                }
                System.Threading.Thread.Sleep(200);
                ImageSavingBl.Getinstance().PutCopy(new MFileCopy(2, OS.Spin.Running.Cache.GetInstance().CacheImgId, CAMERA_COUNT));
                //OS.Spin.Running.Cache.GetInstance().AutoFlaw = last;
                MessageBoxTimeoutA((IntPtr)0, "瑕疵拍照成功!", "瑕疵拍照", 0, 0, 1500);
            }
            catch (Exception ex)
            {
                LogisTrac.WriteLog(string.Format("SnapShoting:{0}", ex.Message));
            }
        }
        private Controller()
        {
            _flawBl = new FlawDetectionBl(CAMERA_COUNT)
            {
                DoAddFlawShot = AddFlawShot
            };
            _flawBl.TlWorker = DoBlCmd;
        }

        public void DoBlCmd(int type)
        {
            WindowsControlEvent?.Invoke(11);
        }
        public void Banding()
        {
            _flawBl.Running = Running;
        }

        private MGoodFlaws good = new MGoodFlaws();
        public void SaveGoods()
        {
            //return;
            try
            {
                if (OS.Spin.Running.Cache.GetInstance().CMeter < 5)
                {
                    return;
                }
                bool isBreak = false;
                for (var i = good.Flaws.Count - 1; i >= 0; i--)
                {
                    var flaws = good.Flaws[i].Flaws;
                    var score = 0;
                    foreach (var flaw in flaws)
                    {
                        score += int.Parse(flaw.Score);
                        //if (flaw.Meter < OS.Spin.Running.Cache.GetInstance().CMeter - 5)
                        //{
                        //    isBreak = true;
                        //    break;
                        //}
                    }
                    if (isBreak)
                    {
                        break;
                    }
                    _tScore += score;
                    //good.Flaws.RemoveAt(i);
                }

                //for(var flaws in _viewFlaws)
                //var good = new MGoodFlaws
                //{
                good.FinishedTime = DateTime.Now;
                good.Score = string.Format("-{0}", Scores);
                good.SnNo = _snNo;
                good.Level = Scores <= 16 ? "A" : "B";
                good.Meter = OS.Spin.Running.Cache.GetInstance().CMeter;
                //};
                _viewFlaws = new ObservableCollection<MFlawRow>();
                //FlawViewShowDialogEvent?.Invoke(ref good);
                _cacheGoods.Add(good);
                good = new MGoodFlaws();
                // 清零
                Zero();
                // 下一个编号
                NextSnNo();
                SaveReports();
            }
            catch (Exception ex)
            {
                LogisTrac.WriteLog(ex);
            }
        }

        public void SaveReports()
        {
            try
            {
                if (null == _cacheGoods || 0 == _cacheGoods.Count)
                {
                    return;
                }
                var rbl = new ReportsSavingBl();
                rbl.SaveReport(_cacheGoods);
                _cacheGoods.Clear();
                MessageBoxTimeoutA((IntPtr)0, "报告保存成功!", "报告保存", 0, 0, 1500);
                //MessageBox.Show("报告保存成功!");
            }
            catch (Exception ex)
            {
                LogisTrac.WriteLog(string.Format("SaveReports:", ex.Message));
            }
        }


        public void Zero()
        {
            try
            {
                good = new MGoodFlaws();
                DoAddFlawShot?.Invoke(null);
                OS.Spin.Running.Cache.GetInstance().CacheImgId = 0;
                OS.Spin.Running.Cache.GetInstance().CMeter = 0;
                WindowsControlEvent?.Invoke(10);
                _flawBl.ReSetDp();
                _tScore = 0;
                _flawCount = 0;
                _flaws.Clear();
                OS.Spin.Running.Cache.GetInstance().FlawId = 1;
            }
            catch (Exception ex)
            {
                LogisTrac.WriteLog(string.Format("Zero:{0}", ex.Message));
            }
        }

        private string _snNo = "A20190529A0002";

        public void MinWindows()
        {
            WindowsControlEvent?.Invoke(0);
        }

        public string SnNo
        {
            get { return _snNo; }
        }

        /// <summary>
        /// 改变编号
        /// </summary>
        public void ChangeSnNo(string sn)
        {
            try
            {
                var no = sn.Substring(sn.Length - 3, 3);
                int rNo;
                if (!int.TryParse(no, out rNo))
                {
                    return;
                }
                _snNo = sn;
            }
            catch (Exception ex)
            {
                LogisTrac.WriteLog(string.Format("ChangeSnNo:{0}", ex.Message));
            }
        }

        public void NextSnNo()
        {
            try
            {
                if (string.IsNullOrEmpty(_snNo))
                {
                    return;
                }
                var no = _snNo.Substring(_snNo.Length - 3, 3);
                var sn = _snNo.Substring(0, _snNo.Length - 3);
                int rNo;
                if (!int.TryParse(no, out rNo))
                {
                    return;
                }
                rNo++;
                no = string.Format("{0:d3}", rNo);
                _snNo = sn + no;
            }
            catch (Exception ex)
            {
                LogisTrac.WriteLog(string.Format("NextSnNo:{0}", ex.Message));
            }
        }

        public void Exit()
        {
            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            //LogisTrac.WriteLog("关闭");
            //System.Environment.Exit(0);
            //LogisTrac.WriteLog("关闭成功");
            //LogisTrac.WriteLog("1" + sw.ElapsedMilliseconds.ToString());
            //_flawBl.Dispose();
            //LogisTrac.WriteLog("_flawBl" + sw.ElapsedMilliseconds.ToString());
            //ImageSavingBl.Getinstance().Dispose();
            //LogisTrac.WriteLog("ImageSavingBl" + sw.ElapsedMilliseconds.ToString());
            WindowsControlEvent?.Invoke(1);
            //LogisTrac.WriteLog(sw.ElapsedMilliseconds.ToString());
            //System.Environment.Exit(0);
            //LogisTrac.WriteLog(sw.ElapsedMilliseconds.ToString());
        }

        public void TestTrigger(double meter)
        {
            _flawBl.CameraTrigger(meter);
        }

        public void AddFlawByUser()
        {
            ImageSavingBl.Getinstance().PutCopy(new MFileCopy(1, OS.Spin.Running.Cache.GetInstance().CacheImgId, CAMERA_COUNT));
            MessageBoxTimeoutA((IntPtr)0, "瑕疵抓拍成功!", "瑕疵抓拍", 0, 0, 1500);
        }

        private void AddFlawShot(MFlawInfo flaw)
        {
            //_flaws.Add(flaw);
            //ViewFlaws.Add()
            try
            {
                MFlawRow flawRow = new MFlawRow()
                {
                    Id = (good.Flaws.Count + 1).ToString(),
                };
                //flawRow.MatImg = mergeCols(flaw.Mats);
                var id = 0;

                foreach (var f in flaw.FinalFlaws)
                {
                    var cflaw = new MFlaw()
                    {
                        Id = string.Format("{0}:{1}", _viewFlaws.Count, id),
                        FlawName = f.FlawName,
                        Score = string.Format("-{0}", f.Scores),
                        Meter = f.Meter
                    };
                    flawRow.Flaws.Add(cflaw);
                    _flawCount += 1;
                    _tScore += f.Scores;
                }

                good.Flaws.Add(flawRow);
                DoAddFlawShot?.Invoke(flaw);
            }
            catch (Exception ex)
            {
                LogisTrac.WriteInfoLog("AddFlawShot");
                LogisTrac.WriteLog(ex);
            }
        }

        private Mat mergeCols(List<Mat> mats)
        {
            //CV_ASSERT(A.cols == B.cols && A.type() == B.type());
            try
            {
                if (0 == mats.Count)
                {
                    return null;
                }

                if (1 == mats.Count)
                {
                    return mats[0];
                }

                if (null == mats[0])
                {
                    return null;
                }
                int totalCols = mats[0].Cols * mats.Count;


                Mat mergedDescriptors = new Mat(mats[0].Rows, totalCols, mats[0].Type());

                for (var i = 0; i < mats.Count; i++)
                {
                    var mat = mats[i];

                    if (null == mat)
                    {
                        return null;
                    }

                    Mat submat = mergedDescriptors.ColRange(mat.Cols * i, mat.Cols * (i + 1));
                    mat.CopyTo(submat);
                }

                return mergedDescriptors;
            }
            catch (Exception ex)
            {
                LogisTrac.WriteInfoLog("mergeCols");
                LogisTrac.WriteLog(ex);
            }
            return null;
        }
    }

}