AIOBOX.cs 36.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 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
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;

namespace Asa.IOModule
{
    /// <summary>
    /// AIOBOX操作类
    /// </summary>
    public class AIOBOX
    {
        private Socket _client;         //客户端
        private bool _quit;
        private bool _loop;
        private string _logPath;        //日志的文件夹路径
        private LogFile _log;           //日志的类
        private LogType _logType;       //日志输出类型

        private bool _frontInputOutput;    //True:Input  False:Output
        private int countInput;            //输入总数
        private int countOutput;           //输出总数
        private int sleepInput;            //自动读取DI间隔
        private int sleepOutput;           //自动读取DO间隔
        private Box_Type _typeInput;       //输入类型
        private Box_Type _typeOutput;      //输出类型
        private byte[] _addressInput;      //输入地址
        private byte[] _addressOutput;     //输出地址
        private bool _autoReadInput;       //自动读取DI
        private bool _autoReadOutput;      //自动读取DO
        private bool _manualReadOutput;    //手动读取DO

        private bool _changeDI;        //DI收到数据触发事件
        private bool _changeDO;        //DO收到数据触发事件
        private bool _changeAI;        //AI收到数据触发事件
        private bool _changeAO;        //AO收到数据触发事件
        private Box_Sta[] _stateDI;    //状态
        private Box_Sta[] _stateDO;    //状态
        private int[] _valueAI;        //模拟量
        private int[] _valueAO;        //模拟量

        private System.Collections.Concurrent.ConcurrentQueue<ushort> _flag;
        private System.Collections.Concurrent.ConcurrentQueue<byte[]> _send;
        private System.Collections.Concurrent.ConcurrentQueue<byte[]> _receive;

        private Thread tRecon;
        private Thread tSend;         //发送命令处理
        private Thread tReceive;      //接收信息处理
        private Thread tListen;       //监听网络
        private Thread tTrigger;      //触发DI、DO改变事件
        private Thread tReadInput;    //自动读取DI线程
        private Thread tReadOutput;   //自动读取DO线程
        private Thread tFlag;         //ModBusTCP标识

        private UdpClient broadcastClient;     //广播客户端
        private IPEndPoint broadcastEndPoint;  //广播远程节点
        private byte[] broadcastBuffer;        //远程返回数据

        /// <summary>
        /// 每条命令发送的间隔
        /// 不能小于15,会出现IO接收不到的情况
        /// 小于30时,会出现接收数据连包的情况
        /// </summary>
        private const int SEND_SLEEP = 30;
        /// <summary>
        /// ModBus端口
        /// </summary>
        public const int PORT = 502;

        /// <summary>
        /// 自动读取DI委托
        /// </summary>
        /// <param name="box">AIOBOX</param>
        /// <param name="sta">所有DI状态</param>
        public delegate void DIO_Changed(AIOBOX box, Box_Sta[] sta);
        /// <summary>
        /// 自动读取DI事件触发
        /// </summary>
        public event DIO_Changed DI_Changed_Event;
        /// <summary>
        /// 自动读取DO事件触发
        /// </summary>
        public event DIO_Changed DO_Changed_Event;
        /// <summary>
        /// 自动读取AI委托
        /// </summary>
        /// <param name="box">AIOBOX</param>
        /// <param name="val">所有AI的值</param>
        public delegate void AIO_Changed(AIOBOX box, int[] val);
        /// <summary>
        /// 自动读取AI事件触发
        /// </summary>
        public event AIO_Changed AI_Changed_Event;
        /// <summary>
        /// 自动读取AO事件触发
        /// </summary>
        public event AIO_Changed AO_Changed_Event;

        /// <summary>
        /// AIOBOX
        /// </summary>
        public AIOBOX()
        {
            _log = null;
            _logPath = null;
            _autoReadInput = false;
            _autoReadOutput = false;
            _manualReadOutput = false;
            sleepInput = 100;
            sleepOutput = 100;
        }

        /// <summary>
        /// IP地址
        /// </summary>
        public string IP { set; get; } = "192.168.1.100";

        /// <summary>
        /// 是否连接
        /// </summary>
        public bool IsConn { get; private set; } = false;

        /// <summary>
        /// 错误信息
        /// </summary>
        public string ErrInfo { get; private set; } = "";







