MsgRecevie.cs 21.3 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
using NetTaste;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using RCS.Model.ClientMoel;
using RCS.Model.Comm;
using RCS.Model.Entity;
using RCS.Model.Equipment;
using RCS.Model.ManualModel;
using RCS.Model.WebApi.Respose;
using RCS.WinClient.Common;
using RCS.WinClient.Service;
using System.Collections;
using System.Net;
using System.Text;
using System.Xml.Linq;
using static RCS.Model.Comm.EnumMsg;

namespace RCS.WinClient.TCP
{
    public class MsgRecevie
    {
        /// <summary>
        /// 指令解析
        /// </summary>
        /// <param name="socketOpt">客户端对象</param>
        public static void TcpTranslate(SocketOpt socketOpt)
        {
            try
            {
                byte[] dataRecv = socketOpt.RecData;
                AgvData? clientMsg = null;

                #region 功能码,数据初步校验
                if (!App.Protocols.TryGetValue(dataRecv[0], out var protocol))
                {
                    App.ExFile.MessageAgvInfo("MsgException", $"和AGV【{socketOpt.ClientIp}】进行Tcp通信错误,第一个字节长度为【{dataRecv[0]}】,不存在与之匹配的协议");
                    socketOpt.SendData = dataRecv;
                    return;
                }
                clientMsg = AgvHeartRecevie(dataRecv, protocol.Details);//无错误时msgClientErr=0;
                socketOpt.EquipmentNo = clientMsg.AgvNo;
                #endregion

                #region 处理接受数据中的异常,
                //异常退出
                if (clientMsg.NewErrMsg != 0)
                {
                    if (clientMsg.NewErrMsg != EnumMsg.ErrMsg.不作处理)
                    {
                        var msg = $"客户端信息出错:【{clientMsg.NewErrMsg}】AGV【{clientMsg.AgvNo}】任务号【{clientMsg.SubTaskNo}】";
                        App.ExFile.MessageLog("MsgException", msg);
                    }
                    return;
                }
                #endregion

                #region 添加循环任务或者单步任务
                //单步任务
                if (App.SingleControlList.Find(a => a.AgvNo == clientMsg.AgvNo) is SingleControl singleControl)
                {
                    //手动控制AGV 
                    //socketOpt.SendData = SendData.GetNewActionData(singleControl.Action.ToString(), null);
                    if (singleControl.Action == 200)
                    {
                        if (clientMsg.ClientAgv.AgvState < EnumMsg.AGVState.手动)
                        {
                            return;
                        }
                        else
                        {
                            singleControl.Action = 0;
                        }
                    }
                    else if (singleControl.Action == 209 && clientMsg.ClientAgv.AgvState < EnumMsg.AGVState.离线)
                    {
                        App.SingleControlList.RemoveAll(a => a.AgvNo == clientMsg.AgvNo);
                    }
                    return;
                }

                //agv循环任务
                if (clientMsg.ClientAgv.AgvState == EnumMsg.AGVState.自动空闲
                  && clientMsg.ClientAgv.AgvTask == null
                  && !App.TaskList.Any(x => x.TaskAgvNo == clientMsg.AgvNo)
                  && App.RecurrentTasks.FirstOrDefault(x => x.agv.AgvNo == clientMsg.AgvNo) is var task && task.agv != null)
                {
                    TaskManage.AddRadomTasks(task.agv, [task.taskType], true);
                }
                #endregion

                #region 更新agv ip地址
                var address = socketOpt.ClientSocket.RemoteEndPoint is IPEndPoint ipEndPoint ? ipEndPoint.Address.ToString() : "";

                if (App.ClientWork.FirstOrDefault(a => a.ClientIp == address) is not ClientControl clientControl)
                    return;

                //启动时更新设备对应ip
                if (clientControl.AgvNo == "" || clientControl.AgvNo == null)
                {
                    clientControl.AgvNo = clientMsg.AgvNo;
                    if (address != clientMsg.ClientAgv.IP)
                    {
                        clientMsg.ClientAgv.IP = address;
                        UpdateManage.UpdateAgvIP(clientControl);
                    }
                }
                #endregion
                //处理客户端指令
                MsgManage.TcpManage(clientMsg, socketOpt);

                if (socketOpt.SendData == null && clientMsg.ClientAgv.RCSToAGV != 0)
                {
                    // var currSubTask = clientMsg.ClientAgv.AgvTask?.SubTaskList?.FirstOrDefault();
                    //var rcsData = new RcsData(currSubTask?.SubTaskNo ?? 0, null);
                    var rcsData = new RcsData(0, null);
                    rcsData.RCSToAGV = clientMsg.ClientAgv.RCSToAGV;
                    socketOpt.SendData = SendData.GetByte(rcsData, clientMsg.ClientAgv.AgvNo, "", "下发报警信息");

                }
            }
            catch (Exception ex)
            {
                App.ExFile.MessageError("TcpTranslate", ex.Message.Replace(Environment.NewLine, ""));
            }
        }

