haobo_v1.cs 32.7 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
using Asa.HaoboSDK_v1;
using ConfigHelper;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Asa.eyemLib;

namespace Asa
{
    class haobo_v1 : XrayImageInterface
    {
        private readonly log4net.ILog LOG;
        RegCfgInfo m_pLastRegCfg;
        static int nPrepareTm = 3000;
        static USER_CALLBACK_HANDLE_ENVENT _dUserCallbackHandleEnvent;
        IMAGE_CORRECT_ENABLE m_pCorrect = new IMAGE_CORRECT_ENABLE();
        byte[] buffer;
        public haobo_v1(string logName = "CarerayImage") {
            LOG = log4net.LogManager.GetLogger(logName);
            LOG.Info("Load haobo_v1");
            //1 初始化DLL
            HBI_FPD_DLL._handel = HBI_FPD_DLL.HBI_Init();
            _dUserCallbackHandleEnvent = DataCallBack;
            //2 注册回调函数
            int _ret = HBI_FPD_DLL.HBI_RegEventCallBackFun(HBI_FPD_DLL._handel, _dUserCallbackHandleEnvent);
            if (_ret != 0) WriteLog("HBI_RegEventCallBackFun" + _ret.ToString());

        }
        public bool Open(bool makeoffsettemplate)
        {
            var HB_Remote_IP = Config.Get("HB_Remote_IP");
            var HB_Remote_PORT = Config.Get<ushort>("HB_Remote_PORT");
            var HB_Local_IP = Config.Get("HB_Local_IP");
            var HB_Local_PORT = Config.Get<ushort>("HB_Local_PORT");
            int _ret = HBI_FPD_DLL.HBI_ConnectDetector(HBI_FPD_DLL._handel, HB_Remote_IP, HB_Remote_PORT, HB_Local_IP, HB_Local_PORT, 20);  //4  连接
            if (_ret != 0)
            {
                LOG.Error("HBI_ConnectDetector" + _ret.ToString());
            }
            else
            {
                GetFirmwareCfg();
                btnSetCorrectEnable();
                _ret = HBI_FPD_DLL.HBI_UpdateTriggerMode(HBI_FPD_DLL._handel, 1);
                if (_ret != 0) WriteLog("HBI_UpdateTriggerMode" + _ret.ToString());
                else WriteLog("success HBI_UpdateTriggerMode" + _ret.ToString());

                _ret = HBI_FPD_DLL.HBI_SetPreAcqTm(HBI_FPD_DLL._handel, 1000);
                if (0 != _ret)
                {
                    WriteLog("HBI_SetPreAcqTm failed!");
                    return false;
                }
            }
            return _ret == 0;
        }
        public bool Close()
        {
            int ret = HBI_FPD_DLL.HBI_DisConnectDetector(HBI_FPD_DLL._handel);
            if (ret != 0)
            {
                LOG.Error("HBI_DisConnectDetector" + ret.ToString());
            }

            return ret == 0;
        }

        /// <summary>
        /// 图像宽度
        /// </summary>
        public int ImageWidth { private set; get; } = 3072;

        /// <summary>
        /// 图像高度
        /// </summary>
        public int ImageHeight { private set; get; } = 3072;
        /// <summary>
        /// 窗宽
        /// </summary>
        public int WindowWidth { set; get; } = 65535;