        /// <summary>
        /// 日志路径,连接前设置路径会自动保存日志
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <param name="type">输出类型</param>
        public void LogPath(string path, LogType type)
        {
            _logPath = path;
            _logType = type;
        }

        /// <summary>
        /// 设置输入端
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="count">数量</param>
        public void SetInput(Box_Type type, int count)
        {
            _typeInput = type;
            countInput = count;
            _frontInputOutput = false;
        }

        /// <summary>
        /// 设置输出端
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="count">数量</param>
        public void SetOutput(Box_Type type, int count)
        {
            _typeOutput = type;
            countOutput = count;
            _frontInputOutput = true;
        }

        /// <summary>
        /// 自动获取IP地址,未连接前使用,必须在同一网段
        /// </summary>
        /// <param name="localIP">本地IP地址</param>
        /// <returns></returns>
        public bool AutoIP(string localIP)
        {
            try
            {
                IPEndPoint local = new IPEndPoint(IPAddress.Parse(localIP), 55654);
                broadcastClient = new UdpClient(local);
                broadcastBuffer = null;

                Thread tTemp = new Thread(new ThreadStart(GetIP));
                tTemp.Start();
                broadcastEndPoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1024);
                byte[] dgram = new byte[] { 0x05, 0x00, 0x07, 0x00, 0x00, 0xC1, 0x59 };
                broadcastClient.Send(dgram, dgram.Length, broadcastEndPoint);
                Thread.Sleep(1000);
                tTemp.Abort();
                broadcastClient.Close();

                ErrInfo = "无法访问";
                if (broadcastBuffer == null) return false;
                if (broadcastBuffer[0] != 0x3B) return false;

                byte[] buff = new byte[broadcastBuffer[7]];
                Array.Copy(broadcastBuffer, 9, buff, 0, buff.Length);
                IP = buff[buff.Length - 12] + "." + buff[buff.Length - 11] + "." + buff[buff.Length - 10] + "." + buff[buff.Length - 9];
                ErrInfo = "OK";
                return true;
            }
            catch (Exception ex)
            {
                ErrInfo = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 检查IP地址
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public bool CheckIP(string ip)
        {
            //IP合法
            string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
            bool rtn = System.Text.RegularExpressions.Regex.IsMatch(ip, pattern);
            if (!rtn)
            {
                ErrInfo = "非法的IP地址";
                return false;
            }

            //Ping服务端
            System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
            System.Net.NetworkInformation.PingReply result = ping.Send(ip, 1000);
            ping.Dispose();
            if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
            {
                ErrInfo = "Ping " + ip + " 请求没有响应";
                return false;
            }
            return true;
        }

        /// <summary>
        /// 连接
        /// </summary>
        public void Connect()
        {
            if (_logPath == null)
                _log = null;
            else
                _log = new LogFile(_logPath, IP);

            _quit = false;
            tRecon = new Thread(new ThreadStart(Reconn));
            tRecon.Start();

            int time = 0;
            while (time < 3000)
            {
                if (IsConn) break;
                else time += 50;
                Thread.Sleep(50);
            }
           
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        public void Close()
        {
            _quit = true;
            Exit();

            if (_log != null)
            {
                _log.OutData("Close OK");
                _log.Close();
                _log = null;
            }
        }

        /// <summary>
        /// 自动读取输入端并触发事件(主动上传数据 = 禁止)
        /// </summary>
        /// <param name="read">是否自动读取</param>
        /// <param name="sleep">间隔,必须大于等于15ms</param>
        public void AutoReadInput(bool read, int sleep)
        {
            if (countInput < 1)
                _autoReadInput = false;
            else if (sleep < 15)
                _autoReadInput = false;
            else if (read)
            {
                _autoReadInput = true;
                sleepInput = sleep;
            }
            else
                _autoReadInput = false;
        }

        /// <summary>
        /// 自动读取输入端并触发事件(主动上传数据 = 使能)
        /// </summary>
        /// <param name="read">是否自动读取</param>
        public void AutoReadInput(bool read)
        {
            if (countInput < 1)
                _autoReadInput = false;
            else if (read)
            {
                _autoReadInput = true;
                sleepInput = 8000;  //IO模块最大10s,避免超过时间,每8秒发送一次心跳包
            }
            else
                _autoReadInput = false;
        }

        /// <summary>
        /// 自动读取输出端,触发事件
        /// </summary>
        /// <param name="read">是否自动读取</param>
        /// <param name="sleep">间隔,必须大于等于15ms</param>
        public void AutoReadOutput(bool read, int sleep)
        {
            if (countOutput < 1)
            {
                _autoReadOutput = false;
                sleepOutput = 100;
            }
            else if (sleep < 15)
            {
                _autoReadOutput = false;
                sleepOutput = 100;
            }
            else if (read)
            {
                _autoReadOutput = true;
                sleepOutput = sleep;
            }
            else
            {
                _autoReadOutput = false;
                _manualReadOutput = true;   //用于第一次连接的时候读取一次状态
                sleepOutput = sleep;
            }
        }

        /// <summary>
        /// 相反状态(ON/OFF)
        /// </summary>
        /// <param name="sta"></param>
        /// <returns></returns>
        public Box_Sta ReverseStatus(Box_Sta sta)
        {
            return sta == Box_Sta.On ? Box_Sta.Off : Box_Sta.On;
        }

        /// <summary>
        /// 相反状态(ON/OFF)
        /// </summary>
        /// <param name="sta"></param>
        public void ReverseStatus(ref Box_Sta sta)
        {
            if (sta == Box_Sta.On)
                sta = Box_Sta.Off;
            else
                sta = Box_Sta.On;
        }

        /// <summary>
        /// 读取单个DI输入状态(ON/OFF)
        /// </summary>
        /// <param name="add">输入地址,从0开始</param>
        /// <returns></returns>
        public Box_Sta ReadDI(int add)
        {
            return _stateDI[add];
        }

        /// <summary>
        /// 读取多个DI输入状态(ON/OFF)
        /// </summary>
        /// <param name="add">起始地址,从0开始</param>
        /// <param name="count">数量</param>
        /// <returns></returns>
        public Box_Sta[] ReadDI(int add, int count)
        {
            Box_Sta[] sta = new Box_Sta[count];
            Array.Copy(_stateDI, add, sta, 0, count);
            return sta;
        }

        /// <summary>
        /// 读取单个AI模拟量的值
        /// </summary>
        /// <param name="add">模拟量地址,从0开始</param>
        /// <returns></returns>
        public int ReadAI(int add)
        {
            return _valueAI[add];
        }

        /// <summary>
        /// 读取多个AI模拟量的值
        /// </summary>
        /// <param name="add">起始地址,从0开始</param>
        /// <param name="count">数量</param>
        /// <returns></returns>
        public int[] ReadAI(int add, int count)
        {
            int[] sta = new int[count];
            Array.Copy(_valueAI, add, sta, 0, count);
            return sta;
        }

        /// <summary>
        /// 读取单个DO输出状态(ON/OFF)
        /// </summary>
        /// <param name="add">输出地址,从0开始</param>
        /// <returns></returns>
        public Box_Sta ReadDO(int add)
        {
            return _stateDO[add];
        }

        /// <summary>
        /// 读取多个DO输出状态(ON/OFF)
        /// </summary>
        /// <param name="add">起始地址,从0开始</param>
        /// <param name="count">数量</param>
        /// <returns></returns>
        public Box_Sta[] ReadDO(int add, int count)
        {
            Box_Sta[] sta = new Box_Sta[count];
            Array.Copy(_stateDO, add, sta, 0, count);
            return sta;
        }

        /// <summary>
        /// 读取单个AO模拟量的值
        /// </summary>
        /// <param name="add">输出地址,从0开始</param>
        /// <returns></returns>
        public int ReadAO(int add)
        {
            return _valueAO[add];
        }

        /// <summary>
        /// 读取多个AO模拟量的值
        /// </summary>
        /// <param name="add">起始地址,从0开始</param>
        /// <param name="count">数量</param>
        /// <returns></returns>
        public int[] ReadAO(int add, int count)
        {
            int[] sta = new int[count];
            Array.Copy(_valueAO, add, sta, 0, count);
            return sta;
        }

        /// <summary>
        /// 写入单个DO输出状态(ON/OFF)
        /// </summary>
        /// <param name="add">输出地址,从0开始</param>
        /// <param name="sta"></param>
        /// <returns></returns>
        public bool WriteDO(int add, Box_Sta sta)
        {
            try
            {
                byte[] data = Command();
                byte[] buff = new byte[12];
                Array.Copy(data, 0, buff, 0, data.Length);
                buff[5] = 6;  //后面字节数
                buff[7] = 5;  //功能码
                buff[9] = _addressOutput[add];  //地址
                buff[10] = (byte)sta;    //写入值
                _send.Enqueue(buff);
                if (!_autoReadOutput)
                    _manualReadOutput = true;
                return true;
            }
            catch (Exception ex)
            {
                ErrInfo = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 获取本地IPv4地址
        /// </summary>
        /// <returns></returns>
        public string[] GetLocalIP()
        {
            List<string> str = new List<string>();
            IPAddress[] add = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            foreach (IPAddress ip in add)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                    str.Add(ip.ToString());
            }
            return str.ToArray();
        }





        /// <summary>
        /// 发送命令
        /// </summary>
        private void Send()
        {
            while (_loop)
            {
                bool rtn = _send.TryDequeue(out byte[] result);
                if (rtn)
                {
                    try
                    {
                        _client.Send(result);
                        if (_log != null)
                        {
                            if (_logType == LogType.All)
                                _log.OutData("Send ", result);
                        }
                    }
                    catch (Exception ex)
                    {
                        IsConn = false;
                        _loop = false;
                        if (_log != null)
                            _log.OutError(ex.Message);
                    }
                }

                Thread.Sleep(SEND_SLEEP);
            }
        }

        /// <summary>
        /// 接收命令
        /// </summary>
        private void Receive()
        {
            while (_loop)
            {
                if (_receive.TryDequeue(out byte[] buff))
                {
                    try
                    {
                        if (_log != null)
                        {
                            if (_logType == LogType.All)
                                _log.OutData("Receive ", buff);
                        }
                        if (buff.Length < 8)
                            continue;

                        if (buff[7] == 1)
                        {
                            ReadDO(buff);
                            _changeDO = true;
                        }
                        else if (buff[7] == 2)
                        {
                            ReadDI(buff);
                            _changeDI = true;
                        }
                        else if (buff[7] == 4)
                        {
                            ReadAI(buff);
                            _changeAI = true;
                        }
                        else if (buff[7] == 5)
                        {
                            //ReadSingle(buff);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (_log != null)
                            _log.OutError(ex.Message);
                    }
                }
                Thread.Sleep(10);
            }
        }

        /// <summary>
        /// 读取写入单个DO,功能码5
        /// </summary>
        /// <param name="buff"></param>
        private void ReadSingle(byte[] buff)
        {
            string s;

            //if (LogOut)
            //{
            //    byte[] bb = new byte[2];
            //    bb[0] = buff[1];
            //    bb[1] = buff[0];
            //    ushort flag = BitConverter.ToUInt16(bb, 0);
            //    s = string.Format("{0:HH:mm:ss:fff} WriteDO {1} fun={2} len={3}", DateTime.Now, flag, buff[7], buff.Length);
            //    _log.Add(s);
            //}


            //    int n = 0;
            //    int move = 0;
            //    byte val = _receive[0][9];
            //    for (int i = 0; i < 8; i++)
            //    {
            //        n = (val & Convert.ToInt32(Math.Pow(2, move))) >> move;
            //        _sta[i + 16] = n == 1 ? Box_Sta.On : Box_Sta.Off;
            //        move++;
            //    }

            //    if (_receive[0][8] == 2)
            //    {
            //        move = 0;
            //        val = _receive[0][10];
            //        for (int i = 8; i < 16; i++)
            //        {
            //            n = (val & Convert.ToInt32(Math.Pow(2, move))) >> move;
            //            _sta[i + 16] = n == 1 ? Box_Sta.On : Box_Sta.Off;
            //            move++;
            //        }
            //    }

            //    ErrInfo = "OK";
            //}
            //catch (Exception ex)
            //{
            //    ErrInfo = ex.Message;
            //}
        }

        /// <summary>
        /// 读取所有DO状态,功能码1
        /// </summary>
        /// <param name="buff"></param>
        private void ReadDO(byte[] buff)
        {
            try
            {
                int idx = 0;
                int count = buff[8];
                for (int i = 1; i <= count; i++)
                {
                    int n = 0;
                    int move = 0;
                    byte val = buff[8 + i];
                    for (int j = 0; j < 8; j++)
                    {
                        n = (val & Convert.ToInt32(Math.Pow(2, move))) >> move;
                        _stateDO[idx++] = n == 1 ? Box_Sta.On : Box_Sta.Off;
                        move++;
                    }
                }
                if (_log != null)
                {
                    if (_logType == LogType.All)
                        _log.OutData("Read All DO");
                }
            }
            catch (Exception ex)
            {
                if (_log != null)
                    _log.OutError(ex.Message);
            }


        }

        /// <summary>
        /// 读取所有DI状态,功能码2
        /// </summary>
        private void ReadDI(byte[] buff)
        {
            try
            {
                int idx = 0;
                int count = buff[8];
                for (int i = 1; i <= count; i++)
                {
                    int n = 0;
                    int move = 0;
                    byte val = buff[8 + i];
                    for (int j = 0; j < 8; j++)
                    {
                        n = (val & Convert.ToInt32(Math.Pow(2, move))) >> move;
                        _stateDI[idx++] = n == 1 ? Box_Sta.On : Box_Sta.Off;
                        move++;
                    }
                }
                if (_log != null)
                {
                    if (_logType == LogType.All)
                        _log.OutData("Read All DI");
                }

                //Test 方法锁
                TestMethod();

            }
            catch (Exception ex)
            {
                if (_log != null)
                    _log.OutError(ex.Message);
            }

        }

        /// <summary>
        /// 读取所有AI的值,功能码4
        /// </summary>
        /// <param name="buff"></param>
        private void ReadAI(byte[] buff)
        {
            try
            {
                if (countInput * 2 == buff[8])
                {
                    _valueAI[0] = buff[9] * 256 + buff[10];
                    _valueAI[1] = buff[11] * 256 + buff[12];
                    _valueAI[2] = buff[13] * 256 + buff[14];
                    _valueAI[3] = buff[15] * 256 + buff[16];
                }
                if (_log != null)
                {
                    if (_logType == LogType.All)
                        _log.OutData("Read All AI");
                }
            }
            catch (Exception ex)
            {
                if (_log != null)
                    _log.OutError(ex.Message);
            }

        }

        /// <summary>
        /// 命令,前7个字节
        /// </summary>
        /// <returns></returns>
        private byte[] Command()
        {
            _flag.TryDequeue(out ushort result);
            byte[] flag = BitConverter.GetBytes(result);
            byte[] data = new byte[7];
            data[0] = flag[1];
            data[1] = flag[0];
            data[2] = 0;
            data[3] = 0;
            data[4] = 0;
            data[5] = 0;
            data[6] = 255;
            return data;
        }

        /// <summary>
        /// 触发DIO改变事件
        /// </summary>
        private void TriggerDIO()
        {
            while (_loop)
            {
                if (_typeInput == Box_Type.DI && DI_Changed_Event != null)
                {
                    //if (_changeDI)
                    //{
                    //    _changeDI = false;
                    //    Box_Sta[] staDI = new Box_Sta[countInput];
                    //    Array.Copy(_stateDI, 0, staDI, 0, staDI.Length);
                    //    if (_log != null)
                    //    {
                    //        if (_logType == LogType.All)
                    //            _log.OutData("Trigger DI Event");
                    //    }
                    //    lock (staDI)
                    //        System.Threading.Tasks.Task.Run(() => DI_Changed_Event.Invoke(this, staDI));
                    //}
                }
                else if (_typeInput == Box_Type.AI && AI_Changed_Event != null)
                {
                    if (_changeAI)
                    {
                        _changeAI = false;
                        int[] valAI = new int[countInput];
                        Array.Copy(_valueAI, 0, valAI, 0, valAI.Length);
                        if (_log != null)
                        {
                            if (_logType == LogType.All)
                                _log.OutData("Trigger AI Event");
                        }
                        lock (valAI)
                            System.Threading.Tasks.Task.Run(() => AI_Changed_Event.Invoke(this, valAI));
                    }
                }

                if (_typeOutput == Box_Type.DO && DO_Changed_Event != null)
                {
                    if (_changeDO)
                    {
                        _changeDO = false;
                        Box_Sta[] staDO = new Box_Sta[countOutput];
                        Array.Copy(_stateDO, 0, staDO, 0, staDO.Length);
                        if (_log != null)
                        {
                            if (_logType == LogType.All)
                                _log.OutData("Trigger DO Event");
                        }
                        lock (staDO)
                            System.Threading.Tasks.Task.Run(() => DO_Changed_Event.Invoke(this, staDO));
                    }
                }
                else if (_typeOutput == Box_Type.AO && AO_Changed_Event != null)
                {
                    if (_changeAO)
                    {
                        _changeAO = false;
                        int[] valAO = new int[countOutput];
                        Array.Copy(_valueAO, 0, valAO, 0, valAO.Length);
                        if (_log != null)
                        {
                            if (_logType == LogType.All)
                                _log.OutData("Trigger AO Event");
                        }
                        lock (valAO)
                            System.Threading.Tasks.Task.Run(() => AO_Changed_Event.Invoke(this, valAO));
                    }
                }

                Thread.Sleep(10);
            }
        }

        /// <summary>
        /// 自动读取输入端线程
        /// </summary>
        private void AutoReadInput()
        {
            while (_loop)
            {
                if (IsConn && _autoReadInput)
                {
                    //if (suspendDI && suspend > 0)
                    //{
                    //    suspendDI = false;
                    //    suspend--;
                    //}
                    //else
                    //{
                        byte[] data = Command();
                        byte[] buff = new byte[12];
                        Array.Copy(data, 0, buff, 0, data.Length);
                        buff[5] = 6;   //后面字节数
                        //功能码
                        if (_typeInput == Box_Type.DI)
                            buff[7] = 2;
                        else if (_typeInput == Box_Type.AI)
                            buff[7] = 4;
                        buff[9] = _addressInput[0];      //地址
                        buff[11] = (byte)countInput;  //个数
                        _send.Enqueue(buff);
                        //suspendDI = true;
                    //}
                }
                Thread.Sleep(sleepInput);
            }
        }

        /// <summary>
        /// 自动读取输出端线程
        /// </summary>
        private void AutoReadOutput()
        {
            while (_loop)
            {
                Thread.Sleep(sleepOutput);
                if (!IsConn) continue;

                if (!_autoReadOutput)
                {
                    if (_manualReadOutput)
                        _manualReadOutput = false;
                    else
                        continue;
                }

                byte[] data = Command();
                byte[] buff = new byte[12];
                Array.Copy(data, 0, buff, 0, data.Length);
                buff[5] = 6;   //后面字节数
                buff[7] = 1;   //功能码
                buff[9] = _addressOutput[0];   //地址
                buff[11] = (byte)countOutput;  //个数
                _send.Enqueue(buff);
            }
        }

        /// <summary>
        /// 监听结果线程
        /// </summary>
        private void Listen()
        {
            byte[] temp = new byte[200];
            int start, len;

            while (_loop)
            {
                try
                {
                    if (_client == null) break;
                    if (_client.Available > 0)
                    {
                        start = 0;
                        int count = _client.Receive(temp);
                        while (count - start > 6)
                        {
                            len = temp[start + 5];
                            len += 6;
                            if (start + len > count) break;
                            byte[] aa = new byte[len];
                            Array.Copy(temp, start, aa, 0, len);
                            _receive.Enqueue(aa);
                            start += len;
                        }
                    }
                }
                catch (Exception ex)
                {
                    IsConn = false;
                    _loop = false;
                    if (_log != null)
                        _log.OutError(ex.Message);
                }
                Thread.Sleep(10);
            }
        }

        private void InitAddr()
        {
            byte n = 0;
            if (_frontInputOutput)
            {
                _addressInput = new byte[countInput];
                for (int i = 0; i < countInput; i++)
                    _addressInput[i] = n++;
                _addressOutput = new byte[countOutput];
                for (int i = 0; i < countOutput; i++)
                    _addressOutput[i] = n++;
            }
            else
            {
                _addressOutput = new byte[countOutput];
                for (int i = 0; i < countOutput; i++)
                    _addressOutput[i] = n++;
                _addressInput = new byte[countInput];
                for (int i = 0; i < countInput; i++)
                    _addressInput[i] = n++;
            }
            _stateDI = new Box_Sta[countInput];
            _stateDO = new Box_Sta[countOutput];
            _valueAI = new int[countInput];
            _valueAO = new int[countOutput];
        }

        private void GetIP()
        {
            broadcastBuffer = broadcastClient.Receive(ref broadcastEndPoint);
        }

        private void Flag()
        {
            ushort n = 0;
            while (_loop)
            {
                if (_flag.Count < 10)
                {
                    _flag.Enqueue(++n);
                    if (n == ushort.MaxValue) n = 0;
                }
                Thread.Sleep(5);
            }
        }

        private void Open()
        {
            try
            {
                //初始化地址
                IsConn = false;
                InitAddr();

                //检查IP地址
                bool rtn = CheckIP(IP);
                if (!rtn) return;

                _send = new System.Collections.Concurrent.ConcurrentQueue<byte[]>();
                _receive = new System.Collections.Concurrent.ConcurrentQueue<byte[]>();
                _flag = new System.Collections.Concurrent.ConcurrentQueue<ushort>();

                //建立连接
                _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 500);
                _client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500);
                _client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
                _client.Connect(IPAddress.Parse(IP), PORT);
                Thread.Sleep(100);  //需要等待一会才能获取连接状态

                tFlag = new Thread(new ThreadStart(Flag));
                tFlag.Start();
                Thread.Sleep(10);
                tSend = new Thread(new ThreadStart(Send));
                tReceive = new Thread(new ThreadStart(Receive));
                tListen = new Thread(new ThreadStart(Listen));
                tTrigger = new Thread(new ThreadStart(TriggerDIO));
                tReadInput = new Thread(new ThreadStart(AutoReadInput));
                tReadOutput = new Thread(new ThreadStart(AutoReadOutput));

                IsConn = true;
                _loop = true;
                tListen.Start();
                tTrigger.Start();
                tSend.Start();
                tReceive.Start();
                tReadInput.Start();
                tReadOutput.Start();

                ErrInfo = "";
                if (_log != null) _log.OutData("Connect OK");
                return;
            }
            catch (Exception ex)
            {
                IsConn = false;
                ErrInfo = ex.Message;
                if (_log != null) _log.OutError(ex.Message);
                return;
            }
        }

        private void Exit()
        {
            IsConn = false;
            _loop = false;
            tListen = null;
            tReadInput = null;
            tReadOutput = null;
            tTrigger = null;
            tSend = null;
            tReceive = null;
            tFlag = null;

            try
            {
                if (_client != null)
                {
                    _client.Shutdown(SocketShutdown.Both);
                    _client.Close();
                }
            }
            catch (Exception ex)
            {
                if (_log != null)
                    _log.OutError(ex.Message);
            }
            finally
            {
                _client = null;
            }
        }

        /// <summary>
        /// 测试方法锁
        /// </summary>
        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
        private void TestMethod()
        {
            Box_Sta[] staDI = new Box_Sta[countInput];
            Array.Copy(_stateDI, 0, staDI, 0, staDI.Length);
            if (_log != null)
            {
                if (_logType == LogType.All)
                    _log.OutData("Trigger DI Event");
            }
            lock (staDI)
                System.Threading.Tasks.Task.Run(() => DI_Changed_Event.Invoke(this, staDI));

        }



        private void Reconn()
        {
            while (!_quit)
            {
                if (IsConn)
                {
                    Thread.Sleep(1000);
                }
                else
                {
                    Exit();
                    Thread.Sleep(100);
                    if (!_quit) Open();
                }
            }
        }
    }

    /// <summary>
    /// IO模块类型
    /// </summary>
    public enum Box_Type : int
    {
        /// <summary>
        /// 数字信号输入
        /// </summary>
        DI,
        /// <summary>
        /// 数字信号输出
        /// </summary>
        DO,
        /// <summary>
        /// 模拟量输入
        /// </summary>
        AI,
        /// <summary>
        /// 模拟量输出
        /// </summary>
        AO
    }

    /// <summary>
    /// IO模块寄存器状态
    /// </summary>
    public enum Box_Sta : int
    {
        /// <summary>
        /// 断开,关闭,低电平
        /// </summary>
        Off = 0,
        /// <summary>
        /// 闭合,打开,高电平
        /// </summary>
        On = 255
    }

    /// <summary>
    /// 日志类型
    /// </summary>
    public enum LogType : int
    {
        /// <summary>
        /// 仅错误信息
        /// </summary>
        OnlyError,
        /// <summary>
        /// 所有
        /// </summary>
        All
    }





}