FrmRobotMain.cs 44.4 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 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
using CodeLibrary;
using DeviceLib;
using log4net;
using OnlineStore.Common;
using OnlineStore.DeviceLibrary;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OnlineStore.AutoCountClient
{
    internal partial class FrmRobotMain : Form
    {
        private FrmLearning frmLearn = null;
        //   internal static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private RobotBean robot = null;
        private List<TabPage> tabPageList = new List<TabPage>();
        private bool LoadOk = false;
        private System.Timers.Timer startTimer = null;
        internal FrmRobotMain()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            startTimer = new System.Timers.Timer();
            startTimer.Interval = 1000;
            startTimer.Enabled = false;
            startTimer.AutoReset = false;
        }

        private void LoadStoreData()
        {
            robot = RobotManager.robot;
            if (robot == null)
            {
                Application.Exit();
            }
            //AddLearnForm();

            FrmInputEquip frm1 = new FrmInputEquip(robot.inputEquip);
            AddForm(" " + robot.inputEquip.Name + " ", frm1);

            FrmXRay test = new FrmXRay(robot.XrayBean);
            AddForm(" " + robot.XrayBean.Name + " ", test);

            FrmOutputEquip frm2 = new FrmOutputEquip(robot.outputEquip);
            AddForm(" " + robot.outputEquip.Name + " ", frm2);
            frm2.resetButtonClick += Frm2_resetButtonClick;
            robot.XrayBean.GetImageEvent += EquipBean_GetImageEvent;


        }

        private void Frm2_resetButtonClick()
        {
            robot.XrayBean.MoveStop = true;
            robot.inputEquip.MoveStop = true;
        }

        private void AddForm(string text, Form form)
        {
            text = text.PadLeft(10, ' ');
            TabPage lineTabPage = new TabPage(text);
            // lineTabPage.AutoScroll = true;
            lineTabPage.Tag = robot;
            Panel linePan = new Panel();
            linePan.Dock = DockStyle.Fill;
            linePan.AutoScroll = true;
            lineTabPage.Controls.Add(linePan);
            form.FormBorderStyle = FormBorderStyle.None;
            form.TopLevel = false;
            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();
            tabPageList.Add(lineTabPage);
            tabControl1.Controls.Add(lineTabPage);
        }
        //private void AddLearnForm( )
        //{
        //    frmLearn = new FrmLearning();  
        //    frmLearn.FormBorderStyle = FormBorderStyle.None;
        //    frmLearn.TopLevel = false;
        //    frmLearn.Dock = DockStyle.Fill; 
        //    frmLearn.Anchor = ((AnchorStyles)((AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left)));
        //    panLearn.Controls.Add(frmLearn);
        //    frmLearn.Show(); 
        //}
        private void FrmMain_Load(object sender, EventArgs e)
        {
            //string fileP = Application.StartupPath + @"\XRAY\tif\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
            FrmBase.GetVersion(true);
            if (!RobotManager.Init())
            {
                LogUtil.error("加载配置失败,直接退出程序");
                Application.Exit();
            }
            FrmDevicePause.Init(this);
            formLineStatus(false);
            string title = ConfigAppSettings.GetValue(Setting_Init.App_Title);
            this.Text = title;
            this.notifyIcon1.Text = title;
            int autoValue = ConfigAppSettings.GetIntValue(Setting_Init.App_AutoRun);
            if (autoValue.Equals(1))
            {
                开机自动启动ToolStripMenuItem.Text = gouStr + " 开机自动启动";
            }
            else
            {
                开机自动启动ToolStripMenuItem.Text = "开机自动启动";
            }
            if (RobotManager.UseBuzzer)
            {
                启用蜂鸣器ToolStripMenuItem.Text = gouStr + " 启用蜂鸣器";
            }
            else
            {
                启用蜂鸣器ToolStripMenuItem.Text = "启用蜂鸣器";
            }
            if (RobotManager.GratingSignal)
            {
                启用光栅信号ToolStripMenuItem.Text = gouStr + "启用光栅信号";
            }
            else
            {
                启用光栅信号ToolStripMenuItem.Text = "启用光栅信号";
            }
            if (RobotManager.UseLabel)
            {
                启用贴标功能ToolStripMenuItem.Text = gouStr + "启用贴标功能";
            }
            else
            {
                启用贴标功能ToolStripMenuItem.Text = "启用贴标功能";
            }
            CSVBomManager.LoadAllCom();

            LoadStoreData();
            LoadListView();
            LogUtil.logBox = this.logBox;
            LoadOk = true;
            //tabPage2.Parent = null;
            // HideForm();
            timer1.Start();
        }
        private void EquipBean_GetImageEvent(Bitmap bitmap)
        {
            try
            {
                if (this.pictureBox1.Image != null)
                {
                    this.pictureBox1.Image.Dispose();
                    this.pictureBox1.Image = null;
                }
                this.pictureBox1.Image = bitmap;
            }
            catch (Exception ex)
            {
                LogUtil.error(" EquipBean_GetImageEvent 出错:" + ex.ToString());
            }
        }

        private void LoadListView()
        {
            this.listView1.Columns.Clear();
            AddHealder("设备名称", 90);
            AddHealder("启用", 50);
            AddHealder("报警", 130);
            AddHealder("状态", 110);
            AddHealder("料盘信息", listView1.Size.Width - 110 - 130 - 50 - 90 - 10);
            //AddHealder("BOX状态", listView1.Size.Width - 100 - 80 - 80 - 100 - 100 - 100 -40- 8);

            AddRow(robot.inputEquip, robot.inputEquip.IsDebug);
            AddRow(robot.XrayBean, robot.XrayBean.IsDebug);
            AddRow(robot.outputEquip, robot.outputEquip.IsDebug);
        }
        private void AddHealder(string name, int widht)
        {
            ColumnHeader preSendwire = new ColumnHeader();
            preSendwire.Text = name;   //设置列标题
            preSendwire.Width = widht;    //设置列宽度
            preSendwire.TextAlign = HorizontalAlignment.Left;   //设置列的对齐方式
            this.listView1.Columns.Add(preSendwire);    //将列头添加到ListView控件。
        }
        private void AddRow(EquipBase equip, bool isDebug)
        {
            ListViewItem lvi = new ListViewItem();
            lvi.Text = equip.Name;
            lvi.SubItems.Add(isDebug ? "✘" : "✔");
            lvi.SubItems.Add(equip.alarmType.ToString());
            lvi.SubItems.Add(equip.GetRunStr());
            lvi.SubItems.Add("");
            this.listView1.Items.Add(lvi);
        }

        private void HideForm()
        {
            this.Opacity = 0;
            this.ShowInTaskbar = false;
            this.notifyIcon1.Visible = true;
            this.Hide();
            GC.Collect();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.contextMenuStrip1.Show();
            }
            if (e.Button == MouseButtons.Left)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Maximized;
                this.ShowInTaskbar = true;
            }
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)//当用户点击窗体右上角X按钮或(Alt + F4)时 发生           
            {
                e.Cancel = true;
                HideForm();
            }
        }

        private void ExitApp()
        {
            DialogResult result = MessageBox.Show("是否确定退出软件?", "提示", MessageBoxButtons.YesNo);
            if (result.Equals(DialogResult.Yes))
            {
                try
                {
                    //如果料仓还在运行状态,先关闭料仓
                    if (!robot.runStatus.Equals(RobotRunStatus.Wait))
                    {
                        LogUtil.info("即将退出程序,停止" + robot.Name + "运行 ");
                        robot.StopRun();
                    }
                    foreach (EquipBase equip in robot.equipsMap.Values)
                    {
                        if (equip.runStatus > RobotRunStatus.Wait)
                        {
                            LogUtil.info("即将退出程序,停止" + equip.Name + "运行 ");
                            equip.StopRun();
                        }
                    }
                    IOManager.instance.CloseAllConnection();
                    ACServerManager.CloseAllPort();
                    RobotManager.robot.XrayBean.XRayDispose();
                    if (Camera._cam != null)
                    {
                        Camera._cam.CloseAll();
                    }
                    if (robot.sQLite!=null)
                        robot.sQLite.Close();
                }
                catch (Exception ex)
                {
                    LogUtil.error("退出出错:", ex);
                }
                System.Environment.Exit(System.Environment.ExitCode);
                //this.Close();
            }
        }
        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                FrmPwd fw = new FrmPwd(10);
                DialogResult result = fw.ShowDialog();
                if (!result.Equals(DialogResult.OK))
                {
                    LogUtil.info("切换界面显示时,没有正确输入密码");
                    return;
                }

                this.Opacity = 100;
                this.Visible = true;
                this.WindowState = FormWindowState.Maximized;
                this.notifyIcon1.Visible = false;
                this.ShowInTaskbar = true;
            }
            catch (Exception ex)
            {
                LogUtil.error("显示界面出错:", ex);
            }
        }

        private void 启动AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!robot.LoadSuccess)
            {
                MessageBox.Show("配置尚未加载完成不能启动!");
                return;
            }
            if (robot.runStatus != RobotRunStatus.Wait)
            {
                MessageBox.Show(robot.Name + "当前状态:" + robot.runStatus + ",不能启动!");
                return;
            }
            LogUtil.info("点击 开始启动");
            startTimer.Interval = 300;
            startTimer.Elapsed += timer_Elapsed;
            startTimer.AutoReset = false;
            startTimer.Enabled = true;
            this.timer1.Start();
        }
        private delegate void ShowFormDelegate();
        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            startTimer.Stop();
            if (robot.runStatus > RobotRunStatus.Wait)
            {
                return;
            }
            if (robot.StartRun())
            {
                BeginInvoke(new ShowFormDelegate(ShowStatus));
            }
        }
        private void ShowStatus()
        {
            formLineStatus(true);
        }

        private void formLineStatus(bool isStart)
        {
            foreach (TabPage tab in tabPageList)
            {
                bool find = false;
                foreach (Control control in tab.Controls)
                {
                    if (control is Panel)
                    {
                        foreach (Control con in control.Controls)
                        {
                            if (con is FrmXRay)
                            {
                                FrmXRay frm = (FrmXRay)con;
                                frm.FormStatus(isStart);
                                find = true;
                                break;
                            }

                        }
                    }
                    if (find)
                    {
                        break;
                    }
                }
            }
            启动AToolStripMenuItem.Enabled = !isStart;
            停止TToolStripMenuItem.Enabled = isStart;
            安全复位ToolStripMenuItem.Enabled = isStart;

        }
        private void 停止TToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (robot != null)
            {
                if (robot.runStatus.Equals(RobotRunStatus.Wait))
                {
                    MessageBox.Show(robot.Name + "设备未启动,不需要停止");
                    return;
                }
                if (robot != null)
                {
                    robot.StopRun();
                }
                formLineStatus(false);
            }
        }

        private void 复位RToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (robot.runStatus.Equals(RobotRunStatus.Wait))
            {
                MessageBox.Show(robot.Name + "设备未启动,无法复位");
                return;
            }
            if (MessageBox.Show("请确认出口夹爪上是否有料盘,请在复位前取下. 点击确认继续", "", MessageBoxButtons.OKCancel) != DialogResult.OK)
                return;
            LogUtil.info(robot.Name + " 点击:复位");
            robot.Reset();
        }
        private void FrmLineStore_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (停止TToolStripMenuItem.Enabled)
            {
                停止TToolStripMenuItem_Click(null, null);
            }

            LogUtil.info(robot.Name + " 点击:停止");
            AgvClient.Dispose();
            if (IOManager.instance != null)
            {
                IOManager.instance.CloseAllDO();
                IOManager.instance.CloseAllConnection();
            }
        }

        private void btnClearLog_Click(object sender, EventArgs e)
        {
            LogUtil.ClearLog();
        }
        private void btnCopyLog_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(logBox.Text);
            MessageBox.Show("已复制日志到粘贴板!");
        }
        private DateTime lastLogTime = DateTime.Now;
        PerformanceCounter curtime = null;
        #region 内存回收  
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);

        /// <summary>  
        /// 释放内存  
        /// </summary>  
        public static void ClearMemory()
        {
            try
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("ClearMemory 出错:" + ex.ToString());
            }
        }
        #endregion

        private void LogM()
        {
            try
            {
                TimeSpan sp = DateTime.Now - lastLogTime;
                if (sp.TotalMinutes > 5)
                {
                    lastLogTime = DateTime.Now;

                    Process process = Process.GetCurrentProcess();
                    if (curtime == null)
                    {
                        curtime = new PerformanceCounter("Process", "% Processor Time", process.ProcessName);
                    }
                    if (process != null)
                    {
                        StringBuilder sbResult = new StringBuilder();
                        PerformanceCounter pf1 = new PerformanceCounter("Process", "Working Set - Private", process.ProcessName);
                        sbResult.AppendFormat(DateTime.Now.ToLongTimeString() + ", 名称:{0} 内存:{1}M ", process.ProcessName, Math.Round(pf1.NextValue() / 1024 / 1024F, 2));
                        sbResult.AppendFormat(", CPU : {0} %", curtime.NextValue() / Environment.ProcessorCount);
                        LogUtil.info(sbResult.ToString());
                    }

                    //ClearMemory();
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("LogM Error: ", ex);
            }
        }
        private string AddMsg(string msg, string warmsg, AlarmType alarmType, DateTime lastTime, string modulename = "", string moduleid = "")
        {
            if (warmsg.Equals("").Equals(false))
            {
                if (alarmType.Equals(AlarmType.None).Equals(false))
                {
                    msg += lastTime.ToLongTimeString() + " " + warmsg + "\r\n";
                    msglist.Add(new AlarmMsg(modulename, "doubleLine."+ moduleid, warmsg));
                }
                else
                {
                    msg += warmsg + "\r\n";
                }
            }
            return msg;
        }
        
        private void timer1_Tick(object sender, EventArgs e)
        {
            LogM();
            if (!this.Visible)
            {
                return;
            }

            lblXrayWork.Visible = robot.XrayBean.InXWork;

            if (robot.XrayBean.carerayImageError)
            {
                robot.XrayBean.MoveStop = true;
                lblXrayWork.Text = "图像平板重启中。";
                lblXrayWork.Visible = true;
                //robot.XrayBean.Alarm(AlarmType.SuddenStop);
            }
            else {
                lblXrayWork.Text = "警告:点料过程中,请勿开门";
            }
            if (RobotManager.robot.SafeStop) {
                lblXrayWork.Text = "设备开始停止,请等待当前料处理完毕";
            }
            foreach (var cr in CodeManager.CamErrCount)
            {
                if (cr.Value > 5)
                {
                    robot.inputEquip.MoveStop = true;
                    lblXrayWork.Text = $"扫码相机({cr.Key})拍照连续失败,请及时处理。";
                    lblXrayWork.Visible = true;
                    robot.inputEquip.Alarm(AlarmType.SuddenStop);
                    break;
                }
            }
            
            string canScanCode = "";
            lblStatus.Text = robot.GetRunStr() + canScanCode;
            string warnMsg = robot.WarnMsg;
            msglist = new List<AlarmMsg>();
            //foreach (EquipBase move in robot.equipsMap.Values)
            //{
            warnMsg = AddMsg(warnMsg, robot.outputEquip.WarnMsg, robot.outputEquip.alarmType, robot.outputEquip.LastAlarmTime,"点料机-出料", "outputEquip");
            
            warnMsg = AddMsg(warnMsg, robot.XrayBean.WarnMsg, robot.XrayBean.alarmType, robot.XrayBean.LastAlarmTime, "点料机-点料", "XrayBean");
            warnMsg = AddMsg(warnMsg, robot.inputEquip.WarnMsg, robot.inputEquip.alarmType, robot.inputEquip.LastAlarmTime, "点料机-入料", "inputEquip");

            //if (move is InputEquip)
            //{
            //BatchMoveBean bean = robot.inputEquip.LeftBatchMove;
            warnMsg = AddMsg(warnMsg, robot.inputEquip.LeftBatchMove.WarnMsg, robot.inputEquip.LeftBatchMove.alarmType, robot.inputEquip.LeftBatchMove.LastAlarmTime, "点料机-左批量轴", "LeftBatch");
            warnMsg = AddMsg(warnMsg, robot.inputEquip.RightBatchMove.WarnMsg, robot.inputEquip.RightBatchMove.alarmType, robot.inputEquip.RightBatchMove.LastAlarmTime, "点料机-右批量轴", "RightBatch");
            //}
            //}
            lblOutTray.Text = "XRay出口处料盘:" + robot.XrayBean.Out_ReelInfo.ToStr();
            lblCurrTray.Text = "XRay扫描区料盘:" + robot.XrayBean.Work_ReelInfo.ToStr();
            lblWarnMsg.Text = warnMsg;
            updateDeviceAlarmMsg(msglist);
            if (robot.runStatus > RobotRunStatus.Wait)
            {
                if (启动AToolStripMenuItem.Enabled.Equals(true))
                {
                    formLineStatus(true);
                }
                if ((robot.runStatus.Equals(RobotRunStatus.HomeMoving) || robot.runStatus.Equals(RobotRunStatus.Reset))
                    && robot.alarmType.Equals(AlarmType.None))
                {
                    SetMenuS(复位RToolStripMenuItem, false);
                    SetMenuS(启动AToolStripMenuItem, false);
                }
                else
                {
                    SetMenuS(复位RToolStripMenuItem, true);
                }
            }
            else
            {
                SetMenuS(启动AToolStripMenuItem, true);
                SetMenuS(复位RToolStripMenuItem, false);
                SetMenuS(停止TToolStripMenuItem, false);
            }
            //if (!chbAGV.Checked.Equals(AgvClient.CurrCancelState))
            //{
            //    chbAGV.Checked = AgvClient.CurrCancelState;
            //}
            if (AgvClient.CurrCancelState)
            {
                aGVCancelStateToolStripMenuItem.Text = gouStr + "禁用 AGV";
            }
            else
            {
                aGVCancelStateToolStripMenuItem.Text = "禁用 AGV";
            }
            UpdateListBox();
        }
        private void UpdateListBox()
        {
            int item_debug_index = 1;
            int item_alarm_index = 2;
            int item_runStr_index = 3;
            int item_move_info_index = 4;
            int i = 0;
            foreach (EquipBase equip in robot.equipsMap.Values)
            {
                SetItemText(i, item_debug_index, equip.IsDebug ? "✘" : "✔");
                SetItemText(i, item_alarm_index, equip.alarmType.ToString());
                SetItemText(i, item_runStr_index, equip.GetRunStr());
                RobotRunStatus s = equip.runStatus;
                string trayInfo = "";
                if (equip.MoveInfo.MoveType.Equals(RobotMoveType.Working) || equip.MoveInfo.MoveType.Equals(RobotMoveType.Labelling))
                {
                    s = RobotRunStatus.Busy;
                    trayInfo = equip.MoveInfo.MoveParam.OutStr();
                }
                else if (equip.SecMoveInfo.MoveType.Equals(RobotMoveType.Working) || equip.SecMoveInfo.MoveType.Equals(RobotMoveType.Labelling))
                {
                    s = RobotRunStatus.Busy;
                    trayInfo = equip.SecMoveInfo.MoveParam.OutStr();
                }
                else if (equip is InputEquip)
                {
                    if (robot.inputEquip.LeftBatchMove.MoveInfo.MoveType.Equals(RobotMoveType.Working) || robot.inputEquip.LeftBatchMove.MoveInfo.MoveType.Equals(RobotMoveType.Labelling))
                    {
                        s = RobotRunStatus.Busy;
                        SetItemText(i, item_runStr_index, "忙碌_左入料");
                        trayInfo = robot.inputEquip.LeftBatchMove.MoveInfo.MoveParam.OutStr();
                    }
                    else if (robot.inputEquip.RightBatchMove.MoveInfo.MoveType.Equals(RobotMoveType.Working) || robot.inputEquip.RightBatchMove.MoveInfo.MoveType.Equals(RobotMoveType.Labelling))
                    {
                        s = RobotRunStatus.Busy;
                        SetItemText(i, item_runStr_index, "忙碌_右入料");
                        trayInfo = robot.inputEquip.RightBatchMove.MoveInfo.MoveParam.OutStr();
                    }
                }
                SetItemText(i, item_move_info_index, trayInfo);
                SetItemColor(i, s, equip.alarmType);
                i++;
            }

        }
        private void SetItemColor(int i, RobotRunStatus runStatus, AlarmType alarmType)
        {
            if (runStatus.Equals(RobotRunStatus.Wait))
            {
                SetItemColor(i, Color.White);
                //listView1.Items[i].BackColor = Color.White;
            }
            else if (alarmType.Equals(AlarmType.IoSingleTimeOut))
            {
                SetItemColor(i, Color.LightCoral);
            }
            else if (alarmType.Equals(AlarmType.None).Equals(false))
            {
                SetItemColor(i, Color.Red);
            }
            else if (runStatus.Equals(RobotRunStatus.HomeMoving) || runStatus.Equals(RobotRunStatus.Reset))
            {
                SetItemColor(i, Color.Orange);
            }
            else if (runStatus.Equals(RobotRunStatus.Busy))
            {
                SetItemColor(i, Color.LimeGreen);
            }
            else if (runStatus.Equals(RobotRunStatus.Runing))
            {
                SetItemColor(i, Color.LightBlue);
            }
        }

        private void SetMenuS(ToolStripMenuItem toolMenu, bool isEn)
        {
            if (!toolMenu.Enabled.Equals(isEn))
            {
                toolMenu.Enabled = isEn;
            }
        }
        private void SetItemColor(int i, Color color)
        {
            if (!listView1.Items[i].BackColor.Equals(color))
            {
                listView1.Items[i].BackColor = color;
            }
        }
        private void SetItemText(int rowIndex, int subIndex, string value)
        {
            if (this.listView1.Items[rowIndex].SubItems.Count > subIndex)
            {
                if (!this.listView1.Items[rowIndex].SubItems[subIndex].Text.Equals(value))
                {
                    this.listView1.Items[rowIndex].SubItems[subIndex].Text = value;
                }
            }
        }


        private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
        {
            try
            {
                Font fntTab;
                Brush bshBack;
                Brush bshFore;
                if (e.Index == this.tabControl1.SelectedIndex)
                {
                    fntTab = new Font(e.Font, FontStyle.Regular);
                    bshBack = new SolidBrush(Color.DodgerBlue);
                    bshFore = Brushes.Black;
                }
                else
                {
                    fntTab = e.Font;
                    bshBack = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, Color.White, Color.White, System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal);
                    bshFore = new SolidBrush(Color.Black);
                }
                string tabName = this.tabControl1.TabPages[e.Index].Text;
                StringFormat sftTab = new StringFormat();
                e.Graphics.FillRectangle(bshBack, e.Bounds);
                Rectangle recTab = e.Bounds;
                recTab = new Rectangle(recTab.X, recTab.Y + 4, recTab.Width, recTab.Height - 4);
                e.Graphics.DrawString(tabName, fntTab, bshFore, recTab, sftTab);
            } catch (Exception ex)
            {
                LogUtil.error("tabControl1_DrawItem: " + ex.ToString());
            }
        }

        private void 版本号ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmAbout about = new FrmAbout();
            about.ShowDialog();
        }


        private void 二维码学习ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IOManager.IOMove(IO_Type.Camera_Led, IO_VALUE.HIGH);
            if (Camera._cam != null)
            {
                Camera._cam.CloseAll();
            }
            CodeLibrary.FrmCodeDecode frm = new CodeLibrary.FrmCodeDecode();
            frm.ShowDialog();
            frm.Dispose();
            IOManager.IOMove(IO_Type.Camera_Led, IO_VALUE.LOW);
        }



        private void 退出ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            LogUtil.info("点击:退出系统");
            ExitApp();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ExitApp();
        }

        private void logBox_VisibleChanged(object sender, EventArgs e)
        {
            if (!LoadOk)
            {
                return;
            }
            if (logBox.Visible)
            {
                LogUtil.UpdateLogbox();
            }
        }

        private void 清空日志ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LogUtil.ClearLog();
        }

        private void 复制日志ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            Clipboard.SetDataObject(logBox.Text);
            MessageBox.Show("已复制日志到粘贴板!");
        }


        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            FrmAgvTest frm = new FrmAgvTest();
            frm.ShowDialog();
        }

        //private void checkBox1_CheckedChanged(object sender, EventArgs e)
        //{
        //    if (!LoadOk)
        //    {
        //        return;
        //    }
        //    if (chbAGV.Checked.Equals(AgvClient.CurrCancelState))
        //    {
        //        return;
        //    }
        //    bool result = chbAGV.Checked;
        //    AgvClient.SetCancelState(result);
        //    LogUtil.info("勾选:AgvClient.SetCancelState =" + result);
        //}

        //private void chbBuzzer_CheckedChanged(object sender, EventArgs e)
        //{
        //    if (!LoadOk)
        //    {
        //        return;
        //    }
        //    if (chbBuzzer.Checked.Equals(RobotManager.UseBuzzer))
        //    {
        //        return;
        //    }
        //    RobotManager.UseBuzzer = chbBuzzer.Checked;
        //    LogUtil.info("勾选:UseBuzzer =" + RobotManager.UseBuzzer);
        //    ConfigAppSettings.SaveValue(Setting_Init.UseBuzzer, (RobotManager.UseBuzzer ? 1 : 0));
        //}

        private void 标签编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                RobotManager.PrintBean.EditLabel();
            }
            catch (Exception ex)
            {
                LogUtil.error("标签编辑错误:" + ex.ToString());
            }
        }

        //private void chbOpenX_CheckedChanged(object sender, EventArgs e)
        //{
        //    if (!LoadOk)
        //    {
        //        return;
        //    }
        //    if (chbOpenX.Checked.Equals(robot.XrayBean.OpenXLine))
        //    {
        //        return;
        //    }
        //    robot.XrayBean.OpenXLine = chbOpenX.Checked;
        //    LogUtil.info("勾选:启用X射线点料 =" + chbOpenX.Checked);
        //}

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            FrmAnalyze frm = new FrmAnalyze();
            frm.ShowDialog();
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {

        }
        private string gouStr = "✔";
        private void 开机自动启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!LoadOk)
            {
                return;
            }
            if (开机自动启动ToolStripMenuItem.Text.Contains(gouStr))
            {
                ConfigAppSettings.SaveValue(Setting_Init.App_AutoRun, 0);
                ManagerUtil.AutoRun(Application.ExecutablePath, false);
                开机自动启动ToolStripMenuItem.Text = "开机自动启动";
            }
            else
            {
                ConfigAppSettings.SaveValue(Setting_Init.App_AutoRun, 1);
                ManagerUtil.AutoRun(Application.ExecutablePath, true);
                开机自动启动ToolStripMenuItem.Text = gouStr + "开机自动启动";
            }
            LogUtil.info(Name + " 点击:" + 开机自动启动ToolStripMenuItem.Text);
        }

        private void 启用蜂鸣器ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!LoadOk)
            {
                return;
            }

            bool result = !启用蜂鸣器ToolStripMenuItem.Text.Contains(gouStr);
            if (result.Equals(RobotManager.UseBuzzer))
            {
                return;
            }
            RobotManager.UseBuzzer = result;
            ConfigAppSettings.SaveValue(Setting_Init.UseBuzzer, (RobotManager.UseBuzzer ? 1 : 0));
            if (result)
            {
                启用蜂鸣器ToolStripMenuItem.Text = gouStr + " 启用蜂鸣器";
            }
            else
            {
                启用蜂鸣器ToolStripMenuItem.Text = "启用蜂鸣器";
            }
            LogUtil.info(Name + " 点击:" + 启用蜂鸣器ToolStripMenuItem.Text);
        }

        private void 启用X射线点料ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!LoadOk)
            {
                return;
            }

            bool result = !启用X射线点料ToolStripMenuItem.Text.Contains(gouStr);
            if (result.Equals(robot.XrayBean.OpenXLine))
            {
                return;
            }
            robot.XrayBean.OpenXLine = result;
            if (result)
            {
                启用X射线点料ToolStripMenuItem.Text = gouStr + " 启用X射线点料";
            }
            else
            {
                启用X射线点料ToolStripMenuItem.Text = "启用X射线点料";
            }
            LogUtil.info(Name + " 点击:" + 启用X射线点料ToolStripMenuItem.Text);
        }

        private void aGVCancelStateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!LoadOk)
            {
                return;
            }

            bool result = !aGVCancelStateToolStripMenuItem.Text.Contains(gouStr);
            if (result.Equals(AgvClient.CurrCancelState))
            {
                return;
            }
            AgvClient.SetCancelState(result);
            //robot.XrayBean.OpenXLine = result;
            if (result)
            {
                aGVCancelStateToolStripMenuItem.Text = gouStr + " AGV cancelState";
            }
            else
            {
                aGVCancelStateToolStripMenuItem.Text = "AGV cancelState";
            }
            LogUtil.info(Name + " 点击:" + aGVCancelStateToolStripMenuItem.Text);
        }

        private void 正常工作模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (!XRayLearnManager.InLearnMode)
            //{
            //    正常工作模式ToolStripMenuItem.Text = gouStr + " 正常工作模式";
            //    元器件学习模式ToolStripMenuItem.Text = "元器件学习模式";
            //    return;
            //}
            //LogUtil.info(Name + " 点击:" + 正常工作模式ToolStripMenuItem.Text + ",设置InLearnMode = false");
            //XRayLearnManager.InLearnMode = false;

            //正常工作模式ToolStripMenuItem.Text = gouStr + " 正常工作模式";
            //元器件学习模式ToolStripMenuItem.Text = "元器件学习模式";

            // tabPage2.Parent = null;
            //tabControl1.TabPages.Insert(0, tabPage1);
            //tabControl1.SelectedIndex = 0;
            //tabPage1.Parent = tabControl1;
        }

        private void 元器件学习模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (XRayLearnManager.InLearnMode)
            //{
            //    正常工作模式ToolStripMenuItem.Text = "正常工作模式";
            //    元器件学习模式ToolStripMenuItem.Text = gouStr + " 元器件学习模式";
            //    return;
            //}
            //LogUtil.info(Name + " 点击:" + 元器件学习模式ToolStripMenuItem.Text + ",设置InLearnMode = true ");
            //XRayLearnManager.InLearnMode = true;
            //正常工作模式ToolStripMenuItem.Text = "正常工作模式";
            //元器件学习模式ToolStripMenuItem.Text = gouStr + " 元器件学习模式";

            //tabPage1.Parent = null;
            //tabControl1.TabPages.Insert(0, tabPage2);
            //tabControl1.SelectedIndex = 0; 
        }

        private void 元器件学习ToolStripMenuItem_Click(object sender, EventArgs e)
        {
                                                  
        }
        private void 单盘ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string backPath = ParamManager.NoConfigPath;
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = ParamManager.NoConfigPath;
            ofd.Multiselect = true;
            ofd.Filter = "PNG|*.png";
            if (DialogResult.OK == ofd.ShowDialog(this)) {
                FrmLearning frm = new FrmLearning();
                frm.ImageFiles = ofd.FileNames;
                frm.ImagePath = ParamManager.NoConfigPath;
                frm.Show();
                //Task.Run(() => { frm.ShowDialog(); });
            }

        }
        private void 批量ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string backPath = ParamManager.NoConfigPath;

            FrmLearning frm = new FrmLearning();
            frm.ImagePath = backPath;
            frm.Show();
            /*
            folderBrowserDialog1.Description = "请选择需要学习的图片文件夹";
            if (!Directory.Exists(backPath))
            {
                Directory.CreateDirectory(backPath);
            }
            folderBrowserDialog1.SelectedPath = backPath;
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result.Equals(DialogResult.OK))
            {
                string folder = folderBrowserDialog1.SelectedPath;
                FrmLearning frm = new FrmLearning();
                frm.ImagePath = folder;
                frm.Show();
                //Task.Run(() => { frm.ShowDialog(); });
            }*/
        }
        private void 元器件库ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmComponentList frm = new FrmComponentList();
            frm.ShowDialog();
        }

        private void 启用光栅信号ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!LoadOk)
            {
                return;
            }

            bool result = !启用光栅信号ToolStripMenuItem.Text.Contains(gouStr);
            if (result.Equals(RobotManager.GratingSignal))
            {
                return;
            }
            RobotManager.GratingSignal = result;
            ConfigAppSettings.SaveValue(Setting_Init.GratingSignal, (RobotManager.GratingSignal ? 1 : 0));
            if (result)
            {
                启用光栅信号ToolStripMenuItem.Text = gouStr + " 启用光栅信号";
            }
            else
            {
                启用光栅信号ToolStripMenuItem.Text = "启用光栅信号";
            }
            LogUtil.info(Name + " 点击:" + 启用光栅信号ToolStripMenuItem.Text);
        }

        private void 启用贴标功能ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!LoadOk)
            {
                return;
            }

            bool result = !启用贴标功能ToolStripMenuItem.Text.Contains(gouStr);
            if (result.Equals(RobotManager.UseLabel))
            {
                return;
            }
            RobotManager.UseLabel = result;
            ConfigAppSettings.SaveValue(Setting_Init.UseLabel, (RobotManager.UseLabel ? 1 : 0));
            if (result)
            {
                启用贴标功能ToolStripMenuItem.Text = gouStr + " 启用贴标功能";
            }
            else
            {
                启用贴标功能ToolStripMenuItem.Text = "启用贴标功能";
            }
            LogUtil.info(Name + " 点击:" + 启用贴标功能ToolStripMenuItem.Text);
        }

        private static string Addr_updateDeviceAlarmMsg = "http://172.16.77.86/myproject/rest/api/qisda/device/updateDeviceAlarmMsg";
        List<AlarmMsg> msglist = new List<AlarmMsg>();
        MyWebClient myWebClient = new MyWebClient(1000);
        /// <summary>
        /// 异常看板
        /// </summary>
        /// <param name="msgList"></param>
        /// <returns></returns>
        public string updateDeviceAlarmMsg(List<AlarmMsg> msgList)
        {
            if (msgList.Count == 0 || !CB_lookboard.Checked)
            {
                return "";
            }

            string msg = "";
            try
            {
                Dictionary<string, string> paramMap = new Dictionary<string, string>();
                string msgListStr = JsonHelper.SerializeObject(msgList);
                paramMap.Add("deviceAlarmList", msgListStr);
                string param = GetAddr(paramMap);
                //DateTime startTime = DateTime.Now;
                if (string.IsNullOrEmpty(myWebClient.Headers["Content-Type"]))
                {
                    myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                }
                myWebClient.UploadStringAsync(new Uri(Addr_updateDeviceAlarmMsg),"POST", param);
                    //string resultStr = HttpHelper.Post(Addr_updateDeviceAlarmMsg, param, 1000);
               
                //LogUtil.debug("updateDeviceAlarmMsg    " + FormUtil.GetSpanStr(DateTime.Now - startTime) + "  【" + server + "】【" + resultStr + "】");
                /*
                RfidData data = JsonHelper.DeserializeJsonToObject<RfidData>(resultStr);

                if (data == null)
                {
                    return msg = " updateDeviceAlarmMsg 没有收到服务器反馈";
                }
                else if (data.code.Equals(0).Equals(false))
                {
                    return msg = " updateDeviceAlarmMsg   【" + server + "】【" + resultStr + "】" + data.msg;
                }
                */
                return "";
            }
            catch (Exception ex)
            {
                LogUtil.error("  updateDeviceAlarmMsg Error:  " + ex.ToString());
            }
            return msg;
        }
        private static string GetAddr( Dictionary<string, string> paramsMap)
        {
            string path="";
            foreach (string paramName in paramsMap.Keys)
            {

                string par = System.Net.WebUtility.UrlEncode(paramsMap[paramName]);
                path += paramName + "=" + par + "&";
            }
            path = path.Substring(0, path.Length - 1);
            return path;
        }
        public class AlarmMsg
        {
            //>>>name :  异常位置名称
            public string name = "";
            //>>>msgKey :  异常信息唯一标识
            public string msgKey = "";
            //>>>msgValue :  异常信息
            public string msgValue = "";
            /// <summary>
            /// 异常信息
            /// </summary>
            /// <param name="name">异常位置名称</param>
            /// <param name="key">异常信息唯一标识</param>
            /// <param name="value">异常信息</param>
            public AlarmMsg(string name, string key, string value)
            {
                this.name = name;
                this.msgKey = key;
                this.msgValue = value;
            }
        }

        private void 安全复位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (robot != null)
            {
                if (robot.runStatus.Equals(RobotRunStatus.Wait))
                {
                    MessageBox.Show(robot.Name + "设备未启动,不需要停止");
                    return;
                }
                if (MessageBox.Show("请确认出口夹爪上是否有料盘,请在复位前取下. 点击确认继续", "", MessageBoxButtons.OKCancel) != DialogResult.OK)
                    return;

                LogUtil.info(robot.Name + " 点击:安全停止");
                if (robot.inputEquip.MoveInfo.MoveType == RobotMoveType.None)
                    robot.StopRun();
                else
                {
                    robot.SafeStop = true;
                    MessageBox.Show("请等待设备入料口放盘完成后自动停止", "");
                }
                formLineStatus(false);
            }



        }
    }
}