        /// <summary>
        /// 窗位
        /// </summary>
        public int WindowLevel { set; get; } = 32768;
        public Bitmap Get48bImage()
        {
            if (buffer == null) return null;
            if (ImageWidth <= 0 || ImageHeight <= 0)
            {
                LOG.Info("宽高不正确,ImageWidth=" + ImageWidth + ", ImageHeight=" + ImageHeight);
                return null;
            }

            int count = ImageWidth * ImageHeight;
            byte[] gray = new byte[count * 2];
            Array.Copy(buffer, 0, gray, 0, gray.Length);

            int idx1 = 0;
            int idx2 = 0;
            int half = WindowWidth / 2;
            byte[] buff = new byte[gray.Length * 3];
            for (int i = 0; i < count; i++)
            {
                short point = BitConverter.ToInt16(gray, idx1);
                //point += 20000;

                if (point < WindowLevel - half)
                {
                    buff[idx2++] = 0;
                    buff[idx2++] = 0;
                    buff[idx2++] = 0;
                    buff[idx2++] = 0;
                    buff[idx2++] = 0;
                    buff[idx2++] = 0;
                }
                else if (point > WindowLevel + half)
                {
                    buff[idx2++] = 255;
                    buff[idx2++] = 255;
                    buff[idx2++] = 255;
                    buff[idx2++] = 255;
                    buff[idx2++] = 255;
                    buff[idx2++] = 255;
                }
                else
                {
                    byte[] bb = BitConverter.GetBytes(point);
                    buff[idx2++] = bb[0];
                    buff[idx2++] = bb[1];
                    buff[idx2++] = bb[0];
                    buff[idx2++] = bb[1];
                    buff[idx2++] = bb[0];
                    buff[idx2++] = bb[1];
                }
                idx1 += 2;
            }
            /*
            //var bufferGCHandle = GCHandle.Alloc(buffer);
            IntPtr intPtr = Marshal.UnsafeAddrOfPinnedArrayElement<byte>(buff, 0);
            Bitmap bmp = new Bitmap(ImageWidth, ImageHeight, ImageWidth * 6, System.Drawing.Imaging.PixelFormat.Format48bppRgb, intPtr);
            //bufferGCHandle.Free();
            */
            Bitmap bmp = new Bitmap(ImageWidth, ImageHeight, System.Drawing.Imaging.PixelFormat.Format48bppRgb);
            System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, ImageWidth, ImageHeight), System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
            Marshal.Copy(buff, 0, bmpData.Scan0, bmpData.Stride * ImageHeight);
            bmp.UnlockBits(bmpData);
            
            return bmp;
        }
        CancellationTokenSource WaitstopToken = new CancellationTokenSource();
        volatile bool buffgetted = false;
        int getpiccount = 0;
        public bool GetImage(int _MaxFrameCount = 3, int MaxDelay = 5000)
        {
            WaitstopToken = new CancellationTokenSource();
            buffer = null;

            //FPD_AQC_MODE stMode = new FPD_AQC_MODE();
            //stMode.aqc_mode = EnumIMAGE_ACQ_MODE.STATIC_ACQ_DEFAULT_MODE;
            //stMode.ndiscard = 0;
            //stMode.nframeid = stMode.nframesum = stMode.ngroupno = 0;
            //int ret = HBI_FPD_DLL.HBI_SingleAcquisition(HBI_FPD_DLL._handel, stMode);   //6
            //if (ret != 0) WriteLog("HBI_SingleAcquisition" + ret.ToString());
            //else WriteLog("0x03 SingleAcquisition成功");
            //if (m_pLastRegCfg.m_SysCfgInfo.m_byWorkMode != 0x01)
            //{
            //    LOG.Error("需要将触发模式改成software mode才能上图");
            //    return false;
            //}
            WriteLog("GetImage start========================");
            getpiccount = _MaxFrameCount;
            buffgetted = false;
            //int ret = HBI_FPD_DLL.HBI_Prepare(HBI_FPD_DLL._handel); //5
            //if (ret != 0) WriteLog("HBI_Prepare" + ret.ToString());
            //else WriteLog("0x02 prepare成功");

            FPD_AQC_MODE stMode = new FPD_AQC_MODE();
            stMode.aqc_mode = EnumIMAGE_ACQ_MODE.STATIC_ACQ_DEFAULT_MODE;
            stMode.ndiscard = 0;
            stMode.nframeid = 0;
            stMode.nframesum = _MaxFrameCount; // 0-表示一直采图,20表示采集20帧图结束
            stMode.ngroupno = 0;
            int ret = HBI_FPD_DLL.HBI_LiveAcquisition(HBI_FPD_DLL._handel, stMode);   //6
            if (ret != 0) WriteLog("HBI_LiveAcquisition" + ret.ToString());


            Task a = Task.Delay(MaxDelay);
            Task b = Task.Run(()=> {
                while (true)
                {
                    Thread.Sleep(100);
                    if (buffgetted)
                        break;
                }
            });

            Task.WaitAny(a, b);
            Thread.Sleep(500);
            /*
            if (buffer != null)
            {
                using (FileStream fileStream = File.OpenWrite("logs\\raw.raw"))
                {
                    fileStream.Write(buffer, 0, buffer.Length);
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }*/
            return buffer != null;
        }
        IntPtr BufferPtr;
        public EyemImage GetRawBufferHandle()
        {
            EyemImage eyemImage = new EyemImage();
            if (buffer == null)
                throw new Exception("图像buffer为空");
            if (ImageWidth <= 0 || ImageHeight <= 0)
            {
                LOG.Info("宽高不正确,ImageWidth=" + ImageWidth + ", ImageHeight=" + ImageHeight);
                throw new Exception("图像宽高不正确");
            }

            BufferPtr = Marshal.AllocHGlobal(buffer.Length);
            Marshal.Copy(buffer, 0, BufferPtr, buffer.Length);
            eyemImage.ucpImage = BufferPtr;
            eyemImage.iWidth = ImageWidth;
            eyemImage.iHeight = ImageHeight;
            eyemImage.iChannels = 1;
            eyemImage.iDepth = 2;
            return eyemImage;
        }

