LineServer.cs 21.5 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
using log4net;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;

namespace OnlineStore.DeviceLibrary
{
    public class LineServer
    {
        //private static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private static object MapLock = "";
        private static TcpServer tcpserver = null;
        public static bool IsStart = false;
        public  static int ClientKeepSecond = 10;
        public static Dictionary<int, BoxInfo> BoxMap = new Dictionary<int, BoxInfo>();

        public static Dictionary<int, TcpClientBean> ClientMap = new Dictionary<int, TcpClientBean>();

        public static BoxInfo GetBoxInfo(int storeID)
        {
            if (BoxMap.ContainsKey(storeID))
            {
                return BoxMap[storeID];
            }
            else
            {
                int newId = storeID;
                if (storeID.Equals(19))
                {
                    newId = 25;
                }
                else if (storeID.Equals(20))
                {
                    newId = 26;
                }
                if (BoxMap.ContainsKey(newId))
                {
                    return BoxMap[newId];
                }
            }
            return null;
        }
        public static bool BoxConnected(int id)
        {
            BoxInfo box = GetBoxInfo(id);
            if (box != null)
            {
                TimeSpan span = DateTime.Now - box.LastMsgTime;
                if (span.TotalSeconds < ClientKeepSecond)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 移栽装置拦截托盘时, 判断是否可以入库,入库执行可以入库,出库过程中不能入库
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool BoxCanInStore(int id)
        {
            BoxInfo box = GetBoxInfo(id);
            if (box != null)
            {
                TimeSpan span = DateTime.Now - box.LastMsgTime;
                if (span.TotalSeconds < ClientKeepSecond && box.SAlarmType.Equals(LineAlarmType.None))
                {
                    LineRunStatus runs = (LineRunStatus)box.SRunStatus;

                    if (runs.Equals(LineRunStatus.Runing))
                    {
                        return true;
                    }
                    else if (runs.Equals(LineRunStatus.Busy))
                    {
                        LineStatus status = (LineStatus)box.SStatus;
                        if (status.Equals(LineStatus.StoreOnline) || status.Equals(LineStatus.InStoreEnd) || status.Equals(LineStatus.InStoreExecute))
                        {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 判断库位是否验证成功
        /// </summary> 
        public static bool RightInPosId(int id, string posId)
        {
            BoxInfo box = GetBoxInfo(id);
            if (box != null)
            {
                TimeSpan span = DateTime.Now - box.LastMsgTime;
                if (span.TotalSeconds < ClientKeepSecond)
                {
                    if (box.WaitInStoreList != null && box.WaitInStoreList.Contains(posId))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        public static bool IsInStorePro(int id, string posId)
        {
            BoxInfo box = GetBoxInfo(id);
            TimeSpan span = DateTime.Now - box.LastMsgTime;

            if (box != null && span.TotalSeconds < ClientKeepSecond)
            {

                LineStatus status = (LineStatus)box.SStatus;
                LineRunStatus runs = (LineRunStatus)box.SRunStatus;

                if (runs.Equals(LineRunStatus.Busy))
                {
                    if (status.Equals(LineStatus.InStoreEnd) || status.Equals(LineStatus.InStoreExecute))
                    {
                        if (box.WaitInStoreList != null && box.WaitInStoreList.Contains(posId))
                        {
                            LogUtil.error("IsInStorePro[" + id + "][" + posId + "],库位还在入库等待列表中,返回false");
                            return false;
                        }
                        return true;
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 移栽装置送盘到料仓门口时,需要判断是否可以将盘送入
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool BoxCanReviceTray(int id, out string NotOkMsg)
        {
            NotOkMsg = " [料仓" + id + "可以入库:离线] ";
            BoxInfo box = GetBoxInfo(id);
            if (box != null)
            {
                TimeSpan span = DateTime.Now - box.LastMsgTime;
                if (span.TotalSeconds > ClientKeepSecond)
                {
                    NotOkMsg = " [料仓" + id + "可以入库:离线] ";
                    return false;
                }
                else if (!box.HasTray.Equals(0))
                {
                    NotOkMsg = " [料仓" + id + "可以入库:仓门口有料] ";
                    return false;
                }
                else if (!box.SAlarmType.Equals(LineAlarmType.None))
                {
                    NotOkMsg = " [料仓" + id + "可以入库:报警中] ";
                    return false;
                }

                if (span.TotalSeconds < ClientKeepSecond && box.HasTray.Equals(0) && box.SAlarmType.Equals(LineAlarmType.None))
                {
                    LineRunStatus runs = (LineRunStatus)box.SRunStatus; 
                    LineStatus movestatus = (LineStatus)box.SStatus;
                    if (runs.Equals(LineRunStatus.Runing))
                    {
                        return true;
                    }
                    else if (runs.Equals(LineRunStatus.Busy) && movestatus.Equals(LineStatus.InStoreEnd))
                    {
                        return true;
                    }
                    else
                    {
                        NotOkMsg = " [料仓" + id + "可以入库:忙碌中] ";
                    }
                }
            }
            return false;
        }
        public static string GetAllCID(int equipId)
        {
            //左侧19,右侧20
            int num = equipId % 100;
            string result = "";
            List<int> IdList = new List<int>();

            if (num.Equals(2))
            {
                for (int i = 7; i <= 10; i++)
                {
                    IdList.Add(i);
                }
                IdList.Add(19);
                IdList.Add(20);
                for (int i = 11; i <= 18; i++)
                {
                    IdList.Add(i);
                }
                for (int i = 1; i <= 6; i++)
                {
                    IdList.Add(i);
                }
            }
            else if (num.Equals(3))
            {
                IdList.Add(19);
                IdList.Add(20);
                for (int i = 11; i <= 18; i++)
                {
                    IdList.Add(i);
                }
                for (int i = 1; i <= 10; i++)
                {
                    IdList.Add(i);
                }
            }
            else
            {
                for (int i = 1; i <= 10; i++)
                {
                    IdList.Add(i);
                }
                IdList.Add(19);
                IdList.Add(20);
                for (int i = 11; i <= 18; i++)
                {
                    IdList.Add(i);
                }
            }
            foreach (int id in IdList)
            {
                //   foreach (BoxInfo box in BoxMap.Values)
                //{
                BoxInfo box = GetBoxInfo(id);
                if (box != null)
                {
                    TimeSpan span = DateTime.Now - box.LastMsgTime;
                    if (span.TotalSeconds < ClientKeepSecond)
                    {
                        if (LineManager.Line.CanIntore(box.ID))
                        {
                            result += box.CId + ",";
                        }
                    }
                }
            }
            if (result.EndsWith(","))
            {
                result = result.Substring(0, result.Length - 1);
            }
            return result;
        }

        public static void StartServer(int port)
        {
            if (!IsStart)
            {
                ClientMap = new Dictionary<int, TcpClientBean>();
                BoxMap = new Dictionary<int, BoxInfo>();
                if (tcpserver == null)
                {
                    tcpserver = new TcpServer();
                }
                IsStart = true;
                tcpserver.Start(port);
                LogUtil.info( "流水线服务器在端口[" + port + "]监听!");
                tcpserver.ReviceMsgEvent += tcp_ReviceMsgEvent;
            }

        }

        public static void StopServer()
        {
            try
            {
                if (IsStart)
                {
                    IsStart = false;
                    tcpserver.Stop();
                }
            }
            catch (Exception ex)
            {
                LogUtil.error( "关闭 监听出错:",ex);
            }
        }
        public static bool UpdateBoxDebug(int id, int isDebug)
        {
            TcpClientBean client = GetClientBean(id);
            if (client != null)
            {
                Dictionary<string, object> paramList = new Dictionary<string, object>();
                paramList.Add(S_Cmd, cmd_updateDebug);
                int canOutStore = LineManager.Line.CanOutStore(id) ? 1 : 0;
                paramList.Add(S_CanOutStore, canOutStore);
                paramList.Add(S_IsDebug, isDebug);
                string msg = ToParamStr(paramList); 
                //TcpClientBean client = ClientMap[id];
                bool result = SendStrToClient(client, msg);
                if (!result)
                {
                    LogUtil.error("UpdateBoxDebug【" + id + "】【" + isDebug + "】失败");
                }
            }
            return false;
        }
        public static bool StartInStore(int id, InOutParam param)
        {
            TcpClientBean client = GetClientBean(id);
            if (client != null)
            {
                Dictionary<string, object> paramList = new Dictionary<string, object>();
                paramList.Add(S_Cmd, cmd_startIn);
                paramList.Add(S_CanOutStore, 0);
                paramList.Add(S_PosId, param.PosId);
                paramList.Add(S_PlateH, param.PlateH);
                paramList.Add(S_PlateW, param.PlateW);
                paramList.Add(S_WareCode, param.WareCode);
                paramList.Add(S_RFID, param.rfid);
                //      string msg = cmd_startIn+cmd_spilt+param.PosId+cmd_spilt+param.PlateH+cmd_spilt+param.PlateW+cmd_spilt+"\r";
                string msg = ToParamStr(paramList);
                //TcpClientBean client = ClientMap[id];
                bool result = SendStrToClient(client, msg);
                if (!result)
                {
                    LogUtil.error("StartInStore【" + id + "】【" + msg + "】失败");
                }
                else
                {
                    LogUtil.info("StartInStore【" + id + "】【" + msg + "】成功");
                }
            }
            else
            {
                LogUtil.error("StartInStore【" + id + "】【" + param.ToStr() + "】失败:料仓不在线");
            } 
            return false;
        }
     

        public static bool CheckInStorePos(int id, InOutParam param)
        {
            try
            {
                TcpClientBean client = GetClientBean(id);
                if (client != null)
                {
                    Dictionary<string, object> paramList = new Dictionary<string, object>();
                    paramList.Add(S_Cmd, cmd_checStartIn);
                    paramList.Add(S_CanOutStore, 0);
                    paramList.Add(S_PosId, param.PosId);
                    paramList.Add(S_PlateH, param.PlateH);
                    paramList.Add(S_PlateW, param.PlateW);
                    paramList.Add(S_WareCode, param.WareCode);
                    paramList.Add(S_RFID, param.rfid);
                    //      string msg = cmd_startIn+cmd_spilt+param.PosId+cmd_spilt+param.PlateH+cmd_spilt+param.PlateW+cmd_spilt+"\r";
                    string msg = ToParamStr(paramList);
                    //TcpClientBean client = ClientMap[id];
                    bool result = SendStrToClient(client, msg);
                    if (!result)
                    {
                        LogUtil.error("CheckInStorePos【" + id + "】【" + msg + "】失败");
                    }
                    else
                    {
                        //  LogUtil.info("CheckInStorePos【" + id + "】【" + msg + "】发送成功");
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("CheckInStorePos【" + id + "】【" + param.ToStr() + "】失败");
            }
            return false;
        }
        
        private static bool SendStrToClient(TcpClientBean client, string sendMsg)
        {
            if (client != null && client.ClientSocket.Connected)
            {
                byte[] sendBuffer = new byte[1024];
                sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
                client.ClientSocket.Send(sendBuffer);
                return true;
            }

            return false;
        }
        private static string ToParamStr(Dictionary<string, object> paramList)
        {
            string result = "";
            result = JsonHelper.SerializeObject(paramList);
            return result + "\r";
        }
        private static void SaveBoxClient(int id, BoxInfo box, TcpClientBean client)
        {
            lock (MapLock)
            {
                if (BoxMap.ContainsKey(id))
                {
                    BoxMap.Remove(id);
                }
                BoxMap.Add(id, box);

                if (ClientMap.ContainsKey(id))
                {
                    ClientMap.Remove(id);
                }
                else
                {
                    LogUtil.info("有新的料仓连接上,料仓ID【" + id + "】,地址【" + client.AddStr + "】");
                }
                ClientMap.Add(id, client);
            }
        }

        private static TcpClientBean GetClientBean(int id)
        {
            if (ClientMap.ContainsKey(id))
            {
                return ClientMap[id];
            }
            else
            {
                int newId = id;
                if (id.Equals(19))
                {
                    newId = 25;
                }
                else if (id.Equals(20))
                {
                    newId = 26;
                }
                if (ClientMap.ContainsKey(newId))
                {
                    return ClientMap[newId];
                }
            }
            return null;
        }
        private static void tcp_ReviceMsgEvent(TcpClientBean client, string msg)
        {
            try
            {
                if (String.IsNullOrEmpty(msg))
                {
                    return;
                }
                ProcessMsg(client, msg);

            }
            catch (Exception ex)
            {
                LogUtil.error("处理料仓消息【" + msg + "】出错:",ex);
            }
        }

        private static bool ProcessMsg(TcpClientBean client, string msg)
        {
            
            //  string[] msgArray = msg.Split(cmd_spilt);
            msg = msg.Replace("\r", "");
           // LogUtil.debug("收到【" + client.AddStr + "】的消息【" + msg + "】");
            StoreSendBean storeSMsg = JsonHelper.DeserializeJsonToObject<StoreSendBean>(msg);

            if (storeSMsg == null)
            {
                LogUtil.error("收到【" + client.AddStr + "】的消息【" + msg + "】,解析失败");
            }
            else
            {
                int id = storeSMsg.StoreId;
                BoxInfo box = new BoxInfo(storeSMsg.StoreId, storeSMsg.Cid, storeSMsg.Seq, storeSMsg.SStatus, storeSMsg.SRunStatus, storeSMsg.DoorHasTray, storeSMsg.AlarmType, storeSMsg.WaitInStoreList);
                SaveBoxClient(id, box, client );

                string cmd = storeSMsg.Cmd;
                if (cmd.StartsWith(cmd_heart))
                {
                }
                else if (cmd.StartsWith(cmd_outend))
                {
                    if (storeSMsg.data == null)
                    {
                        LogUtil.info("收到【" + client.AddStr + "】的出库完成消息【" + msg + "】出库信息为空,不处理");
                    }
                    else
                    { 
                        LogUtil.info("收到【" + client.AddStr + "】的出库完成消息【" + msg + "】");
                        string posId = storeSMsg.data.posId;
                        int plateH = Convert.ToInt32(storeSMsg.data.plateH.Trim());
                        int plateW = Convert.ToInt32(storeSMsg.data.plateW.Trim());
                        InOutParam param = new InOutParam(0, storeSMsg.data.barcode, posId, plateH, plateW,false,
                            storeSMsg.data.urgentReel,storeSMsg.data.cutReel,storeSMsg.data.smallReel,storeSMsg.data.rfid,storeSMsg.data.rfidLoc);
                        LineManager.Line.boxBean_OutStoreEnd(id, param);
                    }
                }

                //给客户端返回消息
                int canOutStore = LineManager.Line.CanOutStore(id) ? 1 : 0;
                Dictionary<string, object> paramList = new Dictionary<string, object>();
                paramList.Add(S_Cmd, cmd_heart);
                paramList.Add(S_CanOutStore, canOutStore);
                string sendMsg = ToParamStr(paramList);
                bool result = SendStrToClient(client, sendMsg);
                if (!result)
                {
                    LogUtil.error("SendHeartBack【" + id + "】【" + msg + "】失败");
                }
                return true;

            }
            return false;
        }

        private static char cmd_spilt = ';';
        private static string cmd_heart = "heart";
        private static string cmd_outend = "outend";
        private static string cmd_startIn = "starIn";
        private static string cmd_updateDebug = "updateDebug";
        public static string cmd_checStartIn = "cmd_checStartIn";


        public static string S_Cmd = "Cmd";
        public static string S_CanOutStore = "CanOutStore";
        public static string S_PosId = "PosId";
        public static string S_PlateW = "PlateW";
        public static string S_PlateH = "PlateH";
        public static string S_WareCode = "WareCode";
        public static string S_IsDebug = "IsDebug";
        public static string S_RFID = "rfid";

    }
    public class StoreReviceBean
    {
        public string Cmd = "";
        public int CanOutStore = 0;
        public string PosId = "";
        public string PlateH = "0";
        public string PlateW = "0";
        public string WareCode = "";
        public int IsDebug = 0;
    }
    public class StoreSendBean
    {
        public StoreSendBean(int id, string cid, int ss, int runs, int doorHasTray, int alarmType)
        {
            this.StoreId = id;
            this.Cid = cid;
            this.SStatus = ss;
            this.SRunStatus = runs;
            this.DoorHasTray = doorHasTray;
            this.AlarmType = alarmType;

        }
        public string Cmd = "";
        public int StoreId = 0;
        public string Cid = "";
        public int Seq = 0;
        public int SStatus = 0;
        public int SRunStatus = 0;
        public int DoorHasTray = 0;
        public int AlarmType = 0;
        //public string PosId = "";
        //public string PlateH = "0";
        //public string PlateW = "0";
        ///// <summary>
        ///// 目标料架
        ///// </summary>
        //public string tShelfI = "";     
        public List<string> WaitInStoreList = new List<string>();
        public InOutData data = null;
    }
    public class InOutData
    {
        public string posId = "";
        public string plateW = "0";
        public string plateH = "0";
        /// <summary>
        /// urgentReel: true 表示紧急料,需要出到料串上
        /// </summary>
        public bool urgentReel = false;
        /// <summary>
        /// cutReel: true 表示分盘料,需要出到料串上
        /// </summary>
        public bool cutReel = false;
        /// <summary>
        /// smallReel: true  小料(7x8),放置到小料架上
        /// </summary>
        public bool smallReel = false;

        /// <summary>
        /// rfid: 分配的料架RFID
        /// </summary>
        public string rfid = "";
        /// <summary>
        /// rfidLoc: 料架的架位,值为 - 1时,可以自由分配皮带线, 
        /// 小料时,架位为1 - 46优先走1 / 2号皮带线,47 - 92优先走3 / 4号皮带线, 
        /// 70,71,72时只能分配到3 / 4号皮带线; 
        /// 大料时,架位1 - 6优先走1 / 2号皮带线, 7 - 12优先走3/ 4号皮带线
        /// </summary>
        public int rfidLoc = 0;


        public   string barcode = "";
    }
}