        /// <summary>
        /// 获取Agv数据,并且对格式进行校验
        /// </summary>
        /// <param name="dataRecv">心跳数据报文</param>
        /// <returns>Agv心跳信息</returns>
        //public static AgvData AgvHeartRecevie(byte[] dataRecv, bool flag)
        //{
        //    try
        //    {
        //        //客户端发送数据对象
        //        var agvData = new AgvData();
        //        //到校验码之前的数据长度
        //        var dataLength = dataRecv[0];
        //        //AGV编码
        //        agvData.AgvNo = BitConverter.ToUInt16(dataRecv, 1).ToString("X");
        //        //获取AGV
        //        var agv = App.AgvList.FirstOrDefault(a => a.AgvNo == agvData.AgvNo);
        //        if (agv == null)
        //        {
        //            agvData.NewErrMsg = EnumMsg.ErrMsg.小车号不存在;
        //            return agvData;
        //        }
        //        if (!agv.IsEnable)
        //        {
        //            agvData.NewErrMsg = EnumMsg.ErrMsg.小车状态不合理;
        //            return agvData;
        //        }
        //        //给AGV赋值
        //        agvData.ClientAgv = agv;
        //        ////获取校验码之前的数据
        //        //var checkData = dataRecv.Take(dataLength).ToArray();
        //        //计算出校验码
        //        var checkCode = ComnMethod.CheckCode(dataRecv, dataLength);
        //        if (checkCode != dataRecv[dataLength])
        //        {
        //            agvData.NewErrMsg = EnumMsg.ErrMsg.校验位错误;
        //            agv.StopReason = $"校验码不匹配,AGV上传【{dataRecv[dataLength]}】,RCS计算【{checkCode}】!";
        //            return agvData;
        //        }
        //        //扫码地标
        //        agv.AGVBarcode = BitConverter.ToUInt16(dataRecv, 3).ToString();
        //        //上位机地标
        //        agv.RCSBarcode = BitConverter.ToUInt16(dataRecv, 5);
        //        //电量
        //        agv.Voltage = dataRecv[7];
        //        //自身状态
        //        agv.AgvState = (EnumMsg.AGVState)dataRecv[8];
        //        //车头方向
        //        agv.AgvDirection = (EnumMsg.Direction)dataRecv[9];
        //        //转盘方向
        //        agv.DialDirection = (EnumMsg.Direction)dataRecv[10];
        //        //顶升状态
        //        agv.HeightState = (EnumMsg.HeightState)dataRecv[11];
        //        //AGV错误
        //        agv.ErrorList = (AGVErrorCode)BitConverter.ToInt64(dataRecv, 12);
        //        //agv.ErrorList = new BitArray(new byte[] { dataRecv[12], dataRecv[13], dataRecv[14], dataRecv[15], dataRecv[16], dataRecv[17], dataRecv[18], dataRecv[19] });
        //        //行驶距离
        //        agv.RunDistance = BitConverter.ToUInt16(dataRecv, 20);
        //        //任务号
        //        agvData.SubTaskNo = BitConverter.ToUInt32(dataRecv, 22);
        //        //动作完成状态
        //        agv.ActState = (EnumMsg.ActState)dataRecv[26];
        //        //坐标X值
        //        agv.XLength = BitConverter.ToInt32(dataRecv, 27);
        //        //坐标Y值
        //        agv.YLength = BitConverter.ToInt32(dataRecv, 31);
        //        //位置可信度
        //        agv.Reliability = dataRecv[35];
        //        //车头角度
        //        agv.Angle = BitConverter.ToInt16(dataRecv, 36);
        //        //顶升高度
        //        agv.AgvHeight = BitConverter.ToUInt16(dataRecv, 38);
        //        //动作
        //        agv.Action = (EnumMsg.ActionType)dataRecv[40];
        //        //是否有货
        //        agv.InStock = (EnumMsg.InStock)dataRecv[41];
        //        //滚筒状态
        //        agv.RollerState = (EnumMsg.RollerState)dataRecv[42];
        //        //速度(毫米)
        //        agv.Speed = dataRecv[68];
        //        //雷达状态
        //        agv.RadarStatus = dataRecv[61];
        //        //雷达区域
        //        agv.RadarArea = dataRecv[62];
        //        // 心跳
        //        agv.Heart = DateTime.Now;
        //        // 停止原因
        //        agv.StopReason = string.Empty;