        public void FreeRawBufferHandle()
        {
            try
            {
                Marshal.FreeHGlobal(BufferPtr);
            }
            catch { }
        }


        /// <summary>
        /// 设置曝光时间
        /// </summary>
        /// <param name="time"></param>
        public bool SetExposureTime(int time)
        {
            WriteLog(string.Format("Set LiveAcquisition time.:[{0}]\n", time));
            int _ret = HBI_FPD_DLL.HBI_SetLiveAcquisitionTime(HBI_FPD_DLL._handel, time);
            if (0 != _ret)
            {
                LOG.Error("HBI_SetLiveAcquisitionTime failed!");
                return false;
            }
            else
            {
                WriteLog("HBI_SetLiveAcquisitionTime success!\n");
                return true;
            }
        }
        //////////////////////////////////////////////////////////////////////////////
        ////////////////////////////// 回调函数 //////////////////////////////////////
        //////////////////////////////////////////////////////////////////////////////
        private int DataCallBack(byte cmd, IntPtr buff, int len, int id)
        {
            int status = 0;
            switch (cmd)
            {
                case (byte)(eCallbackEventCommType.ECALLBACK_TYPE_NET_ERR_MSG):
                    WriteLog(string.Format("ECALLBACK_TYPE_NET_ERR_MSG,recode={0}\n", len));
                    if (len <= 0 && len >= -7)
                    {
                        if (len == 0)
                            WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,Err:网络未连接!\n");
                        else if (len == -1)
                            WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,Err:参数异常!\n");
                        else if (len == -2)
                            WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,Err:准备就绪的描述符数返回失败!\n");
                        else if (len == -3)
                            WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,Err:接收超时!\n");
                        else if (len == -4)
                            WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,Err:接收失败!\n");
                        else if (len == -5)
                            WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,Err:端口不可读!\n");
                        else if (len == -6)
                            WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,network card unusual!\n");
                        else if (len == -7)
                            WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,network card ok!\n");
                        status = (int)EFpdStatusType.FPD_STATUS_DISCONN;
                    }
                    else if (len == 1)
                    { // connect
                        WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,开始监听!\n");
                        status = (int)EFpdStatusType.FPD_STATUS_CONN;
                    }
                    else if (len == 2)
                    { // ready
                        WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,ready!\n");
                        status = (int)EFpdStatusType.FPD_STATUS_READY;
                    }
                    else if (len == 3)
                    { // busy
                        WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,busy!\n");
                        status = (int)EFpdStatusType.FPD_STATUS_BUSY;
                    }
                    else if (len == 4)
                    { // prepare
                        WriteLog("ECALLBACK_TYPE_NET_ERR_MSG,prepare!\n");
                        status = (int)EFpdStatusType.FPD_STATUS_PREPARE;
                    }
                    else
                        WriteLog(string.Format("ECALLBACK_TYPE_NET_ERR_MSG,Err:other error={0}\n", len));

                    //
                    if (status != -1)
                    {
                        ////// 更新图标
                        ////theDemo->PostMessage(WM_USER_CONNECT_STATUS_ICON, (WPARAM)status, (LPARAM)0);
                        ////// 更新状态信息
                        if (len <= 0 && len >= -6)
                        {
                            //触发断开消息
                            HBI_FPD_DLL.HBI_DisConnectDetector(HBI_FPD_DLL._handel);
                            // 更新平板断开信息
                            Close();
                            //btnDisconnect_Click(null, null);
                        }
                    }
                    break;
                case (byte)(eCallbackEventCommType.ECALLBACK_TYPE_ROM_UPLOAD):
                    WriteLog("ECALLBACK_TYPE_ROM_UPLOAD!\n");
                    // 当前反馈固件参数,转化为结构体
                    m_pLastRegCfg = (RegCfgInfo)Marshal.PtrToStructure(buff, typeof(RegCfgInfo));
                    ////#if 0
                    ////                    PrintFirmwrae(); // 打印结构体信息
                    ////#endif
                    break;
                case (byte)(eCallbackEventCommType.ECALLBACK_TYPE_SET_CFG_OK):
                    WriteLog("ECALLBACK_TYPE_SET_CFG_OK!\n");
                    break;
                //----------------图像-------------------
                case (byte)(eCallbackEventCommType.ECALLBACK_TYPE_SINGLE_IMAGE):
                case (byte)(eCallbackEventCommType.ECALLBACK_TYPE_MULTIPLE_IMAGE):
                    getpiccount--;
                    if (getpiccount > 0)
                        return 1;

#if savebmp8
                    //byte[] bytess = new byte[len];
                    //Marshal.Copy(buff, bytess, 0, len);
                    //////
                    ////WriteLog("success,ECALLBACK_TYPE_MULTIPLE_IMAGE or ECALLBACK_TYPE_SINGLE_IMAGE!\n");
                    ////if (!Directory.Exists(Directory.GetCurrentDirectory() + "\\raw_dir")) Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\raw_dir");
                    ////string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".raw";
                    ////FileStream fs = new FileStream(Directory.GetCurrentDirectory() + "\\raw_dir\\" + fileName, FileMode.CreateNew);
                    ////BinaryWriter bw = new BinaryWriter(fs);
                    ////bw.Write(bytess, 0, bytess.Length);
                    ////bw.Close();
                    ////fs.Close();
#else
                    WriteLog($"success,IMAGE!ww={m_pLastRegCfg.m_SysBaseInfo.m_sImageWidth},hh={m_pLastRegCfg.m_SysBaseInfo.m_sImageHeight},len={len}");
                    buffer = new byte[len];
                    Marshal.Copy(buff, buffer, 0, len);
                    buffgetted = true;
                    WaitstopToken.Cancel(false);
                    if (false && 0 == HBI_FPD_DLL.HBI_16UCConvertTo8UC(HBI_FPD_DLL._handel, buff, ref len))
                    {
                        WriteLog("success,ECALLBACK_TYPE_MULTIPLE_IMAGE or ECALLBACK_TYPE_SINGLE_IMAGE!\n");
                        if (!Directory.Exists(Directory.GetCurrentDirectory() + "\\raw_dir")) Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\raw_dir");
                        string fileName = Directory.GetCurrentDirectory() + "\\raw_dir\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bmp";
                        int ww = m_pLastRegCfg.m_SysBaseInfo.m_sImageWidth;
                        int hh = m_pLastRegCfg.m_SysBaseInfo.m_sImageHeight;
                        ImageWidth = ww;
                        ImageHeight = hh;
                        SaveBmp8(ww, hh, buff, fileName);
                    }
#endif
                    break;
                #region
                case (byte)(eCallbackEventCommType.ECALLBACK_TYPE_THREAD_EVENT):
                    if (len == 100)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,start recv data!\n");
                    else if (len == 101)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,end recv data!\n");
                    else if (len == 104)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,Packet Retransmission:start recv data!\n");
                    else if (len == 105)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,Frame Retransmission:start recv data!\n");
                    else if (len == 106)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,Frame loss retransmission over,end recv data!\n");
                    else if (len == 107)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,image buff is null:end recv data!\n");
                    else if (len == 108)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,Generate Offset Template:start thread!\n");
                    else if (len == 109)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,Generate Offset Template:end thread!\n");
                    else if (len == 110)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,Generate Gain Template:start thread!\n");
                    else if (len == 111)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,Generate Gain Template:end thread!\n");
                    else if (len == 112)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,offset calibrate:success!\n");
                    else if (len == 113)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,offset calibrate:failed!\n");
                    else if (len == 114)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,gain calibrate:success!\n");
                    else if (len == 115)
                        WriteLog("ECALLBACK_TYPE_THREAD_EVENT,gain calibrate:failed!\n");
                    else
                        WriteLog(string.Format("ECALLBACK_TYPE_THREAD_EVENT,Err:未知错误[{0}]\n", len));
                    break;
                #endregion

                case (byte)(eCallbackEventCommType.ECALLBACK_TYPE_GENERATE_TEMPLATE):
                    int ECALLBACK_TEMPLATE_RESULT = 0X09;
                    if (len == ECALLBACK_TEMPLATE_RESULT)
                    {
                        //if (theDoc->m_templateHwnd != NULL)
                        // PostMessage(theDoc->m_templateHwnd, WM_USER_NOTICE_TEMPLATE_TOOL, (WPARAM)nid, (LPARAM)0);
                        if (id == -1)
                            WriteLog("offset template generate failed!");
                        else if (id == 1)
                            WriteLog("offset template generate success!");
                        else if (id == -2)
                            WriteLog("gain template generate failed!");
                        else if (id == 2)
                            WriteLog("gain template generate success!");
                        else if (id == -3)
                            WriteLog("defect template generate failed!");
                        else if (id == 3)
                            WriteLog("defect template generate success!");
                        else if (id == 4)
                            WriteLog("defect acq light image success!");
                        else if (id == -4)
                            WriteLog("defect acq light image failed!");
                        else
                            WriteLog("err:other error!");

                        inState = id;
                    }
                    break;

                default:
                    WriteLog(string.Format("ECALLBACK_TYPE_THREAD_EVENT,ECALLBACK_TYPE_INVALVE,command=[{0}]\n", cmd));
                    break;
            }
            return 1;
        }

