AgvClient.cs 17.7 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Agv
{
    /// <summary>
    /// AGV客户端
    /// </summary>
    public class AgvClient
    {
        private bool _loopClient;
        private int _countRecon;
        private bool _loopRecon;
        private Socket _clientSocket;        //客户端
        private List<Node> _node;
        private List<Node> _nodeNoneState;
        private Thread tSend;          //发送
        private Thread tListen;        //监听网络
        private Thread tRecon;
        private string SERVER_IP;        //远程IP地址
        private int SERVER_PORT;    //端口
        /// <summary>
        /// 小车接收事件委托
        /// </summary>
        public delegate void ReceiveEvent(Node node);
        /// <summary>
        /// 服务器连接事件
        /// </summary>
        /// <param name="status"></param>
        public delegate void ConnectEvent(bool status);
        /// <summary>
        /// 小车接收事件
        /// </summary>
        public event ReceiveEvent Received;
        /// <summary>
        /// 服务器连接事件
        /// </summary>
        public event ConnectEvent Connected;

        /// <summary>
        /// 服务端信息
        /// </summary>
        public string ServerInfo
        {
            get
            {
                return string.Format("{0}:{1}", SERVER_IP, SERVER_PORT.ToString());
            }
        }
        /// <summary>
        ///  AGV客户端
        /// </summary>
        public AgvClient()
        {
            _node = new List<Node>();
            _nodeNoneState = new List<Node>();
        }

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

        /// <summary>
        /// 发送命令的时间间隔,不能大于10s(单位:秒)
        /// </summary>
        public int SendSleep { set; get; } = 1;
        /// <summary>
        /// 禁用状态(true:发送None,false:正常发送)
        /// </summary>
        public bool CancelState { get; set; } = true;


        /// <summary>
        /// 连接
        /// </summary>
        public void Connect(string serverIP, int port = 12000)
        {
            SERVER_IP = serverIP;
            SERVER_PORT = port;
            _countRecon = 0;
            _loopRecon = true;
            IsConn = false;
            _loopClient = true;

            tListen = new Thread(new ThreadStart(ListenServerNet));
            tSend = new Thread(new ThreadStart(KeepSendStatus));
            tRecon = new Thread(new ThreadStart(Reconnect));
            tRecon.Start();
            //Open();
            tListen.Start();
            tSend.Start();
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public void Close()
        {
            CancelState = true;
            _loopClient = false;
            _loopRecon = false;
            SendStatus();
            if (_clientSocket != null)
            {
                _clientSocket.Close();
                _clientSocket = null;
            }
        }

        /// <summary>
        /// 设置状态
        /// </summary>
        /// <param name="nodeName">节点名</param>
        /// <param name="mark">虚拟rfid</param>
        /// <param name="rfid">rfid</param>
        /// <param name="action">动作</param>
        /// <param name="level">等级</param>
        /// <param name="shelf">料架类型</param>
        /// <param name="type">客户端类型</param>
        public void SetStatus(string nodeName, string mark = "", string rfid = "", ClientAction action = ClientAction.None, ClientLevel level = ClientLevel.Low, ClientShelf shelf = ClientShelf.None, ClientType type = ClientType.None)
        {
            int index = _node.FindIndex(s => s.Name == nodeName);
            if (index == -1)  //没有找到
            {
                Node node = new Node
                {
                    Name = nodeName,
                    RFID = rfid,
                    Action = action,
                    Level = level,
                    Shelf = shelf,
                    Type = type,
                    Mark = mark
                };
                _node.Add(node);
                _nodeNoneState.Add(new Node { Name=nodeName});
                log.info(string.Format("SetStatus To Server[{0}]:[{1}]", ServerInfo, node.ToText()));
            }
            else
            {
                _node[index].RFID = rfid;
                _node[index].Action = action;
                _node[index].Level = level;
                _node[index].Shelf = shelf;
                _node[index].Type = type;
                _node[index].Mark = mark;
                log.info(string.Format("SetStatus To Server[{0}]:[{1}]", ServerInfo, _node[index].ToText()));
            }
        }



        /// <summary>
        /// 重连线程
        /// </summary>
        private void Reconnect()
        {
            while (_loopRecon)
            {
                if (!IsConn)
                {
                    Open();
                    if (IsConn)
                    {
                        _countRecon = 0;
                        log.info(string.Format("连接到服务端[{0}]成功",ServerInfo));
                        Connected?.Invoke(IsConn);
                    }
                    else
                    {
                        log.warn("连接服务器失败" + ++_countRecon + "次");
                    }
                }
                Thread.Sleep(2000);
            }
        }

        /// <summary>
        /// 打开,连接到服务器
        /// </summary>
        private void Open()
        {
            try
            {
                if (CheckIP(SERVER_IP))
                {
                    _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 2000);
                    _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 2000);
                    _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
                    _clientSocket.Connect(IPAddress.Parse(SERVER_IP), SERVER_PORT);
                    if (!_loopRecon) return;
                    IsConn = true;
                    Connected?.Invoke(IsConn);
                }
            }
            catch (Exception ex)
            {
                IsConn = false;
                log.error("Open Error", ex);
            }
        }

        /// <summary>
        /// 监听服务端发送的内容
        /// </summary>
        private void ListenServerNet()
        {
            int timeout = 100;
            while (true)
            {
                while (_loopClient)
                {
                    Thread.Sleep(timeout);
                    if (!IsConn) continue;
                    if (_clientSocket == null) continue;
                    if (!_loopClient) break;

                    try
                    {
                        // 定义一个缓存区;
                        byte[] arrMsgRec = new byte[1024];
                        // 将接收到的数据存入到输入  arrMsgRec中;
                        int length = -1;
                        if (_clientSocket!=null && _clientSocket.Poll(-1, SelectMode.SelectRead))
                        {
                            try
                            {
                                length = _clientSocket.Receive(arrMsgRec); // 接收数据,并返回数据的长度;
                                if (length == 0)//连接正常断开
                                {
                                    IsConn = false;
                                    Connected?.Invoke(IsConn);
                                    log.info(string.Format("服务端[{1}]断开与客户端的连接", _clientSocket.RemoteEndPoint.ToString(), ServerInfo));
                                    break;
                                }
                            }
                            catch (ObjectDisposedException ode)
                            {
                                IsConn = false;
                                Connected?.Invoke(IsConn);
                                log.info(string.Format("客户端已关闭"));
                            }
                        }

                        if (length > 0)
                        {
                            byte[] buff = new byte[length];
                            Array.Copy(arrMsgRec, 0, buff, 0, length);
                            StickyBagHandle(buff);
                        }
                    }
                    catch (SocketException se)
                    {
                        IsConn = false;
                        Connected?.Invoke(IsConn);
                        log.error(string.Format("客户端接收服务端[{0}]的消息出现异常", ServerInfo), se);
                    }
                    catch (Exception ex)
                    {
                        IsConn = false;
                        log.error("ListenNet Error", ex);
                        Connected?.Invoke(IsConn);
                    }
                }
            }
        }

        #region 粘包处理
        byte[] surplusBuffer = null;//不完整的数据包,即用户自定义缓冲区
        /// <summary>
        /// 粘包处理
        /// </summary>
        /// <param name="bytes"></param>
        private void StickyBagHandle(byte[] bytes)
        {
            //bytes 为系统缓冲区数据
            //bytesRead为系统缓冲区长度
            int bytesRead = bytes.Length;
            if (bytesRead > 0)
            {
                if (surplusBuffer !=null)
                {
                    byte[] curBuffer = surplusBuffer.Concat(bytes).ToArray();//拼接上一次剩余的包
                    //更新会话的最新字节
                    surplusBuffer = curBuffer;//同步
                }
                else
                {
                    if (Common.CheckHeadChar(bytes, out int startIdx))//检查是否存在指定包头识别字符
                    {
                        //添加会话ID的bytes
                        byte[] tmp = new byte[bytesRead - startIdx];
                        Buffer.BlockCopy(bytes, startIdx, tmp, 0, bytesRead - startIdx);
                        surplusBuffer = tmp;//同步
                    }
                    else
                        return;
                }

                //已经完成读取每个数据包长度
                int haveRead = 0;
                //这里totalLen的长度有可能大于缓冲区大小的(因为 这里的surplusBuffer 是系统缓冲区+不完整的数据包)
                int totalLen = surplusBuffer.Length;
                while (haveRead <= totalLen)
                {
                    //如果在N次拆解后剩余的数据包连一个包头的长度都不够
                    //说明是上次读取N个完整数据包后,剩下的最后一个非完整的数据包
                    if (totalLen - haveRead < Common.headSize)
                    {
                        byte[] byteSub = new byte[totalLen - haveRead];
                        //把剩下不够一个完整的数据包存起来
                        Buffer.BlockCopy(surplusBuffer, haveRead, byteSub, 0, totalLen - haveRead);
                        surplusBuffer = byteSub;

                        totalLen = 0;

                        break;

                    }

                    //如果够了一个完整包,则读取包头的数据
                    byte[] headByte = new byte[Common.headSize];
                    Buffer.BlockCopy(surplusBuffer, haveRead, headByte, 0, Common.headSize);//从缓冲区里读取包头的字节
                                                                                            //判断包头起始符
                    int bodySize = BitConverter.ToUInt16(headByte, 2);//从包头里面分析出包体的长度
                                                                      //这里的 haveRead=等于N个数据包的长度 从0开始;0,1,2,3....N

                    //如果自定义缓冲区拆解N个包后的长度 大于 总长度,说最后一段数据不够一个完整的包了,拆出来保存
                    if (haveRead + Common.headSize + bodySize > totalLen)
                    {
                        byte[] byteSub = new byte[totalLen - haveRead];
                        Buffer.BlockCopy(surplusBuffer, haveRead, byteSub, 0, totalLen - haveRead);
                        surplusBuffer = byteSub;
                        break;
                    }
                    else
                    {
                        //挨个分解每个包,解析成实际文字
                        //String strc = Encoding.UTF8.GetString(surplusBuffer, haveRead + headSize, bodySize);
                        byte[] resBytes = new byte[bodySize];
                        Buffer.BlockCopy(surplusBuffer, haveRead + Common.headSize, resBytes, 0, bodySize);
                        log.debug(string.Format("[Receive data from Server[{0}]: {1}", ServerInfo, Common.HexBuff(resBytes)));
                        DecodeNode(resBytes);
                        //依次累加当前的数据包的长度
                        haveRead = haveRead + Common.headSize + bodySize;
                        if (Common.headSize + bodySize == bytesRead)//如果当前接收的数据包长度正好等于缓冲区长度,则待拼接的不规则数据长度归0
                        {
                            surplusBuffer = null;//设置空 回到原始状态
                            totalLen = 0;//清0
                        }

                    }

                }

            }

        }
        #endregion
        private void DecodeNode(byte[] resultBytes)
        {
            Node node = Common.Decode(resultBytes);
            if (node == null)
            {
                log.error("命令解析失败");
            }
            else
            {
                log.info(string.Format("Received事件触发:{0}", node.ToText()));
                Received?.Invoke(node);
            }
        }
        /// <summary>
        /// 连续发送状态线程
        /// </summary>
        private void KeepSendStatus()
        {

            while (_loopClient)
            {
                Thread.Sleep(SendSleep * 1000);
                if (!IsConn) continue;
                if (_clientSocket == null) continue;
                SendStatus();

            }
        }

        private void SendStatus()
        {
            bool bln;
            if (Common.EnDecodeSingleNode)
            {
                for (int i = 0; i < _node.Count; i++)
                {
                    Thread.Sleep(100);
                    if (!CancelState)
                    {
                        byte[] buff = Common.Encode(_node[i]);
                        bln = Send(buff);
                    }
                    else
                    {
                        Node nostate = _node[i].ToCopy();
                        nostate.Action = ClientAction.None;
                        byte[] buff = Common.Encode(nostate);
                        bln = Send(buff);
                    }
                    if (!bln) continue;
                }
            }
            else
            {
                if (_node.Count == 0) return;
                if (!CancelState)
                {
                    byte[] buff = Common.Encode(_node);
                    bln = Send(buff);
                }
                else
                {
                    byte[] buff = Common.Encode(_nodeNoneState);
                    bln = Send(buff);
                }
            }
        }

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

            try
            {
                if (buff == null) return false;
                _clientSocket.Send(buff);
                log.debug(string.Format("Send to Server:{0}", Common.HexBuff(buff)));
                return true;
            }
            catch (Exception ex)
            {
                log.error("Send Error", ex);
                IsConn = false;
                Connected?.Invoke(IsConn);
                return false;
            }

        }

        /// <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("非法的IP地址" + 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.warn("Ping " + ip + " 请求没有响应");
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                log.error("CheckIP Error", ex);
                return false;
            }
        }

    }

}