        //        //记录日志
        //        //var msg = $"AGV编码【{agv.AgvNo}】自身状态【{agv.AgvState}】当前地标【{agv.AGVBarcode}】上位机地标【{agv.RCSBarcode}】" +
        //        //          $"X坐标【{agv.XLength}】Y坐标【{agv.YLength}】任务号【{agvData.SubTaskNo}】动作状态【{agv.ActState}】" +
        //        //          $"车头方向【{agv.AgvDirection}】顶升状态【{agv.HeightState}】位置可信度【{agv.Reliability}】";
        //        //App.ExFile.MessageLog("GetMotion" + agvData.AgvNo, msg);
        //        var msg = $"任务号【{agvData.SubTaskNo}】" + ComnMethod.GetLogInfo(agv);
        //        App.ExFile.MessageAgvInfo("GetMotionTest" + agvData.AgvNo, msg);
        //        AgvLogInfo(dataRecv);
        //        return agvData;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception($"AgvHeartRecevie方法,异常信息:{ex.Message},\n 堆栈:{ex.StackTrace}");
        //    }
        //}


        /// <summary>
        /// 获取Agv数据,并且对格式进行校验
        /// </summary>
        /// <param name="dataRecv">心跳数据报文</param>
        /// <returns>Agv心跳信息</returns>
        public static AgvData AgvHeartRecevie(byte[] dataRecv, IEnumerable<ProtocolDetail> protocolDetails)
        {
            try
            {
                //客户端发送数据对象
                var agvData = new AgvData();

                //到校验码之前的数据长度
                var dataLength = dataRecv[0];

                //计算出校验码
                var checkCode = ComnMethod.CheckCode(dataRecv, dataLength);
                if (checkCode != dataRecv[dataLength])
                {
                    agvData.NewErrMsg = EnumMsg.ErrMsg.校验位错误;
                    App.ExFile.MessageError("AgvHeartRecevie", $"校验码不匹配,AGV上传【{dataRecv[dataLength]}】,RCS计算【{checkCode}】!");
                    return agvData;
                }

                //AGV编码
                agvData.AgvNo = BitConverter.ToUInt16(dataRecv, 1).ToString("X");
                //获取AGV
                var agv = App.AgvList.FirstOrDefault(a => a.AgvNo == agvData.AgvNo);
                if (agv == null)
                {
                    agvData.NewErrMsg = EnumMsg.ErrMsg.小车号不存在;
                    return agvData;
                }
                if (!agv.IsEnable)
                {
                    agvData.NewErrMsg = EnumMsg.ErrMsg.小车状态不合理;
                    return agvData;
                }

                //给AGV赋值
                agvData.ClientAgv = agv;

                //协议解析
                var res = ComnMethod.ProtocolAnalysis(protocolDetails, dataRecv);
                ComnMethod.ProtocolTempToInstance(res, agv);

                agvData.SubTaskNo = agv.SubTaskNo;
                agv.Heart = DateTime.Now;
                agv.StopReason = "";
                agv.RCSToAGV = 0;
                var log = new StringBuilder();
                foreach (var item in res)
                {
                    log.Append(item.Name)
                       .Append(':')
                       .Append('【')
                       .Append(item.Value)
                       .Append('】')
                       .Append(' ');
                }
                var msg = log.ToString();
                App.ExFile.MessageAgvInfo("GetMotionTest" + agvData.AgvNo, msg);
                return agvData;
            }
            catch (Exception ex)
            {
                throw new Exception($"AgvHeartRecevie方法,异常信息:{ex.Message},\n 堆栈:{ex.StackTrace}");
            }
        }