        private void GetFirmwareCfg()
        {
            m_pLastRegCfg = new RegCfgInfo();//RegCfgInfo 1024
            int _ret = Marshal.SizeOf(m_pLastRegCfg);
            _ret = HBI_FPD_DLL.HBI_GetDevCfgInfo(HBI_FPD_DLL._handel, ref m_pLastRegCfg);       //获取固件参数,连接后即可获取参数
            if (_ret != 0) { WriteLog("Error,HBI_GetDevCfgInfo" + _ret.ToString()); return; }   // WriteLog("HBI_GetDevCfgInfo:\n", img_pro.nwidth, img_pro.nheight);

            // 测试,置零,检查结果
            ushort usValue = (ushort)(((m_pLastRegCfg.m_EtherInfo.m_sDestUDPPort & 0xff) << 8) | ((m_pLastRegCfg.m_EtherInfo.m_sDestUDPPort >> 8) & 0xff));// 高低位需要转换
            WriteLog(string.Format("\tSourceIP:{0}.{1}.{2}.{3}:{4}\n",
               (int)(m_pLastRegCfg.m_EtherInfo.m_byDestIP[0]), (int)(m_pLastRegCfg.m_EtherInfo.m_byDestIP[1]),
                (int)(m_pLastRegCfg.m_EtherInfo.m_byDestIP[2]), (int)(m_pLastRegCfg.m_EtherInfo.m_byDestIP[3]), (ushort)(usValue)));
            usValue = (ushort)(((m_pLastRegCfg.m_EtherInfo.m_sSourceUDPPort & 0xff) << 8) | ((m_pLastRegCfg.m_EtherInfo.m_sSourceUDPPort >> 8) & 0xff));
            WriteLog(string.Format("\tDestIP:{0}.{1}.{2}.{3}:{4}\n", (int)(m_pLastRegCfg.m_EtherInfo.m_bySourceIP[0]), (int)(m_pLastRegCfg.m_EtherInfo.m_bySourceIP[1]),
                (int)(m_pLastRegCfg.m_EtherInfo.m_bySourceIP[2]),
                (int)(m_pLastRegCfg.m_EtherInfo.m_bySourceIP[3]), (ushort)(usValue)));

            if (m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize >= 0x01 && m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize <= 0x06)
            {
                if (m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize == 0x01)
                    WriteLog(string.Format("\tPanelSize:0x{0:X000},fpd type:4343\n", (int)m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize));
                else if (m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize == 0x02)
                    WriteLog(string.Format("\tPanelSize:0x{0:X000},fpd type:3543\n", (int)m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize));
                else if (m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize == 0x03)
                    WriteLog(string.Format("\tPanelSize:0x{0:X000},fpd type:1613\n", (int)m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize));
                else if (m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize == 0x04)
                    WriteLog(string.Format("\tPanelSize:0x{0:X000},fpd type:3030\n", (int)m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize));
                else if (m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize == 0x05)
                    WriteLog(string.Format("\tPanelSize:0x{0:X000},fpd type:2530\n", (int)m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize));
                else
                    WriteLog(string.Format("\tPanelSize:0x{0:X000},fpd type:3025\n", (int)m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize));
            }
            else
            {
                WriteLog(string.Format("\tErr:fpd property:Do not know!fpd type:0x{0:X000}\n", (int)m_pLastRegCfg.m_SysBaseInfo.m_byPanelSize));
            }
            WriteLog(string.Format("\twidth={0},hight={1}\n", m_pLastRegCfg.m_SysBaseInfo.m_sImageWidth, m_pLastRegCfg.m_SysBaseInfo.m_sImageHeight));
            WriteLog("\tdatatype is unsigned char.\n");
            WriteLog("\tdatabit is 16bits.\n");
            WriteLog("\tdata is little endian.\n");

            //cboxWorkMode.Enabled = true;

            #region workmode 等值显示
            if (m_pLastRegCfg.m_SysCfgInfo.m_byWorkMode == 0x01)//workmode
            {
                WriteLog(string.Format("\tstatic software trigger.{0:X}\n", (int)(m_pLastRegCfg.m_SysCfgInfo.m_byWorkMode)));
                //cboxWorkMode.SelectedIndex = 1;
            }
            else if (m_pLastRegCfg.m_SysCfgInfo.m_byWorkMode == 0x03)
            {
                //cboxWorkMode.SelectedIndex = 0;
                WriteLog(string.Format("\tstatic hvg trigger.{0:X000}\n", (int)(m_pLastRegCfg.m_SysCfgInfo.m_byWorkMode)));
            }
            else if (m_pLastRegCfg.m_SysCfgInfo.m_byWorkMode == 0x04)
            {
                //cboxWorkMode.SelectedIndex = 2;
                WriteLog(string.Format("\tstatic hvg trigger.{0:X000}\n", (int)(m_pLastRegCfg.m_SysCfgInfo.m_byWorkMode)));
            }
            else WriteLog(string.Format("\tother trigger mode.{0:X000}\n", (int)(m_pLastRegCfg.m_SysCfgInfo.m_byWorkMode)));

            //
            //if (m_pLastRegCfg.m_ImgCaliCfg.m_byOffsetCorrection >= 0x00 && m_pLastRegCfg.m_ImgCaliCfg.m_byOffsetCorrection <= 3)
            //    cboxOffsetEnable.SelectedIndex = m_pLastRegCfg.m_ImgCaliCfg.m_byOffsetCorrection;
            //else
            //    cboxOffsetEnable.SelectedIndex = 0;
            WriteLog(string.Format("\tOffset correction disenable.0x{0:X000}\n", (int)(m_pLastRegCfg.m_ImgCaliCfg.m_byOffsetCorrection)));

            //if (m_pLastRegCfg.m_ImgCaliCfg.m_byGainCorrection >= 0x00 && m_pLastRegCfg.m_ImgCaliCfg.m_byGainCorrection <= 2)
            //    cboxGainEnable.SelectedIndex = m_pLastRegCfg.m_ImgCaliCfg.m_byGainCorrection;
            //else
            //    cboxGainEnable.SelectedIndex = 0;
            WriteLog(string.Format("\tGain correction disenable.0x{0:X000}\n", (int)(m_pLastRegCfg.m_ImgCaliCfg.m_byGainCorrection)));

            //if (m_pLastRegCfg.m_ImgCaliCfg.m_byDefectCorrection >= 0x00 && m_pLastRegCfg.m_ImgCaliCfg.m_byDefectCorrection <= 2)
            //    cboxDefectEnable.SelectedIndex = m_pLastRegCfg.m_ImgCaliCfg.m_byDefectCorrection;
            //else
            //    cboxDefectEnable.SelectedIndex = 0;
            WriteLog(string.Format("\tDefect correction disenable.0x{0:X000}\n", (int)(m_pLastRegCfg.m_ImgCaliCfg.m_byDefectCorrection)));

            //if (m_pLastRegCfg.m_ImgCaliCfg.m_byDummyCorrection >= 0x00 && m_pLastRegCfg.m_ImgCaliCfg.m_byDummyCorrection <= 3)
            //    cboxDummyEnable.SelectedIndex = m_pLastRegCfg.m_ImgCaliCfg.m_byDummyCorrection;
            //else
            //    cboxDummyEnable.SelectedIndex = 0;
            WriteLog(string.Format("\tDummy correction disenable.0x{0:X000}\n", (int)(m_pLastRegCfg.m_ImgCaliCfg.m_byDummyCorrection)));

            //// 更新显示信息
            //PostMessage(WM_USER_CURR_FPD_INFO, (WPARAM)0, (LPARAM)0);
            #endregion
        }
        private void btnSetCorrectEnable()
        {
            WriteLog("set correct enable begin!\n");

            //m_pCorrect.bFeedbackCfg = false; // false - ECALLBACK_TYPE_SET_CFG_OK Event
            m_pCorrect.bFeedbackCfg = true;  // true  - ECALLBACK_TYPE_ROM_UPLOAD Event
            m_pCorrect.ucOffsetCorrection = (char)1;//(char)m_pLastRegCfg.m_ImgCaliCfg.m_byOffsetCorrection;
            m_pCorrect.ucGainCorrection = (char)1;//(char)m_pLastRegCfg.m_ImgCaliCfg.m_byGainCorrection;
            m_pCorrect.ucDefectCorrection = (char)m_pLastRegCfg.m_ImgCaliCfg.m_byDefectCorrection;
            m_pCorrect.ucDummyCorrection = (char)0/*cboxDummyEnable.SelectedIndex*/; // 暂时不支持

            // 打印软触发使能参数
            WriteLog("HBI_UpdateCorrectEnable\n");
            WriteLog(String.Format("\tm_pCorrect.ucOffsetCorrection={0}\n", (int)m_pCorrect.ucOffsetCorrection));
            WriteLog(String.Format("\tm_pCorrect.ucGainCorrection={0}\n", (int)m_pCorrect.ucGainCorrection));
            WriteLog(String.Format("\tm_pCorrect.ucDefectCorrection={0}\n", (int)m_pCorrect.ucDefectCorrection));
            WriteLog(String.Format("\tm_pCorrect.ucDummyCorrection={0}\n", (int)m_pCorrect.ucDummyCorrection));
            int _ret = HBI_FPD_DLL.HBI_UpdateCorrectEnable(HBI_FPD_DLL._handel, ref m_pCorrect);
            if (_ret == 0)
            {
                WriteLog("\tHBI_UpdateCorrectEnable success!\n");
            }
            else
            {
                WriteLog("HBI_UpdateCorrectEnable failed!");
            }
        }
        public static void SaveBmp8(int width, int height, IntPtr buff, string savePath)
        {
            int nwidth = width;
            int nheight = height;
            short fiBitCount = 8;
            int iLineByteCnt = (((width * fiBitCount) + 31) >> 5) << 2;
            int dataSize = iLineByteCnt * height;

            //byte[] fsbytes = new byte[14];//文件头
            //byte[] fibytes = new byte[40];//信息头
            byte[] pbytes = new byte[256 * 4];//调色板
            byte[] bfType = new byte[2];
            bfType[0] = (int)'B';
            bfType[1] = (int)'M';
            byte[] bfSize = BitConverter.GetBytes(dataSize + 14 + 40 + 1024);
            byte[] bfReserved = new byte[4] { 0, 0, 0, 0 };
            byte[] biOffbits = BitConverter.GetBytes(1024 + 14 + 40);


            byte[] biSize = BitConverter.GetBytes(40);
            byte[] biWidth = BitConverter.GetBytes(width);
            byte[] biHeight = BitConverter.GetBytes(-1 * height);
            byte[] biPlanes = new byte[] { 0, 1 };
            byte[] biBitCount = BitConverter.GetBytes(fiBitCount);
            byte[] biCompression = new byte[] { 0, 0, 0, 0 };
            byte[] biSizeImage = new byte[] { 0, 0, 0, 0 };
            byte[] biXYPelsPerMeter = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] biClrUsed = BitConverter.GetBytes(256);
            byte[] biClrImportant = BitConverter.GetBytes(256);

