IDHIK.cs 32.8 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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
using MvCodeReaderSDKNet; 
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace IDHIKCamera
{
    public class IDHIK
    {
        private IDHIK() { }

        private static IDHIK instance = null;
        public static IDHIK Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new IDHIK();
                }

                return instance;
            }
        }

        protected string[] _name;
        public string _errInfo;
        protected int _count;
        protected bool[] _isOpen;
        public List<string> cameraName = new List<string>();
        public bool DrawLine = true;

        /// <summary>
        /// 当前相机
        /// </summary>
        private MvCodeReader[] cameraCurr;
        /// <summary>
        /// 所有相机列表
        /// </summary>
        private MvCodeReader.MV_CODEREADER_DEVICE_INFO_LIST cameraAll;

        private bool LoadOk = false;

        public bool Load()
        {
            if (LoadOk)
            {
                return true;
            }

            try
            {
                LoadOk = true;
                cameraAll = new MvCodeReader.MV_CODEREADER_DEVICE_INFO_LIST();
                cameraAll.nDeviceNum = 0;
                int nRet = MvCodeReader.MV_CODEREADER_EnumDevices_NET(ref cameraAll, MvCodeReader.MV_CODEREADER_GIGE_DEVICE);
                if (0 != nRet)
                {
                    SetErrorMsg("Load failed", nRet);
                    LibLogUtil.Error("IDHIK   Load camera error : " + _errInfo);
                    return false;
                }

                cameraName = new List<string>();

                string strUserDefinedName = "";
                for (int i = 0; i < cameraAll.nDeviceNum; i++)
                {
                    MvCodeReader.MV_CODEREADER_DEVICE_INFO stDevInfo = (MvCodeReader.MV_CODEREADER_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[i], typeof(MvCodeReader.MV_CODEREADER_DEVICE_INFO));
                    if (stDevInfo.nTLayerType == MvCodeReader.MV_CODEREADER_GIGE_DEVICE)
                    {
                        IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(stDevInfo.SpecialInfo.stGigEInfo, 0);
                        MvCodeReader.MV_CODEREADER_GIGE_DEVICE_INFO stGigEDeviceInfo = (MvCodeReader.MV_CODEREADER_GIGE_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MvCodeReader.MV_CODEREADER_GIGE_DEVICE_INFO));
                        string name = "";
                        if (stGigEDeviceInfo.chUserDefinedName != "")
                        {
                            byte[] byteUserDefinedName = Encoding.GetEncoding("GB2312").GetBytes(stGigEDeviceInfo.chUserDefinedName);
                            bool bIsValidUTF8 = IsTextUTF8(byteUserDefinedName);
                            if (bIsValidUTF8)
                            {
                                strUserDefinedName = Encoding.UTF8.GetString(byteUserDefinedName);
                            }
                            else
                            {
                                strUserDefinedName = Encoding.GetEncoding("GB2312").GetString(byteUserDefinedName);
                            }
                            name = "GEV: " + strUserDefinedName + " (" + stGigEDeviceInfo.chSerialNumber + ")";

                        }
                        else
                        {
                            name = stGigEDeviceInfo.chModelName + " (" + stGigEDeviceInfo.chSerialNumber + ")";
                        }
                        if (name.Contains("ID"))
                        {
                            LibLogUtil.Info("IDHIK 加载到相机:" + name);
                        }
                        else
                        {

                            LibLogUtil.Info("IDHIK 加载到相机:" + name + ",非ID相机");
                        }
                        cameraName.Add(name);
                    }
                }

                _name = cameraName.ToArray();
                _count = cameraName.Count;
                _isOpen = new bool[_count];

                cameraCurr = new MvCodeReader[_count];
                SetErrorMsg("Load OK");
                LibLogUtil.Info("IDHIK 加载完成,共" + _count + "个相机:");

                return true;
            }
            catch (Exception ex)
            {
                SetErrorMsg(ex.Message);
                return false;
            }
        }

        public bool OpenAll()
        {
            lock (cameraCurr)
            {
                bool rtn = true;
                for (int i = 0; i < cameraName.Count; i++)
                {
                    rtn = Open(i);
                    if (!rtn) break;
                }
                return rtn;
            }
        }

        public   bool Open(string name)
        {
            int n = cameraName.FindIndex(s => s == name);
            if (n == -1)
            {
                SetErrorMsg(name + " Not find", n);
                return false;
            }
            else
                return Open(n);
        }
        public bool Open(int index)
        {
            lock (cameraCurr)
            {
                //   _index = index;
                if (index < 0 || index >= _count)
                {
                    SetErrorMsg("Not find index :" + index);
                    LibLogUtil.Error("open camera " + index + " error : " + _errInfo);
                    return false;
                }
                if (cameraCurr[index] != null) Close(index);

                try
                {
                    MvCodeReader.MV_CODEREADER_DEVICE_INFO stDevInfo = (MvCodeReader.MV_CODEREADER_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[index], typeof(MvCodeReader.MV_CODEREADER_DEVICE_INFO));
                    cameraCurr[index] = new MvCodeReader();

                    int nRet = cameraCurr[index].MV_CODEREADER_CreateHandle_NET(ref stDevInfo);
                    if (nRet != MvCodeReader.MV_CODEREADER_OK)
                    {
                        SetErrorMsg("open camera " + index + " error MV_CODEREADER_CreateHandle_NET fail : ", nRet);
                        return false;
                    }
                    nRet = cameraCurr[index].MV_CODEREADER_OpenDevice_NET();
                    if (MvCodeReader.MV_CODEREADER_OK != nRet)
                    {
                        cameraCurr[index].MV_CODEREADER_DestroyHandle_NET();
                        SetErrorMsg("open camera " + index + " error MV_CODEREADER_OpenDevice_NET fail : ", nRet);
                        return false;
                    }

                    // ch:设置采集连续模式 | en:Set Continues Aquisition Mode
                    cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("TriggerMode", (uint)MvCodeReader.MV_CODEREADER_TRIGGER_MODE.MV_CODEREADER_TRIGGER_MODE_OFF);
                    _isOpen[index] = true;
                    SetErrorMsg("OK");
                    LibLogUtil.Info("open camera " + index + " " + _errInfo);
                    return true;
                }
                catch (Exception ex)
                {
                    LibLogUtil.Error("打开相机出错:" + ex.ToString());
                    SetErrorMsg(ex.Message);
                    return false;
                }
            }
        }

        public bool Open_AddParameter(int index)
        {
            lock (cameraCurr)
            {
                //   _index = index;
                if (index < 0 || index >= _count)
                {
                    SetErrorMsg("Not find index :" + index);
                    LibLogUtil.Error("open camera " + index + " error : " + _errInfo);
                    return false;
                }
                if (cameraCurr[index] != null) Close(index);

                try
                {
                    MvCodeReader.MV_CODEREADER_DEVICE_INFO stDevInfo = (MvCodeReader.MV_CODEREADER_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[index], typeof(MvCodeReader.MV_CODEREADER_DEVICE_INFO));
                    cameraCurr[index] = new MvCodeReader();

                    int nRet = cameraCurr[index].MV_CODEREADER_CreateHandle_NET(ref stDevInfo);
                    if (nRet != MvCodeReader.MV_CODEREADER_OK)
                    {
                        SetErrorMsg("open camera " + index + " error MV_CODEREADER_CreateHandle_NET fail : ", nRet);
                        return false;
                    }
                    nRet = cameraCurr[index].MV_CODEREADER_OpenDevice_NET();
                    if (MvCodeReader.MV_CODEREADER_OK != nRet)
                    {
                        cameraCurr[index].MV_CODEREADER_DestroyHandle_NET();
                        SetErrorMsg("open camera " + index + " error MV_CODEREADER_OpenDevice_NET fail : ", nRet);
                        return false;
                    }
                    //1.相机修改为相机修改normal模式
                    var RunningMode = cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("RunningMode", 0);
                    LibLogUtil.Info($"设置为normal模式为:{RunningMode}");
                    //2.设置为触发模式
                    var tggerMode = cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("tggerMode", 0);
                    LibLogUtil.Info($"设置为触发模式为:{tggerMode}");
                    //3.设置为软触发
                    var TriggerMode = cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("TriggerMode", 1);
                    LibLogUtil.Info($"设置为软触发模式为:{TriggerMode}");
                    //4.设置软触发源
                    var TriggerSource = cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("TriggerSource", 7);
                    LibLogUtil.Info($"设置为软触发源:{TriggerSource}");
                    //5.设置拍照张数
                    var AcquisitionBurstFrameCount = cameraCurr[index].MV_CODEREADER_SetIntValue_NET("AcquisitionBurstFrameCount", 5);
                    LibLogUtil.Info($"设置拍照张数:{AcquisitionBurstFrameCount}");
                    //6.设置图片压缩比例
                    var JpgQuality = cameraCurr[index].MV_CODEREADER_SetIntValue_NET("JpgQuality", 50);
                    LibLogUtil.Info($"设置图片压缩比例:{JpgQuality}");
                    //ch:设置采集连续模式 | en:Set Continues Aquisition Mode
                    //cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("TriggerMode", (uint)MvCodeReader.MV_CODEREADER_TRIGGER_MODE.MV_CODEREADER_TRIGGER_MODE_OFF);
                    _isOpen[index] = true;
                    SetErrorMsg("OK");
                    LibLogUtil.Info("open camera " + index + " " + _errInfo);
                    return true;
                }
                catch (Exception ex)
                {
                    LibLogUtil.Error("打开相机出错:" + ex.ToString());
                    SetErrorMsg(ex.Message);
                    return false;
                }
            }
        }
        public Image GrabOne_AddParameter(int index, out List<CodeInfo> codeInfos)
        {
            codeInfos = new List<CodeInfo>();
            if (cameraCurr[index] == null || ((!_isOpen[index])))
            {
                bool result = Open(index);
                if (!result)
                {
                    return null;
                }
            }
            if (cameraCurr[index] == null)
            {
                SetErrorMsg("Camera null");
                return null;
            }
            try
            {
                return ImageCapture(index, out codeInfos);
            }
            catch (Exception ex)
            {
                SetErrorMsg(ex.Message);
                return null;
            }
            finally
            {
                if (cameraCurr[index] != null)
                {
                    cameraCurr[index].MV_CODEREADER_StopGrabbing_NET();

                    var LineSelector=cameraCurr[index].MV_CODEREADER_SetEnumValue_NET("LineSelector",5);
                    LibLogUtil.Info($"前置条件:{LineSelector}");
                    var LineInverter=cameraCurr[index].MV_CODEREADER_SetBoolValue_NET("LineInverter", false);
                    LibLogUtil.Info($"关闭光源:{LineInverter}");
                }
                //Task.Run(() => { IDHIK.Instance.Close(index); Thread.Sleep(500); IDHIK.Instance.Open(index); });
            }
        }
        public   void Close(int index)
        {
            lock (cameraCurr)
            {
                if (cameraCurr[index] != null)
                {
                    LibLogUtil.Info($"  close  camer  [{index}] ");
                    _isOpen[index] = false;
                    cameraCurr[index].MV_CODEREADER_CloseDevice_NET();
                    cameraCurr[index].MV_CODEREADER_DestroyHandle_NET();
                    cameraCurr[index] = null;
                }
            }
        }
        public void Close(string name)
        {
            lock (cameraCurr)
            {
                int index = cameraName.FindIndex(s => s == name);
                if (index == -1)
                {
                    SetErrorMsg($"name {name} Not find");
                    return;
                }
                if (cameraCurr[index] != null)
                {
                    LibLogUtil.Info($"  close  camera [{name}] [{index}] ");
                    _isOpen[index] = false;
                    cameraCurr[index].MV_CODEREADER_CloseDevice_NET();
                    cameraCurr[index].MV_CODEREADER_DestroyHandle_NET();
                    cameraCurr[index] = null;
                }
            }
        }
        public void CloseAll()
        {

            if (cameraCurr == null)
                return;
            lock (cameraCurr)
            {
                LibLogUtil.Info("   cameraCurr.Length : " + cameraCurr.Length.ToString());
                for (int i = 0; i < cameraCurr.Length; i++)
                {
                    if (cameraCurr[i] != null)
                    {
                        LibLogUtil.Info($"  close  cameraCurr[{i}]  ");
                        _isOpen[i] = false;
                        cameraCurr[i].MV_CODEREADER_CloseDevice_NET();
                        cameraCurr[i].MV_CODEREADER_DestroyHandle_NET();
                        cameraCurr[i] = null;
                    }
                }
            }
        }

        public Image GrabOne(int index, out List<CodeInfo> codeInfos)
        {
            codeInfos = new List<CodeInfo>();
            if (cameraCurr[index] == null || ((!_isOpen[index])))
            {
                bool result = Open(index);
                if (!result)
                {
                    return null;
                }
            }
            if (cameraCurr[index] == null)
            {
                SetErrorMsg("Camera null");
                return null;
            }
            try
            {

                return ImageCapture(index, out codeInfos);
            }
            catch (Exception ex)
            {
                SetErrorMsg(ex.Message);
                return null;
            }
            finally
            {
                if (cameraCurr[index] != null)
                {
                    cameraCurr[index].MV_CODEREADER_StopGrabbing_NET();
                }
                Task.Run(() => { IDHIK.Instance.Close(index); Thread.Sleep(500); IDHIK.Instance.Open(index); });
            }
        }

        public Image GrabOne(string name, out List<CodeInfo> codeInfos)
        {
            codeInfos = new List<CodeInfo>();
            int idx = Array.FindIndex(_name, s => s == name);
            if (idx == -1)
                return null;
            else
                return GrabOne(idx, out codeInfos);
        }

        // ch:用于从驱动获取图像的缓存 | en:Buffer for getting image from driver
        private byte[] m_BufForDriver = new byte[1024 * 1024 * 20];

        private Bitmap bmp = null;
        private Image ImageCapture(int index, out List<CodeInfo> codeList)
        {
            IntPtr pstFrameInfoEx2= IntPtr.Zero, pData= IntPtr.Zero; 
            codeList = new List<CodeInfo>();
            if (!StartGrabbing(index))
            {
                return null;
            }
            try
            {
                int nRet = MvCodeReader.MV_CODEREADER_OK;
                Thread.Sleep(50);
                MvCodeReader.MV_CODEREADER_IMAGE_OUT_INFO_EX2 stFrameInfoEx2 = new MvCodeReader.MV_CODEREADER_IMAGE_OUT_INFO_EX2();
                pstFrameInfoEx2 = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MvCodeReader.MV_CODEREADER_IMAGE_OUT_INFO_EX2)));
                Marshal.StructureToPtr(stFrameInfoEx2, pstFrameInfoEx2, false);
                for (int i = 0; i < 4; i++)
                {
                    nRet = cameraCurr[index].MV_CODEREADER_GetOneFrameTimeoutEx2_NET(ref pData, pstFrameInfoEx2, 1000);
                    if (nRet == MvCodeReader.MV_CODEREADER_OK)
                    {

                        stFrameInfoEx2 = (MvCodeReader.MV_CODEREADER_IMAGE_OUT_INFO_EX2)Marshal.PtrToStructure(pstFrameInfoEx2, typeof(MvCodeReader.MV_CODEREADER_IMAGE_OUT_INFO_EX2));
                        break;
                    }
                    else
                    {
                        LibLogUtil.Error(" Can not grab one : "+ nRet);
                        Thread.Sleep(50);
                    }
                }
                List<Point[]> pts=new List<Point[]>();
                if (nRet == MvCodeReader.MV_CODEREADER_OK)
                {
                    if (0 >= stFrameInfoEx2.nFrameLen)
                    {
                        SetErrorMsg("Can not grab one : ", nRet);
                        return null;
                    }
                    MvCodeReader.MV_CODEREADER_RESULT_BCR_EX2 stBcrResultEx2 = (MvCodeReader.MV_CODEREADER_RESULT_BCR_EX2)Marshal.PtrToStructure(stFrameInfoEx2.UnparsedBcrList.pstCodeListEx2, typeof(MvCodeReader.MV_CODEREADER_RESULT_BCR_EX2));

                    for (int i = 0; i < stBcrResultEx2.nCodeNum; ++i)
                    {
                        // 条码位置的4个点坐标
                        Point[] stPointList = new Point[4];
                        CodeInfo code = new CodeInfo();
                        int suX = 0;
                        int suY = 0;
                        for (int j = 0; j < 4; ++j)
                        {
                            stPointList[j].X = (int)(stBcrResultEx2.stBcrInfoEx2[i].pt[j].x);
                            stPointList[j].Y = (int)(stBcrResultEx2.stBcrInfoEx2[i].pt[j].y);
                            suX += (int)(stBcrResultEx2.stBcrInfoEx2[i].pt[j].x);
                            suY += (int)(stBcrResultEx2.stBcrInfoEx2[i].pt[j].y);
                        }
                        pts.Add(stPointList);
                        code.CodeType = GetBarType((MvCodeReader.MV_CODEREADER_CODE_TYPE)stBcrResultEx2.stBcrInfoEx2[i].nBarType);
                        String strCode = System.Text.Encoding.Default.GetString(stBcrResultEx2.stBcrInfoEx2[i].chCode);
                        //code.CodeStr = ReplaceCode(  String.IsNullOrEmpty(strCode) ? "" : strCode);
                        code.CodeStr = RemoveNUL(String.IsNullOrEmpty(strCode) ? "" : strCode);

                        code.Orientation = stBcrResultEx2.stBcrInfoEx2[i].nAngle;
                        code.X = suX / 4;
                        code.Y = suY / 4;

                        codeList.Add(code);
                    }
                    // 绘制图像
                    Marshal.Copy(pData, m_BufForDriver, 0, (int)stFrameInfoEx2.nFrameLen);
                    if (stFrameInfoEx2.enPixelType == MvCodeReader.MvCodeReaderGvspPixelType.PixelType_CodeReader_Gvsp_Mono8)
                    {
                        IntPtr pImage = Marshal.UnsafeAddrOfPinnedArrayElement(m_BufForDriver, 0);
                        bmp = new Bitmap(stFrameInfoEx2.nWidth, stFrameInfoEx2.nHeight, stFrameInfoEx2.nWidth, PixelFormat.Format8bppIndexed, pImage);
                        ColorPalette cp = bmp.Palette;
                        for (int i = 0; i < 256; i++)
                        {
                            cp.Entries[i] = Color.FromArgb(i, i, i);
                        }
                        bmp.Palette = cp;

                        if (DrawLine)
                        {
                            Graphics g = Graphics.FromImage(bmp);
                            Pen pen = new Pen(Color.Blue, 3);                   // 画笔颜色

                            foreach (Point[] points in pts)
                            {
                                g.DrawPolygon(pen, points);
                            }
                            g.Save();
                            g.Dispose();
                        }

                        return bmp;
                    }
                    else if (stFrameInfoEx2.enPixelType == MvCodeReader.MvCodeReaderGvspPixelType.PixelType_CodeReader_Gvsp_Jpeg)
                    {
                        MemoryStream ms = new MemoryStream();
                        ms.Write(m_BufForDriver, 0, (int)stFrameInfoEx2.nFrameLen);

                        Image img = Bitmap.FromStream(ms);
                        if (DrawLine)
                        {
                            Graphics g = Graphics.FromImage(img);
                            Pen pen = new Pen(Color.Blue, 3);                   // 画笔颜色

                            foreach (Point[] points in pts)
                            {
                                g.DrawPolygon(pen, points);
                            }
                            g.Save();
                            g.Dispose();
                        }
                        return img;
                    }
                }
            }
            catch (Exception ex)
            {
                SetErrorMsg(ex.ToString());
            }
            finally
            {              
                StopGrabbing(index);
                Marshal.FreeHGlobal(pstFrameInfoEx2);
                //Marshal.FreeHGlobal(pData);
            }          
            return null; 
        }
        private bool StartGrabbing(int index)
        {
            // ch:开始采集 | en:Start Grabbing
            int rtn = cameraCurr[index].MV_CODEREADER_StartGrabbing_NET();
            LibLogUtil.Info($"相机索引:{rtn}");
            if (rtn != MvCodeReader.MV_CODEREADER_OK)
            {
                SetErrorMsg("Can not grab one : ", rtn);
                return false;
            }
            return true;
        }
        private bool StopGrabbing(int index)
        {

            // ch:停止采集 | en:Stop Grabbing
            int nRet = cameraCurr[index].MV_CODEREADER_StopGrabbing_NET();
            LibLogUtil.Info($"关闭结果{nRet};索引{index}");
            if (nRet != MvCodeReader.MV_CODEREADER_OK)
            {
                SetErrorMsg("Stop Grabbing Fail!", nRet);
                return false;
            }
            return true;
        }
         
        public static T DeepClone<T>(T _object)
        {
            try
            {
                T dstobject;
                using (MemoryStream mStream = new MemoryStream())
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(mStream, _object);
                    mStream.Seek(0, SeekOrigin.Begin);//指定当前流的位置为流的开头。
                    dstobject = (T)bf.Deserialize(mStream);
                    mStream.Close();
                }
                return dstobject;
            }
            catch (Exception e)
            {
                LibLogUtil.Error("DeepClone" + e.ToString());
                return default;
            }
        } 

        private static void __OnFreeCallBack(IntPtr pImg)
        {
            Marshal.FreeHGlobal(pImg);
        }

        // ch:显示错误信息 | en:Show error message
        private string SetErrorMsg(string csMessage, int nErrorNum = 0)
        {
            string errorMsg;
            if (nErrorNum == 0)
            {
                errorMsg = csMessage;
            }
            else
            {
                errorMsg = csMessage + ": Error =" + String.Format("{0:X}", nErrorNum);
            }

            switch (nErrorNum)
            {
                case MvCodeReader.MV_CODEREADER_E_HANDLE: errorMsg += " Error or invalid handle "; break;
                case MvCodeReader.MV_CODEREADER_E_SUPPORT: errorMsg += " Not supported function "; break;
                case MvCodeReader.MV_CODEREADER_E_BUFOVER: errorMsg += " Cache is full "; break;
                case MvCodeReader.MV_CODEREADER_E_CALLORDER: errorMsg += " Function calling order error "; break;
                case MvCodeReader.MV_CODEREADER_E_PARAMETER: errorMsg += " Incorrect parameter "; break;
                case MvCodeReader.MV_CODEREADER_E_RESOURCE: errorMsg += " Applying resource failed "; break;
                case MvCodeReader.MV_CODEREADER_E_NODATA: errorMsg += " No data "; break;
                case MvCodeReader.MV_CODEREADER_E_PRECONDITION: errorMsg += " Precondition error, or running environment changed "; break;
                case MvCodeReader.MV_CODEREADER_E_VERSION: errorMsg += " Version mismatches "; break;
                case MvCodeReader.MV_CODEREADER_E_NOENOUGH_BUF: errorMsg += " Insufficient memory "; break;
                case MvCodeReader.MV_CODEREADER_E_UNKNOW: errorMsg += " Unknown error "; break;
                case MvCodeReader.MV_CODEREADER_E_GC_GENERIC: errorMsg += " General error "; break;
                case MvCodeReader.MV_CODEREADER_E_GC_ACCESS: errorMsg += " Node accessing condition error "; break;
                case MvCodeReader.MV_CODEREADER_E_ACCESS_DENIED: errorMsg += " No permission "; break;
                case MvCodeReader.MV_CODEREADER_E_BUSY: errorMsg += " Device is busy, or network disconnected "; break;
                case MvCodeReader.MV_CODEREADER_E_NETER: errorMsg += " Network error "; break;
            }
            _errInfo = errorMsg;
            // if(nErrorNum > 0)
            {
                LibLogUtil.Error(errorMsg);
            }
            return errorMsg;
        }
        private static String GetBarType(MvCodeReader.MV_CODEREADER_CODE_TYPE nBarType)
        {
            switch (nBarType)
            {
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_TDCR_DM:
                    return "Data Matrix";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_TDCR_QR:
                    return "QR Code";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_EAN8:
                    return "EAN-8";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_UPCE:
                    return "UPC-E";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_UPCA:
                    return "UPC-A";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_EAN13:
                    return "EAN-13";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_ISBN13:
                    return "ISBN-13";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CODABAR:
                    return "Codabar";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_ITF25:
                    return "ITF-25";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CODE39:
                    return "Code 39";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CODE93:
                    return "Code 93";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CODE128:
                    return "Code 128";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_TDCR_PDF417:
                    return "PDF417";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_MATRIX25:
                    return "MATRIX25";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_MSI:
                    return "MSI";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CODE11:
                    return "Code 11";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_INDUSTRIAL25:
                    return "Industral-25";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_CHINAPOST:
                    return "CHINAPOST";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_BCR_ITF14:
                    return "ITF-14";
                case MvCodeReader.MV_CODEREADER_CODE_TYPE.MV_CODEREADER_TDCR_ECC140:
                    return "ECC140";
                default:
                    return "/";
            }
        }
        // 判断字符编码
        public static bool IsTextUTF8(byte[] inputStream)
        {
            int encodingBytesCount = 0;
            bool allTextsAreASCIIChars = true;

            for (int i = 0; i < inputStream.Length; i++)
            {
                byte current = inputStream[i];

                if ((current & 0x80) == 0x80)
                {
                    allTextsAreASCIIChars = false;
                }
                // First byte
                if (encodingBytesCount == 0)
                {
                    if ((current & 0x80) == 0)
                    {
                        // ASCII chars, from 0x00-0x7F
                        continue;
                    }

                    if ((current & 0xC0) == 0xC0)
                    {
                        encodingBytesCount = 1;
                        current <<= 2;

                        // More than two bytes used to encoding a unicode char.
                        // Calculate the real length.
                        while ((current & 0x80) == 0x80)
                        {
                            current <<= 1;
                            encodingBytesCount++;
                        }
                    }
                    else
                    {
                        // Invalid bits structure for UTF8 encoding rule.
                        return false;
                    }
                }
                else
                {
                    // Following bytes, must start with 10.
                    if ((current & 0xC0) == 0x80)
                    {
                        encodingBytesCount--;
                    }
                    else
                    {
                        // Invalid bits structure for UTF8 encoding rule.
                        return false;
                    }
                }
            }

            if (encodingBytesCount != 0)
            {
                // Invalid bits structure for UTF8 encoding rule.
                // Wrong following bytes count.
                return false;
            }

            // Although UTF8 supports encoding for ASCII chars, we regard as a input stream, whose contents are all ASCII as default encoding.
            return !allTextsAreASCIIChars;
        }

        public static string RemoveNUL(string input)
        {
            // 将 [NUL] 隐藏字符,替换为空字符串
            string result = input.Replace("\x00", "");
            return result;
        }

        /// <summary>
        /// 处理接收后的二维码
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string ReplaceCode(string message)
        {
            message = message.Trim();
            message = message.Replace("\r", "");
            message = message.Replace("\n", "");
            char a = (char)02;
            message = message.Replace(a.ToString(), "");
            message = message.Trim();
            if (!HasChinese(message))
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                byte[] bytes = asciiEncoding.GetBytes(message);
                List<byte> newBytes = new List<byte>();
                foreach (byte by in bytes)
                {
                    int value = (int)by;
                    if (value.Equals(24) || value.Equals(30) || value.Equals(29) || value.Equals(4))
                    {
                        continue;
                    }
                    if (value.Equals(00))
                    {
                        continue;
                    }
                    if (!value.Equals(24))
                    {
                        newBytes.Add(by);
                    }
                }
                message = asciiEncoding.GetString(newBytes.ToArray());
            }
            return message;
        }
        public static bool HasChinese(string str)
        {
            return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
        }
    }   
}