Form1.cs 34.2 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 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
using CodeLibrary;
using Common;
using ConfigHelper;
using DeviceLibrary;
using OnlineStore;
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.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace TheMachine
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            CheckForIllegalCrossThreadCalls = false;
            crc.OpenResourceLog = true;
            InitializeComponent();
            this.FormClosing += Form1_FormClosing;
            this.Text = Setting_Init.App_Title + " " + Setting_Init.App_CID;
            crc.GetLanguageEvent += Crc_GetLanguageEvent;
            crc.LanguageChangeEvent += Crc_LanguageChangeEvent;
            crc.CurrLanguage = Crc_GetLanguageEvent();
            t1.Interval = 1000;
            t1.Tick += T1_Tick;
            t1.Start();
            GC.KeepAlive(t1);
        }

        private void Crc_LanguageChangeEvent(object sender, EventArgs e)
        {
            if (RobotManage.IsConfigMode)
            {
                showDebugTabPages(true);
            }

            //if (tabc.TabCount > tabpagecount)
            //    addTablePage();


            LanguageProcess();
        }

        private string Crc_GetLanguageEvent()
        {
            return Setting_Init.App_Default_Language;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
            }
        }

        LogControl lc = new LogControl();
        IOControls ioc = new IOControls();
        AxisControl ac = new AxisControl();
        uc_boxdebug bd = new uc_boxdebug();
        SettingControl sc = new SettingControl();

        readonly System.Windows.Forms.Timer t1 = new System.Windows.Forms.Timer();
        private void Form1_Load(object sender, EventArgs e)
        {
            this.Width = Screen.PrimaryScreen.WorkingArea.Width;//获取主显⽰设备的桌⾯宽度
            this.Height = Screen.PrimaryScreen.WorkingArea.Height;//获取主显⽰设备的桌⾯⾼度

            if (this.Width > 1366)
                this.Width = 1366;
            if (this.Height > 900)
                this.Height = 900;

            List<CodeInfo> codeInfos = new List<CodeInfo>();
            //codeInfos.Add(new CodeInfo("", 528, 406));
            codeInfos.Add(new CodeInfo("", 925, 520));
            //codeInfos.Add(new CodeInfo("", 564, 684));

            btn_run.Enabled = false;
            //btn_stop.Enabled = false;
            #region 报警信息listview初始化
            listView1.View = View.Details;
            ColumnHeader emptycol = new ColumnHeader();
            emptycol.Text = "";
            emptycol.Width = 0;
            ColumnHeader msgcol = new ColumnHeader();
            msgcol.Text = $"信息";
            msgcol.Width = 530;
            ColumnHeader timecol = new ColumnHeader();
            timecol.Text = $"时间";
            timecol.Width = 180;
            listView1.Columns.Add(emptycol);
            listView1.Columns.Add(timecol);
            listView1.Columns.Add(msgcol);
            listView1.ColumnWidthChanging += listView_ColumnWidthChanging;
            #endregion

            #region 状态信息listview初始化
            stateView.View = View.Details;
            ColumnHeader c1 = new ColumnHeader();
            c1.Text = "";
            c1.Width = 0;
            ColumnHeader c2 = new ColumnHeader();
            c2.Text = $"模块";
            c2.Width = 120;
            ColumnHeader c3 = new ColumnHeader();
            c3.Text = $"步骤";
            c3.Width = 120;
            ColumnHeader c4 = new ColumnHeader();
            c4.Text = $"信息";
            c4.Width = 370;

            stateView.Columns.Add(c1);
            stateView.Columns.Add(c2);
            stateView.Columns.Add(c3);
            stateView.Columns.Add(c4);
            stateView.ColumnWidthChanging += listView_ColumnWidthChanging;
            #endregion

            LogUtil.info("开始初始化");
            cb_EnableBuzzer.Checked = Setting_Init.Enable_Buzzer;
            AlarmBuzzer.BuzzerStateChange += AlarmBuzzer_BuzzerStateChange;
            RobotManage.DataInitEvent += RobotManage_DataInitEvent;
            RobotManage.LoadFinishEvent += RobotManage_LoadFinishEvent;
            if (!Setting_Init.Disable_LogWindow)
                AddForm("tab_log", crc.GetString(L.tab_log, "日志"), lc);

            RobotManage.UserPauseSet += RobotManage_UserPauseSet;

            CodeManager.camera_event += CameraB_camera_event;
            IntPtr camAIntptr = pictureBox2.Handle;
            var loadtask = Task.Run(() =>
            {
                RobotManage.Init();
            });
            ListViewItem lvi = new ListViewItem(new string[] { "", DateTime.Now.ToString(), crc.GetString(L.device_initializing, "设备加载中,请稍后...") });
            lvi.ForeColor = Color.DarkGreen;
            listView1.Items.Add(lvi);
            //while (!loadtask.IsCompleted) {
            //    Thread.Sleep(100);
            //    Application.DoEvents();
            //}
            LoadWindow();
            tabc.Enabled = false;
            pnl.Enabled = false;
        }
        private void CameraB_camera_event(object sender, Bitmap e)
        {
            this.Invoke((EventHandler<Bitmap>)delegate
            {
                pictureBox2.Visible = true;
                pictureBox2.Image = DeepClone(e);
            }, sender, e);
        }
        private void AlarmBuzzer_BuzzerStateChange(object sender, bool e)
        {
            this.Invoke((EventHandler<bool>)delegate
            {
                btn_PauseBuzzer.Visible = e;
            }, sender, e);
        }

        private void listView_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
        {
            e.NewWidth = (sender as ListView).Columns[e.ColumnIndex].Width;
            e.Cancel = true;
        }
        const int tabpagecount = 4;
        void addTablePage()
        {
            //this.SuspendLayout();
            AddForm("tab_io", crc.GetString(L.tab_io, "IO调试"), ioc);
            AddForm("tab_axis", crc.GetString(L.tab_axis, "伺服调试"), ac);
            AddForm("tab_store", crc.GetString(L.tab_store, "库位调试"), bd);
            AddForm("tab_setting", crc.GetString(L.tab_setting, "相关设置"), sc);
            //this.ResumeLayout(true);
            //this.PerformLayout();
            crc.LanguageProcess(this);
        }

        private void T1_Tick(object sender, EventArgs e)
        {
            SetState(MoveInfo.List);
        }

        void SetState(List<MoveInfo> moveInfoList)
        {
            if (RobotManage.mainMachine == null)
                return;

            this.SuspendLayout();
            stateView.Items.Clear();
            foreach (MoveInfo moveInfo in moveInfoList)
            {
                if (moveInfo.Equals(RobotManage.mainMachine.ResetMoveInfo) && RobotManage.mainMachine.runStatus != RunStatus.HomeReset)
                {
                    continue;
                }
                else if (moveInfo.Equals(RobotManage.mainMachine.AIOTMoveInfo) && !RobotManage.mainMachine.AutoInOutTest)
                {
                    continue;
                }
                ListViewItem lvi = new ListViewItem(new string[] { "", moveInfo.Name, moveInfo.MoveStep.ToString(), moveInfo.GetStateStr() });
                stateView.Items.Add(lvi);
            }
            this.ResumeLayout(true);

        }

        List<TabPage> tabPages = new List<TabPage>();
        void showDebugTabPages(bool show)
        {
            if (this.InvokeRequired)
            {
                this.Invoke((EventHandler)delegate
                {
                    showDebugTabPages(show);
                });
                return;
            }
            foreach (var item in tabPages)
            {
                if (show)
                { 
                    item.Text = crc.GetString(item.Name, item.Text);
                    item.Parent = tabc;
                }
                else
                {
                    item.Parent = null;
                }
            }
            crc.LanguageProcess(this);
        }

        private void AddForm(string id, string text, UserControl form)
        {
            foreach (TabPage tp in tabc.TabPages)
            {
                if (tp.Name == id)
                {
                    tp.Text = text;
                    return;
                }
            }
            TabPage lineTabPage = new TabPage(text);
            lineTabPage.Name = id;
            Panel linePan = new Panel();
            linePan.Dock = DockStyle.Fill;
            linePan.AutoScroll = true;
            lineTabPage.Controls.Add(linePan);
            linePan.Controls.Add(form);
            form.Dock = DockStyle.Fill;
            linePan.Anchor = ((AnchorStyles)((AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left)));
            form.Anchor = ((AnchorStyles)((AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left)));
            form.Show();
            tabPages.Add(lineTabPage);
            tabc.TabPages.Add(lineTabPage);

        }

        private void 启用调试模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!RobotManage.IsConfigMode && !FrmPassCheck.CheckPassword())
                return;
            RobotManage.IsConfigMode = RobotManage.IsConfigMode ? false : true;

            (sender as ToolStripMenuItem).Text = !RobotManage.IsConfigMode ? crc.GetString(L.enable_config_mode, "启用配置模式") : crc.GetString(L.disable_config_mode, "停用配置模式");
            crc.LanguageChange();
            showDebugTabPages(RobotManage.IsConfigMode);
            this.WindowState = FormWindowState.Maximized;
            //if (RobotManage.IsConfigMode)
            //{
            //    //RobotManage.Config = (Robot_Config)CSVConfigReader.LoadConfig(RobotManage.Config);
            //    // addTablePage();
            //    //RobotManage.LoadDebug();
            //}
            //else
            //{
            //    var tc = tabc.TabPages.Count;
            //    for (int i = 1; i <= tabpagecount; i++)
            //    {
            //        tabc.TabPages[tc - i].Parent = null;
            //    }
            //}
        }

        public delegate void setmsgdelegate(List<Msg> msgs);
        private void MainMachine_ProcessMsgEvent(List<Msg> msgs)
        {
            if (msgs == null || msgs.Count == 0)
                return;
            try
            {
                var d = new setmsgdelegate(SetMsg);
                this.Invoke(d, msgs);
            }
            catch (Exception e)
            {
                LogUtil.info("MainMachine_ProcessMsgEvent:" + e.ToString());
            }
        }
        private void RobotManage_DataInitEvent(bool state, string msg)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke((EventHandler)delegate
                    {
                        RobotManage_DataInitEvent(state, msg);
                    });
                    return;
                }
            }
            catch(Exception ex)
            {
                LogUtil.error($"RobotManage_DataInitEvent,{state},{msg}",ex);
            }

            ioc.Config = RobotManage.Config;
            bd.Config = RobotManage.Config;

            addTablePage();
        }
        private void RobotManage_LoadFinishEvent(bool state, string msg)
        {
            if (this.InvokeRequired)
            {
                this.Invoke((EventHandler)delegate
                {
                    RobotManage_LoadFinishEvent(state, msg);
                });
                return;
            }
            showDebugTabPages(false);
            启用调试模式ToolStripMenuItem.Enabled = true;
            pnl.Enabled = true;
            tabc.Enabled = true;
            LogUtil.info($"初始化完成:{state},{msg}");
            if (state)
            {
                CodeManager.LoadCamera(true);
                foreach (var cameraName in CodeManager.hikNameList)
                {
                    try
                    {
                        Camera._cam.CaptureOnImage(cameraName, out Bitmap bmp, true);
                        LogUtil.error($"测试拍照:{cameraName}完成");
                        bmp?.Dispose();
                    }
                    catch (Exception ex)
                    {
                        LogUtil.error($"测试拍照错误:{cameraName}:" + ex.ToString());
                    }
                }
                btn_run.Enabled = true;
                //btn_stop.Enabled = true;
                RobotManage.mainMachine.ProcessMsgEvent += MainMachine_ProcessMsgEvent;
            }
            var lm = new List<Msg>();
            foreach (string ms in msg.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var m = new Msg();
                m.datetime = DateTime.Now;
                m.msgtxt = ms;
                m.msgLevel = state ? MsgLevel.info : MsgLevel.warning;
                lm.Add(m);
            }
            SetMsg(lm);
            WindowManager.Show();
            RobotManage.mainMachine.UploadVideoProcessInit();
        }
        object showMsgLoc = new object();
        private List<Msg> allMsgList = new List<Msg>();
        //void SetMsg(List<Msg> msgs)
        //{
        //    if (Monitor.TryEnter(showMsgLoc))
        //    {
        //        try
        //        {

        //            if (msgs == null || msgs.Count <= 0)
        //            {
        //                if (allMsgList.Count <= 0)
        //                {
        //                    return;
        //                }
        //                msgs = new List<Msg>();
        //            }
        //            this.SuspendLayout();
        //            listView1.Items.Clear();
        //            msgs.Sort((a, b) =>
        //            {
        //                if (a.msgLevel == b.msgLevel)
        //                    return 0;
        //                if (a.msgLevel == MsgLevel.alarm)
        //                    return -1;
        //                if (b.msgLevel == MsgLevel.alarm)
        //                    return 1;
        //                if (a.msgLevel == MsgLevel.warning)
        //                    return b.msgLevel == MsgLevel.info ? -1 : -1;
        //                if (a.msgLevel == MsgLevel.info)
        //                    return 1;
        //                return 0;
        //            });

        //            try
        //            {
        //                allMsgList.AddRange(msgs);
        //                int maxCount = 5;
        //                if (msgs.Count > maxCount)
        //                {
        //                    maxCount = msgs.Count;
        //                }
        //                if (allMsgList.Count > maxCount)
        //                {
        //                    allMsgList.RemoveRange(0, allMsgList.Count - maxCount);
        //                }

        //            }
        //            catch (Exception ex)
        //            {
        //                LogUtil.error(" SetMsg 出错:" + ex.ToString());
        //                allMsgList = new List<Msg>(msgs);
        //            } 
        //            foreach (Msg msg in allMsgList)
        //            {
        //                if (string.IsNullOrEmpty(msg.msgtxt) || msg.datetime == null)
        //                    continue;

        //                List<Msg> lists = (from m in msgs where m.msgtxt.Equals(msg.msgtxt) select m).ToList();

        //                if (lists.Count <= 0 && msg.msgLevel != MsgLevel.info)
        //                {
        //                    //如果已经超时2分钟,不显示
        //                    TimeSpan span = DateTime.Now - msg.datetime;
        //                    if (span.TotalMinutes > 2)
        //                    {
        //                        continue;
        //                    }
        //                }
        //                ListViewItem lvi = new ListViewItem(new string[] { "", msg.datetime.ToString(), msg.msgtxt });
        //                if (msg.msgLevel == MsgLevel.info)
        //                    lvi.ForeColor = Color.DarkGreen;
        //                else
        //                    lvi.ForeColor = Color.Red;
        //                listView1.Items.Add(lvi);
        //                if (lists.Count > 0)
        //                {
        //                    if (msg.errInfo == ErrInfo.X09_BoxNotDetect)
        //                    {
        //                        if (btn_IgnoreX09.Visible) continue;
        //                        btn_IgnoreX09.Invoke(new Action(() =>
        //                        {
        //                            btn_IgnoreX09.Visible = true;
        //                        }));
        //                    }
        //                    else if (msg.errInfo == ErrInfo.X09_Clear)
        //                    {
        //                        if (!btn_IgnoreX09.Visible) continue;
        //                        btn_IgnoreX09.Invoke(new Action(() =>
        //                        {
        //                            btn_IgnoreX09.Visible = false;
        //                        }));
        //                    }
        //                    else if (msg.errInfo == ErrInfo.RunBtn)// || msg.errInfo == ErrInfo.ResetBtn)
        //                    {
        //                        Task.Run(() =>
        //                        {
        //                            Task.Delay(1000).Wait();
        //                            if (!RobotManage.isRunning || RobotManage.IsUserPause)
        //                                btn_run_Click(this, EventArgs.Empty);
        //                        });

        //                    }
        //                    else if (msg.errInfo == ErrInfo.SuddenStop)
        //                    {
        //                        Task.Run(() =>
        //                        {
        //                            if (RobotManage.isRunning)
        //                                btn_stop_Click(this, EventArgs.Empty);
        //                        });

        //                    }
        //                }
        //            }
        //            this.ResumeLayout(true);
        //        }
        //        finally
        //        { Monitor.Exit(showMsgLoc); }
        //    }

        //}
        void SetMsg(List<Msg> msgs)
        {
            if (Monitor.TryEnter(showMsgLoc))
            {
                try
                {
                    this.SuspendLayout();
                    listView1.Items.Clear();
                    foreach (Msg msg in msgs)
                    {
                        if (string.IsNullOrEmpty(msg.msgtxt) || msg.datetime == null)
                            continue;

                        ListViewItem lvi = new ListViewItem(new string[] { "", msg.datetime.ToString(), msg.msgtxt });
                        if (msg.msgLevel == MsgLevel.info)
                            lvi.ForeColor = Color.DarkGreen;
                        else
                            lvi.ForeColor = Color.Red;
                        listView1.Items.Add(lvi);
                        if (msg.errInfo == ErrInfo.X09_BoxNotDetect)
                        {
                            RobotManage.mainMachine.ShowIgnoreFixtureAlarm = true;
                            if (btn_IgnoreX09.Visible) continue;
                            btn_IgnoreX09.Invoke(new Action(() =>
                            {
                                btn_IgnoreX09.Visible = true;
                            }));
                            
                        }
                        else if (msg.errInfo == ErrInfo.X09_Clear)
                        {
                            RobotManage.mainMachine.ShowIgnoreFixtureAlarm = false;
                            if (!btn_IgnoreX09.Visible) continue;
                            btn_IgnoreX09.Invoke(new Action(() =>
                            {
                                btn_IgnoreX09.Visible = false;
                            }));
                        }
                        else if (msg.errInfo == ErrInfo.RunBtn)// || msg.errInfo == ErrInfo.ResetBtn)
                        {
                            Task.Run(() =>
                            {
                                Task.Delay(1000).Wait();
                                if (!RobotManage.isRunning || RobotManage.IsUserPause)
                                    btn_run_Click(this, EventArgs.Empty);
                            });

                        }
                        else if (msg.errInfo == ErrInfo.SuddenStop)
                        {
                            Task.Run(() =>
                            {
                                if (RobotManage.isRunning)
                                    btn_stop_Click(this, EventArgs.Empty);
                            });

                        }
                    }
                    this.ResumeLayout(true);
                }
                finally
                { Monitor.Exit(showMsgLoc); }
            }

        }
        private void btn_run_Click(object sender, EventArgs e)
        {
            if (!RobotManage.isRunning)
            {
                if (RobotManage.mainMachine.IOValue(IO_Type.SuddenStop_BTN).Equals(IO_VALUE.LOW))
                {
                    Msg.add(crc.GetString(L.device_suddenstop_cant_start, "急停中,无法启动"), MsgLevel.warning);
                    MainMachine_ProcessMsgEvent(Msg.get());
                    return;
                }
                btn_run.Enabled = false;
                LogUtil.info("用户按下启动按钮");
                RobotManage.Start();
            }
            else if (!RobotManage.IsUserPause)
            {
                RobotManage.UserPause(crc.GetString("Res0023.aff4439b","用户按下启动按钮"), true);
            }
            else if (RobotManage.IsUserPause)
            {
                RobotManage.UserPause(crc.GetString("Res0023.aff4439b","用户按下启动按钮"), false);
            }
        }
        private void RobotManage_UserPauseSet(object sender, bool e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke((EventHandler<bool>)delegate
                {
                    RobotManage_UserPauseSet(sender, e);
                }, sender, e);
                return;
            }
            btn_run.Enabled = true;
            if (RobotManage.isRunning)
            {
                btn_stop.Enabled = true;
            }
            else
            {
                btn_stop.Enabled = false;
                btn_run.Text = crc.GetString(L.start, "启动");
                btn_run.BackColor = Color.Transparent;
                cb_IgnoreSafecheck.Enabled = true;
                return;
            }
            if (e)
            {
                (btn_run as Button).Text = crc.GetString(L.device_resume, "恢复运行");
                (btn_run as Button).BackColor = Color.LightGreen;
                cb_IgnoreSafecheck.Enabled = true;
            }
            else
            {
                (btn_run as Button).Text = crc.GetString(L.device_pause, "暂停运行");
                (btn_run as Button).BackColor = Color.Yellow;
                cb_IgnoreSafecheck.Enabled = false;
            }

        }
        private void btn_stop_Click(object sender, EventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke((EventHandler)delegate
                {
                    btn_stop_Click(sender, e);
                }, sender, e);
                return;
            }
            if (!btn_stop.Enabled)//已经停止,无需重复调用停止
                return;
            btn_stop.Enabled = false;
            LogUtil.info("用户按下停止按钮");
            Task.Run(() => { RobotManage.Stop(); });

            //btn_run.Text = crc.GetString(L.start, "启动");
            //btn_run.BackColor = Color.Transparent;
            //cb_IgnoreSafecheck.Enabled = true;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (RobotManage.isRunning)
            {
                MessageBox.Show(crc.GetString(L.device_isrunning_cant_exit, "机器尚在运行,不能退出,请先停止运行."));
            }
            else
            {
                RobotManage.Stop();
                RobotManage.ShutDown();
                Thread.Sleep(2000);
                Application.Exit();
            }
        }

        private void cb_IgnoreSafecheck_CheckedChanged(object sender, EventArgs e)
        {
            RobotManage.IgnoreSafecheck((sender as CheckBox).Checked);
        }

        private void cb_IgnoreGratingSignal_CheckedChanged(object sender, EventArgs e)
        {
            RobotManage.IgnoreGratingSignal((sender as CheckBox).Checked);
        }

        private void 二维码识别调试ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (RobotManage.mainMachine.IsScanRunning())
            //{
            //    MessageBox.Show("扫码还没完成,无法打开调试!请稍后再试.");
            //    return;
            //}

            IOManager.IOMove(IO_Type.Camera_Led, IO_VALUE.HIGH);
            if (Camera._cam != null)
            {
                Camera._cam.CloseAll();
            }
            CodeLibrary.CodeResourceControl.GetLanguageEvent += Crc_GetLanguageEvent;
            CodeLibrary.FrmCodeDecode frm = new CodeLibrary.FrmCodeDecode();
            frm.CurrLanguage = Crc_GetLanguageEvent();

            frm.chbZxing.Checked = false;
            try
            {
                frm.ShowDialog();
                frm.Dispose();
            }
            catch { }

            //IOManager.IOMove(IO_Type.Camera_Led, IO_VALUE.LOW);
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox1 aboutBox1 = new AboutBox1();
            aboutBox1.ShowDialog();
        }

        private void cb_EnableBuzzer_CheckedChanged(object sender, EventArgs e)
        {
            Setting_Init.Enable_Buzzer = cb_EnableBuzzer.Checked;
            AlarmBuzzer.Enable = cb_EnableBuzzer.Checked;
        }

        private void btn_PauseBuzzer_Click(object sender, EventArgs e)
        {
            LogUtil.info("用户点击 本次关闭蜂鸣器");
            AlarmBuzzer.MuteOnce();
        }

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            var obj = sender as PictureBox;
            if (obj.Dock == DockStyle.Fill)
                obj.Dock = DockStyle.None;
            else
            {
                obj.BringToFront();
                obj.Dock = DockStyle.Fill;
            }
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            var obj = sender as PictureBox;
            if (obj.Dock == DockStyle.Fill)
                obj.Dock = DockStyle.None;
        }


        private void btn_IgnoreX09_Click(object sender, EventArgs e)
        {
            DialogResult rtn = MessageBox.Show(crc.GetString("confirm_no_reel_in_com", "请确保料盘已从库位中取出") + "!", crc.GetString("title", "Warning"), MessageBoxButtons.YesNo);
            if (rtn.Equals(DialogResult.Yes))
            {
                RobotManage.mainMachine.IgnoreX09();
                btn_IgnoreX09.Visible = false;
            }

        }

        private void btn_releasestring_Click(object sender, EventArgs e)
        {
            if (RobotManage.mainMachine.StringMoveInfo.MoveStep == MoveStep.Wait)
            {
                MessageBox.Show(crc.GetString(L.safty_releaseed_string, "料串已是释放状态"));
                return;
            }
            else if (RobotManage.mainMachine.StringMoveInfo.MoveStep >= MoveStep.StringOut_01)
            {
                MessageBox.Show(crc.GetString(L.safty_releaseing_string, "正在执行料串释放"));
                return;
            }

            Task.Run(() =>
            {
                int timeout = 2 * 60;
                while (timeout > 0)
                {
                    Task.Delay(500).Wait();
                    timeout--;
                    if (timeout % 2 == 0)
                    {
                        Invoke((EventHandler)delegate
                        {
                            (sender as Button).Text = crc.GetString(L.safty_releaseing_string, $"正在执行料串释放") + $"({timeout / 2})";
                        });
                    }
                    var step = RobotManage.mainMachine.StringMoveInfo.MoveStep;
                    var clampstep = RobotManage.mainMachine.ClampMoveInfo.MoveStep;
                    if (step == MoveStep.StringReadyGet && clampstep >= MoveStep.ReelClamp_GetHeight)
                    {
                        RobotManage.mainMachine.StringMoveInfo.NextMoveStep(MoveStep.StringOut_01);
                        break;
                    }
                    if (step == MoveStep.StringReadyPut)
                    {
                        RobotManage.mainMachine.StringMoveInfo.NextMoveStep(MoveStep.StringOut_01);
                        break;
                    }
                }

                Invoke((EventHandler)delegate
                {
                    //btn_releaseleftshelf.BackColor = Color.Transparent;
                    (sender as Button).Text = crc.GetString(L.safty_release_string, "安全释放料串");
                });
            });
        }
        [HandleProcessCorruptedStateExceptions]
        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)
            {
                LogUtil.info("GetStringCenterA" + e.ToString());
                return default;
            }
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            LanguageProcess();
        }
        void LanguageProcess()
        {
            crc.LanguageProcess(this, this.GetType().Name);
            crc.ProcessListItem(menuStrip1.Items, "menuStrip1");

            listView1.Columns[1].Text = crc.GetString(L.table_datetime, "时间");
            listView1.Columns[2].Text = crc.GetString(L.table_info, "信息");

            stateView.Columns[1].Text = crc.GetString(L.table_module, "模块");
            stateView.Columns[2].Text = crc.GetString(L.table_step, "步骤");
            stateView.Columns[3].Text = crc.GetString(L.table_info, "信息");

            启用调试模式ToolStripMenuItem.Text = !RobotManage.IsConfigMode ? crc.GetString(L.enable_config_mode, "启用配置模式") : crc.GetString(L.disable_config_mode, "停用配置模式");
            btn_releasestring.Text = crc.GetString(L.safty_release_string, "安全释放料串");

            btn_run.Text = crc.GetString(L.start, "启动");

            if (RobotManage.isRunning)
            {
                RobotManage_UserPauseSet(null, RobotManage.IsUserPause);
            } 
        }

        private void 简体中文ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Setting_Init.App_Default_Language = crc.China;
            crc.LanguageChange();
        }

        private void 日本语ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Setting_Init.App_Default_Language = crc.Japan;
            crc.LanguageChange();
        }

        private void englishToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Setting_Init.App_Default_Language = crc.English;
            crc.LanguageChange();
        }
        #region 窗口管理
        void LoadWindow()
        {
            var ipcamera = new WindInfo() { Parent = panelVideo, Name = WindInfo.IPCamera };

            WindowManager.windInfos.Add(ipcamera);
            WindowManager.Start();
        }
        /// <summary>
        /// 销毁窗口
        /// </summary>
        /// <param name="e"></param>
        protected override void OnHandleDestroyed(EventArgs e)
        {
            foreach (var wnd in WindowManager.windInfos)
            {
                if (wnd.WindowHandle != IntPtr.Zero)
                {
                    WindowUtil.PostMessage(wnd.WindowHandle, WindowUtil.WM_CLOSE, 0, 0);
                    // Delay for it to get the message
                    System.Threading.Thread.Sleep(1000);

                    // Clear internal handle
                    wnd.WindowHandle = IntPtr.Zero;
                }
            }
            base.OnHandleDestroyed(e);
        }
        #endregion

        private void panelVideo_DoubleClick(object sender, EventArgs e)
        {
            var obj = sender as Panel;
            if (obj.Dock == DockStyle.Fill)
                obj.Dock = DockStyle.None;
            else
            {
                obj.BringToFront();
                obj.Dock = DockStyle.Fill;
            }
        }

        private void panelVideo_MouseDown(object sender, MouseEventArgs e)
        {
            var obj = sender as Panel;
            if (obj.Dock == DockStyle.Fill)
                obj.Dock = DockStyle.None;
        }

        private void tabc_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabc.SelectedIndex == 1)
            {
                WindowManager.Show();
                panelVideo.Refresh();
            }
            //else
            //{
            //    WindowManager.Hide();
            //    panelVideo.Refresh();
            //}
        }
    }
}