            //调色版
            for (int i = 0; i < 256; i++)
            {
                pbytes[i * 4] = (byte)i;
                pbytes[i * 4 + 1] = (byte)i;
                pbytes[i * 4 + 2] = (byte)i;
                pbytes[i * 4 + 3] = 255;
            }

            byte[] data = new byte[dataSize];
            Marshal.Copy(buff, data, 0, width * height);

            using (FileStream fileStream = File.OpenWrite(savePath))
            {
                fileStream.Write(bfType, 0, 2);
                fileStream.Write(bfSize, 0, 4);
                fileStream.Write(bfReserved, 0, 4);
                fileStream.Write(biOffbits, 0, 4);
                //
                fileStream.Write(biSize, 0, 4);
                fileStream.Write(biWidth, 0, 4);
                fileStream.Write(biHeight, 0, 4);
                fileStream.Write(biPlanes, 0, 2);
                fileStream.Write(biBitCount, 0, 2);
                fileStream.Write(biCompression, 0, 4);
                fileStream.Write(biSizeImage, 0, 4);
                fileStream.Write(biXYPelsPerMeter, 0, 8);
                fileStream.Write(biClrUsed, 0, 4);
                fileStream.Write(biClrImportant, 0, 4);
                //
                fileStream.Write(pbytes, 0, pbytes.Length);
                //
                fileStream.Write(data, 0, data.Length);
                //
                fileStream.Close();
                fileStream.Dispose();
            }
        }
        /// <summary>
        /// 加载本地RAW图片,64字节头
        /// </summary>
        /// <param name="filePath">图片路径</param>
        public void LoadRAW(string filePath)
        {
            buffer = System.IO.File.ReadAllBytes(filePath);

        }

        /// <summary>
        /// 保存本地RAW图片
        /// </summary>
        /// <param name="filePath">图片路径</param>
        public void SaveRAW(string filePath)
        {
            if (buffer == null) return;

            System.IO.File.WriteAllBytes(filePath, buffer);


        }

        int inState = int.MinValue;
        /// <summary>
        /// 校准平板
        /// </summary>
        /// <param name="mode">1:暗场校准,2亮场校准</param>
        /// <returns></returns>
        public async Task<bool> GenerateTemplate(int mode)
        {
            inState = int.MinValue;
            EnumIMAGE_ACQ_MODE tmode;
            if (mode == 1)
            {
                tmode = EnumIMAGE_ACQ_MODE.OFFSET_TEMPLATE_MODE;

            }
            else
            {
                tmode = EnumIMAGE_ACQ_MODE.GAIN_TEMPLATE_MODE;
            }

            int ret = HBI_FPD_DLL.HBI_ImmediateGenerateTemplate(HBI_FPD_DLL._handel, tmode);
            WriteLog($"ret:{ret},tmode:{tmode}");
            if (ret != 0)
                return false;
            Task a = Task.Delay(60*1000);
            Task b = Task.Run(() => {
                while (true)
                {                    
                    Thread.Sleep(100);
                    //WriteLog($"inState:{inState}");
                    if (inState==2 || inState==1)
                        break;
                }
            });
            var result = await Task.WhenAny(a, b);
            if (result == a) {
                WriteLog($"{tmode}: time out");
                return false;
            }
            return true;
        }

        void WriteLog(string log) {
            LOG.Info(log);
        }
    }
}