AgvServer.cs 23.4 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
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using Common;
using System.Threading;
using System.Collections.Concurrent;
using System.Linq;

namespace DeviceLibrary
{
    /// <summary>
    /// AGV服务端,要求每个线体拥有不用的IP,根据IP来查找客户端
    /// </summary>
    public class AgvServer
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger("AgvServer");
        private bool _loop;
        private Socket _server;         //服务端
        private List<Client> _client;   //所有客户端
        private Thread tListenClient;   //监听客户端连接
        private static int PORT = 9501;    //端口
        private Thread tPingClient;   //ping
        /// <summary>
        /// 节点改变事件
        /// </summary>
        /// <param name="nodeIndex"></param>
        public delegate void NodeChangedEvent(int nodeIndex);
        /// <summary>
        /// 节点改变
        /// </summary>
        public event NodeChangedEvent NodeChanged;
        /// <summary>
        /// 节点在线
        /// </summary>
        public event NodeChangedEvent NodeOnline;

        /// <summary>
        /// AGV服务端
        /// </summary>
        public AgvServer(int port=9501)
        {
            PORT = port;
            _client = new List<Client>();
        }

        /// <summary>
        /// 开启服务
        /// </summary>
        public void Start()
        {
            try
            {
                IPEndPoint localEP = new IPEndPoint(IPAddress.Any, PORT);
                _server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _server.Bind(localEP);
                _server.Listen(100);
                log.Info("Server Start");
                _loop = true;
                _client = new List<Client>();
                tListenClient = new Thread(new ThreadStart(ListenClient));
                tListenClient.Start();
               tPingClient = new Thread(new ThreadStart(KeepLiveClient));
                tPingClient.Start();
            }
            catch (Exception ex)
            {
                log.Error("Start()", ex);
            }
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        public void Stop()
        {
            _loop = false;
            for (int i = 0; i < _client.Count; i++)
            {
                _client[i].Loop = false;
                _client[i].IsConn = false;
                _client[i].Socket.Close();
            }
            _server.Close();
            _client = null;
            Thread.Sleep(50);
            log.Info("Server Stop");
        }

        public Dictionary<string, DateTime> readyEnterTime = new Dictionary<string, DateTime>();
        public Dictionary<string, DateTime> readyLeaveTime = new Dictionary<string, DateTime>();
        public bool ReadyEnter(string nodeName, string rfid = "")
        {
            int nodeIdx = AGVManager.nodeInfo.FindIndex(s => s.Name == nodeName);
            string ip = AGVManager.nodeInfo[nodeIdx].IP;
            int idx = FindClient(ip);
            if (idx == -1)
            {
                log.Error("ReadyEnter 没有找到" + nodeName + " " + ip);
                return false;
            }
            else
            {
                try
                {
                    if (!readyEnterTime.ContainsKey(nodeName))
                    {
                        readyEnterTime.Add(nodeName, DateTime.Now);
                    }
                    else
                    {
                        TimeSpan timeSpan = DateTime.Now - readyEnterTime[nodeName];
                        if (timeSpan.TotalSeconds < 15)
                        {
                            log.Debug(nodeName + " " + ip + " ReadyEnter 15秒内不重复发送");
                            return false;
                        }
                        else if (timeSpan.TotalSeconds > 30)
                        {
                            readyEnterTime[nodeName] = DateTime.Now;
                        }
                    }
                }
                catch (Exception ex) { log.Debug(ex.Message + ";" + ex.StackTrace); }

                ClientNode node = new ClientNode(nodeName, rfid, eNodeStatus.ReadyEnter);
                byte[] buff = Encode(node);
                return Send(idx, buff);
            }
        }

        public bool ReadyLeave(string nodeName, string rfid = "")
        {
            int nodeIdx = AGVManager.nodeInfo.FindIndex(s => s.Name == nodeName);
            string ip = AGVManager.nodeInfo[nodeIdx].IP;
            int idx = FindClient(ip);
            if (idx == -1)
            {
                log.Error("ReadyLeave 没有找到" + nodeName + " " + ip);
                return false;
            }
            else
            {
                try
                {
                    if (!readyLeaveTime.ContainsKey(nodeName))
                    {
                        readyLeaveTime.Add(nodeName, DateTime.Now);
                    }
                    else
                    {
                        TimeSpan timeSpan = DateTime.Now - readyLeaveTime[nodeName];
                        if (timeSpan.TotalSeconds < 45)
                        {
                            log.Debug(nodeName + " " + ip + " ReadyLeave 45秒内不重复发送");
                            return false;
                        }
                        else if (timeSpan.TotalMinutes > 1)
                        {
                            readyLeaveTime[nodeName] = DateTime.Now;
                        }
                    }
                }
                catch (Exception ex) { log.Debug(ex.Message + ";" + ex.StackTrace); }

                ClientNode node = new ClientNode(nodeName, rfid, eNodeStatus.ReadyLeave);
                byte[] buff = Encode(node);
                return Send(idx, buff);
            }
        }

        public bool FinishEnter(string nodeName, string rfid = "")
        {
            int nodeIdx = AGVManager.nodeInfo.FindIndex(s => s.Name == nodeName);
            string ip = AGVManager.nodeInfo[nodeIdx].IP;
            int idx = FindClient(ip);
            if (idx == -1)
            {
                log.Error("FinishEnter 没有找到" + nodeName + " " + ip);
                return false;
            }
            else
            {
                ClientNode node = new ClientNode(nodeName, rfid, eNodeStatus.FinishEnter);
                byte[] buff = Encode(node);
                return Send(idx, buff);
            }
        }

        public bool FinishLeave(string nodeName, string rfid = "")
        {
            int nodeIdx = AGVManager.nodeInfo.FindIndex(s => s.Name == nodeName);
            string ip = AGVManager.nodeInfo[nodeIdx].IP;
            int idx = FindClient(ip);
            if (idx == -1)
            {
                log.Error("FinishLeave 没有找到" + nodeName + " " + ip);
                return false;
            }
            else
            {
                ClientNode node = new ClientNode(nodeName, rfid, eNodeStatus.FinishLeave);
                byte[] buff = Encode(node);
                return Send(idx, buff);
            }
        }


        private void KeepLiveClient()
        {
            int n;

            while (_loop)
            {
                n = 0;
                while (n < 5000)  //所有产线间隔
                {
                    Thread.Sleep(50);
                    n += 50;
                    if (!_loop) return;
                }

                for (int i = 0; i < AGVManager.nodeInfo.Count; i++)
                {
                    try
                    {
                        if (!_loop)
                            break;
                        Thread.Sleep(1000);
                        if (!AGVManager.nodeInfo[i].IP.Equals(""))
                            AGVManager.nodeInfo[i].Online = CheckIP(AGVManager.nodeInfo[i].Name, AGVManager.nodeInfo[i].IP);
                        NodeOnline?.Invoke(i);
                    }
                    catch (Exception e)
                    {
                        log.Error("PingClient", e);
                    }
                }

            }
        }

        public bool CheckIP(string name, 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.Error("非法的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.Debug(name + " Ping " + ip + " 请求没有响应");
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                log.Error("CheckIP", ex);
                return false;
            }
        }

        /// <summary>
        /// 监听客户端
        /// </summary>
        private void ListenClient()
        {
            while (_loop)
            {
                try
                {
                    Socket socket = _server.Accept();  //这边会暂停,不需要sleep
                    IPEndPoint ep = (IPEndPoint)socket.RemoteEndPoint;
                    Thread listen = new Thread(new ParameterizedThreadStart(ListenNet));
                    string ip = ep.Address.ToString();

                    //新的客户端
                    Client client = new Client
                    {
                        IP = ip,
                        Loop = true,
                        IsConn = true,
                        Socket = socket,
                        ListenNet = listen,
                        nodeName = new List<string>(),
                    };

                    //重连后关闭旧连接
                    int idx = _client.FindIndex(s => s.IP.Equals(ip));
                    if (idx > -1)
                    {
                        _client[idx].IsConn = false;
                        _client[idx].nodeName.Clear();
                        _client[idx].Loop = false;
                        _client[idx].Socket.Close();
                        _client.RemoveAt(idx);
                    }

                    _client.Add(client);
                    listen.Start(_client.Count - 1);
                    log.Info(string.Format("[{0}] 已连接", client.IP));
                }
                catch (SocketException)
                {
                    //关闭连接,退出阻塞Accept
                    log.Debug("服务端关闭连接,退出阻塞Accept");
                }
                catch (Exception ex)
                {
                    log.Error("ListenClient()", ex);
                }
            }
        }

        //临时缓存
        //线程安全的字典
        ConcurrentDictionary<string, byte[]> dic = new ConcurrentDictionary<string, byte[]>();
        /// <summary>
        /// 客户端数据接收
        /// </summary>
        /// <param name="obj">索引</param>
        private void ListenNet(object obj)
        {
            int sleep = 50;
            Client client = _client[(int)obj];
            byte[] temp = new byte[127];
            int time = 0;

            while (client.Loop)
            {
                Thread.Sleep(sleep);
                try
                {
                    if (!client.Loop) break;
                    if (client.Socket.Available > 0)
                    {
                        time = 0;
                        byte[] supBuff = null;
                        int count = client.Socket.Receive(temp);
                        if (!dic.TryGetValue(client.IP, out supBuff)) //第一次收到开头必须是0xAD开头的字节
                        {
                            if (temp[0].Equals(0xAD))
                            {
                                supBuff = new byte[count];
                                Array.Copy(temp, 0, supBuff, 0, count);
                                //log.Info(string.Format("start with AB receive:{0}", HexBuff(supBuff)));
                            }
                            else
                            {
                                //log.Info(string.Format("start without AB receive:{0}", HexBuff(temp)));
                                for (int i = 0; i < count; i++)
                                {
                                    if (!temp[i].Equals(0xAD))
                                        continue;
                                    supBuff = new byte[count - i];
                                    Array.Copy(temp, i, supBuff, 0, count - i);
                                    //log.Info(string.Format("start without AB receive after filter:{0}", HexBuff(supBuff)));
                                    break;
                                }
                            }
                            dic.TryAdd(client.IP, supBuff);
                        }
                        else
                        {
                            byte[] tmp = new byte[count];
                            Array.Copy(temp, 0, tmp, 0, count);
                            byte[] curBuff = supBuff.Concat(tmp).ToArray();
                            dic.TryUpdate(client.IP, curBuff, supBuff);
                            supBuff = curBuff;
                            //log.Info(string.Format("receive:{0}",HexBuff(tmp)));
                            //log.Info(string.Format("buff:{0}",HexBuff(supBuff)));
                            //log.Info(string.Format("curBuf:{0}",HexBuff(curBuff)));
                            //log.Info(string.Format("dic[0]:{0}", HexBuff(dic[client.IP])));
                        }

                        List<byte> buf = new List<byte>();
                        for (int i = 0; i < supBuff.Length; i++)
                        {
                            if (supBuff[i].Equals(0XAD))
                            {
                                if (buf.Count > 0)
                                    buf.Clear();
                                buf.Add(supBuff[i]);
                            }
                            else if (supBuff[i].Equals(0XDA))
                            {
                                buf.Add(supBuff[i]);
                                byte[] buff = buf.ToArray();
                                //Array.Copy(temp, 0, buff, 0, count);

                                ClientNode node = Decode(client, buff);
                                if (node == null)
                                {
                                    log.Debug(client.IP + " 解码失败:" + HexBuff(buff));
                                }
                                else
                                {
                                    if (!node.Name.StartsWith("A") && !node.Name.Equals("S21")&& !node.Name.Equals("S22"))
                                    {
                                        log.Info("Receive[" + client.IP + "]:[" + HexBuff(buff) + "],解码内容:" + node.StatetText());
                                    }
                                    log.Debug("Receive[" + client.IP + "]:[" + HexBuff(buff) + "],解码内容:" + node.StatetText());
                                    int idx = client.nodeName.FindIndex(s => s == node.Name);
                                    if (idx == -1) client.nodeName.Add(node.Name);
                                    UpdateNode(node);
                                }
                                if (buf.Count > 0)
                                    buf.Clear();
                            }
                            else
                            {
                                buf.Add(supBuff[i]);
                            }
                        }
                        if (buf.Count > 0)//存在部分包
                        {
                            dic.TryUpdate(client.IP, buf.ToArray(), supBuff);
                        }
                        else
                            dic.TryRemove(client.IP, out byte[] bb);

                    }
                    else
                    {
                        time += sleep;
                        if (time > 1000 * 60 * 60 * 1)
                        {
                            Offline(client);
                            log.Debug("[" + client.IP + "] 超过1H没有收到数据,关闭连接");
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error("ListenNet()", ex);
                }

            }
        }

        /// <summary>
        /// 编码-定长12字节
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private byte[] Encode(ClientNode node)
        {
            int idx = 0;
            byte[] buff = new byte[12];
            buff[idx++] = 0xAD;
            buff[idx++] = (byte)node.Name[0];
            buff[idx++] = Convert.ToByte(node.Name.Substring(1));
            buff[idx++] = (byte)node.RFID[0];
            //buff[idx++] = 0X00;
            //buff[idx++] = 0X00;
            //buff[idx++] = 0X00;
            buff[idx++] = Convert.ToByte(node.RFID.Substring(1));
            buff[idx++] = (byte)node.GetState();
            buff[idx++] = 0;
            idx += 4;  //预留
            buff[idx] = 0xDA;
            return buff;
        }

        /// <summary>
        /// 解码-定长12字节
        /// </summary>
        /// <param name="buff"></param>
        /// <returns></returns>
        private ClientNode Decode(Client client, byte[] buff)
        {
            int idx = 0;
            string name = "";
            string rfid = "";
            if (buff[idx++] != 0xAD) return null;
            if (buff[idx] == 0x00 && buff[idx + 1] == 0x00)//收到产线
            {
                int k = AGVManager.nodeInfo.FindIndex(s => client.IP.Equals(s.IP) && !s.Name.StartsWith("A"));
                if (k > -1)
                {
                    name = AGVManager.nodeInfo[k].Name;
                    rfid = "";
                }
                idx += 2;
                idx += 2;
            }
            else
            {
                name = (char)buff[idx] + buff[idx + 1].ToString();
                idx += 2;
                rfid = (char)buff[idx] + buff[idx + 1].ToString();
                idx += 2;
            }

            eNodeStatus action = (eNodeStatus)buff[idx++];

            ClientLevel level = (ClientLevel)buff[idx++];
            idx += 4;  //预留
            if (buff[idx] != 0xDA) return null;

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

        private void UpdateNode(ClientNode node)
        {
            int idx = AGVManager.nodeInfo.FindIndex(s => s.Name == node.Name);
            if (idx == -1)
            {
                log.Error("UpdateNode " + node.Name + " 不存在");
                return;
            }

            if (!AGVManager.nodeInfo[idx].Online)
            {
                AGVManager.nodeInfo[idx].Online = true;
                NodeOnline?.Invoke(idx);
            }

            if (!AGVManager.nodeInfo[idx].StateEquals(node.GetState()) ||
                AGVManager.nodeInfo[idx].RFID != node.RFID || AGVManager.nodeInfo[idx].ClientLevel != node.ClientLevel)
            {

                AGVManager.nodeInfo[idx].UpdateNodeStatus(node.GetState());
                AGVManager.nodeInfo[idx].ClientLevel = node.ClientLevel;
                AGVManager.nodeInfo[idx].RFID = node.RFID;
                log.Info("节点更新 " + node.StatetText());
                NodeChanged?.Invoke(idx);
            }
        }

        private void Offline(Client client)
        {
            client.Loop = false;
            client.IsConn = false;
            client.Socket.Close();

            for (int i = 0; i < client.nodeName.Count; i++)
            {
                int idx = AGVManager.nodeInfo.FindIndex(s => s.Name == client.nodeName[i]);
                if (idx == -1) continue;
                AGVManager.nodeInfo[idx].Offline();
                NodeChanged(idx);
                NodeOnline(idx);
            }
            client.nodeName.Clear();
            //_client.Remove(client);
        }

        /// <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>
        /// 查找客户端
        /// </summary>
        /// <param ip="ip">ip地址</param>
        /// <returns></returns>
        private int FindClient(string ip)
        {
            int index = -1;
            if (_client == null) return index;

            try
            {
                foreach (Client item in _client)
                {
                    if (item.IsConn)
                    {
                        //Common.log.Info("已连接客户端:" + string.Join("#", item.IP));
                        if (item.IP.Equals(ip))
                        {
                            index = _client.IndexOf(item);
                            break;
                        }
                        //int idx = item.nodeName.FindIndex(a => a == name);
                        //if (idx != -1)
                        //{
                        //    index = _client.IndexOf(item);
                        //    break;
                        //}
                    }
                }
            }
            catch { };
            return index;
        }

        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="idx"></param>
        /// <param name="buff"></param>
        /// <returns></returns>
        private bool Send(int idx, byte[] buff)
        {
            string ip = "[" + _client[idx].IP + "]";

            if (!_client[idx].IsConn)
            {
                log.Error(ip + " 没有连接");
                return false;
            }

            try
            {
                if (_client[idx].IsConn)
                    _client[idx].Socket.Send(buff);
                if (buff.Length > 2)
                    log.Info("SendTo" + ip + ": " + HexBuff(buff));
                return true;
            }
            catch (Exception ex)
            {
                log.Error("Send Error: " + ip, ex);
                return false;
            }
        }

    }

    /// <summary>
    /// 客户端
    /// </summary>
    public class Client
    {
        /// <summary>
        /// 循环
        /// </summary>
        public bool Loop;
        /// <summary>
        /// IP地址
        /// </summary>
        public string IP;
        /// <summary>
        /// 是否连接
        /// </summary>
        public bool IsConn;
        /// <summary>
        /// 节点名称集合
        /// </summary>
        public List<string> nodeName;
        /// <summary>
        /// 套接字
        /// </summary>
        public Socket Socket;
        /// <summary>
        /// 接收数据线程
        /// </summary>
        public Thread ListenNet;
    }


}