Frm_Main.xaml.cs 35.3 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
using HHWCS.Bll;
using HHWCS.Model;
using HHWCSHost.Controls;
using OPCHelper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace HHWCSHost.View
{
    /// <summary>
    /// Frm_Main.xaml 的交互逻辑
    /// </summary>
    public partial class Frm_Main : Window
    {
        #region 属性

        const string plcAdressPrefix = "S7:[S7 connection_1]";

        //所有子窗口
        Dictionary<string, Window> windows = new Dictionary<string, Window>();
        private System.Timers.Timer timer = new System.Timers.Timer();
        int inTimer = 0;

        //OPC相关
        /// <summary>
        /// OPC地址
        /// </summary>
        public string PLCIP { get; set; }
        public OPCHelp PLC { get; set; }
        /// <summary>
        /// 创建item后返回的索引值,需要用到这个去进行数据读取
        /// </summary>
        public int[] ServerHandle { get; set; }

        //堆垛机
        //public List<StockerMonitor> StockerMonitors { get; set; }

        public LogInfo LogInfo { get; set; }

        public List<DeviceAddressEntity> DeviceAddressEntities { get; set; }
        public List<DeviceEntity> DeviceEntities { get; set; }
        public List<DevicePropEntity> DevicePropEntities { get; set; }
        public List<DeviceTypeEntity> DeviceTypeEntities { get; set; }

        #endregion

        public Frm_Main()
        {
            InitializeComponent();
            //日志组件最先初始化
            LogInfo = new LogInfo(450, 400);
            panel_Bottom.Children.Add(LogInfo);

            InitMenu();
            InitStatusBar();
            InitTimer();
            InitOPC();
            InitDeviceData();
            InitStockerAndStationMonitor();
        }

        #region 初始化
        private void InitDeviceData()
        {
            var temp = Bll.GetAllDevice();
            var temp2 = Bll.GetAllDeviceAddress();
            var temp3 = Bll.GetAllDeviceProp();
            var temp4 = Bll.GetAllDeviceType();
            if (!temp.Success || !temp2.Success || !temp3.Success || !temp4.Success)
            {
                btn_OpenPLCConnect.IsEnabled = false;
                MessageBox.Show("获取设备数据出错");
                AddLogToUI("获取设备数据出错", 2);
                return;
            }
            DeviceEntities = temp.Data;
            DeviceAddressEntities = temp2.Data;
            DevicePropEntities = temp3.Data;
            DeviceTypeEntities = temp4.Data;
            //属性地址校验
            //foreach (var item in DeviceEntities)
            //{
            //    if (DeviceAddressEntities.Count(t => t.DeviceId == item.Id) == 0)
            //    {
            //        String msg = "错误:设备" + item.Code + " " + item.Name + "无属性地址";
            //        MessageBox.Show("msg");
            //        AddLogToUI(msg, 2);
            //        btn_OpenPLCConnect.IsEnabled = false;
            //        return;
            //    }
            //    //todo:校验属性是否都存在
            //    if (DevicePropEntities.Count(t => t.DeviceTypeId == item.DeviceTypeId) != DeviceAddressEntities.Count(t => t.DeviceId == item.Id))
            //    {
            //        String msg = "错误:设备" + item.Code + " " + item.Name + "属性地址与类型属性规定不一致";
            //        MessageBox.Show("msg");
            //        AddLogToUI(msg, 2);
            //        btn_OpenPLCConnect.IsEnabled = false;
            //        return;
            //    }
            //}
            //属性地址获取无误后初始化监控
            //InitStockerAndStationMonitor();
        }

        private void InitStockerAndStationMonitor()
        {
            //堆垛机
            var stockers = FindDevByType("stocker").Data;
            foreach (var item in stockers)
            {
                StockerMonitor stockerMonitor = new StockerMonitor(16, false, false, 980, 100);
                stockerMonitor.ControlName = item.Name;
                stockerMonitor.Name = item.Code;
                this.RegisterName(item.Code, stockerMonitor);
                panel_Stocker.Children.Add(stockerMonitor);
                StockerInfo stockerInfo = new StockerInfo(400, 400);
                stockerInfo.ControlName = item.Name;
                stockerInfo.Name = item.Code;
                panel_Bottom.Children.Add(stockerInfo);
            }

            //接入站台
            var staionForStockerIn = FindDevByType("stationForStockerIn").Data;
            foreach (var item in staionForStockerIn)
            {
                StationInfo stationInfo = new StationInfo(450, 400);
                stationInfo.ControlName = item.Name;
                stationInfo.Name = item.Code;
                panel_Bottom.Children.Add(stationInfo);
            }

            //接出站台
            var staionForStockerOut = FindDevByType("stationForStockerOut").Data;
            foreach (var item in staionForStockerOut)
            {
                StationInfo stationInfo = new StationInfo(450, 400);
                stationInfo.ControlName = item.Name;
                stationInfo.Name = item.Code;
                panel_Bottom.Children.Add(stationInfo);
            }

            //出入站台
            var station = FindDevByType("station").Data;
            foreach (var item in station)
            {
                StationInfo stationInfo = new StationInfo(450, 400);
                stationInfo.ControlName = item.Name;
                stationInfo.Name = item.Code;
                panel_Bottom.Children.Add(stationInfo);
            }

        }

        private void InitOPC()
        {
            try
            {
                PLCIP = ConfigurationManager.AppSettings["OPCServerIP"];
                PLC = new OPCHelp("192.168.10.100");
            }
            catch (Exception ex)
            {
                MessageBox.Show("未能获取到OPC配置,请检查。", "注意", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void InitStatusBar()
        {
            statusBar.Items.Add("欢迎:" + AppCommon.User.UserName + " 登录时间:" + DateTime.Now.ToString());
        }

        private void InitMenu()
        {
            //构建菜单
            //系统
            MenuItem menu_sys = new MenuItem();
            menu_sys.Header = "系统";
            MenuItem menu_sys_exit = new MenuItem();
            menu_sys_exit.Header = "退出";
            menu_sys_exit.Click += Menu_sys_exit_Click;
            menu_sys.Items.Add(menu_sys_exit);

            //设备
            MenuItem menu_device = new MenuItem();
            menu_device.Header = "设备管理";
            MenuItem menu_device_info = new MenuItem();
            menu_device_info.Header = "设备信息管理";
            menu_device_info.Click += Menu_device_info_Click;
            menu_device.Items.Add(menu_device_info);
            MenuItem menu_device_OPCTest = new MenuItem();
            menu_device_OPCTest.Header = "OPC测试";
            menu_device_OPCTest.Click += Menu_device_OPCTest_Click;
            menu_device.Items.Add(menu_device_OPCTest);

            //任务
            MenuItem menu_task = new MenuItem();
            menu_task.Header = "任务管理";
            MenuItem menu_task_info = new MenuItem();
            menu_task_info.Header = "任务查看";
            menu_task_info.Click += Menu_task_info_Click;
            menu_task.Items.Add(menu_task_info);

            //仓库
            MenuItem menu_warehouse = new MenuItem();
            menu_warehouse.Header = "仓库信息";
            MenuItem menu_location = new MenuItem();
            menu_location.Header = "货位";
            menu_location.Click += Menu_location_Click;
            MenuItem menu_pallet = new MenuItem();
            menu_pallet.Header = "托盘";
            menu_pallet.Click += Menu_pallet_Click;
            menu_warehouse.Items.Add(menu_location);
            menu_warehouse.Items.Add(menu_pallet);



            menu.Items.Add(menu_sys);
            menu.Items.Add(menu_device);
            menu.Items.Add(menu_task);
            menu.Items.Add(menu_warehouse);

            //工具栏
            btn_OpenPLCConnect.IsEnabled = true;
            btn_ClosePLCConnect.IsEnabled = false;
        }


        /// <summary>
        /// 打开监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_OpenPLCConnect_Click(object sender, RoutedEventArgs e)
        {
            if (PLC == null)
            {
                MessageBox.Show("PLC连接初始化失败! 请检查PLC配置然后重启本程序", "注意", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (PLC.OpenConn() == false)
            {
                MessageBox.Show("打开PLC连接失败");
                return;
            }
            PLC.CreateGroup("group1");
            AddOPCItems();
            //
            btn_ClosePLCConnect.IsEnabled = true;
            btn_OpenPLCConnect.IsEnabled = false;
            //同步锁置0
            inTimer = 0;
            timer.Enabled = true;
        }

        private void AddOPCItems()
        {
            ServerHandle = new int[DeviceAddressEntities.Count];
            for (int i = 0; i < DeviceAddressEntities.Count; i++)
            {
                var temp = DeviceAddressEntities[i];
                ServerHandle[i] = PLC.AddAddr(plcAdressPrefix + temp.Address, i);
                temp.ServerHandle = ServerHandle[i];
            }
        }

        /// <summary>
        /// 关闭监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ClosePLCConnect_Click(object sender, RoutedEventArgs e)
        {
            if (PLC.GetConnStatus())
            {
                if (!PLC.CloseConn())
                {
                    MessageBox.Show("关闭失败请稍后重试");
                };
            }
            btn_ClosePLCConnect.IsEnabled = false;
            btn_OpenPLCConnect.IsEnabled = true;
            timer.Enabled = false;
            //同步锁置1
        }

        private void InitTimer()
        {
            timer.Interval = 2000; //3秒触发一次
            timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
            timer.AutoReset = true;//每到指定时间Elapsed事件是到时间就触发
            timer.Enabled = false; //指示 Timer 是否应引发 Elapsed 事件。
        }
        #endregion

        /// <summary>
        /// 程序主时钟
        /// 出库优先
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTimedEvent(object sender, ElapsedEventArgs e)
        {
            //同步线程防止重入
            if (Interlocked.Exchange(ref inTimer, 1) == 0)
            {
                //todo:完善主控时钟

                #region 测试监控赋值

                InitDeviceData();
                //日志
                DeviceEntities.ForEach(item => DeviceAddressEntities.FindAll(t => t.DeviceId == item.Id).Join(DevicePropEntities.FindAll(t => t.DeviceTypeId == item.DeviceTypeId && t.IsMonitor == 1), t => t.DevicePropCode, a => a.Code, (a, b) => new { a, b }).Where(t => t.a.value != t.b.MonitorCompareValue).Select(t => t.b).ToList().ForEach(t => AddLogToUI("报警:" + t.Name + " 信息:" + t.MonitorFailure, 2)));
                //底部面板
                Dispatcher.Invoke(new Action(() =>
                        {
                            foreach (var item in panel_Bottom.Children)
                            {
                                if (item is StockerInfo temp)
                                {
                                    var a = DeviceEntities.Find(t => t.Code == temp.Name);
                                    temp.SetProps(DeviceEntities.Find(t => t.Code == temp.Name), DevicePropEntities.FindAll(t => t.DeviceTypeId == a.DeviceTypeId), DeviceAddressEntities.FindAll(t => t.DeviceId == a.Id));
                                }
                            };
                        }
                    ));
                //图形监控
                Dispatcher.Invoke(new Action(() =>
                {
                    foreach (var item in FindDevByType("stocker").Data)
                    {
                        //货架监控方面先不实现
                        var addressEntities = DeviceAddressEntities.FindAll(t => t.DeviceId == item.Id);
                        var stockerMonitor = (StockerMonitor)panel_Stocker.FindName(item.Code);
                        var status = addressEntities.Find(t => t.DevicePropCode == "TaskExcuteStatus").value;
                        var column = addressEntities.Find(t => t.DevicePropCode == "CurrentColumn").value;
                        if (status == "-1" || column == "-1")
                        {
                            break;
                        }
                        stockerMonitor.SetStocker(Convert.ToInt32(status), Convert.ToInt32(column));
                    }
                    foreach (var item in FindDevByType("stationForStockerIn").Data)
                    {
                        var s = this.FindName(item.Code);
                        var address = DeviceAddressEntities.FindAll(t => t.DeviceId == item.Id);
                        if (s is StationH stationH)
                        {

                        }
                        else if (s is StationV stationV)
                        {

                        }
                    }
                    foreach (var item in FindDevByType("stationForStockerOut").Data)
                    {

                    }
                    foreach (var item in FindDevByType("station").Data)
                    {

                    }
                    foreach (var item in FindDevByType("conveyor").Data)
                    {

                    }
                }));


                //return;
                #endregion

                #region 检查是否连接正常
                if (PLC.GetConnStatus())
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        if (this.grid.Background == Brushes.Red)
                        {
                            this.grid.Background = Brushes.White;
                        }
                    }));
                }
                else
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        if (this.grid.Background != Brushes.Red)
                        {
                            this.grid.Background = Brushes.Red;
                        }
                        if (!((TextBlock)this.LogInfo.list_Log.SelectedItem).Text.Contains("失去通讯连接,请关闭连接后重新打开"))
                        {
                            this.LogInfo.AddLogs("失去通讯连接,请关闭连接后重新打开", 2);
                        }
                    }));
                    //这里直接retrun,并没有更改inTimer的值,后续不会再次进入这个循环,需要关闭连接然后重新打开连接来重置这个参数;
                    return;
                }
                #endregion

                #region 堆垛机操作
                //找出所有堆垛机
                var stockersResult = FindDevByType("stocker");
                if (stockersResult.Success)
                {
                    var stockers = stockersResult.Data;
                    //遍历所有出库性质的任务
                    ExcuteTaskOut(stockers);
                    //响应入库性质的任务完成
                    ExcuteTaskComplete(stockers);

                    //响应任务校验为2时,重新写入任务
                    //响应双重入库处理
                    //响应高度不匹配
                    //响应空出及发送地址错的处理

                }

                #endregion

                #region 响应堆垛机接入站台

                var stationForStockerInResult = FindDevByType("stationForStockerIn");
                if (stationForStockerInResult.Success)
                {
                    foreach (var stationForStockerIn in stationForStockerInResult.Data)
                    {
                        var props = DeviceAddressEntities.FindAll(t => t.DeviceId == stationForStockerIn.Id);
                        if (ReadAddress(props) && ValidateStationForStockerIn(props))
                        {
                            //查询对应堆垛机是否达到可以入库的状态
                            var stocker = FindDevByType("stocker").Data.Find(t => t.Roadway == stationForStockerIn.Roadway);
                            if (stocker != null)
                            {
                                if (ValidateStockerOut(DeviceAddressEntities.FindAll(t => t.DeviceId == stocker.Id)))
                                {
                                    //todo:下发堆垛机任务,响应站台,待站台逻辑理清后再做处理
                                    //待站台逻辑

                                }
                            }
                        }
                    }
                }

                #endregion

                #region 响应堆垛机接出站台

                var stationForStockerOutResult = FindDevByType("stationForStockerOut");
                if (stationForStockerOutResult.Success)
                {
                    foreach (var stationForStockerOut in stationForStockerOutResult.Data)
                    {
                        var props = DeviceAddressEntities.FindAll(t => t.DeviceId == stationForStockerOut.Id);
                        if (ReadAddress(props))
                        {
                            //todo:站台响应逻辑
                            //PLC 有新消息标记 && WCS回复有新消息标记:此时WCS已经回复了消息,等待PLC响应,不做处理,如果PLC新标记为3,表示解析错误

                            //PLC没有新消息标记 && WCS有新消息标记:此时PLC已经确认消息,清除WCS回复消息

                            //PLC有新消息标记 && WCS没有新消息标记:此时PLC发送了消息而WCS没有响应,写响应逻辑发送地址数据给PLC

                        }

                    }
                }

                #endregion

                #region 响应出入库站台

                //todo:与接出站台类似,整出则完成任务、扫描到托盘号则请求任务、连接LED设备等,待确认后再写

                #endregion

                Interlocked.Exchange(ref inTimer, 0);
            }
        }

        #region 功能函数

        /// <summary>
        /// todo:校验堆垛机接入站台是否
        /// </summary>
        /// <param name="props"></param>
        /// <returns></returns>
        private bool ValidateStationForStockerIn(List<DeviceAddressEntity> props)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 响应入库性质的任务完成
        /// </summary>
        /// <param name="stockers"></param>
        private void ExcuteTaskComplete(List<DeviceEntity> stockers)
        {
            foreach (var stocker in stockers)
            {
                var propDatas = DeviceAddressEntities.FindAll(t => t.DeviceId == stocker.Id);
                if (ReadAddress(propDatas) && ValidateStockerForCompleteTask(stocker))
                {
                    //现获取要写入的数据的转换后类型,如果转换出错就不进行处理
                    BllResult writeDataResult = TansforAddressDataType(DevicePropEntities.Find(t => t.DeviceTypeId == stocker.DeviceTypeId && t.Code == "TaskNo1").Type, "0");
                    if (!writeDataResult.Success)
                    {
                        AddLogToUI(writeDataResult.Msg, 2);
                        break;
                    }
                    //获取任务号
                    var writeData = writeDataResult.Data;
                    var propData = propDatas.Find(t => t.DevicePropCode == "TaskNo1");
                    var taskCompleteResult = Bll.CompleteTask(propData.value);
                    if (taskCompleteResult.Success)
                    {
                        //任务完成成功:任务执行完成后由PLC向WCS发送任务完成消息,WCS清除任务信息,随后PLC更新堆垛机状态为待机
                        //清除任务
                        bool writeFlag = PLC.WriteData(new int[] { propData.ServerHandle }, new object[] { writeData });
                        if (!writeFlag)
                        {
                            AddLogToUI("完成任务" + propData.value + "成功,但是清除堆垛机" + stocker.ToString() + "任务失败", 2);
                        }
                    }
                    else
                    {
                        AddLogToUI("任务" + propData.value + " 堆垛机" + stocker.ToString() + "完成任务失败:" + taskCompleteResult.Msg, 2);
                    }
                }
            }
        }

        /// <summary>
        /// 数据类型转换
        /// </summary>
        /// <param name="type"></param>
        /// <param name="v"></param>
        /// <returns></returns>
        private BllResult TansforAddressDataType(string type, string data)
        {
            try
            {
                object obj = null;
                switch (type)
                {
                    case "BYTE": obj = Convert.ToUInt16(data); break;
                    case "DWORD": obj = Convert.ToUInt32(data); break;
                    case "BOOL": obj = Convert.ToBoolean(data); break;
                    case "WORD": obj = Convert.ToUInt32(data); break;
                    default:
                        obj = data;
                        break;
                }
                return BllResultFactory.Sucess(obj, "成功");
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(null, "数据转换出现异常,值:" + data + " 目标类型:" + type + " 异常:" + ex.ToString());
            }
        }

        /// <summary>
        /// todo:校验堆垛机是否可以进行任务完成
        /// </summary>
        /// <param name="stocker"></param>
        /// <returns></returns>
        private bool ValidateStockerForCompleteTask(DeviceEntity stocker)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 堆垛机执行出库任务
        /// </summary>
        /// <param name="taskEntities"></param>
        /// <param name="stockers"></param>
        private void ExcuteTaskOut(List<DeviceEntity> stockers)
        {
            List<TaskEntity> taskEntities = GetAllTaskOut();
            foreach (var task in taskEntities)
            {
                //获取任务所在巷道,即库位对应的巷道
                var BllResult = Bll.GetAllLocations(task.ContainerCode, null, null, null, null, null, null);
                if (!BllResult.Success)
                {
                    AddLogToUI("任务" + task.Id + "获取库位失败,消息:" + BllResult.Msg, 2);
                    continue;
                }
                var location = BllResult.Data[0];
                //查看巷道堆垛机和接出站台是否空闲无故障
                int stockerCount = stockers.Count(t => t.Roadway == location.Roadway);
                if (stockerCount != 1)
                {
                    AddLogToUI("任务" + task.Id + "获取巷道堆垛机失败,巷道:" + location.Roadway + " 对应:" + stockerCount + "个", 2);
                    continue;
                }
                var stocker = stockers.Where(t => t.Roadway == location.Roadway).First();
                //获取这个堆垛机的地址
                //地址校验交由初始化完成
                var props = DeviceAddressEntities.Where(t => t.DeviceId == stocker.Id).ToList();
                //堆垛机出库任务校验
                if (ReadAddress(props) && ValidateStockerOut(props))
                {
                    //校验对应堆垛机接出站台是否可以,按巷道查询
                    var stationForStockerOutResult = FindDevByType("stationForStockerOut");
                    if (stationForStockerOutResult.Success)
                    {
                        var stationForStockerOuts = stationForStockerOutResult.Data.FindAll(t => t.Roadway == location.Roadway);
                        foreach (var stationForStockerOut in stationForStockerOuts)
                        {
                            //校验接出站台是否可用
                            if (ValidateStationForStockerOut(stationForStockerOut))
                            {
                                if (stationForStockerOut.SelfAddress != -1)
                                {
                                    //可用,下发任务
                                    BllResult sendResult = SendTaskToStocker(stocker, stationForStockerOut, task);
                                    if (!BllResult.Success)
                                    {
                                        AddLogToUI("堆垛机" + stocker.ToString() + "下发任务失败:" + sendResult.Msg, 2);
                                    }
                                }
                                else
                                {
                                    AddLogToUI("堆垛机" + stocker.ToString() + "接出站台没有配置自身地址数据", 2);
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// todo:下发堆垛机任务
        /// </summary>
        /// <param name="stocker">堆垛机</param>
        /// <param name="stationForStocker">堆垛机接出接入站台</param>
        /// <param name="task">任务实体</param>
        /// <returns></returns>
        private BllResult SendTaskToStocker(DeviceEntity stocker, DeviceEntity stationForStocker, TaskEntity task)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取所有未完成的出库任务
        /// </summary>
        /// <returns></returns>
        private static List<TaskEntity> GetAllTaskOut()
        {
            List<TaskEntity> taskEntities = new List<TaskEntity>();
            var result = Bll.GetTasks("10", null, null, null, null);
            if (result.Success)
            {
                taskEntities = result.Data.Where(t => t.Type == 300 || t.Type == 400 || t.Type == 600 || t.Type == 700 || t.Type == 800).ToList();
            }

            return taskEntities;
        }


        /// <summary>
        /// todo:校验堆垛机接出站台是否可用
        /// </summary>
        /// <param name="stationForStockerOut"></param>
        /// <returns></returns>
        private bool ValidateStationForStockerOut(DeviceEntity stationForStockerOut)
        {
            throw new NotImplementedException();
        }

        private void AddLogToUI(string log, int level)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                this.LogInfo.AddLogs(log, level);
            }));
        }

        /// <summary>
        /// 读取所有地址数据
        /// </summary>
        private void ReadAllAddressData()
        {
            if (PLC == null || PLC.GetConnStatus() == false)
            {
                return;
            }
            var addressValues = PLC.ReadData(ServerHandle);
            if (addressValues == null)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    this.grid.Background = Brushes.Red;
                    this.LogInfo.AddLogs("地址读取失败!", 2);
                }));
                return;
            }
            else
            {
                for (int i = 0; i < DeviceAddressEntities.Count; i++)
                {
                    DeviceAddressEntities[i].value = addressValues.GetValue(i + 1).ToString();
                }
            }
        }

        /// <summary>
        /// 读取特定地址
        /// </summary>
        /// <param name="deviceAddressEntities"></param>
        private bool ReadAddress(List<DeviceAddressEntity> deviceAddressEntities)
        {
            if (PLC == null || PLC.GetConnStatus() == false || deviceAddressEntities == null || deviceAddressEntities.Count == 0)
            {
                AddLogToUI("地址读取失败,请检查通讯连接", 2);
                return false;
            }
            int[] handles = deviceAddressEntities.Select(t => t.ServerHandle).ToArray();
            var array = PLC.ReadData(handles);
            for (int i = 0; i < deviceAddressEntities.Count; i++)
            {
                deviceAddressEntities[i].value = array.GetValue(i + 1).ToString();
            }
            return true;
        }

        /// <summary>
        /// 堆垛机出库任务校验
        ///  堆垛机接收任务(入库、出库、拣选、转库)条件:
        ///1.    工作模式=2 联机;
        ///2.	操作模式=5  联机;
        ///3.	工作状态=0  待机;
        ///4.	DB101.DBB19=1 待机;   执行状态
        ///5.	叉原位,叉上无货;
        ///6.	堆垛机无故障;hack:?????哪个地址???
        ///7.	写入任务,任务号,任务标志=1—4
        ///hack:根据协议,出入库堆垛机条件其实是一样的,只是写入的任务和标志不同,这里暂时用同一个方法
        /// </summary>
        /// <param name="deviceAddressEntities"></param>
        /// <returns></returns>
        private bool ValidateStockerOut(List<DeviceAddressEntity> deviceAddressEntities)
        {
            try
            {
                if (deviceAddressEntities.First(t => t.DevicePropCode == "WorkModel").value == "2"
                    && deviceAddressEntities.First(t => t.DevicePropCode == "OperationModel").value == "5"
                    && deviceAddressEntities.First(t => t.DevicePropCode == "WorkStatus").value == "0"
                    && deviceAddressEntities.First(t => t.DevicePropCode == "TaskExcuteStatus").value == "1"
                    && deviceAddressEntities.First(t => t.DevicePropCode == "HasPallet").value == "1"
                    && deviceAddressEntities.First(t => t.DevicePropCode == "TaskNo1").value == "0"
                    // &&
                    )
                {
                    return true;
                }
            }
            catch (ArgumentNullException ex)
            {
                AddLogToUI("堆垛机属性地址不明确", 2);
            }
            catch (Exception ex)
            {
                AddLogToUI("堆垛机属性地址不明确", 2);
            }
            return false;
        }

        /// <summary>
        /// 查找指定设备类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private BllResult<List<DeviceEntity>> FindDevByType(string type)
        {
            try
            {
                var temp = DeviceEntities.Join(DeviceTypeEntities, a => a.Type, b => b.Id, (a, b) => new
                {
                    a,
                    b
                }).Where(c => c.b.Code == type).Select(d => d.a).ToList();
                return BllResultFactory.Sucess<List<DeviceEntity>>(temp, "成功");
            }
            catch (Exception)
            {
                return BllResultFactory.Error<List<DeviceEntity>>(new List<DeviceEntity>(), "异常或没有数据");
            }
        }

        #endregion

        #region 窗体事件

        private void Menu_pallet_Click(object sender, RoutedEventArgs e)
        {
            Frm_Pallet frm_Pallet = (Frm_Pallet)windows.FirstOrDefault(t => t.Key == "frm_Pallet").Value;
            if (frm_Pallet == null)
            {
                frm_Pallet = new Frm_Pallet();
                windows.Add("frm_Pallet", frm_Pallet);
            }
            frm_Pallet.Show();
            if (frm_Pallet.WindowState == WindowState.Minimized)
                frm_Pallet.WindowState = WindowState.Normal;
            frm_Pallet.Activate();
        }

        private void Menu_location_Click(object sender, RoutedEventArgs e)
        {
            Frm_Location frm_Location = (Frm_Location)windows.FirstOrDefault(t => t.Key == "frm_Location").Value;
            if (frm_Location == null)
            {
                frm_Location = new Frm_Location();
                windows.Add("frm_Location", frm_Location);
            }
            frm_Location.Show();
            if (frm_Location.WindowState == WindowState.Minimized)
                frm_Location.WindowState = WindowState.Normal;
            frm_Location.Activate();
        }

        private void Menu_device_OPCTest_Click(object sender, RoutedEventArgs e)
        {
            Frm_OPCTest frm_OPCTest = (Frm_OPCTest)windows.FirstOrDefault(t => t.Key == "frm_OPCTest").Value;
            if (frm_OPCTest == null)
            {
                frm_OPCTest = new Frm_OPCTest();
                windows.Add("frm_OPCTest", frm_OPCTest);
            }
            frm_OPCTest.Show();
            if (frm_OPCTest.WindowState == WindowState.Minimized)
                frm_OPCTest.WindowState = WindowState.Normal;
            frm_OPCTest.Activate();
        }

        private void Menu_task_info_Click(object sender, RoutedEventArgs e)
        {
            Frm_TaskInfo frm_TaskInfo = (Frm_TaskInfo)windows.FirstOrDefault(t => t.Key == "frm_taskinfo").Value;
            if (frm_TaskInfo == null)
            {
                frm_TaskInfo = new Frm_TaskInfo();
                windows.Add("frm_taskinfo", frm_TaskInfo);
            }
            frm_TaskInfo.Show();
            if (frm_TaskInfo.WindowState == WindowState.Minimized)
                frm_TaskInfo.WindowState = WindowState.Normal;
            frm_TaskInfo.Activate();

        }

        private void Menu_device_info_Click(object sender, RoutedEventArgs e)
        {
            Frm_DeviceInfo frm_DeviceInfo = (Frm_DeviceInfo)windows.FirstOrDefault(t => t.Key == "frm_DeviceInfo").Value;
            if (frm_DeviceInfo == null)
            {
                frm_DeviceInfo = new Frm_DeviceInfo();
                windows.Add("frm_DeviceInfo", frm_DeviceInfo);
            }
            frm_DeviceInfo.Show();
            if (frm_DeviceInfo.WindowState == WindowState.Minimized)
                frm_DeviceInfo.WindowState = WindowState.Normal;
            frm_DeviceInfo.Activate();
        }

        private void Menu_sys_exit_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void btn_UpdateTask_Click(object sender, RoutedEventArgs e)
        {
            timer.Enabled = !timer.Enabled;
            inTimer = 0;
            //dgv_1.ItemsSource = Bill.GetTasks(null, null, null, DateTime.Now.AddDays(-7), null).Data.OrderBy(t => t.Status).ThenBy(t => t.Created).Take(100);
        }
        #endregion

    }
}