        /// <summary>
        /// 获取工位/门的信息
        /// </summary>
        /// <param name="dataRecv"></param>
        /// <returns></returns>
        public static void StationHeartRecevie(byte[] dataRecv)
        {
            HslCommunication.Core.IByteTransform ByteTransform = new HslCommunication.Core.ReverseBytesTransform();

            try
            {



                var stationCode = Encoding.ASCII.GetString(dataRecv, 2, 8).Replace("\0", "");

                //需要转换
                var station = new GlueMachine();
                if (station == null)
                {
                    return;
                }

                station.IsInstock = dataRecv[10] != 0;
                station.IsAllowPut = dataRecv[11] != 0;
                station.IsLooseShaftInPlace = dataRecv[12] != 0;
                station.IsCloseShaftCompleted = dataRecv[13] != 0;
                station.IsAllowPick = dataRecv[14] != 0;

                station.IsInsertShaftCompleted = dataRecv[18] != 0;
                station.IsDownInPlace = dataRecv[19] != 0;
                station.IsUnloadShaftCompleted = dataRecv[20] != 0;


                station.Size = dataRecv[16];

                station.Heigh = BitConverter.ToInt16(dataRecv, 26);
                station.CameraX = (sbyte)dataRecv[28];
                station.CameraY = (sbyte)dataRecv[29];
                station.ScanCodeSuccess = dataRecv[30];
                station.ReLoad = (sbyte)dataRecv[23];//重复上布确认
                station.ReUnLoad = (sbyte)dataRecv[24];//重复卸布确认

                if (station.ReLoad > 0 && station.ReUnLoad == 0)
                {

                }
                if (station.ReLoad == 0 && station.ReUnLoad > 0)
                {

                }


                try
                {

                    App.ExFile.MessageLog($"StationHeartRecevie{station.Name}", $"{Newtonsoft.Json.JsonConvert.SerializeObject(station)}");

                }
                catch (Exception ex)
                {
                    App.ExFile.MessageLog($"StationHeartRecevie{station.Name}", $"日志记录失败");
                }

            }
            catch (Exception Ex)
            {
                throw new Exception("StationHeartRecevie:" + Ex.Message.Replace(Environment.NewLine, "") + Ex.StackTrace);
            }
        }


