AgvClient.cs 17.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
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace AsaPL
{
    /// <summary>
    /// AGV客户端,对接双层线、生产线
    /// </summary>
    public class AgvClient
    {
        private bool _loop;
        private Socket _client;        //客户端
        private List<ClientNode> _node;
        private int countRecon;       //重连次数
        private Thread tSend;         //发送线程
        private Thread tListen;       //监听网络线程
        private Thread tRecon;        //重连线程

        private readonly log4net.ILog LOG;
        private readonly string IP;        //远程IP地址
        private const int PORT = 9501;    //端口
        private const int SEND_INTERVAL = 2000;  //客户端发送所有节点后的间隔

        /// <summary>
        /// 小车动作事件
        /// </summary>
        public delegate void ActionEvent(string name);
        /// <summary>
        /// 小车已准备好,料架准备进入流水线
        /// </summary>
        public event ActionEvent ReadyEnter;
        /// <summary>
        /// 小车已准备好,料架准备流出流水线
        /// </summary>
        public event ActionEvent ReadyLeave;

        public event ActionEvent AGVFinishEnter;
        public event ActionEvent AGVFinishLeave;
        /// <summary>
        /// AGV客户端,对接双层线、生产线
        /// </summary>
        /// <param name="serverIP">服务器IP地址</param>
        /// <param name="logName"></param>
        public AgvClient(string serverIP, string logName = "AgvClient")
        {
            IP = serverIP;
            _node = new List<ClientNode>();
            LOG = log4net.LogManager.GetLogger(logName);
        }
        
        /// <summary>
        /// 是否连接服务器
        /// </summary>
        public bool IsConn { private set; get; } = false;

        /// <summary>
        /// 取消状态,true发送none,false发送实际状态
        /// </summary>
        public bool CancelState { set; get; } = false;



        /// <summary>
        /// 连接
        /// </summary>
        public void Connect()
        {
            countRecon = 0;
            _loop = true;
            IsConn = false;
            tRecon = new Thread(new ThreadStart(Reconnect));
            tListen = new Thread(new ThreadStart(ListenNet));
            tSend = new Thread(new ThreadStart(SendStatus));
            tRecon.Start();
            tListen.Start();
            tSend.Start();
            LOG.Info("Connect");
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public void Close()
        {
            _loop = false;
            IsConn = false;

            if (_client != null)
            {
                _client.Close();
                _client = null;
            }
            LOG.Info("Close");
        }

        /// <summary>
        /// 设置状态
        /// </summary>
        /// <param name="name">节点名称</param>
        /// <param name="rfid">RFID</param>
        /// <param name="action"></param>
        /// <param name="level"></param>
        public void SetStatus(string name, string rfid = "", ClientAction action = ClientAction.None, ClientLevel level = ClientLevel.Low)
        {
            int idx = _node.FindIndex(s => s.Name.Equals(name));
            if (idx == -1)
            {
                ClientNode node = new ClientNode(name, rfid, action, level);
                _node.Add(node);
                idx = _node.Count - 1;
            }
            else
            {
                _node[idx].RFID = rfid;
                _node[idx].Action = action;
                _node[idx].Level = level;
            }
            LOG.Info("SetStatus " + _node[idx].ToText());
        }

        /// <summary>
        /// 允许进入
        /// </summary>
        /// <param name="name"></param>
        public void MayEnter(string name)
        {
            LOG.Info(name + " MayEnter");
            ClientNode node = new ClientNode(name, "", ClientAction.MayEnter, ClientLevel.High);
            byte[] buff = Encode(node);
            bool bln = Send(buff);
        }

        /// <summary>
        /// 允许离开
        /// </summary>
        /// <param name="name"></param>
        public void MayLeave(string name)
        {
            LOG.Info(name + " MayLeave");
            ClientNode node = new ClientNode(name, "", ClientAction.MayLeave, ClientLevel.High);
            byte[] buff = Encode(node);
            bool bln = Send(buff);
        }

        /// <summary>
        /// 完成进入
        /// </summary>
        /// <param name="name"></param>
        public void FinishEnter(string name)
        {
            LOG.Info(name + " FinishEnter");
            ClientNode node = new ClientNode(name, "", ClientAction.FinishEnter, ClientLevel.High);
            byte[] buff = Encode(node);
            bool bln = Send(buff);
        }

        /// <summary>
        /// 完成离开
        /// </summary>
        /// <param name="name"></param>
        public void FinishLeave(string name)
        {
            LOG.Info(name + " FinishLeave");
            ClientNode node = new ClientNode(name, "", ClientAction.FinishLeave, ClientLevel.High);
            byte[] buff = Encode(node);
            bool bln = Send(buff);
        }



        /// <summary>
        /// 重连线程
        /// </summary>
        private void Reconnect()
        {
            while (_loop)
            {
                if (!IsConn)
                {
                    Open();
                    if (IsConn)
                    {
                        countRecon = 0;
                        LOG.Info("Server connection successful");
                    }
                    else
                    {
                        LOG.Info("Server connection failed " + ++countRecon + " times");
                    }
                }
                Thread.Sleep(1000);
            }
        }

        /// <summary>
        /// 打开,连接到服务器
        /// </summary>
        private void Open()
        {
            try
            {
                LOG.Info("Connect " + IP + ":" + PORT);
                if (CheckIP(IP))
                {
                    _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    _client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 2000);
                    _client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 2000);
                    _client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
                    _client.Connect(IPAddress.Parse(IP), PORT);
                    if (!_loop) return;
                    IsConn = true;
                    LOG.Info("Connect OK");
                }
            }
            catch (Exception ex)
            {
                IsConn = false;
                LOG.Error("Open()", ex);
            }
        }

        /// <summary>
        /// 监听线程
        /// </summary>
        private void ListenNet()
        {
            byte[] temp = new byte[200];

            while (_loop)
            {
                Thread.Sleep(100);
                if (!IsConn) continue;
                if (_client == null) continue;

                try
                {
                    if (_client.Available > 0)
                    {
                        int count = _client.Receive(temp);
                        byte[] _buffer = new byte[count];
                        Array.Copy(temp, 0, _buffer, 0, count);

                        ClientNode node = Decode(_buffer);
                        if (node == null)
                        {
                            LOG.Info("Command decoding failed: " + HexBuff(_buffer));
                        }
                        else
                        {
                            LOG.Info("From server: " + node.ToText());
                            Resolve(node);
                        }
                    }
                }
                catch (Exception ex)
                {
                    IsConn = false;
                    LOG.Error("ListenNet()", ex);
                }
            }
        }

        /// <summary>
        /// 分析数据包
        /// </summary>
        /// <param name="result"></param>
        private void Resolve(ClientNode result)
        {
            try
            {
                if (result.Action == ClientAction.ReadyEnter)
                {
                    LOG.Info("Trigger ReadyEnter Event");
                    ReadyEnter?.Invoke(result.Name);
                }
                else if (result.Action == ClientAction.ReadyLeave)
                {
                    LOG.Info("Trigger ReadyLeave Event");
                    ReadyLeave?.Invoke(result.Name);
                }
                else if(result.Action == ClientAction.FinishEnter)
                {
                    LOG.Info("Trigger FinishEnter Event");
                    AGVFinishEnter?.Invoke(result.Name);
                }
                else if(result.Action == ClientAction.FinishLeave)
                {
                    LOG.Info("Trigger FinishLeave Event");
                   AGVFinishLeave.Invoke(result.Name);
                }
            }
            catch (Exception ex)
            {
                LOG.Error("Resolve()", ex);
            }
        }

        /// <summary>
        /// 连续发送状态线程
        /// </summary>
        private void SendStatus()
        {
            while (_loop)
            {
                if (!IsConn) continue;
                Thread.Sleep(SEND_INTERVAL);
                if (!IsConn) continue;

                for (int i = 0; i < _node.Count; i++)
                {
                    if (!_loop) break;
                    Thread.Sleep(100);
                    byte[] buff = Encode(_node[i]);
                    bool bln = Send(buff);

                    if (!bln)
                    {
                        IsConn = false;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="buff"></param>
        /// <returns></returns>
        private bool Send(byte[] buff)
        {
            if (!IsConn)
            {
                LOG.Info("服务器没有连接");
                return false;
            }

            try
            {
                _client.Send(buff);
                LOG.Debug("Send: " + HexBuff(buff));
                return true;
            }
            catch (Exception ex)
            {
                LOG.Error("Send()", ex);
                IsConn = false;
                return false;
            }

        }

        /// <summary>
        /// 编码
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private byte[] Encode(ClientNode node)
        {
            int idx = 0;
            byte[] buff = new byte[12];
            buff[idx++] = 0xAD;
            try
            {
                buff[idx++] = (byte)node.Name[0];
                buff[idx++] = Convert.ToByte(node.Name.Substring(1));
                buff[idx++] = (byte)node.RFID[0];
                buff[idx++] = Convert.ToByte(node.RFID.Substring(1));
            }
            catch(Exception ex)
            {
                LOG.Error("encode:",ex);
            }

            if (CancelState)
                buff[idx++] = (byte)ClientAction.None;
            else
                buff[idx++] = (byte)node.Action;

            buff[idx++] = (byte)node.Level;
            idx += 4;  //预留
            buff[idx] = 0xDA;
            return buff;
        }

        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="buff"></param>
        /// <returns></returns>
        private ClientNode Decode(byte[] buff)
        {
            int idx = 0;
            if (buff[idx++] != 0xAD) return null;
            string name = (char)buff[idx] + buff[idx + 1].ToString();
            idx += 2;
            string rfid = (char)buff[idx] + buff[idx + 1].ToString();
            idx += 2;
            ClientAction action = (ClientAction)buff[idx++];
            ClientLevel level = (ClientLevel)buff[idx++];
            idx += 4;  //预留
            if (buff[idx] != 0xDA) return null;

            ClientNode node = new ClientNode(name, rfid, action, level);
            return node;
        }

        /// <summary>
        /// 16进制
        /// </summary>
        /// <param name="buff"></param>
        /// <returns></returns>
        private string HexBuff(byte[] buff)
        {
            string s = "";
            if (buff == null) return s;

            for (int i = 0; i < buff.Length; i++)
                s += buff[i].ToString("X2") + " ";
            return s;
        }

        /// <summary>
        /// 检查IP地址
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        private 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)
            {
                LOG.Info("Illegal IP address " + ip);
                return false;
            }

            //Ping服务端
            try
            {
                System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
                System.Net.NetworkInformation.PingReply result = ping.Send(ip, 2000);
                ping.Dispose();
                if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
                {
                    LOG.Info("Ping " + ip + " request timeout");
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                LOG.Error("CheckIP()", ex);
                return false;
            }
        }


    }

    /// <summary>
    /// 客户端的节点
    /// </summary>
    public class ClientNode
    {
        private string rfid = "00";

        /// <summary>
        /// 节点名称
        /// </summary>
        public string Name { set; get; }
        /// <summary>
        /// RFID
        /// </summary>
        public string RFID
        {
            set
            {
                if (value.Length < 2)
                    rfid = value.PadLeft(2, '0');
                else
                    rfid = value;
            }
            get
            {
                return rfid;
            }
        }
        /// <summary>
        /// 动作
        /// </summary>
        public ClientAction Action { set; get; }
        /// <summary>
        /// 优先级
        /// </summary>
        public ClientLevel Level { set; get; }

        /// <summary>
        /// 客户端节点
        /// </summary>
        /// <param name="name"></param>
        /// <param name="rfid"></param>
        /// <param name="action"></param>
        /// <param name="level"></param>
        public ClientNode(string name, string rfid, ClientAction action, ClientLevel level)
        {
            Name = name;
            RFID = rfid;
            Action = action;
            Level = level;
        }

        /// <summary>
        /// 所有属性的文本形式
        /// </summary>
        /// <returns></returns>
        public string ToText()
        {
            string s = string.Format("Name={0}, Action={1}, Level={2}", Name, Action, Level);
            return s;
        }

    }

    /// <summary>
    /// 客户端的动作
    /// </summary>
    public enum ClientAction : byte
    {
        /// <summary>
        /// 没有动作
        /// </summary>
        None = 0,
        /// <summary>
        /// 需要7寸D料架
        /// </summary>
        NeedD = 1,
        /// <summary>
        /// 需要大尺寸C料架
        /// </summary>
        NeedC = 2,
        /// <summary>
        /// 需要进入料架
        /// </summary>
        NeedEnter = 3,
        /// <summary>
        /// 需要出去料架
        /// </summary>
        NeedLeave = 4,
        /// <summary>
        /// 需要进入离开料架
        /// </summary>
        NeedEnterLeave = 5,
        /// <summary>
        /// 准备进入,服务器发送
        /// </summary>
        ReadyEnter = 6,
        /// <summary>
        /// 可以进入料架
        /// </summary>
        MayEnter = 7,
        /// <summary>
        /// 完成进入料架
        /// </summary>
        FinishEnter = 8,
        /// <summary>
        /// 准备离开,服务器发送
        /// </summary>
        ReadyLeave = 9,
        /// <summary>
        /// 可以出去料架
        /// </summary>
        MayLeave = 10,
        /// <summary>
        /// 完成出去料架
        /// </summary>
        FinishLeave = 11,

    }

    /// <summary>
    /// 客户端的优先级
    /// </summary>
    public enum ClientLevel : byte
    {
        /// <summary>
        /// 低
        /// </summary>
        Low = 0,
        /// <summary>
        /// 中等
        /// </summary>
        Middle = 1,
        /// <summary>
        /// 高
        /// </summary>
        High = 2
    }


}