Frm_Main.xaml.cs 110 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 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
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;
using LEDhelp;
using HHWCS;
using HHWCSHost.Model;
using HHECS.View.UserOperation;

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

        //const string plcAdressPrefix = "S7:[S7 connection_1]";
        private object locker = new object();

        //所有子窗口
        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; }

        /// <summary>
        /// 时钟控制器
        /// </summary>
        bool stop = false;


        public LEDModel led { get; set; }
        #endregion

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

            InitMenu();
            InitStatusBar();
            InitTimer();
            InitOPC();
            InitDeviceData();
            led = new LEDModel()
            {
                LED = new LEDHelper(AppCommon.LedIP, AppCommon.LedPort, AppCommon.LedTimer),
                InfoQueue = new Queue<string>()
            };
            led.BeginSendInfo();
            //单机版不需要
            WMSHeartbeat();
        }

        #region 初始化
        private void InitDeviceData()
        {
            var temp = AppCommon.Bll.GetAllDevice();
            var temp2 = AppCommon.Bll.GetAllDeviceAddress();
            var temp3 = AppCommon.Bll.GetAllDeviceProp();
            var temp4 = AppCommon.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(32, false, false, 1200, 100)
                {
                    ControlName = item.Name,
                    Name = item.Code
                };
                this.RegisterName(item.Code, stockerMonitor);
                panel_Stocker.Children.Add(stockerMonitor);
                StockerInfo stockerInfo = new StockerInfo(450, 500)
                {
                    ControlName = item.Name,
                    Name = item.Code
                };
                stockerInfo.DoubleInEvent += this.DoubleInHandle;
                stockerInfo.EmptyOutEvent += this.EmptyOutHandle;
                panel_Bottom.Children.Add(stockerInfo);
            }

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

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

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

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

        private void InitOPC()
        {
            try
            {
                PLCIP = ConfigurationManager.AppSettings["OPCServerIP"];
                PLC = new OPCHelp(PLCIP);
            }
            catch (Exception)
            {
                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
            {
                Header = "系统"
            };
            MenuItem menu_sys_exit = new MenuItem
            {
                Header = "退出"
            };
            MenuItem menu_relogin = new MenuItem
            {
                Header = "重新连接WMS"
            };
            menu_sys_exit.Click += Menu_sys_exit_Click;
            menu_relogin.Click += Menu_relogin_Click;
            menu_sys.Items.Add(menu_relogin);
            menu_sys.Items.Add(menu_sys_exit);


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

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

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

            //权限
            MenuItem menu_Right = new MenuItem
            {
                Header = "权限管理"
            };

            MenuItem menu_Permission = new MenuItem
            {
                Header = "权限"
            };
            menu_Permission.Click += Menu_Permission_Click;
            MenuItem menu_Role = new MenuItem
            {
                Header = "角色"
            };
            menu_Role.Click += Menu_Role_Click;
            MenuItem menu_User = new MenuItem
            {
                Header = "用户"
            };
            menu_User.Click += Menu_User_Click;
            menu_Right.Items.Add(menu_Permission);
            menu_Right.Items.Add(menu_Role);
            menu_Right.Items.Add(menu_User);


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

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

        private void Menu_User_Click(object sender, RoutedEventArgs e)
        {
            WinUser win = new WinUser();
            win.ShowDialog();
        }

        private void Menu_Role_Click(object sender, RoutedEventArgs e)
        {
            WinRole win = new WinRole();
            win.ShowDialog();
        }

        private void Menu_Permission_Click(object sender, RoutedEventArgs e)
        {
            WinPermission win = new WinPermission();
            win.ShowDialog();
        }

        private async void Menu_relogin_Click(object sender, RoutedEventArgs e)
        {
            var ret = await AppCommon.Bll.Login(AppCommon.User.UserName, AppCommon.User.Password);
            if (ret.Success)
            {
                MessageBox.Show("重新连接WMS成功");
            }
            else
            {
                MessageBox.Show("重新连接WMS失败:" + ret.Msg, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }


        /// <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
            stop = false;
            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(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
            stop = true;
        }

        private void InitTimer()
        {
            timer.Interval = 1000; //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)
            //{
            lock (locker)
            {
                #region 是否结束处理

                if (stop)
                {
                    if (PLC.GetConnStatus())
                    {
                        PLC.CloseConn();
                    }
                    Dispatcher.Invoke(() =>
                    {
                        btn_ClosePLCConnect.IsEnabled = false;
                        btn_OpenPLCConnect.IsEnabled = true;
                        timer.Enabled = false;
                    });

                    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 readAllAddressDataResult = ReadAllAddressData();
                if (!readAllAddressDataResult.Success)
                {
                    AddLogToUI("读取地址数据失败,请尝试关闭连接后重新连接;", 2);
                    return;
                }

                //日志
                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));
                        }
                        if (item is StationInfo station)
                        {
                            var a = DeviceEntities.Find(t => t.Code == station.Name);
                            station.SetProp(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);
                        stockerMonitor.SetProp(addressEntities);
                    }
                    foreach (var item in FindDevByType("conveyor").Data)
                    {
                        var cv = this.FindName(item.Code);
                        if (cv is StationV stationV)
                        {
                            stationV.SetProp(DeviceAddressEntities.FindAll(t => t.DeviceId == item.Id));
                        }
                        if (cv is StationH stationH)
                        {
                            stationH.SetProp(DeviceAddressEntities.FindAll(t => t.DeviceId == item.Id));
                        }
                    }
                }));

                #endregion

                #region 堆垛机操作
                //找出所有堆垛机
                var stockersResult = FindDevByType("stocker");
                if (stockersResult.Success)
                {
                    var stockers = stockersResult.Data;
                    //响应任务完成
                    ExcuteTaskComplete(stockers);
                    //遍历所有出库性质的任务
                    ExcuteTaskOut(stockers);
                    //响应入库任务
                    ExcuteTaskIn(stockers);
                    //同巷道内的移库,当堆垛机状态为0,1,2时,均可以响应巷道内的移库
                    ExcuteTaskTransferInRoadway(stockers);

                }

                #endregion

                #region 响应堆垛机接入站台

                var stationForStockerInResult = FindDevByType("stationForStockerIn");
                if (stationForStockerInResult.Success)
                {
                    foreach (var stationForStockerIn in stationForStockerInResult.Data)
                    {
                        var addresses = DeviceAddressEntities.FindAll(t => t.DeviceId == stationForStockerIn.Id);
                        var readResult = ReadAddress(addresses);
                        if (readResult.Success)
                        {
                            //这里先直接回应一个响应
                            //如果PLC标记为3,则表示解析有误,这里报警
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "3")
                            {
                                AddLogToUI("PLC解析站台" + stationForStockerIn + "数据失败,请检查基础数据!", 2);
                                continue;
                            }

                            //PLC 有新消息标记 && WCS回复有新消息标记:此时WCS已经回复了消息,等待PLC响应,不做处理,如果PLC新标记为3,表示解析错误
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "1" && addresses.Find(t => t.DevicePropCode == "WCSFlag").value == "1")
                            {
                                continue;
                            }

                            //PLC没有新消息标记 && WCS有新消息标记:此时PLC已经确认消息,清除WCS回复消息
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value != "1" && addresses.Find(t => t.DevicePropCode == "WCSFlag").value == "1")
                            {
                                var result = WriteWCSStationDataAddress(addresses, "0", "0", "0", "0", "0", "0", "", "0", "0");
                                if (result.Success)
                                {
                                    AddLogToUI("清空" + stationForStockerIn + "WCS区地址成功", 1);
                                }
                                else
                                {
                                    AddLogToUI("清空" + stationForStockerIn + "WCS区地址失败:" + result.Msg, 2);
                                }
                                continue;
                            }

                            //PLC有新消息标记 && WCS没有新消息标记:此时PLC发送了消息而WCS没有响应,写响应逻辑发送地址数据给PLC
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "1"
                                && addresses.Find(t => t.DevicePropCode == "WCSFlag").value != "1"
                                //这里做一次校验防止与PLC扫描冲突
                                && addresses.Find(t => t.DevicePropCode == "Type").value != "0"
                                && addresses.Find(t => t.DevicePropCode == "PLCNo").value != "0"
                                && addresses.Find(t => t.DevicePropCode == "StationNo").value != "0"
                                && !String.IsNullOrWhiteSpace(addresses.Find(t => t.DevicePropCode == "Barcode").value))
                            {
                                //判断报文类型
                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "1")
                                {
                                    //地址请求
                                    AddLogToUI("堆垛机接入站台" + stationForStockerIn + "暂时没有实现地址请求", 3);
                                    continue;
                                }
                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "2")
                                {
                                    //响应一个位置到达请求
                                    //更新任务状态为35
                                    String palletCode = addresses.Find(t => t.DevicePropCode == "Barcode").value;
                                    var bllResult = AppCommon.Bll.GetTaskUncompleteByPalletCode(palletCode);
                                    if (!bllResult.Success)
                                    {
                                        AddLogToUI("站台" + stationForStockerIn + "对应托盘" + palletCode + "没有查找到任务数据", 2);
                                        continue;
                                    }
                                    var task = bllResult.Data;
                                    if (task.LastStatus > 31)
                                    {
                                        AddLogToUI("站台" + stationForStockerIn + "对应托盘" + palletCode + "没有查找到任务" + task.Id + "状态已经超过30,应已响应,请检查", 2);
                                        continue;
                                    }
                                    //给他回一个位置到达
                                    var temp = WriteWCSStationDataAddress(addresses, "1", "8", addresses.Find(t => t.DevicePropCode == "PLCNo").value, "0", addresses.Find(t => t.DevicePropCode == "StationNo").value, addresses.Find(t => t.DevicePropCode == "TaskNo").value, addresses.Find(t => t.DevicePropCode == "Barcode").value, "0", "0");
                                    if (temp.Success)
                                    {
                                        //位置到达回复成功后,更新任务状态
                                        AppCommon.Bll.SetTaskStatus(task.Id, 35);
                                        AddLogToUI("位置到达:任务" + task.Id + "位置到达写入" + stationForStockerIn + "WCS区地址成功", 1);
                                    }
                                    else
                                    {
                                        AddLogToUI("位置到达:写入" + stationForStockerIn + "WCS区地址失败:" + temp.Msg, 2);
                                    }
                                    continue;
                                }
                                //判断报文类型
                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "3")
                                {
                                    //地址请求
                                    AddLogToUI("堆垛机接入站台" + stationForStockerIn + "暂时没有控制指令请求", 3);
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            AddLogToUI(readResult.Msg, 2);
                        }
                    }
                }

                #endregion

                #region 响应堆垛机接出站台

                var stationForStockerOutResult = FindDevByType("stationForStockerOut");
                if (stationForStockerOutResult.Success)
                {
                    foreach (var stationForStockerOut in stationForStockerOutResult.Data)
                    {
                        var addresses = DeviceAddressEntities.FindAll(t => t.DeviceId == stationForStockerOut.Id);
                        var readResult = ReadAddress(addresses);
                        if (readResult.Success)
                        {
                            //如果PLC标记为3,则表示解析有误,这里报警
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "3")
                            {
                                AddLogToUI("PLC解析站台" + stationForStockerOut + "数据失败,请检查基础数据!", 2);
                                continue;
                            }

                            //PLC 有新消息标记 && WCS回复有新消息标记:此时WCS已经回复了消息,等待PLC响应,不做处理,如果PLC新标记为3,表示解析错误
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "1" && addresses.Find(t => t.DevicePropCode == "WCSFlag").value == "1")
                            {
                                continue;
                            }

                            //PLC没有新消息标记 && WCS有新消息标记:此时PLC已经确认消息,清除WCS回复消息
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value != "1" && addresses.Find(t => t.DevicePropCode == "WCSFlag").value == "1")
                            {
                                var result = WriteWCSStationDataAddress(addresses, "0", "0", "0", "0", "0", "0", "", "0", "0");
                                if (result.Success)
                                {
                                    AddLogToUI("清空" + stationForStockerOut + "WCS区地址成功", 1);
                                }
                                else
                                {
                                    AddLogToUI("清空" + stationForStockerOut + "WCS区地址失败:" + result.Msg, 2);
                                }
                                continue;
                            }

                            //PLC有新消息标记 && WCS没有新消息标记:此时PLC发送了消息而WCS没有响应,写响应逻辑发送地址数据给PLC
                            //加入地址校验,防止PLC写入与WCS读取冲突;堆垛机接出站台,地址请求时时没有带条码的,需要我们写入
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "1"
                                && addresses.Find(t => t.DevicePropCode == "WCSFlag").value != "1"
                                && addresses.Find(t => t.DevicePropCode == "Type").value != "0"
                                && addresses.Find(t => t.DevicePropCode == "PLCNo").value != "0"
                                && addresses.Find(t => t.DevicePropCode == "StationNo").value != "0"
                                )
                            {
                                //判断报文类型
                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "1")
                                {
                                    //表示地址请求
                                    //hack:假设没有移库任务
                                    //获取任务状态为25的任务
                                    var tasksResult = AppCommon.Bll.GetTasks("25", null, null, null, null);
                                    if (!tasksResult.Success || tasksResult.Data.Count == 0)
                                    {
                                        AddLogToUI("未找到站台" + stationForStockerOut + "对应的任务,无法响应地址请求", 2);
                                        continue;
                                    }
                                    int roadWay = stationForStockerOut.Roadway;
                                    string palletCode = "";
                                    TaskEntity task = null;
                                    foreach (var item in tasksResult.Data)
                                    {
                                        var locationResult = AppCommon.Bll.GetAllLocations(item.ContainerCode, null, null, null, null, null, null);
                                        if (locationResult.Success)
                                        {
                                            LocationEntity locationEntity = locationResult.Data[0];
                                            if (locationEntity.Roadway == roadWay)
                                            {
                                                //说明这个任务是这个巷道的,则获取他的托盘号
                                                palletCode = item.ContainerCode;
                                                task = item;
                                                break;
                                            }
                                        }
                                    }
                                    if (string.IsNullOrEmpty(palletCode))
                                    {
                                        AddLogToUI("未找到站台" + stationForStockerOut + "对应的任务所对应的库位,无法响应地址请求", 2);
                                        continue;
                                    }

                                    //判断是不是移库,如果是移库则是去堆垛机接入站台
                                    if (task.Type == 800)
                                    {
                                        //todo:移库堆垛机接入站台处理
                                    }
                                    else
                                    {
                                        int flag = 0;
                                        if (task.Type == 300 || task.Type == 600)
                                        {
                                            flag = 1;
                                        }
                                        //获取一个站台
                                        var station = DeviceEntities.Join(DeviceTypeEntities, a => a.DeviceTypeId, b => b.Id, (a, b) => new { a, b }).Where(t => t.b.Code == "stationOut" || t.b.Code == "station").Select(t => t.a).FirstOrDefault();
                                        if (station != null)
                                        {
                                            //写入响应数据
                                            var result = WriteWCSStationDataAddress(addresses, "1", "6", addresses.Find(t => t.DevicePropCode == "PLCNo").value, "0", addresses.Find(t => t.DevicePropCode == "StationNo").value, addresses.Find(t => t.DevicePropCode == "TaskNo").value, palletCode, station.SelfAddress.ToString(), flag.ToString());
                                            if (result.Success)
                                            {
                                                //更新任务状态为28,表示这条任务已经响应了地址请求
                                                AppCommon.Bll.SetTaskStatus(task.Id, 28);
                                                AddLogToUI("写入" + stationForStockerOut + "WCS区地址成功", 1);
                                            }
                                            else
                                            {
                                                AddLogToUI("写入" + stationForStockerOut + "WCS区地址失败:" + result.Msg, 2);
                                            }
                                        }
                                        else
                                        {
                                            AddLogToUI("未找到出库站台", 2);
                                        }
                                    }
                                }
                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "2")
                                {
                                    //地址请求
                                    AddLogToUI("堆垛机接入站台" + stationForStockerOut + "暂时没有实现位置到达请求", 3);
                                    continue;
                                }
                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "3")
                                {
                                    //地址请求
                                    AddLogToUI("堆垛机接入站台" + stationForStockerOut + "暂时没有实现控制指令请求", 3);
                                    continue;
                                }

                            }

                        }
                        else
                        {
                            AddLogToUI("读取" + stationForStockerOut + "地址失败:" + readResult.Msg, 2);
                        }
                    }
                }

                #endregion

                #region 响应出入库站台(拣选台)

                //todo:与接出站台类似,整出则完成任务、扫描到托盘号则请求任务、连接LED设备等,待确认后再写
                //目前立体库中只有station
                var stations = FindDevByType("station");
                if (stations.Success)
                {
                    foreach (var station in stations.Data)
                    {
                        var addresses = DeviceAddressEntities.FindAll(t => t.DeviceId == station.Id);
                        var readResult = ReadAddress(addresses);
                        if (readResult.Success)
                        {
                            //如果PLC标记为3,则表示解析有误,这里报警
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "3")
                            {
                                AddLogToUI("PLC解析站台" + station + "数据失败,请检查基础数据!", 2);
                                continue;
                            }

                            //PLC 有新消息标记 && WCS回复有新消息标记:此时WCS已经回复了消息,等待PLC响应,不做处理,如果PLC新标记为3,表示解析错误
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "1" && addresses.Find(t => t.DevicePropCode == "WCSFlag").value == "1")
                            {
                                continue;
                            }

                            //PLC没有新消息标记 && WCS有新消息标记:此时PLC已经确认消息,清除WCS回复消息
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value != "1" && addresses.Find(t => t.DevicePropCode == "WCSFlag").value == "1")
                            {
                                var result = WriteWCSStationDataAddress(addresses, "0", "0", "0", "0", "0", "0", "", "0", "0");
                                if (result.Success)
                                {
                                    AddLogToUI("清空" + station + "WCS区地址成功", 1);
                                }
                                else
                                {
                                    AddLogToUI("清空" + station + "WCS区地址失败:" + result.Msg, 2);
                                }
                                continue;
                            }

                            //PLC有新消息标记 && WCS没有新消息标记:此时PLC发送了消息而WCS没有响应,写响应逻辑发送地址数据给PLC
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "1"
                                && addresses.Find(t => t.DevicePropCode == "WCSFlag").value != "1"
                                && addresses.Find(t => t.DevicePropCode == "Type").value != "0"
                                && addresses.Find(t => t.DevicePropCode == "PLCNo").value != "0"
                                && addresses.Find(t => t.DevicePropCode == "StationNo").value != "0"
                                && !String.IsNullOrWhiteSpace(addresses.Find(t => t.DevicePropCode == "Barcode").value))
                            {
                                //获取任务
                                string pallet = addresses.Find(t => t.DevicePropCode == "Barcode").value;
                                var taskResult = AppCommon.Bll.GetTaskUncompleteByPalletCode(pallet);
                                if (!taskResult.Success)
                                {
                                    AddLogToUI(station + " 根据" + pallet + "获取任务失败:" + taskResult.Msg, 3);
                                    continue;
                                }
                                TaskEntity taskEntity = taskResult.Data;
                                //判断报文类型
                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "1")
                                {
                                    //表示地址请求,此时可能是分拣回库,也可能是新入库,也可能是空托入库,这里空托入库如果没有任务就自动生成任务(自动生成空托盘入库暂时不实现)
                                    //获取目标库位
                                    //hack:这里临时加个判断,如果任务状态不是31,则不响应
                                    if (taskEntity.LastStatus == 31)
                                    {
                                        LocationEntity location;
                                        if (taskEntity.Type == 100 || taskEntity.Type == 500)
                                        {
                                            var locationResult = AppCommon.Bll.GetAllLocations(null, null, null, null, null, null, taskEntity.DestinationLocation);
                                            if (!locationResult.Success)
                                            {
                                                AddLogToUI("未找到任务" + taskEntity.Id + "对应的" + taskEntity.DestinationLocation + "库位", 2);
                                                continue;
                                            }
                                            location = locationResult.Data[0];
                                        }
                                        else if (taskEntity.Type == 200 || taskEntity.Type == 400 || taskEntity.Type == 900 || taskEntity.Type == 700)
                                        {
                                            var locationResult = AppCommon.Bll.GetAllLocations(null, null, null, null, null, null, taskEntity.SourceLocation);
                                            if (!locationResult.Success)
                                            {
                                                AddLogToUI("未找到任务" + taskEntity.Id + "对应的" + taskEntity.SourceLocation + "库位", 2);
                                                continue;
                                            }
                                            location = locationResult.Data[0];
                                        }
                                        else
                                        {
                                            AddLogToUI("任务" + taskEntity.Id + "对应的类型" + taskEntity.Type + "不符合地址请求要求", 2);
                                            continue;
                                        }
                                        //获取这个库位的目标巷道,从而得出对应的接入站台
                                        var stockerStationIns = DeviceEntities.Join(DeviceTypeEntities, t => t.DeviceTypeId, a => a.Id, (a, b) => new { a, b }).Where(t => t.b.Code == "stationForStockerIn" && t.a.Roadway == location.Roadway).Select(t => t.a).ToList();
                                        if (stockerStationIns.Count == 0)
                                        {
                                            AddLogToUI("未找到任务" + taskEntity.Id + "对应的堆垛机接入站台,巷道:" + location.Roadway + ",托盘:" + taskEntity.ContainerCode, 2);
                                            continue;
                                        }
                                        else
                                        {
                                            var stockerStationIn = stockerStationIns[0];
                                            //写入响应地址
                                            var result = WriteWCSStationDataAddress(addresses, "1", "06", addresses.Find(t => t.DevicePropCode == "PLCNo").value, "0", addresses.Find(t => t.DevicePropCode == "StationNo").value, addresses.Find(t => t.DevicePropCode == "TaskNo").value, addresses.Find(t => t.DevicePropCode == "Barcode").value, stockerStationIn.SelfAddress.ToString(), "0");
                                            if (result.Success)
                                            {
                                                //这里清空led显示
                                                led.InfoQueue.Enqueue(" ");
                                                AddLogToUI("写入" + station + "WCS区地址成功;任务:" + taskEntity.Id.ToString(), 1);
                                            }
                                            else
                                            {
                                                AddLogToUI("写入" + station + "WCS区地址失败,任务:" + taskEntity.Id.ToString() + "消息:" + result.Msg, 2);
                                            }
                                        }
                                    }
                                }

                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "2")
                                {
                                    //表示位置到达,此时检查任务,如果是整出、空出则完成任务
                                    //写给PLC的一个标志位,当为1时,表示托盘到此中止;当为2时,表示托盘还需要回库;
                                    int flag = 0;
                                    if (taskEntity.LastStatus != 28)
                                    {
                                        AddLogToUI("站台" + station + "位置到达,但是任务" + taskEntity.Id + "状态为" + taskEntity.LastStatus + ",此处要求状态为28才会处理", 2);
                                        continue;
                                    }
                                    if (taskEntity.Type == 300 || taskEntity.Type == 600)
                                    {
                                        var result = AppCommon.Bll.CompleteTask(taskEntity.Id.ToString());
                                        if (result.Success)
                                        {
                                            flag = 1;
                                            AddLogToUI("站台" + station + ",完成" + taskEntity.Id.ToString() + "成功", 1);
                                        }
                                        else
                                        {
                                            AddLogToUI("完成任务" + taskEntity.Id.ToString() + "失败:" + result.Msg, 2);
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        //如果是其他类型的任务则更新状态为到达站台并响应
                                        var result = AppCommon.Bll.SetTaskStatus(taskEntity.Id, 30);
                                        if (result.Success)
                                        {
                                            flag = 2;
                                            AddLogToUI("站台" + station + ",更新任务" + taskEntity.Id.ToString() + "状态30成功", 1);
                                        }
                                        else
                                        {
                                            AddLogToUI("站台" + station + ",更新任务" + taskEntity.Id.ToString() + "状态30失败:" + result.Msg, 2);
                                            continue;
                                        }
                                    }
                                    //响应一个位置请求
                                    var temp = WriteWCSStationDataAddress(addresses, "1", "8", addresses.Find(t => t.DevicePropCode == "PLCNo").value, "0", addresses.Find(t => t.DevicePropCode == "StationNo").value, addresses.Find(t => t.DevicePropCode == "TaskNo").value, addresses.Find(t => t.DevicePropCode == "Barcode").value, "0", flag.ToString());
                                    if (temp.Success)
                                    {
                                        //发送电子屏
                                        SendToLED(taskEntity);
                                        AddLogToUI("位置到达写入" + station + "WCS区地址成功", 1);
                                    }
                                    else
                                    {
                                        AddLogToUI("位置到达写入" + station + "WCS区地址失败:" + temp.Msg, 2);
                                    }
                                    continue;
                                }

                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "3")
                                {
                                    //表示控制指令
                                    //todo:控制指令先不弄
                                    AddLogToUI("控制指令暂时没有实现", 1);
                                }

                            }
                        }
                        else
                        {
                            AddLogToUI("读取" + station + "地址失败:" + readResult.Msg, 2);
                        }
                    }
                }

                #endregion

                #region 响应只入站台

                var stationIns = FindDevByType("stationIn");
                if (stationIns.Success)
                {
                    foreach (var stationIn in stationIns.Data)
                    {
                        var addresses = DeviceAddressEntities.FindAll(t => t.DeviceId == stationIn.Id);
                        var readResult = ReadAddress(addresses);
                        if (readResult.Success)
                        {
                            //如果PLC标记为3,则表示解析有误,这里报警
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "3")
                            {
                                AddLogToUI("PLC解析站台" + stationIn + "数据失败,请检查基础数据!", 2);
                                continue;
                            }

                            //PLC 有新消息标记 && WCS回复有新消息标记:此时WCS已经回复了消息,等待PLC响应,不做处理,如果PLC新标记为3,表示解析错误
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "1" && addresses.Find(t => t.DevicePropCode == "WCSFlag").value == "1")
                            {
                                continue;
                            }

                            //PLC没有新消息标记 && WCS有新消息标记:此时PLC已经确认消息,清除WCS回复消息
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value != "1" && addresses.Find(t => t.DevicePropCode == "WCSFlag").value == "1")
                            {
                                var result = WriteWCSStationDataAddress(addresses, "0", "0", "0", "0", "0", "0", "", "0", "0");
                                if (result.Success)
                                {
                                    AddLogToUI("清空" + stationIn + "WCS区地址成功", 1);
                                }
                                else
                                {
                                    AddLogToUI("清空" + stationIn + "WCS区地址失败:" + result.Msg, 2);
                                }
                                continue;
                            }

                            //PLC有新消息标记 && WCS没有新消息标记:此时PLC发送了消息而WCS没有响应,写响应逻辑发送地址数据给PLC
                            if (addresses.Find(t => t.DevicePropCode == "Flag").value == "1"
                                && addresses.Find(t => t.DevicePropCode == "WCSFlag").value != "1"
                                && addresses.Find(t => t.DevicePropCode == "Type").value != "0"
                                && addresses.Find(t => t.DevicePropCode == "PLCNo").value != "0"
                                && addresses.Find(t => t.DevicePropCode == "StationNo").value != "0"
                                && !String.IsNullOrWhiteSpace(addresses.Find(t => t.DevicePropCode == "Barcode").value))
                            {
                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "1")
                                {
                                    //获取任务
                                    string pallet = addresses.Find(t => t.DevicePropCode == "Barcode").value;
                                    if (pallet == "??????" || pallet == "NoRead")
                                    {
                                        AddLogToUI(stationIn + "未识别的条码", 3);
                                        StationBack(addresses, stationIn);
                                        continue;
                                    }
                                    var taskResult = AppCommon.Bll.GetTaskUncompleteByPalletCode(pallet);
                                    if (!taskResult.Success)
                                    {
                                        AddLogToUI(stationIn + " 根据" + pallet + "获取任务失败:" + taskResult.Msg, 2);
                                        StationBack(addresses, stationIn);
                                        continue;
                                    }
                                    TaskEntity taskEntity = taskResult.Data;
                                    if (taskEntity.LastStatus >= 30)
                                    {
                                        AddLogToUI(stationIn + " 根据" + pallet + "获取任务成功,但任务状态已超过30", 2);
                                        StationBack(addresses, stationIn);
                                        continue;
                                    }
                                    //判断任务,这里只允许整入和空入库任务,如果托盘带有其他类型任务则报错
                                    if (taskEntity.Type != 100 && taskEntity.Type != 500)
                                    {
                                        AddLogToUI("站台" + stationIn + ",任务" + taskEntity.Id + ",任务类型不符合要求,入库站台只能整入或者空入", 2);
                                        StationBack(addresses, stationIn);
                                        continue;
                                    }
                                    if (taskEntity.Station > 20)
                                    {
                                        AddLogToUI("站台" + stationIn + ",任务" + taskEntity.Id + ",任务状态不符合,入库站台任务状态是刚下达或开始执行状态", 2);
                                        StationBack(addresses, stationIn);
                                        continue;
                                    }
                                    //电气高度标志
                                    int height = Convert.ToInt32(addresses.Find(t => t.DevicePropCode == "Height").value);
                                    if (String.IsNullOrWhiteSpace(taskEntity.DestinationLocation))
                                    {
                                        BllResult<string> bllResult = AppCommon.Bll.GetDestinationLocation<string>(taskEntity.Id, height);
                                        if (bllResult.Success)
                                        {
                                            taskEntity.DestinationLocation = bllResult.Data;
                                        }
                                        else
                                        {
                                            AddLogToUI("站台" + stationIn + ",任务" + taskEntity.Id + ",获取目标库位失败", 2);
                                            StationBack(addresses, stationIn);
                                            continue;
                                        }

                                    }
                                    var locationResult = AppCommon.Bll.GetAllLocations(null, null, null, null, null, null, taskEntity.DestinationLocation);
                                    if (!locationResult.Success)
                                    {
                                        AddLogToUI("站台" + stationIn + "未找到任务" + taskEntity.Id + ",托盘:" + taskEntity.ContainerCode + ",目标库位编码:" + taskEntity.DestinationLocation + "的库位;请检查库位编码是否正确", 2);
                                        StationBack(addresses, stationIn);
                                        continue;
                                    }
                                    var location = locationResult.Data[0];
                                    //校验这个库位与电气反馈高度对比
                                    //0可以入1到5层,1只能去第五层
                                    //int height =Convert.ToInt32(addresses.Find(t => t.DevicePropCode == "Height").value);
                                    switch (height)
                                    {
                                        case 0:
                                            break;
                                        case 1:
                                            if (location.Layer != 5)
                                            {
                                                AddLogToUI(stationIn + "货物超高" + height, 2);
                                                StationBack(addresses, stationIn);
                                                continue;
                                            }
                                            break;
                                        default:
                                            AddLogToUI(stationIn + "未识别的高度值" + height, 2);
                                            StationBack(addresses, stationIn);
                                            continue;
                                    }
                                    if (!String.IsNullOrEmpty(location.ContainerCode))
                                    {
                                        AddLogToUI(stationIn + "重入", 2);
                                        StationBack(addresses, stationIn);
                                        continue;
                                    }
                                    //获取这个库位的目标巷道,从而得出对应的接入站台
                                    var stockerStationIns = DeviceEntities.Join(DeviceTypeEntities, t => t.DeviceTypeId, a => a.Id, (a, b) => new { a, b }).Where(t => t.b.Code == "stationForStockerIn" && t.a.Roadway == location.Roadway).Select(t => t.a).ToList();
                                    if (stockerStationIns.Count == 0)
                                    {
                                        AddLogToUI("站台" + stationIn + "未找到任务" + taskEntity.Id + "对应的堆垛机接入站台,巷道:" + location.Roadway + ",托盘:" + taskEntity.ContainerCode, 2);
                                        StationBack(addresses, stationIn);
                                        continue;
                                    }
                                    var stockerStationIn = stockerStationIns[0];
                                    var result = WriteWCSStationDataAddress(addresses, "1", "06", addresses.Find(t => t.DevicePropCode == "PLCNo").value, "0", addresses.Find(t => t.DevicePropCode == "StationNo").value, addresses.Find(t => t.DevicePropCode == "TaskNo").value, addresses.Find(t => t.DevicePropCode == "Barcode").value, stockerStationIn.SelfAddress.ToString(), "0");
                                    if (result.Success)
                                    {
                                        //这里将任务状态更新为30,表示达到了站台,即入库进行整个流程的后一半
                                        SendToLED(taskEntity);
                                        AppCommon.Bll.SetTaskStatus(taskEntity.Id, 30);
                                        AddLogToUI("写入" + stationIn + "WCS区地址成功,任务:" + taskEntity.Id, 1);
                                    }
                                    else
                                    {
                                        AddLogToUI("写入" + stationIn + "WCS区地址失败,任务:" + taskEntity.Id + ",消息:" + result.Msg, 2);
                                    }
                                }

                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "2")
                                {
                                    //地址请求
                                    AddLogToUI("入库站台" + stationIn + "暂时没有实现位置到达请求", 3);
                                    continue;
                                }

                                if (addresses.Find(t => t.DevicePropCode == "Type").value == "3")
                                {
                                    //地址请求
                                    AddLogToUI("入库站台" + stationIn + "暂时没有实现控制指令请求", 3);
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            AddLogToUI("读取" + stationIn + "地址失败:" + readResult.Msg, 2);
                        }
                    }
                }

                #endregion

                #region 响应只出站台
                //这个目前不涉及
                #endregion

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


        #region 功能函数

        /// <summary>
        /// 入库口回退
        /// </summary>
        /// <param name="deviceAddresses"></param>
        /// <returns></returns>
        private void StationBack(List<DeviceAddressEntity> addresses, DeviceEntity device)
        {
            //获取地址
            var result = WriteWCSStationDataAddress(addresses, "1", "06", addresses.Find(t => t.DevicePropCode == "PLCNo").value, "0", addresses.Find(t => t.DevicePropCode == "StationNo").value, addresses.Find(t => t.DevicePropCode == "TaskNo").value, addresses.Find(t => t.DevicePropCode == "Barcode").value, device.BackAddress, "0");
            if (result.Success)
            {
                AddLogToUI($"{device}回退成功", 1);
            }
            else
            {
                AddLogToUI($"{device}回退写入失败,请人工处理", 2);
            }

        }

        /// <summary>
        /// 处理重入
        /// </summary>
        /// <param name="location"></param>
        /// <param name="device"></param>
        /// <returns></returns>
        public BllResult DoubleInHandle(LocationEntity location, DeviceEntity device)
        {
            if (PLC == null || PLC.GetConnStatus() == false || DeviceAddressEntities == null || DeviceAddressEntities.Count == 0)
            {
                //AddLogToUI("地址读取失败,请检查通讯连接", 2);
                return BllResultFactory.Error(null, "地址读取失败,请检查通讯连接");
            }
            var addresses = DeviceAddressEntities.FindAll(t => t.DeviceId == device.Id);
            //获取任务和是否重入
            var taskProp = addresses.Find(t => t.DevicePropCode == "TaskNo1");
            var doubleInProp = addresses.Find(t => t.DevicePropCode == "DoubleIn");
            if (taskProp == null | doubleInProp == null)
            {
                return BllResultFactory.Error(null, $"未找到堆垛机{device}的任务和重入属性");
            }
            if (doubleInProp.value != "True")
            {
                return BllResultFactory.Error(null, $"堆垛机{device}未报重入错误");
            }
            var taskResult = AppCommon.Bll.GetTasks(null, taskProp.value, null, null, null);
            if (taskResult.Success)
            {
                var task = taskResult.Data[0];
                if (task.LastStatus < 40)
                {
                    BllResult temp = AppCommon.Bll.TaskDoubleInHandle("1", location.Code, task.Id);
                    if (temp.Success)
                    {
                        BllResult sendResult = SendTaskToStocker(addresses, "5", "0", "0", "0", "0", location.Row.ToString(), location.Layer.ToString(), location.Line.ToString(), task.Id.ToString(), "0");
                        if (sendResult.Success)
                        {
                            return BllResultFactory.Sucess(null, "成功");
                        }
                        else
                        {
                            //回滚
                            AppCommon.Bll.TaskDoubleInHandle("0", "", task.Id);
                            return BllResultFactory.Error(null, $"处理{device}重入失败:{sendResult.Msg}");
                        }
                    }
                    else
                    {
                        return BllResultFactory.Error(null, $"处理{device}重入失败:{temp.Msg}");
                    }
                }
                else
                {
                    return BllResultFactory.Error(null, $"{device}对应的任务Id:{taskProp.value}已完成");
                }
            }
            else
            {
                return BllResultFactory.Error(null, $"未找到{device}对应的任务Id:{taskProp.value}");
            }

        }


        /// <summary>
        /// 处理空出
        /// 1.标记任务
        /// 2.完成空出任务
        /// 3.清空堆垛机交换区
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        public BllResult EmptyOutHandle(DeviceEntity device)
        {
            if (PLC == null || PLC.GetConnStatus() == false || DeviceAddressEntities == null || DeviceAddressEntities.Count == 0)
            {
                //AddLogToUI("地址读取失败,请检查通讯连接", 2);
                return BllResultFactory.Error(null, "地址读取失败,请检查通讯连接");
            }
            var addresses = DeviceAddressEntities.FindAll(t => t.DeviceId == device.Id);
            //获取任务和是否重入
            var taskProp = addresses.Find(t => t.DevicePropCode == "TaskNo1");
            var emptyOutProp = addresses.Find(t => t.DevicePropCode == "EmptyOut");
            if (taskProp == null | emptyOutProp == null)
            {
                return BllResultFactory.Error(null, $"未找到堆垛机{device}的任务和空出属性");
            }
            if (emptyOutProp.value != "True")
            {
                return BllResultFactory.Error(null, $"堆垛机{device}未报空出错误");
            }
            var taskResult = AppCommon.Bll.GetTasks(null, taskProp.value, null, null, null);
            if (taskResult.Success)
            {
                var task = taskResult.Data[0];
                if (task.LastStatus < 40)
                {
                    BllResult temp = AppCommon.Bll.EmptyOutHandle("1", "40", task);
                    if (temp.Success)
                    {
                        //清空WCS交换区
                        BllResult sendResult = SendTaskToStocker(addresses, "0", "0", "0", "0", "0", "0", "0", "0", "0", "0");
                        if (sendResult.Success)
                        {
                            return BllResultFactory.Sucess(null, "成功");
                        }
                        else
                        {
                            //回滚
                            AppCommon.Bll.EmptyOutHandle("0", task.LastStatus.ToString(), task);
                            return BllResultFactory.Error(null, "空出处理失败:" + sendResult.Msg);
                        }
                    }
                    else
                    {
                        return temp;
                    }
                }
                else
                {
                    return BllResultFactory.Error(null, $"{device}对应的任务Id:{taskProp.value}已完成");
                }
            }
            else
            {
                return BllResultFactory.Error(null, $"未找到{device}对应的任务Id:{taskProp.value}");
            }

        }

        /// <summary>
        /// 同巷道内移库
        /// </summary>
        /// <param name="stockers"></param>
        private void ExcuteTaskTransferInRoadway(List<DeviceEntity> stockers)
        {
            List<TaskEntity> taskEntities = GetAllTaskOut();
            foreach (var task in taskEntities)
            {
                if (task.Type == 800)
                {
                    var temp1 = AppCommon.Bll.GetAllLocations(null, null, null, null, null, null, task.SourceLocation);
                    var temp2 = AppCommon.Bll.GetAllLocations(null, null, null, null, null, null, task.DestinationLocation);
                    if (!temp1.Success || !temp2.Success)
                    {
                        AddLogToUI("执行移库任务:" + task.Id + ",未找到移库库位" + task.SourceLocation + "或" + task.DestinationLocation, 2);
                        continue;
                    }
                    var location1 = temp1.Data[0];
                    var location2 = temp2.Data[0];
                    if (location1.Roadway == location2.Roadway)
                    {
                        //如果是同一个巷道
                        //查看巷道堆垛机
                        int stockerCount = stockers.Count(t => t.Roadway == location1.Roadway);
                        if (stockerCount != 1)
                        {
                            AddLogToUI("任务" + task.Id + "获取巷道堆垛机失败,巷道:" + location1.Roadway + " 对应:" + stockerCount + "个", 2);
                            continue;
                        }
                        var stocker = stockers.Find(t => t.Roadway == location1.Roadway);
                        //获取这个堆垛机的地址
                        //地址校验交由初始化完成
                        var props = DeviceAddressEntities.Where(t => t.DeviceId == stocker.Id).ToList();
                        //堆垛机出库任务校验
                        var result = ReadAddress(props);
                        if (result.Success)
                        {
                            if (ValidateStockerTransferInRoadway(props))
                            {
                                var tempResult = SendTaskToStocker(props, "3", "0", location1.Row.ToString(), location1.Layer.ToString(), location1.Line.ToString(), location2.Row.ToString(), location2.Layer.ToString(), location2.Line.ToString(), task.Id.ToString(), "0");
                                if (!tempResult.Success)
                                {
                                    AddLogToUI("堆垛机" + stocker.ToString() + "下发任务失败:" + tempResult.Msg, 2);
                                }
                                else
                                {
                                    //同巷道的移库,更新任务状态到38
                                    AppCommon.Bll.SetTaskStatus(task.Id, 38);
                                    AddLogToUI("堆垛机" + stocker.ToString() + "下发任务成功,任务号:" + task.Id, 1);
                                }
                            }
                        }
                        else
                        {
                            AddLogToUI("读取" + stocker + "地址数据失败", 2);
                        }
                    }
                }
            }
        }

        private void SendToLED(TaskEntity taskEntity)
        {
            string taskType = AppCommon.GetTaskType(taskEntity.Type.ToString());
            string locationCode = "";
            if (!String.IsNullOrEmpty(taskEntity.SourceLocation))
            {
                locationCode += taskEntity.SourceLocation;
            }
            if (!string.IsNullOrEmpty(taskEntity.DestinationLocation))
            {
                if (string.IsNullOrEmpty(locationCode))
                {
                    locationCode += taskEntity.DestinationLocation;
                }
                else
                {
                    locationCode += "->" + taskEntity.DestinationLocation;
                }
            }
            string text = String.Format("任务号:{0}\\n任务类型:{1}\\n托盘条码:{2}\\n仓位:{3}\\n", taskEntity.Id, taskType, taskEntity.ContainerCode, locationCode);
            //这里加上明细
            var taskDetails = AppCommon.Bll.GetTaskDetailsByTaskId(taskEntity.Id);
            if (taskDetails.Success)
            {
                text += $"物料:数量\\n";
                foreach (var item in taskDetails.Data)
                {
                    text += $"{item.MaterialName}:{item.Qty}\\n";
                }
            }
            led.InfoQueue.Enqueue(text);
        }

        /// <summary>
        /// 响应堆垛机入库任务
        /// </summary>
        /// <param name="stockers"></param>
        private void ExcuteTaskIn(List<DeviceEntity> stockers)
        {
            //查询状态为35的任务
            var result = AppCommon.Bll.GetTasks("35", null, null, null, null);
            if (result.Success)
            {
                var tasks = result.Data;
                foreach (var task in tasks)
                {
                    LocationEntity locationEntity = null;
                    if (task.Type == 100 || task.Type == 500 || task.Type == 800)
                    {
                        var locationResult = AppCommon.Bll.GetAllLocations(null, null, null, null, null, null, task.DestinationLocation);
                        if (locationResult.Success)
                        {
                            locationEntity = locationResult.Data[0];
                        }
                        else
                        {
                            AddLogToUI("任务" + task.Id + "对应货位" + task.DestinationLocation + "未找到", 2);
                            continue;
                        }

                    }
                    else if (task.Type == 200 || task.Type == 400 || task.Type == 700 || task.Type == 900)
                    {
                        var locationResult = AppCommon.Bll.GetAllLocations(null, null, null, null, null, null, task.SourceLocation);
                        if (locationResult.Success)
                        {
                            locationEntity = locationResult.Data[0];
                        }
                        else
                        {
                            AddLogToUI("任务" + task.Id + "对应货位" + task.SourceLocation + "未找到", 2);
                            continue;
                        }
                    }
                    else
                    {
                        AddLogToUI("任务" + task.Id + "类型不符合堆垛机执行入库,类型:" + task.Type, 2);
                        continue;
                    }
                    //通过货位所在巷道来查询堆垛机
                    var stocker = stockers.Find(t => t.Roadway == locationEntity.Roadway);
                    if (stocker == null)
                    {
                        AddLogToUI("未配置巷道" + locationEntity.Roadway + "对应的堆垛机,无法执行入库任务" + task.Id, 2);
                        continue;
                    }
                    //校验这个堆垛机是否可以执行入库任务
                    var addresses = DeviceAddressEntities.FindAll(t => t.DeviceId == stocker.Id);
                    var readResult = ReadAddress(addresses);
                    if (!readResult.Success)
                    {
                        AddLogToUI("读取地址失败,堆垛机:" + stocker, 2);
                        continue;
                    }
                    if (ValidateStockerIn(addresses))
                    {
                        //下发任务
                        var sendResult = SendTaskToStocker(addresses, "1", "0", "0", "0", "0", locationEntity.Row.ToString(), locationEntity.Layer.ToString(), locationEntity.Line.ToString(), task.Id.ToString(), "0");
                        if (!sendResult.Success)
                        {
                            AddLogToUI("下发堆垛机" + stocker + "任务" + task.Id + "失败:" + sendResult.Msg, 2);
                            continue;
                        }
                        else
                        {
                            //刷新任务状态到38
                            AppCommon.Bll.SetTaskStatus(task.Id, 38);
                            AddLogToUI("下发堆垛机" + stocker + "任务" + task.Id + "成功。库位:" + locationEntity.Code + " 行列层:" + locationEntity.Row + "," + locationEntity.Line + "," + locationEntity.Layer, 1);
                        }
                    }
                }
            }
        }

        /// <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);
                var result = ReadAddress(propDatas);
                if (result.Success)
                {
                    if (ValidateStockerForCompleteTask(propDatas))
                    {
                        //获取任务号
                        var propData = propDatas.Find(t => t.DevicePropCode == "TaskNo1");
                        //判断任务状态
                        var taskResult = AppCommon.Bll.GetTasks(null, propData.value, null, null, null);
                        if (!taskResult.Success)
                        {
                            AddLogToUI("堆垛机" + stocker + "任务" + propData.value + ",未获取到任务", 2);
                            continue;
                        }
                        TaskEntity taskEntity = taskResult.Data[0];
                        if (taskEntity.LastStatus < 25)
                        {
                            //说明堆垛机是在执行出库任务,更新任务到25
                            var temp1 = AppCommon.Bll.SetTaskStatus(taskEntity.Id, 25);
                            if (!temp1.Success)
                            {
                                AddLogToUI("堆垛机" + stocker + "完成任务" + taskEntity.Id + "时,更新任务状态失败:" + temp1.Msg, 2);
                                continue;
                            }
                            else
                            {
                                AddLogToUI("堆垛机" + stocker + "完成任务" + taskEntity.Id + "时,更新任务状态成功" + temp1.Msg, 1);
                            }
                        }
                        else
                        {
                            //说明堆垛机是在执行入的,此时完成任务
                            var temp1 = AppCommon.Bll.CompleteTask(taskEntity.Id.ToString());
                            if (!temp1.Success)
                            {
                                AddLogToUI("堆垛机" + stocker + "完成任务" + taskEntity.Id + "时失败:" + temp1.Msg, 2);
                                continue;
                            }
                            else
                            {
                                AddLogToUI("堆垛机" + stocker + "完成任务" + taskEntity.Id + "成功", 1);
                            }
                        }


                        //任务完成成功:任务执行完成后由PLC向WCS发送任务完成消息,WCS清除任务信息,随后PLC更新堆垛机状态为待机
                        //清除任务,hack:这里暂时只清除了任务号
                        //var temp2 = propDatas.Where(t => t.DevicePropCode == "TaskNo1" || t.DevicePropCode == "TaskNo2").ToList();
                        //temp2.ForEach(t => t.value = "0");
                        //var writeResult = WriteAddress(temp2);
                        //if (!writeResult.Success)
                        //{
                        //    AddLogToUI("完成任务" + propData.value + "成功,但是清除堆垛机" + stocker.ToString() + "任务失败", 2);
                        //}
                        //这里清除wcs区
                        var sendResult = SendTaskToStocker(propDatas, "0", "0", "0", "0", "0", "0", "0", "0", "0", "0");
                        if (sendResult.Success)
                        {
                            AddLogToUI("清除堆垛机" + stocker.ToString() + "任务" + taskEntity.Id + "成功", 1);
                        }
                        else
                        {
                            AddLogToUI("清除堆垛机" + stocker.ToString() + "任务" + taskEntity.Id + "失败", 2);
                        }
                    }
                }
                else
                {
                    AddLogToUI("读取" + stocker + "地址数据失败:" + result.Msg, 2);
                }
            }
        }

        /// <summary>
        /// 数据类型转换WCS-->PLC
        /// </summary>
        /// <param name="type"></param>
        /// <param name="v"></param>
        /// <returns></returns>
        private BllResult TansforWCSDataToAddressData(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.ToUInt16(data); break;
                    case "CHAR": obj = AppCommon.Bll.StringToASCII(data + "\u0003"); break;
                    default:
                        obj = data;
                        break;
                }
                return BllResultFactory.Sucess(obj, "成功");
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(null, "WCS到PLC数据转换出现异常,值:" + data + " 目标类型:" + type + " 异常:" + ex.ToString());
            }
        }

        /// <summary>
        /// 数据类型转换PLC-->WCS
        /// </summary>
        /// <param name="type"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private BllResult<String> TransforAddressDataToWCSData(string type, object data)
        {
            string str;
            try
            {
                switch (type)
                {
                    case "BYTE":
                    case "DWORD":
                    case "BOOL":
                    case "WORD": str = data.ToString(); break;
                    case "CHAR": str = AppCommon.Bll.ASCIIToString((short[])data).Trim().Replace("\u0003", ""); break;
                    default:
                        str = data.ToString();
                        break;
                }
                return BllResultFactory.Sucess<string>(str, "成功");
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<string>(null, "PLC到WCS数据转换出现异常,值:" + data + " 目标类型:" + type + " 异常:" + ex.ToString());
            }
        }

        /// <summary>
        /// 校验堆垛机是否可以进行任务完成
        /// </summary>
        /// <param name="stocker"></param>
        /// <returns></returns>
        private bool ValidateStockerForCompleteTask(List<DeviceAddressEntity> addresses)
        {
            if (addresses.Find(t => t.DevicePropCode == "TaskExcuteStatus").value == "3"
                    //这里加上WCS交换区检测,防止PLC来不及反应重复完成任务,交换区数据是会在完成任务后才会清除
                    && addresses.First(t => t.DevicePropCode == "WCSTaskFlag").value != "0"
                )
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 堆垛机执行出库任务
        /// hack:这里需要和电气讨论任务校验失败的情况
        /// </summary>
        /// <param name="taskEntities"></param>
        /// <param name="stockers"></param>
        private void ExcuteTaskOut(List<DeviceEntity> stockers)
        {
            List<TaskEntity> taskEntities = GetAllTaskOut();
            taskEntities = taskEntities.OrderBy(t => t.LastUpdated).ToList();
            foreach (var task in taskEntities)
            {
                //获取任务所在巷道,即库位对应的巷道
                var BllResult = AppCommon.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.Find(t => t.Roadway == location.Roadway);
                //获取这个堆垛机的地址
                //地址校验交由初始化完成
                var props = DeviceAddressEntities.Where(t => t.DeviceId == stocker.Id).ToList();
                //堆垛机出库任务校验
                var result = ReadAddress(props);
                if (result.Success)
                {
                    if (ValidateStockerOut(props))
                    {
                        //判断任务是不是移库,如果是移库,判断两个库位是不是在同一个巷道
                        if (task.Type == 800)
                        {
                            var temp1 = AppCommon.Bll.GetAllLocations(null, null, null, null, null, null, task.SourceLocation);
                            var temp2 = AppCommon.Bll.GetAllLocations(null, null, null, null, null, null, task.DestinationLocation);
                            if (!temp1.Success || !temp2.Success)
                            {
                                AddLogToUI("堆垛机" + stocker + "执行移库任务时" + task.Id + "未找到移库库位" + task.SourceLocation + "或" + task.DestinationLocation, 2);
                                continue;
                            }
                            var location1 = temp1.Data[0];
                            var location2 = temp2.Data[0];
                            if (location1.Roadway == location2.Roadway)
                            {
                                //如果是同一个巷道
                                //var tempResult = SendTaskToStocker(props, "3", "0", location1.Row.ToString(), location1.Layer.ToString(), location1.Column.ToString(), location2.Row.ToString(), location2.Layer.ToString(), location2.Column.ToString(), task.Id.ToString(), "0");
                                //if (!tempResult.Success)
                                //{
                                //    AddLogToUI("堆垛机" + stocker.ToString() + "下发任务失败:" + tempResult.Msg, 2);
                                //}
                                //else
                                //{
                                //    //同巷道的移库,更新任务状态到38
                                //    AppCommon.Bll.SetTaskStatus(task.Id, 38);
                                //    AddLogToUI("堆垛机" + stocker.ToString() + "下发任务成功,任务号:" + task.Id, 1);
                                //}
                                continue;
                            }
                        }
                        //这里不再校验出库站台是否空闲,判断堆垛机工作状态即可;
                        //可用,下发任务
                        BllResult sendResult = SendTaskToStocker(props, "2", "0", location.Row.ToString(), location.Layer.ToString(), location.Line.ToString(), "0", "0", "0", task.Id.ToString(), "0");
                        if (!BllResult.Success)
                        {
                            AddLogToUI("堆垛机" + stocker.ToString() + "下发任务失败:" + sendResult.Msg, 2);
                        }
                        else
                        {
                            //更新任务到开始执行
                            AppCommon.Bll.SetTaskStatus(task.Id, 20);
                            AddLogToUI("堆垛机" + stocker.ToString() + "下发任务成功,任务号:" + task.Id + ";库位:" + location.Code, 1);
                        }
                    }
                }
                else
                {
                    AddLogToUI("读取" + stocker + "地址数据失败", 2);
                }
            }
        }

        /// <summary>
        /// 下发任务,校验码先不做
        /// </summary>
        /// <param name="addresses"></param>
        /// <param name="task"></param>
        /// <returns></returns>
        private BllResult SendTaskToStocker(List<DeviceAddressEntity> addresses, string flag, string stop, string fromRow, string fromLayer, string fromColumn, string toRow, string toLayer, string toColumn, string taskNo, string validateCode)
        {
            try
            {
                List<DeviceAddressEntity> temp = new List<DeviceAddressEntity>();
                var wcsFlag = addresses.Find(t => t.DevicePropCode == "WCSTaskFlag");
                wcsFlag.value = flag;
                var wcsStop = addresses.Find(t => t.DevicePropCode == "WCSStop");
                wcsStop.value = stop;
                var wcsFromRow = addresses.Find(t => t.DevicePropCode == "WCSFromRow");
                wcsFromRow.value = fromRow;
                var wcsFromLayer = addresses.Find(t => t.DevicePropCode == "WCSFromLayer");
                wcsFromLayer.value = fromLayer;
                var wcsFromColumn = addresses.Find(t => t.DevicePropCode == "WCSFromColumn");
                wcsFromColumn.value = fromColumn;
                var wcsToRow = addresses.Find(t => t.DevicePropCode == "WCSToRow");
                wcsToRow.value = toRow;
                var wcsToLayer = addresses.Find(t => t.DevicePropCode == "WCSToLayer");
                wcsToLayer.value = toLayer;
                var wcsToColumn = addresses.Find(t => t.DevicePropCode == "WCSToColumn");
                wcsToColumn.value = toColumn;
                var wcsTaskNo = addresses.Find(t => t.DevicePropCode == "WCSTaskNo");
                wcsTaskNo.value = taskNo;
                var wcsValidateCode = addresses.Find(t => t.DevicePropCode == "WCSValidateCode");
                wcsValidateCode.value = validateCode;
                temp.Add(wcsFlag);
                temp.Add(wcsStop);
                temp.Add(wcsFromRow);
                temp.Add(wcsFromLayer);
                temp.Add(wcsFromColumn);
                temp.Add(wcsToColumn);
                temp.Add(wcsToLayer);
                temp.Add(wcsToRow);
                temp.Add(wcsTaskNo);
                temp.Add(wcsValidateCode);
                return WriteAddress(temp);
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(null, "异常:" + ex.ToString());
            }
        }

        /// <summary>
        /// 获取所有未完成的出库任务,注意这里只会返回状态为10的任务
        /// </summary>
        /// <returns></returns>
        private static List<TaskEntity> GetAllTaskOut()
        {
            List<TaskEntity> taskEntities = new List<TaskEntity>();
            var result = AppCommon.Bll.GetTasks("10", null, null, null, null);
            if (result.Success)
            {
                taskEntities = result.Data.Where(t => t.Type == 200 || t.Type == 300 || t.Type == 400 || t.Type == 900 || t.Type == 600 || t.Type == 700 || t.Type == 800).ToList();
            }

            return taskEntities;
        }

        /// <summary>
        /// 添加界面日志,1绿色,2红色,3黄色
        /// </summary>
        /// <param name="log"></param>
        /// <param name="level"></param>
        private void AddLogToUI(string log, int level)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                this.LogInfo.AddLogs(log, level);
            }));
        }

        /// <summary>
        /// 读取所有地址数据
        /// </summary>
        private BllResult ReadAllAddressData()
        {
            return ReadAddress(DeviceAddressEntities);
        }

        /// <summary>
        /// 读取特定地址
        /// </summary>
        /// <param name="deviceAddressEntities"></param>
        private BllResult ReadAddress(List<DeviceAddressEntity> deviceAddressEntities)
        {
            if (PLC == null || PLC.GetConnStatus() == false || deviceAddressEntities == null || deviceAddressEntities.Count == 0)
            {
                //AddLogToUI("地址读取失败,请检查通讯连接", 2);
                return BllResultFactory.Error(null, "地址读取失败,请检查通讯连接");
            }
            var temp = deviceAddressEntities.Join(DeviceEntities, a => a.DeviceId, b => b.Id, (a, b) => new { a, b }).Join(DevicePropEntities, a => new { a = a.a.DevicePropCode, b = a.b.DeviceTypeId }, b => new { a = b.Code, b = b.DeviceTypeId }, (a, b) => new { address = a.a, b = b.Type }).ToList();
            if (temp.Count != deviceAddressEntities.Count)
            {
                return BllResultFactory.Error(null, "读取地址时,传入地址与实际属性不匹配,请检查基础数据");
            }

            int[] handles = temp.Select(t => t.address.ServerHandle).ToArray();
            var array = PLC.ReadData(handles);
            for (int i = 0; i < temp.Count; i++)
            {
                var result = TransforAddressDataToWCSData(temp[i].b, array.GetValue(i + 1));
                if (!result.Success)
                {
                    return BllResultFactory.Error(null, "转换PLC数据到WCS类型错误,值:" + array.GetValue(i + 1) + " 类型:" + temp[i].b);
                }
                temp[i].address.value = result.Data;
            }
            return BllResultFactory.Sucess(null, "成功");
        }

        /// <summary>
        /// 写入PLC数据
        /// </summary>
        /// <param name="deviceAddressEntities"></param>
        /// <returns></returns>
        private BllResult WriteAddress(List<DeviceAddressEntity> deviceAddressEntities)
        {
            if (PLC == null || PLC.GetConnStatus() == false || deviceAddressEntities == null || deviceAddressEntities.Count == 0)
            {
                return BllResultFactory.Error(null, "地址读取失败,请检查通讯连接");
            }
            var temp = deviceAddressEntities.Join(DeviceEntities, a => a.DeviceId, b => b.Id, (a, b) => new { a, b }).Join(DevicePropEntities, a => new { a = a.a.DevicePropCode, b = a.b.DeviceTypeId }, b => new { a = b.Code, b = b.DeviceTypeId }, (a, b) => new { address = a.a, b = b.Type }).ToList();
            if (temp.Count != deviceAddressEntities.Count)
            {
                return BllResultFactory.Error(null, "写入地址数据时,传入地址与实际属性不匹配,请检查基础数据");
            }
            var serverHandel = deviceAddressEntities.Select(t => t.ServerHandle).ToArray();
            object[] values = new object[serverHandel.Count<int>()];
            for (int i = 0; i < temp.Count; i++)
            {
                var result = TansforWCSDataToAddressData(temp[i].b, temp[i].address.value);
                if (!result.Success)
                {
                    return BllResultFactory.Error(null, "转换WCS数据到PLC类型错误,值:" + temp[i].address.value + " 类型:" + temp[i].b);
                }
                values[i] = result.Data;
            }
            if (PLC.WriteData(serverHandel, values))
            {
                return BllResultFactory.Sucess(null, "成功");
            }
            else
            {
                return BllResultFactory.Error(null, "写入失败!");
            }

        }

        /// <summary>
        /// 写入WCS站台区地址
        /// </summary>
        /// <param name="addresses"></param>
        /// <param name="flag"></param>
        /// <param name="type"></param>
        /// <param name="loadstatus"></param>
        /// <param name="stationno"></param>
        /// <param name="taskno"></param>
        /// <param name="barcode"></param>
        /// <param name="backup"></param>
        /// <returns></returns>
        private BllResult WriteWCSStationDataAddress(List<DeviceAddressEntity> addresses, string flag, string type, string plcno, string loadstatus, string stationno, string taskno, string barcode, string toaddress, string backup)
        {
            List<DeviceAddressEntity> temp = new List<DeviceAddressEntity>();
            var wcsflag = addresses.Find(t => t.DevicePropCode == "WCSFlag");
            wcsflag.value = flag;
            var wcstype = addresses.Find(t => t.DevicePropCode == "WCSType");
            wcstype.value = type;
            var wcsplcno = addresses.Find(t => t.DevicePropCode == "WCSPLCNo");
            wcsplcno.value = plcno;
            var wcsloadstatus = addresses.Find(t => t.DevicePropCode == "LoadStatus");
            wcsloadstatus.value = loadstatus;
            var wcsstationno = addresses.Find(t => t.DevicePropCode == "WCSStationNo");
            wcsstationno.value = stationno;
            var wcstaskno = addresses.Find(t => t.DevicePropCode == "WCSTaskNo");
            wcstaskno.value = taskno;
            var wcsbarcode = addresses.Find(t => t.DevicePropCode == "WCSBarcode");
            wcsbarcode.value = barcode;
            var wcstoaddress = addresses.Find(t => t.DevicePropCode == "WCSToAddress");
            wcstoaddress.value = toaddress;
            var wcsbackup = addresses.Find(t => t.DevicePropCode == "WCSBackUp");
            wcsbackup.value = backup;
            temp.Add(wcsflag);
            temp.Add(wcstype);
            temp.Add(wcsplcno);
            temp.Add(wcsloadstatus);
            temp.Add(wcsstationno);
            temp.Add(wcstaskno);
            temp.Add(wcsbarcode);
            temp.Add(wcstoaddress);
            temp.Add(wcsbackup);
            return WriteAddress(temp);
        }

        /// <summary>
        /// 堆垛机出库任务校验
        ///  堆垛机接收任务(入库、出库、拣选、转库)条件:
        ///1.    工作模式=2 联机;
        ///2.	操作模式=5  联机;
        ///3.	工作状态=0  待机,或者等于2 出库;
        ///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 == "WorkStatus").value == "2")
                    && deviceAddressEntities.First(t => t.DevicePropCode == "TaskExcuteStatus").value == "1"
                    && deviceAddressEntities.First(t => t.DevicePropCode == "HasPallet").value == "1"
                    && deviceAddressEntities.First(t => t.DevicePropCode == "TaskNo1").value == "0"
                    //这里加上WCS交换区检测,防止PLC来不及反应重复写入任务
                    && deviceAddressEntities.First(t => t.DevicePropCode == "WCSTaskFlag").value == "0"
                    )
                {
                    return true;
                }
            }
            catch (ArgumentNullException)
            {
                AddLogToUI("堆垛机属性地址不明确", 2);
            }
            catch (Exception)
            {
                AddLogToUI("堆垛机属性地址不明确", 2);
            }
            return false;
        }

        /// <summary>
        /// 巷道内移库任务校验条件
        /// </summary>
        /// <param name="deviceAddressEntities"></param>
        /// <returns></returns>
        private bool ValidateStockerTransferInRoadway(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 != "5")
                    && deviceAddressEntities.First(t => t.DevicePropCode == "TaskExcuteStatus").value == "1"
                    && deviceAddressEntities.First(t => t.DevicePropCode == "HasPallet").value == "1"
                    && deviceAddressEntities.First(t => t.DevicePropCode == "TaskNo1").value == "0"
                    //这里加上WCS交换区检测,防止PLC来不及反应重复写入任务
                    && deviceAddressEntities.First(t => t.DevicePropCode == "WCSTaskFlag").value == "0"
                    )
                {
                    return true;
                }
            }
            catch (ArgumentNullException)
            {
                AddLogToUI("堆垛机属性地址不明确", 2);
            }
            catch (Exception)
            {
                AddLogToUI("堆垛机属性地址不明确", 2);
            }
            return false;
        }

        /// <summary>
        /// 堆垛机入库任务校验
        /// </summary>
        /// <param name="deviceAddressEntities"></param>
        /// <returns></returns>
        private bool ValidateStockerIn(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 == "WorkStatus").value == "1")
                    && deviceAddressEntities.First(t => t.DevicePropCode == "TaskExcuteStatus").value == "1"
                    && deviceAddressEntities.First(t => t.DevicePropCode == "HasPallet").value == "1"
                    && deviceAddressEntities.First(t => t.DevicePropCode == "TaskNo1").value == "0"
                    //这里加上WCS交换区检测,防止PLC来不及反应重复写入任务
                    && deviceAddressEntities.First(t => t.DevicePropCode == "WCSTaskFlag").value == "0"
                    )
                {
                    return true;
                }
            }
            catch (ArgumentNullException)
            {
                AddLogToUI("堆垛机属性地址不明确", 2);
            }
            catch (Exception)
            {
                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.DeviceTypeId, 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>(), "异常或没有数据");
            }
        }

        /// <summary>
        /// WMS心跳
        /// </summary>
        private void WMSHeartbeat()
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    await Task.Delay(6000);
                    var ret = AppCommon.Bll.HeartBeat();
                    if (!ret.Success)
                    {
                        stop = true;
                        AddLogToUI("与WMS失去连接,程序处理中止,请检查网络并重启程序", 3);
                    }
                }
            });
        }

        #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

        private void btn_GoBack_Click(object sender, RoutedEventArgs e)
        {

            if (PLC == null || PLC.GetConnStatus() == false)
            {
                MessageBox.Show("地址读取失败,请检查通讯连接");
            }
            else
            {
                var a = DeviceAddressEntities.FindAll(t => t.DeviceId == 11);
                var b = ReadAddress(a);
                if (b.Success)
                {
                    string pallet = a.Find(t => t.DevicePropCode == "Barcode").value;
                    var c = AppCommon.Bll.GetTaskUncompleteByPalletCode(pallet);
                    if (c.Success)
                    {
                        var d = c.Data;
                        if (d.LastStatus != 30)
                        {
                            MessageBox.Show($"托盘{pallet}对应的任务{d.Id}状态为{d.LastStatus},状态非30,请检查");
                        }
                        else
                        {
                            var df = AppCommon.Bll.SetTaskStatus(d.Id, 31);
                            if (df.Success)
                            {
                                AddLogToUI($"任务{d.Id}回库成功", 1);
                            }
                            else
                            {
                                MessageBox.Show($"任务{d.Id}回库失败,消息:{df.Msg}");
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show($"未获取到{pallet}对应的任务");
                    }
                }
                else
                {
                    MessageBox.Show("读取地址失败");
                }
            }
        }
    }
}