        public static void AgvLogInfo(byte[] bytes)
        {
            try
            {
                byte[] tempBytes = new byte[70];
                //  bytes.CopyTo(tempBytes, 51);
                Array.Copy(bytes, 51, tempBytes, 0, 70);
                var checkCode = ComnMethod.CheckCode(tempBytes, 55);
                var agvNo = BitConverter.ToInt16(bytes, 1).ToString("X");
                //if (checkCode != (sbyte)bytes[110])
                //{
                //    App.ExFile.MessageLog($"AgvLogInfo_{agvNo}", $"校验码未通过,上传数据{bytes[107]},计算数据{checkCode}");
                //    return;
                //}

                StringBuilder sb = new();
                sb.Append("单字节:");

                //51   1   手自动
                var temp = (sbyte)bytes[51];
                sb.Append(temp);
                sb.Append('_');
                //52  1   当前方向
                temp = (sbyte)bytes[52];
                sb.Append(temp);
                sb.Append('_');
                //53  1   下个方向
                temp = (sbyte)bytes[53];
                sb.Append(temp);
                sb.Append('_');
                //54  1   下下个方向
                temp = (sbyte)bytes[54];
                sb.Append(temp);
                sb.Append('_');
                //55  1   电量
                temp = (sbyte)bytes[55];
                sb.Append(temp);
                sb.Append('_');
                //56  1   当前站点
                temp = (sbyte)bytes[56];
                sb.Append(temp);
                sb.Append('_');
                //57  1   全部站点数
                temp = (sbyte)bytes[57];
                sb.Append(temp);
                sb.Append('_');
                //58  1   完成状态
                temp = (sbyte)bytes[58];
                sb.Append(temp);
                sb.Append('_');
                //59  1   充电状态
                temp = (sbyte)bytes[59];
                sb.Append(temp);
                sb.Append('_');
                //60  1   物料到位检测
                temp = (sbyte)bytes[60];
                sb.Append(temp);
                sb.Append('_');
                //61  1
                temp = (sbyte)bytes[61];
                sb.Append(temp);
                sb.Append('_');
                //62  1
                temp = (sbyte)bytes[62];
                sb.Append(temp);
                sb.Append('_');
                //63  1
                temp = (sbyte)bytes[63];
                sb.Append(temp);
                sb.Append('_');
                //64  1
                temp = (sbyte)bytes[64];
                sb.Append(temp);
                sb.Append('_');
                //65  1
                temp = (sbyte)bytes[65];
                sb.Append(temp);

                sb.Append("双字节:");
                //66  2   报警代码
                var temp2 = BitConverter.ToInt16(bytes, 66);
                sb.Append(temp2.ToString("X"));
                sb.Append('_');
                //68  2   速度
                var temp21 = BitConverter.ToUInt16(bytes, 68);
                sb.Append(temp21);
                sb.Append('_');
                //70  2   下发舵轮角度
                temp2 = BitConverter.ToInt16(bytes, 70);
                sb.Append(temp2);
                sb.Append('_');
                //72  2   反馈舵轮角度
                temp2 = BitConverter.ToInt16(bytes, 72);
                sb.Append(temp2);
                sb.Append('_');
                //74  2   设置高度
                temp2 = BitConverter.ToInt16(bytes, 74);
                sb.Append(temp2);
                sb.Append('_');
                //76  2   实际高度
                temp2 = BitConverter.ToInt16(bytes, 76);
                sb.Append(temp2);
                sb.Append('_');
                //78  2   角度偏差
                temp2 = BitConverter.ToInt16(bytes, 78);
                sb.Append(temp2);
                sb.Append('_');
                //80  2   位置偏差
                temp2 = BitConverter.ToInt16(bytes, 80);
                sb.Append(temp2);
                sb.Append('_');
                //82  2
                temp2 = BitConverter.ToInt16(bytes, 82);

                sb.Append(temp2);
                sb.Append('_');
                //84  2
                temp2 = BitConverter.ToInt16(bytes, 84);
                sb.Append(temp2);

                sb.Append("四字节:");
                //86  4   点1X
                var temp3 = BitConverter.ToInt32(bytes, 86);
                sb.Append(temp3);
                sb.Append('_');
                //90  4   点1Y
                temp3 = BitConverter.ToInt32(bytes, 90);
                sb.Append(temp3);
                sb.Append('_');
                //94  4   点2X
                temp3 = BitConverter.ToInt32(bytes, 94);
                sb.Append(temp3);
                sb.Append('_');
                //98  4   点2Y
                temp3 = BitConverter.ToInt32(bytes, 98);
                sb.Append(temp3);
                sb.Append('_');
                //102 4   点3X
                temp3 = BitConverter.ToInt32(bytes, 102);
                sb.Append(temp3);
                sb.Append('_');
                //106 4   点3Y
                temp3 = BitConverter.ToInt32(bytes, 106);
                sb.Append(temp3);
                sb.Append('_');

                // 110  4   当前X
                temp3 = BitConverter.ToInt32(bytes, 110);
                sb.Append(temp3);
                sb.Append('_');
                //114 4   当前Y
                temp3 = BitConverter.ToInt32(bytes, 114);
                sb.Append(temp3);
                sb.Append('_');
                //118 2   当前角度
                temp2 = BitConverter.ToInt16(bytes, 118);
                sb.Append(temp2);
                App.ExFile.MessageAgvInfo($"AgvLogInfo_{agvNo}", sb.ToString());
            }
            catch (Exception ex)
            {
                App.ExFile.MessageError("AgvLogInfo", ex.ToString());
            }
        }
    }
}