/// <summary>
        /// 具体的站台实现逻辑
        /// </summary>
        /// <param name="stations"></param>
        /// <param name="plcs"></param>
        /// <returns></returns>
        public override void Excute(List <Equipment> stations, List <Equipment> allEquipments, IPLC plc)
        {
            //每隔3秒处理一次到达和离开
            if (DateTime.Now.Subtract(excuteDateTime).Seconds > 3)
            {
                excuteDateTime = DateTime.Now;
            }
            else
            {
                return;
            }
            var locations = AppSession.Dal.GetCommonModelByCondition <Location>($"where type = 'D'");

            if (locations.Success)
            {
                foreach (var station in stations)
                {
                    BllResult result = null;
                    try
                    {
                        var location = locations.Data.FirstOrDefault(t => t.SrmCode == station.Code);
                        if (station.EquipmentProps.FirstOrDefault(t => t.EquipmentTypeTemplateCode == StationProps.AGV_Arrive_WCS.ToString())?.Value == true.ToString())
                        {
                            //如果AGV到达,并且库位是停用的,就改为可以用
                            if (location.IsStop == true)
                            {
                                location.IsStop = false;
                                AppSession.Dal.UpdateCommonModel <Location>(location);
                                result = BllResultFactory.Sucess($"AGV站台[{station.Code}][{station.Name}]到达,对应的库位{location.Code}更改为可用");
                            }
                        }
                        if (station.EquipmentProps.FirstOrDefault(t => t.EquipmentTypeTemplateCode == StationProps.AGV_Leave_WCS.ToString())?.Value == true.ToString())
                        {
                            //如果AGV不是到达,并且库位未锁定,就改为停用,恢复为1层1列
                            if (location.IsStop == false)
                            {
                                var stepTraceResult = AppSession.Dal.GetCommonModelByCondition <StepTrace>($"where status < {StepTraceStatus.下发桁车放货.GetIndexInt()} and nextStationId = '{station.StationId}'");
                                if (stepTraceResult.Success)
                                {
                                    foreach (var stepTrace in stepTraceResult.Data.Where(t => t.Status < StepTraceStatus.发桁车取货.GetIndexInt()))
                                    {
                                        stepTrace.NextStationId = 0;
                                        stepTrace.WCSLayer      = null;
                                        stepTrace.WCSLine       = null;
                                        stepTrace.Status        = StepTraceStatus.设备请求下料.GetIndexInt();
                                        AppSession.Dal.UpdateCommonModel <StepTrace>(stepTrace);
                                    }
                                    foreach (var stepTrace in stepTraceResult.Data.Where(t => t.Status == StepTraceStatus.发桁车取货.GetIndexInt()))
                                    {
                                        var stationCode = string.Empty;

                                        switch (station.Code)
                                        {
                                        case "StationForFinished1":
                                            stationCode = "StationForFinished2";
                                            break;

                                        case "StationForFinished2":
                                            stationCode = "StationForFinished1";
                                            break;

                                        case "StationForFinished3":
                                            stationCode = "StationForFinished4";
                                            break;

                                        case "StationForFinished4":
                                            stationCode = "StationForFinished3";
                                            break;
                                        }
                                        var otherStation = stations.Find(t => t.Code == stationCode);
                                        if (otherStation != null)
                                        {
                                            List <Station>    stationList        = station.StationList.Where(t => t.Id == otherStation.StationId).ToList();
                                            TrussNormalExcute trussNormalExcutea = new TrussNormalExcute();
                                            trussNormalExcutea.setStation(stationList, stepTrace, stepTrace.NextStepId);
                                        }
                                    }
                                }
                                location.Line   = 1;
                                location.Layer  = 1;
                                location.IsStop = true;
                                AppSession.Dal.UpdateCommonModel <Location>(location);
                                result = BllResultFactory.Sucess($"AGV站台[{station.Code}][{station.Name}]离开,对应的库位{location.Code}更改为停用,并且恢复到1列1层");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        result = BllResultFactory.Error($"AGV站台[{station.Code}][{station.Name}]处理发生异常:{ex.Message}");
                    }
                    LogResult(result);
                }
            }
        }
Пример #2
0
 /// <summary>
 /// 处理 上料请求
 /// 注意:allEquipments引用所有设备,此为共享应用
 /// </summary>
 /// <param name="bevel"></param>
 /// <param name="allEquipments"></param>
 /// <param name="plc"></param>
 /// <returns></returns>
 public override BllResult ExcuteArrive(Equipment bevel, List <Equipment> allEquipments, List <StepTrace> stepTraceList, IPLC plc)
 {
     try
     {
         //var count = stepTraceList.Count(t => t.Status == StepTraceStatus.响应放货完成.GetIndexInt() && t.StationId == bevel.StationId);
         //if (count > 1)
         //{
         //    Logger.Log($"处理设备[{bevel.Name}]对应的站台[{bevel.StationId}]上料完成的时候,出现数据错误,站台有多个对应的任务", LogLevel.Error);
         //    return BllResultFactory.Error();
         //}
         //var stepTrace = stepTraceList.FirstOrDefault(t => t.Status == StepTraceStatus.响应放货完成.GetIndexInt() && t.StationId == bevel.StationId);
         var ArriveTaskId  = bevel.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == MachineProps.ArriveTaskId.ToString());
         var convertResult = int.TryParse(ArriveTaskId.Value, out int stepTraceId);
         if (!convertResult)
         {
             Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 下料请求失败,工序任务的id[{ArriveTaskId.Value}]转化为整数失败!", LogLevel.Error);
             return(BllResultFactory.Error());
         }
         if (stepTraceId == 0)
         {
             Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 下料请求失败,工序跟踪ID为0", LogLevel.Error);
             return(BllResultFactory.Error());
         }
         var stepTrace = stepTraceList.FirstOrDefault(t => t.Id == stepTraceId);
         if (stepTrace == null)
         {
             Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 下料请求失败,找不到未完成的工序任务id[{stepTraceId}]", LogLevel.Error);
             return(BllResultFactory.Error());
         }
         var number = bevel.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == MachineProps.ArriveRealAddress.ToString());
         //记录旧数据
         var stepTraceClone = (StepTrace)stepTrace.DeepClone();
         //更新数据
         if (stepTrace.NextStepId != 0)
         {
             stepTrace.StepId     = stepTrace.NextStepId;
             stepTrace.NextStepId = 0;
         }
         stepTrace.StationId     = stepTrace.NextStationId;
         stepTrace.NextStationId = 0;
         stepTrace.Status        = StepTraceStatus.设备开始生产.GetIndexInt();
         stepTrace.UpdateTime    = DateTime.Now;
         stepTrace.UpdateBy      = App.User.UserCode;
         var updateResult = AppSession.Dal.UpdateCommonModel <StepTrace>(stepTrace);
         if (updateResult.Success)
         {
             BllResult plcResult = SendAckToPlc(bevel, plc, MachineMessageFlag.WCS回复允许上料, number.Value, stepTrace.Id.ToString(), "", "0", stepTrace.WcsProductType.ToString(), stepTrace.PipeLength.ToString(), stepTrace.PipeDiameter.ToString(), stepTrace.PipeThickness.ToString(), bevel.GoAddress);
             if (plcResult.Success)
             {
                 Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 上料请求成功,对应的任务[{stepTrace.Id}]信息写入设备", LogLevel.Success);
             }
             else
             {
                 //PLC写入失败,就把数据改回来
                 AppSession.Dal.UpdateCommonModel <StepTrace>(stepTraceClone);
                 Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 上料请求失败,对应的任务[{stepTrace.Id}]信息写入PLC失败,原因:{plcResult.Msg}", LogLevel.Error);
             }
             return(plcResult);
         }
     }
     catch (Exception ex)
     {
         Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 上料请求时候,发生异常:{ex.Message}", LogLevel.Exception, ex);
         return(BllResultFactory.Error());
     }
     return(BllResultFactory.Sucess());
 }
Пример #3
0
        /// <summary>
        /// 重新下发桁车任务
        /// 重新下发任务限制:
        /// 取货:货叉在中心、联机、无货
        /// 放货:货叉在中心、联机、有货
        /// </summary>
        /// <param name="truss">桁架</param>
        /// <param name="plc"></param>
        /// <param name="stepTrace"></param>
        /// <param name="taskFlag">货叉标志</param>
        /// <param name="stationId">站台点位</param>
        /// <returns></returns>
        protected BllResult ReSendTask(Equipment truss, IPLC plc, StepTrace stepTrace, TrussTaskFlag taskFlag, string stationId)
        {
            var station = truss.StationList.FirstOrDefault(t => t.Id.ToString() == stationId);

            if (station == null)
            {
                Logger.Log($"未查询到ID为{stationId}的站台", LogLevel.Error);
                return(BllResultFactory.Error());
            }
            int    trussStationId = 0;
            string wcsLine        = "0";
            string wcsLayer       = "0";

            using (IDbConnection connection = AppSession.Dal.GetConnection())
            {
                IDbTransaction tran = null;
                try
                {
                    if (taskFlag == TrussTaskFlag.机械手取货)
                    {
                        trussStationId = int.Parse(station.TrussTakeStationId.ToString());
                    }
                    else if (taskFlag == TrussTaskFlag.机械手放货)
                    {
                        trussStationId = int.Parse(station.TrussPutStationId.ToString());
                        wcsLine        = string.IsNullOrEmpty(stepTrace.WCSLine) ? "0" : stepTrace.WCSLine;
                        wcsLayer       = string.IsNullOrEmpty(stepTrace.WCSLayer) ? "0" : stepTrace.WCSLayer;
                    }
                    if (trussStationId == 0)
                    {
                        Logger.Log($"站台[{station.Id}][{station.Name}]没有对应的桁架点位数据,请补齐数据", LogLevel.Error);
                        return(BllResultFactory.Error());
                    }

                    stepTrace.SendAgain = 2;
                    stepTrace.SrmCode   = truss.Code;

                    connection.Open();
                    tran = connection.BeginTransaction();

                    connection.Update <StepTrace>(stepTrace, tran);
                    //TODO: 这里这个更新有用吗???????
                    connection.Update <Equipment>(truss, tran);

                    BllResult sendResult = SendTaskToTruss(truss, plc, taskFlag, stepTrace.WcsProductType.ToString(), trussStationId.ToString(), wcsLine, wcsLayer, stepTrace.Id.ToString());
                    if (sendResult.Success)
                    {
                        tran?.Commit();
                        Logger.Log($"重新下发桁车{truss.Name}任务,任务id:{stepTrace.Id},操作类型:{taskFlag},目的站台:{stationId} {station.Name},桁车点位{trussStationId},成功", LogLevel.Info);
                        return(BllResultFactory.Sucess());
                    }
                    else
                    {
                        tran?.Rollback();
                        stepTrace.SendAgain = 1;
                        Logger.Log($"重新下发桁车{truss.Name}任务,任务id:{stepTrace.Id},操作类型:{taskFlag},目的站台:{stationId} {station.Name},桁车点位{trussStationId},失败:{sendResult.Msg};", LogLevel.Error);
                        return(BllResultFactory.Error());
                    }
                }
                catch (Exception ex)
                {
                    tran?.Rollback();
                    stepTrace.SendAgain = 1;
                    Logger.Log($"重新下发桁车{truss.Name}任务,任务id:{stepTrace.Id},操作类型:{taskFlag},目的站台:{stationId} {station.Name},桁车点位{trussStationId},失败:{ex.Message},回滚任务{stepTrace.Id}状态。", LogLevel.Exception, ex);
                    return(BllResultFactory.Error());
                }
            }
        }
Пример #4
0
 /// <summary>
 /// 执行下料请求
 /// 注意:allEquipments引用所有设备,此为共享应用
 /// </summary>
 /// <param name="machineTool"></param>
 /// <param name="allEquipments"></param>
 /// <param name="plc"></param>
 /// <returns></returns>
 public override BllResult ExcuteRequest(Equipment machineTool, List <Equipment> allEquipments, List <StepTrace> stepTraceList, IPLC plc)
 {
     try
     {
         var Step_Trace_Id = machineTool.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == MachineToolToECSProps.Step_Trace_ID.ToString());
         var convertResult = int.TryParse(Step_Trace_Id.Value, out int stepTraceId);
         if (!convertResult)
         {
             Logger.Log($"处理设备【{machineTool.Name}】下料请求失败,工序任务的id[{Step_Trace_Id.Value}]转化为整数失败!", LogLevel.Error);
             return(BllResultFactory.Error());
         }
         if (stepTraceId > 0)
         {
             var stepTrace = stepTraceList.FirstOrDefault(t => t.Id == Convert.ToInt32(Step_Trace_Id.Value));
             if (stepTrace != null)
             {
                 if (stepTrace.Status == StepTraceStatus.设备开始生产.GetIndexInt())
                 {
                     //修改工序跟踪
                     stepTrace.Status     = StepTraceStatus.设备请求下料.GetIndexInt();
                     stepTrace.UpdateTime = DateTime.Now;
                     stepTrace.UpdateBy   = App.User.UserCode;
                     AppSession.Dal.UpdateCommonModel <StepTrace>(stepTrace);
                     return(BllResultFactory.Sucess());
                 }
                 if (stepTrace.Status > StepTraceStatus.设备请求下料.GetIndexInt())
                 {
                     var WCS_Step_Trace_Id = machineTool.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == EcsToMachineToolPorps.WCS_Step_Trace_Id.ToString());
                     WCS_Step_Trace_Id.Value = "0";
                     BllResult plcResult = plc.Write(WCS_Step_Trace_Id);
                     if (plcResult.Success)
                     {
                         Logger.Log($"清除设备【{machineTool.Name}】的任务号{stepTrace.Id}成功", LogLevel.Success);
                         return(BllResultFactory.Sucess());
                     }
                     else
                     {
                         Logger.Log($"清除设备【{machineTool.Name}】的任务号{stepTrace.Id}失败,写入PLC失败:{plcResult.Msg}", LogLevel.Error);
                         return(BllResultFactory.Error());
                     }
                 }
             }
             else
             {
                 Logger.Log($"处理设备【{machineTool.Name}】下料请求失败,找不到未完成的工序任务id[{Step_Trace_Id.Value}]", LogLevel.Error);
                 return(BllResultFactory.Error());
             }
         }
         else
         {
             // 如果不存在 已经处理过的任务,但是还在请求下线,说明是手动上的,或是id丢了
             if (!stepTraceList.Exists(t => t.StationId == machineTool.StationId && t.Status >= StepTraceStatus.设备请求下料.GetIndexInt()))
             {
                 Logger.Log($"处理设备[{machineTool.Name}]的站台[{machineTool.StationId}]下料请求失败,工序跟踪ID为0", LogLevel.Error);
                 return(BllResultFactory.Error());
             }
         }
     }
     catch (Exception ex)
     {
         Logger.Log($"处理设备【{machineTool.Name}】下料请求时候,发生异常:{ex.Message}", LogLevel.Exception, ex);
         return(BllResultFactory.Error());
     }
     return(BllResultFactory.Sucess());
 }
Пример #5
0
        /// <summary>
        /// 执行下料请求
        /// 注意:allEquipments引用所有设备,此为共享应用
        /// </summary>
        /// <param name="bevel"></param>
        /// <param name="allEquipments"></param>
        /// <param name="plc"></param>
        /// <returns></returns>
        public override BllResult ExcuteRequest(Equipment bevel, List <Equipment> allEquipments, List <StepTrace> stepTraceList, IPLC plc)
        {
            try
            {
                var RequestTaskId = bevel.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == MachineProps.RequestTaskId.ToString());
                var convertResult = int.TryParse(RequestTaskId.Value, out int stepTraceId);
                if (!convertResult)
                {
                    Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 下料请求失败,工序任务的id[{RequestTaskId.Value}]转化为整数失败!", LogLevel.Error);
                    return(BllResultFactory.Error());
                }
                var stepTrace = stepTraceList.FirstOrDefault(t => t.Id == stepTraceId);
                if (stepTrace == null)
                {
                    Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 下料请求失败,找不到未完成的工序任务id[{RequestTaskId.Value}]", LogLevel.Error);
                    return(BllResultFactory.Error());
                }
                var nextEquipment = allEquipments.FirstOrDefault(t => t.SelfAddress == bevel.GoAddress.ToString());
                //判断是否有上料请求  响应下料
                if (nextEquipment == null)
                {
                    Logger.Log($"工位[{bevel.StationCode}]的设备[{bevel.Name}] 响应地址请求失败,原因:组队缓存位没有设置对应的下个设备", LogLevel.Error);
                    return(BllResultFactory.Error());
                }
                //组队区输送线没货才能去
                var HasGoods = nextEquipment.EquipmentProps.FirstOrDefault(t => t.EquipmentTypeTemplateCode == PipeLineProps.HasGoods.ToString());
                if (HasGoods.Value != PipeLineGoods.无货.GetIndexString())
                {
                    return(BllResultFactory.Error());
                }
                //如果已经有了去下个设备的任务,那么就不能去,需要等待
                if (stepTraceList.Exists(t => t.NextStationId == nextEquipment.StationId))
                {
                    return(BllResultFactory.Error());
                }
                //就生成AGV任务并且插入数据库   小车任务的状态和类型需要重新定义?
                CarTask taskCar = new CarTask();
                //taskCar.StepTraceId = Convert.ToInt32(Step_Trace_Id);
                taskCar.StepTraceId  = stepTrace.Id;
                taskCar.CarNo        = 1;
                taskCar.Type         = CarTaskType.取货和放货.GetIndexInt();
                taskCar.FromLocation = bevel.Station.TrussTakeStationId.ToString();
                taskCar.ToLocation   = nextEquipment.Station.TrussPutStationId.ToString();
                taskCar.ReSend       = 0;
                taskCar.Status       = TaskCarStatus.Init.GetIndexInt();
                taskCar.CreateTime   = DateTime.Now;
                taskCar.EndTime      = DateTime.Now;
                taskCar.StartTime    = DateTime.Now;
                taskCar.UpdateTime   = DateTime.Now;

                //修改工序监控
                stepTrace.NextStationId = nextEquipment.StationId;
                stepTrace.Status        = StepTraceStatus.等待任务执行.GetIndexInt();
                stepTrace.UpdateTime    = DateTime.Now;
                stepTrace.UpdateBy      = App.User.UserCode;

                var requestNumber = bevel.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == PipeLineProps.RequestNumber.ToString());

                using (IDbConnection connection = AppSession.Dal.GetConnection())
                {
                    IDbTransaction tran = null;
                    try
                    {
                        connection.Open();
                        tran = connection.BeginTransaction();
                        var step     = connection.Get <Step>(stepTrace.StepId, transaction: tran);
                        var nextStep = connection.QueryFirstOrDefault <Step>($"select top 1 * from step where  sequence > {step.Sequence} order by sequence", transaction: tran);
                        stepTrace.NextStepId = nextStep.Id.Value;
                        connection.Insert <CarTask>(taskCar, transaction: tran);
                        connection.Update <StepTrace>(stepTrace, transaction: tran);

                        var sendResult = SendAddressReplyToPlc(bevel, plc, MachineMessageFlag.WCS回复允许下料, requestNumber.Value, stepTrace.Id.ToString(), "", "0", stepTrace.WcsProductType.ToString(), stepTrace.PipeLength.ToString(), stepTrace.PipeDiameter.ToString(), stepTrace.PipeThickness.ToString(), bevel.GoAddress);
                        if (sendResult.Success)
                        {
                            tran.Commit();
                            Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 下料请求 成功,任务:{stepTrace.Id}", LogLevel.Success);
                            return(BllResultFactory.Sucess());
                        }
                        else
                        {
                            tran?.Rollback();
                            Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 下料请求的时候,写入PLC失败,任务:{stepTrace.Id},原因:{sendResult.Msg}", LogLevel.Error);
                            return(BllResultFactory.Error());
                        }
                    }
                    catch (Exception ex)
                    {
                        tran?.Rollback();
                        Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 下料请求的时候,发生异常,任务:{stepTrace.Id},原因:{ex.Message}", LogLevel.Exception, ex);
                        return(BllResultFactory.Error());
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log($"处理设备【{bevel.Name}】下料请求时候,发生异常:{ex.Message}", LogLevel.Exception, ex);
                return(BllResultFactory.Error());
            }
        }
Пример #6
0
        public override BllResult ExcuteArrive(Equipment station, List <Equipment> allEquipments, IPLC plc)
        {
            var isSuccess = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.ArriveResult.ToString()).Value;

            if (isSuccess == StationArriveResult.成功.GetIndexString())
            {
                //获取条码
                var barcode           = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.ArriveBarcode.ToString()).Value;
                var arriveRealAddress = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.ArriveRealAddress.ToString()).Value;
                if (string.IsNullOrWhiteSpace(barcode))
                {
                    return(BllResultFactory.Error($"站台{station.Name}有位置到达但是没有条码信息"));
                }
                else
                {
                    var taskResult = AppSession.Dal.GetCommonModelByCondition <TaskEntity>($"where containerCode = '{barcode}' and taskStatus < {TaskEntityStatus.任务完成.GetIndexInt()} and deleted = 0");
                    if (taskResult.Success)
                    {
                        if (taskResult.Data.Count > 1)
                        {
                            return(BllResultFactory.Error($"站台{station.Name}根据条码{barcode}查找到了多条任务,请检查数据"));
                        }
                        else
                        {
                            var task = taskResult.Data[0];
                            //校验任务类型
                            if (task.TaskType == TaskType.整盘出库.GetIndexInt() || task.TaskType == TaskType.空容器出库.GetIndexInt())
                            {
                                return(BllResultFactory.Error($"站台{station.Name}不接受整盘出库和空托盘出库任务"));
                            }
                            //判断任务是否有分配库位,没有则调用库位分配函数
                            if (string.IsNullOrWhiteSpace(task.ToLocationCode))
                            {
                                LocationAssignReqModelInfo info = new LocationAssignReqModelInfo();
                                info.TaskNo = task.RemoteTaskNo;
                                info.Height = task.ReqHeight;
                                info.Weight = task.ReqWeight;
                                info.Length = task.ReqLength;
                                info.Width  = task.ReqWidth;
                                var temp4 = AppSession.TaskService.GetDestinationLocationFromWMS(info);
                                if (!temp4.Success)
                                {
                                    return(BllResultFactory.Error($"站台{station.Name}请求没有去向地址,并且请求上游系统分配库位失败:{temp4.Msg}"));
                                }
                                task.ToLocationCode = temp4.Data.Code;
                            }

                            int    tempStatus = task.TaskStatus; //记录原始状态以便回滚
                            string tempArrivaEquipmentCode = task.Gateway;
                            task.TaskStatus = TaskEntityStatus.响应接入站台到达.GetIndexInt();
                            task.Gateway    = station.Code; //记录站台
                            var temp = AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                            if (temp.Success)
                            {
                                //回复位置到达
                                temp = SendAckToPlc(station, plc, StationMessageFlag.WCSPLCACK, StationLoadStatus.回复到达, arriveRealAddress, "0");
                                if (temp.Success)
                                {
                                    return(BllResultFactory.Sucess($"响应站台{station.Name}位置到达成功,条码{barcode},任务{task.Id}"));
                                }
                                else
                                {
                                    task.TaskStatus = tempStatus;
                                    task.Gateway    = tempArrivaEquipmentCode;
                                    AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                                    return(BllResultFactory.Error($"响应站台{station.Name}位置到达失败,条码{barcode},任务{task.Id},回滚任务状态"));
                                }
                            }
                            else
                            {
                                task.TaskStatus = tempStatus;
                                task.Gateway    = tempArrivaEquipmentCode;
                                AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                                return(BllResultFactory.Error($"响应站台{station.Name}位置到达请求失败,条码{barcode},任务{task.Id},回滚任务状态"));
                            }
                        }
                    }
                    else
                    {
                        return(BllResultFactory.Error($"站台{station.Name}根据条码{barcode}没有查询到任务:{taskResult.Msg}"));
                    }
                }
            }
            else
            {
                return(BllResultFactory.Error($"站台{station.Name}位置电控报告到达失败"));
            }
        }
 public override BllResult ExcuteArrive(Equipment station, List <Equipment> allEquipments, IPLC plc)
 {
     return(BllResultFactory.Error($"只入站台{station.Name}不处理到达"));
 }
Пример #8
0
        /// <summary>
        /// 导入数据库原材料
        /// </summary>
        private BllResult importDataBaseMaterial()
        {
            try
            {
                foreach (var value in inputlist)
                {
                    value.clear();
                }

                inputgrid1.ItemsSource = null;
                var stationCacheResult = AppSession.Dal.GetCommonModelByConditionWithZero <StationCache>($" where status = 0 ");
                if (!stationCacheResult.Success)
                {
                    return(BllResultFactory.Error($"导入数据库原材料时候,读取数据库出错,原因:{stationCacheResult.Msg}!"));
                }
                //缓存区没有新管子
                if (stationCacheResult.Data.Count == 0)
                {
                    return(BllResultFactory.Error("数据库中没有未套料得管子信息!"));
                }
                if (stationCacheResult.Data.Count > 11)
                {
                    return(BllResultFactory.Error("获取到超过11个原材料信息,请检查数据库!"));
                }

                for (int i = 0; i < stationCacheResult.Data.Count; i++)
                {
                    //string ID = material.Data[i].Id.ToString().Replace(" ", "");
                    string WaiJing        = stationCacheResult.Data[i].Diameter.ToString().Replace(" ", "");       //外径
                    string BiHou          = stationCacheResult.Data[i].Thickness.ToString().Replace(" ", "");      //壁厚
                    string CaiZhi         = stationCacheResult.Data[i].WcsProductType.ToString().Replace(" ", ""); //材质
                    string Dengji         = "0";
                    string MaterialLength = stationCacheResult.Data[i].MaterialLength.ToString().Replace(" ", "");
                    string LuPiHao        = "0";
                    string WuLiaoHao      = stationCacheResult.Data[i].Id.ToString().Replace(" ", "");

                    if (string.IsNullOrWhiteSpace(WaiJing))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(BiHou))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(CaiZhi))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(LuPiHao))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(WuLiaoHao))
                    {
                        continue;
                    }
                    if (!int.TryParse(MaterialLength, out int Length))
                    {
                        continue;
                    }

                    inputlist[i].WaiJing   = WaiJing;
                    inputlist[i].BiHou     = BiHou;
                    inputlist[i].CaiZhi    = CaiZhi;
                    inputlist[i].Dengji    = Dengji;
                    inputlist[i].length    = Length;
                    inputlist[i].LuPiHao   = LuPiHao;
                    inputlist[i].WuLiaoHao = WuLiaoHao;
                }
                return(BllResultFactory.Sucess("导入数据库原材料成功!"));
            }
            catch (Exception ex)
            {
                return(BllResultFactory.Error($"导入数据库原材料发生异常:{ex.Message}"));
            }
        }
Пример #9
0
        /// <summary>
        /// 导入数据库工单
        /// </summary>
        private BllResult importDataBaseOrder()
        {
            try
            {
                foreach (var value in outputlist)
                {
                    value.clear();
                }
                outputgrid1.ItemsSource = null;
                var pipeOrderResult = AppSession.Dal.GetCommonModelByConditionWithZero <PipeOrder>($" where status = '0' ");
                if (!pipeOrderResult.Success)
                {
                    return(BllResultFactory.Error($"导入数据库工单时候,读取数据库出错,原因:{pipeOrderResult.Msg}!"));
                }
                //没有新工单的就返回
                if (pipeOrderResult.Data.Count == 0)
                {
                    return(BllResultFactory.Error("数据库中没有未套料的工单信息!"));
                }

                for (int i = 0; i < pipeOrderResult.Data.Count; i++)
                {
                    //string pipeId = product.Data[i].Id.ToString().Replace(" ", "");
                    //外径
                    string WaiJing = pipeOrderResult.Data[i].Diameter.ToString().Replace(" ", "");
                    //壁厚
                    string BiHou = pipeOrderResult.Data[i].Thickness.ToString().Replace(" ", "");
                    //材质
                    string CaiZhi = pipeOrderResult.Data[i].ProductCode.ToString().Replace(" ", "");
                    //长度
                    string MaterialLength = pipeOrderResult.Data[i].Length.ToString().Replace(" ", "");
                    //物料号
                    string WuLiaoHao = pipeOrderResult.Data[i].Diameter.ToString().Replace(" ", "");
                    //管件编号
                    string GuanJianBianHao = pipeOrderResult.Data[i].Id.ToString().Replace(" ", "");
                    //等级
                    string Dengji = "0";

                    string LuPiHao = "0";
                    if (string.IsNullOrWhiteSpace(WaiJing))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(BiHou))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(CaiZhi))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(LuPiHao))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(WuLiaoHao))
                    {
                        continue;
                    }
                    if (!int.TryParse(MaterialLength, out int Length))
                    {
                        continue;
                    }

                    outputlist[i].WaiJing         = WaiJing;
                    outputlist[i].BiHou           = BiHou;
                    outputlist[i].CaiZhi          = CaiZhi;
                    outputlist[i].Dengji          = Dengji;
                    outputlist[i].length          = Length;
                    outputlist[i].GuanJianBianHao = GuanJianBianHao;
                    //outputlist[i].WuLiaoHao = WuLiaoHao;
                    //outputlist[i].LuPiHao = LuPiHao;
                }
                return(BllResultFactory.Sucess("导入数据库工单成功!"));
            }
            catch (Exception ex)
            {
                return(BllResultFactory.Error($"导入数据库工单发生异常:{ex.Message}"));
            }
        }
Пример #10
0
        /// <summary>
        /// 导入Excel原材料
        /// </summary>
        private BllResult importExcelMaterial()
        {
            try
            {
                foreach (var value in inputlist)
                {
                    value.clear();
                }

                inputgrid1.ItemsSource = null;

                var dateresult = cSVFile.OpenCSVFile();
                if (dateresult == null)
                {
                    return(BllResultFactory.Error("未能成功打开CSV文件"));
                }
                if (dateresult.Columns.Count != 7)
                {
                    return(BllResultFactory.Error("CSV文件列数不正确,无法导入"));
                }
                for (int i = 0; i < dateresult.Rows.Count; i++)
                {
                    int fl = 0;

                    string WaiJing   = dateresult.Rows[i][0].ToString().Replace(" ", "");
                    string BiHou     = dateresult.Rows[i][1].ToString().Replace(" ", "");
                    string CaiZhi    = dateresult.Rows[i][2].ToString().Replace(" ", "");
                    string Dengji    = dateresult.Rows[i][3].ToString().Replace(" ", "");
                    string length    = dateresult.Rows[i][4].ToString().Replace(" ", "");
                    string LuPiHao   = dateresult.Rows[i][5].ToString().Replace(" ", "");
                    string WuLiaoHao = dateresult.Rows[i][6].ToString().Replace(" ", "");

                    if (string.IsNullOrWhiteSpace(WaiJing))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(BiHou))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(CaiZhi))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(Dengji))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(LuPiHao))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(WuLiaoHao))
                    {
                        continue;
                    }
                    if (!int.TryParse(length, out fl))
                    {
                        continue;
                    }

                    inputlist[i].WaiJing   = WaiJing;
                    inputlist[i].BiHou     = BiHou;
                    inputlist[i].CaiZhi    = CaiZhi;
                    inputlist[i].Dengji    = Dengji;
                    inputlist[i].length    = fl;
                    inputlist[i].LuPiHao   = LuPiHao;
                    inputlist[i].WuLiaoHao = WuLiaoHao;
                }

                int realcount = inputlist.Count(a => !string.IsNullOrWhiteSpace(a.WaiJing));
                if (realcount != dateresult.Rows.Count)
                {
                    return(BllResultFactory.Error("未能全部导入文件内容,部分数据为空或格式不正确,实际导入" + realcount + "条数据"));
                }
                else
                {
                    return(BllResultFactory.Sucess("导入Excel原材料成功!"));
                }
            }
            catch (Exception ex)
            {
                return(BllResultFactory.Error($"导入Excel原材料发生异常:{ex.Message}"));
            }
        }
Пример #11
0
        /// <summary>
        /// 导入Excel工单
        /// </summary>
        private BllResult importExcelOrder()
        {
            try
            {
                var countResult = AppSession.Dal.GetCommonModelCount <PipeOrder>($" where status = { StationCacheStatus.初始.GetIndexString()}");
                if (!countResult.Success)
                {
                    return(BllResultFactory.Error($"在数据库中查询未套料工单的时候,查询数据库发生错误,原因:{countResult.Msg}"));
                }
                if (countResult.Data > 0)
                {
                    return(BllResultFactory.Error($"数据库中存在未套料工单,不要反复保存!"));
                }
                foreach (var value in outputlist)
                {
                    value.clear();
                }
                outputgrid1.ItemsSource = null;

                var dateresult = cSVFile.OpenCSVFile();
                if (dateresult == null)
                {
                    return(BllResultFactory.Error("未能成功打开CSV文件"));
                }

                if (dateresult.Columns.Count != 7)
                {
                    return(BllResultFactory.Error("CSV文件列数不正确,无法导入"));
                }
                for (int i = 0; i < dateresult.Rows.Count; i++)
                {
                    string ZuDuiCheck = dateresult.Rows[i][6].ToString().Replace(" ", "");
                    //string TiaoMa = dateresult.Rows[i][5].ToString().Replace(" ", "");
                    if (ZuDuiCheck != "1" && ZuDuiCheck != "2" && ZuDuiCheck != "3" && ZuDuiCheck != "4")
                    {
                        return(BllResultFactory.Error("模板中组对平台值错误,平台值只能为1、2、3、4"));
                    }

                    DataView myDataView = new DataView(dateresult);
                    if (myDataView.ToTable(true, "条码").Rows.Count < dateresult.Rows.Count)
                    {
                        return(BllResultFactory.Error("条码重复,请检查"));
                    }
                }

                for (int i = 0; i < dateresult.Rows.Count; i++)
                {
                    //外径
                    string WaiJing = dateresult.Rows[i][1].ToString().Replace(" ", "");
                    //壁厚
                    string BiHou = dateresult.Rows[i][2].ToString().Replace(" ", "");
                    //材质
                    string CaiZhi = dateresult.Rows[i][0].ToString().Replace(" ", "");
                    //等级
                    string Dengji = dateresult.Rows[i][4].ToString().Replace(" ", "");
                    //长度
                    string Length = dateresult.Rows[i][3].ToString().Replace(" ", "");
                    //条码
                    string Code = dateresult.Rows[i][5].ToString().Replace(" ", "");//cf
                    //组对工位
                    string ZuDui = dateresult.Rows[i][6].ToString().Replace(" ", "");

                    if (!decimal.TryParse(WaiJing, out decimal diameter))
                    {
                        continue;
                    }
                    if (!decimal.TryParse(BiHou, out decimal thickness))
                    {
                        continue;
                    }
                    if (!int.TryParse(CaiZhi, out int productCode))
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(Dengji))
                    {
                        continue;
                    }
                    if (!int.TryParse(Length, out int lengthInt))
                    {
                        continue;
                    }
                    if (!int.TryParse(ZuDui, out int AssemblyStation))
                    {
                        continue;
                    }

                    //var transfer = AppSession.Dal.GetCommonModelByCondition<ProductHeader>($"where name = '{CaiZhi}'");
                    //if(!transfer.Success)
                    //{
                    //    MessageBox.Show($"查找材料对应信息失败,请检查字典是否录入相关材料信息");
                    //    return;
                    //}

                    //将表格中内容写入数据库
                    PipeOrder pipeOrder = new PipeOrder();
                    pipeOrder.Diameter        = diameter;
                    pipeOrder.Thickness       = thickness;
                    pipeOrder.ProductCode     = productCode;
                    pipeOrder.Length          = lengthInt;
                    pipeOrder.Status          = StationCacheStatus.初始.GetIndexInt();
                    pipeOrder.Code            = Code;
                    pipeOrder.AssemblyStation = AssemblyStation;//cf
                    //pipeOrder.StationCode = 1;
                    var insertResult = AppSession.Dal.InsertCommonModel <PipeOrder>(pipeOrder);
                    if (!insertResult.Success)
                    {
                        continue;
                    }
                    else
                    {
                        pipeOrder.Id = insertResult.Data;
                    }
                    outputlist[i].WaiJing         = WaiJing;
                    outputlist[i].BiHou           = BiHou;
                    outputlist[i].CaiZhi          = CaiZhi;
                    outputlist[i].Dengji          = Dengji;
                    outputlist[i].length          = lengthInt;
                    outputlist[i].GuanJianBianHao = pipeOrder.Id.ToString();
                    outputlist[i].Code            = Code;//cf
                    outputlist[i].AssemblyStation = AssemblyStation;
                }
                int realcount = outputlist.Count(a => !string.IsNullOrWhiteSpace(a.WaiJing));
                if (realcount != dateresult.Rows.Count)
                {
                    return(BllResultFactory.Error("未能全部导入文件内容,部分数据为空或格式不正确,实际导入" + realcount + "条数据"));
                }
                else
                {
                    return(BllResultFactory.Sucess("导入Excel工单成功!"));
                }
            }
            catch (Exception ex)
            {
                return(BllResultFactory.Error($"导入Excel工单发生异常:{ex.Message}"));
            }
        }
Пример #12
0
 public BllResult CopyEquipment(EquipmentType equipmentType)
 {
     using (IDbConnection connection = AppSession.Dal.GetConnection())
     {
         IDbTransaction transaction = null;
         try
         {
             connection.Open();
             transaction = connection.BeginTransaction();
             var temp = AppSession.Dal.GetCommonModelByCondition <EquipmentType>($"where id = {equipmentType.Id}", connection, transaction);
             if (temp.Success)
             {
                 var e     = temp.Data[0];
                 var temp2 = AppSession.Dal.GetCommonModelByCondition <EquipmentTypeTemplate>($"where equipmentTypeId = {e.Id}", connection, transaction);
                 if (temp2.Success)
                 {
                     var props = temp2.Data;
                     //e.Id = null;
                     e.Code = e.Code + "2";
                     var temp3 = AppSession.Dal.InsertCommonModel <EquipmentType>(e, connection, transaction);
                     if (temp3.Success)
                     {
                         props.ForEach(t =>
                         {
                             t.EquipmentTypeId = temp3.Data.Value;
                         });
                         foreach (var item in props)
                         {
                             var temp4 = AppSession.Dal.InsertCommonModel <EquipmentTypeTemplate>(item, connection, transaction);
                             if (!temp4.Success)
                             {
                                 transaction?.Rollback();
                                 return(BllResultFactory.Error($"复制出错:{temp4.Msg}"));
                             }
                         }
                         transaction.Commit();
                         return(BllResultFactory.Sucess());
                     }
                     else
                     {
                         transaction?.Rollback();
                         return(BllResultFactory.Error($"复制出错:{temp3.Msg}"));
                     }
                 }
                 else
                 {
                     transaction?.Rollback();
                     return(BllResultFactory.Error($"复制出错:{temp2.Msg}"));
                 }
             }
             else
             {
                 transaction?.Rollback();
                 return(BllResultFactory.Error($"复制出错:{temp.Msg}"));
             }
         }
         catch (Exception ex)
         {
             transaction?.Rollback();
             return(BllResultFactory.Error($"复制出错:{ex.Message}"));
         }
     }
 }
Пример #13
0
        public BllResult SyncEquipmentProp(int?id, string plcDb)
        {
            using (IDbConnection connection = AppSession.Dal.GetConnection())
            {
                IDbTransaction tran = null;
                try
                {
                    connection.Open();
                    tran = connection.BeginTransaction();

                    //现获取这个设备,防止同步删除
                    var a = AppSession.Dal.GetCommonModelByCondition <Equipment>($"where id = {id}");
                    if (!a.Success)
                    {
                        tran.Rollback();
                        return(BllResultFactory.Error("同步失败,设备已被同步删除"));
                    }
                    var equipment = a.Data[0];
                    //查询对应模板的属性
                    var b = AppSession.Dal.GetCommonModelByCondition <EquipmentTypeTemplate>($"where equipmentTypeId = {equipment.EquipmentTypeId}");
                    if (!b.Success)
                    {
                        tran.Rollback();
                        return(BllResultFactory.Error("同步失败,设备无模板属性"));
                    }
                    var templateProps = b.Data;
                    var c             = AppSession.Dal.GetCommonModelByCondition <EquipmentProp>($"where equipmentId = {equipment.Id}");
                    var props         = new List <EquipmentProp>();
                    if (c.Success)
                    {
                        props = c.Data;
                    }
                    var idsFordelete = props.Where(t => !templateProps.Exists(i => i.Id == t.EquipmentTypeTemplateId)).Select(t => t.Id).ToList();
                    if (idsFordelete != null && idsFordelete.Count > 0)
                    {
                        connection.DeleteList <EquipmentProp>("where id in @ids", new { ids = idsFordelete }, tran);
                    }
                    var propForAdd = templateProps.Where(t => !props.Exists(i => i.EquipmentTypeTemplateId == t.Id)).ToList();
                    List <EquipmentProp> propListToAdd = new List <EquipmentProp>();
                    foreach (var item in propForAdd)
                    {
                        EquipmentProp equipmentProp = new EquipmentProp();
                        equipmentProp.EquipmentId               = equipment.Id;
                        equipmentProp.EquipmentTypeTemplateId   = item.Id;
                        equipmentProp.EquipmentTypeTemplateCode = item.Code;
                        equipmentProp.ServerHandle              = 0;
                        if (string.IsNullOrWhiteSpace(plcDb) || !string.IsNullOrWhiteSpace(item.Address))
                        {
                            equipmentProp.Address = item.Address;
                        }
                        else
                        {
                            switch (item.DataType)
                            {
                            case "BOOL": { equipmentProp.Address = plcDb + "X" + item.Offset; break; }

                            case "BYTE": { equipmentProp.Address = plcDb + "B" + item.Offset; break; }

                            case "INT": { equipmentProp.Address = plcDb + "W" + item.Offset; break; }

                            case "DINT": { equipmentProp.Address = plcDb + "D" + item.Offset; break; }

                            case "CHAR": { equipmentProp.Address = plcDb + "CHAR" + item.Offset + ",20"; break; }

                            default: { equipmentProp.Address = item.Address; break; }
                            }
                        }

                        equipmentProp.Value      = "";
                        equipmentProp.Remark     = item.Name;
                        equipmentProp.CreateTime = DateTime.Now;
                        equipmentProp.CreateBy   = "";
                        propListToAdd.Add(equipmentProp);
                    }
                    propListToAdd.ForEach(t => connection.Insert <EquipmentProp>(t, tran));
                    tran.Commit();
                    return(BllResultFactory.Sucess("成功"));
                }
                catch (Exception ex)
                {
                    tran?.Rollback();
                    AppSession.LogService.WriteDBExceptionLog(ex);
                    return(BllResultFactory.Error($"删除失败:{ex.Message}"));
                }
            }
        }
 public override BllResult ExcuteRequest(Equipment station, List <Equipment> allEquipments, IPLC plc)
 {
     return(BllResultFactory.Error($"只出口{station.Name}不处理地址请求"));
 }
Пример #15
0
        /// <summary>
        /// 单叉整任务下发
        /// </summary>
        /// <param name="srm"></param>
        /// <param name="plc"></param>
        /// <param name="newTaskFlag"></param>
        /// <param name="getForkTaskFlag"></param>
        /// <param name="getForkRow"></param>
        /// <param name="getForkColumn"></param>
        /// <param name="getForkLayer"></param>
        /// <param name="getForkStation"></param>
        /// <param name="putForkTaskFlag"></param>
        /// <param name="putForkRow"></param>
        /// <param name="putForkColumn"></param>
        /// <param name="putForkLayer"></param>
        /// <param name="putForkStation"></param>
        /// <param name="taskNo"></param>
        /// <param name="forkTaskFlag"></param>
        /// <returns></returns>
        public BllResult SendTaskToSRM(Equipment srm, IPLC plc, SSRMNewTaskFlag newTaskFlag,
                                       SRMForkTaskFlag getForkTaskFlag, string getForkRow, string getForkColumn, string getForkLayer, string getForkStation,
                                       SRMForkTaskFlag putForkTaskFlag, string putForkRow, string putForkColumn, string putForkLayer, string putForkStation,
                                       string taskNo, SSRMTaskCompleteFlag completeFlag)
        {
            try
            {
                List <EquipmentProp> propsToWriter = new List <EquipmentProp>();
                var props = srm.EquipmentProps;

                var action = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSNewTask.ToString());
                action.Value = newTaskFlag.GetIndexString();

                //--

                var getTaskFlag = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSGetFork1TaskFlag.ToString());
                getTaskFlag.Value = getForkTaskFlag.GetIndexString();

                var getRow = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSGetRow.ToString());
                getRow.Value = getForkRow;

                var getStation = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSGetPort.ToString());
                getStation.Value = getForkStation;

                var getColumn = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSGetColumn.ToString());
                getColumn.Value = getForkColumn;

                var getLayer = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSGetLayer.ToString());
                getLayer.Value = getForkLayer;

                //--

                var putTaskFlag = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSPutFork1TaskFlag.ToString());
                putTaskFlag.Value = putForkTaskFlag.GetIndexString();

                var putRow = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSPutRow.ToString());
                putRow.Value = putForkRow;

                var putStation = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSPutPort.ToString());
                putStation.Value = putForkStation;

                var putColumn = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSPutColumn.ToString());
                putColumn.Value = putForkColumn;

                var putLayer = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSPutLayer.ToString());
                putLayer.Value = putForkLayer;

                // -
                var taskNoProp = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSTaskNo.ToString());
                taskNoProp.Value = taskNo;

                // -
                var taskFlagProp = props.Find(t => t.EquipmentTypeTemplateCode == SSRMProps.WCSTaskCompleteFlag.ToString());
                taskFlagProp.Value = completeFlag.GetIndexString();


                propsToWriter.AddRange(new List <EquipmentProp>()
                {
                    action, getTaskFlag, getRow, getColumn, getLayer, getStation, putTaskFlag, putRow, putStation, putColumn, putLayer, taskNoProp, taskFlagProp
                });
                return(plc.Writes(propsToWriter));
            }
            catch (Exception ex)
            {
                Logger.Log($"PLC写入信息错误:" + ex.Message, LogLevel.Exception);
                return(BllResultFactory.Error($"下发任务出现异常:{ex.Message}"));
            }
        }
Пример #16
0
        public override BllResult ExcuteArrive(Equipment station, List <Equipment> allEquipments, IPLC plc)
        {
            var isSuccess = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.ArriveResult.ToString()).Value;

            if (isSuccess == StationArriveResult.成功.GetIndexString())
            {
                //获取条码
                var barcode           = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.ArriveBarcode.ToString()).Value;
                var arriveRealAddress = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.ArriveRealAddress.ToString()).Value;
                if (string.IsNullOrWhiteSpace(barcode))
                {
                    return(BllResultFactory.Error($"站台{station.Name}有位置到达但是没有条码信息"));
                }
                else
                {
                    var taskResult = AppSession.Dal.GetCommonModelByCondition <TaskEntity>(
                        $"where containerCode = '{barcode}' and taskStatus < {TaskEntityStatus.任务完成.GetIndexInt()} and deleted = 0");
                    if (taskResult.Success)
                    {
                        if (taskResult.Data.Count > 1)
                        {
                            return(BllResultFactory.Error($"站台{station.Name}根据条码{barcode}查找到了多条任务,请检查数据"));
                        }
                        else
                        {
                            var task = taskResult.Data[0];
                            //判断任务类型,整出性质的任务直接完成,需要回库性质的任务需要更换阶段
                            if (task.TaskType == TaskType.整盘出库.GetIndexInt() ||
                                task.TaskType == TaskType.空容器出库.GetIndexInt() ||
                                task.TaskType == TaskType.换站.GetIndexInt())
                            {
                                using (IDbConnection connection = AppSession.Dal.GetConnection())
                                {
                                    IDbTransaction transaction = null;
                                    try
                                    {
                                        connection.Open();
                                        transaction = connection.BeginTransaction();
                                        var result = AppSession.TaskService.CompleteTask(task.Id.Value, App.User.UserCode, connection, transaction);
                                        if (result.Success)
                                        {
                                            //回复位置到达
                                            result = SendAckToPlc(station, plc, StationMessageFlag.WCSPLCACK, StationLoadStatus.回复到达, station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.ArriveRealAddress.ToString()).Value, "0");
                                            if (result.Success)
                                            {
                                                transaction.Commit();
                                                //发送LED
                                                AppSession.BllService.SendLED(station, task);
                                                return(BllResultFactory.Sucess($"响应站台{station.Name}位置到达成功,完成任务成功,条码{barcode},任务{task.Id}"));
                                            }
                                            else
                                            {
                                                transaction.Rollback();
                                                return(BllResultFactory.Error($"响应站台{station.Name}位置到达失败,条码{barcode},任务{task.Id},详情:{result.Msg}"));
                                            }
                                        }
                                        else
                                        {
                                            transaction.Rollback();
                                            return(BllResultFactory.Error($"响应站台{station.Name}位置到达请求失败,完成任务失败,条码{barcode},任务{task.Id},详情:{result.Msg}"));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        transaction?.Rollback();
                                        return(BllResultFactory.Error($"响应站台{station.Name}位置到达请求失败,完成任务失败,条码{barcode},任务{task.Id},详情:{ex.Message}"));
                                    }
                                }
                            }
                            else
                            {
                                //其他
                                using (IDbConnection connection = AppSession.Dal.GetConnection())
                                {
                                    IDbTransaction transaction = null;
                                    try
                                    {
                                        connection.Open();
                                        transaction     = connection.BeginTransaction();
                                        task.Stage      = (int)TaskStageFlag.入; //一定要转换任务阶段
                                        task.TaskStatus = (int)TaskEntityStatus.到达拣选站台;
                                        task.Gateway    = station.Code;
                                        var result = AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                                        if (result.Success)
                                        {
                                            result = SendAckToPlc(station, plc, StationMessageFlag.WCSPLCACK, StationLoadStatus.回复到达, arriveRealAddress, "0");
                                            if (result.Success)
                                            {
                                                transaction.Commit();
                                                return(BllResultFactory.Sucess($"响应站台{station.Name}位置到达成功,更新任务状态成功,条码{barcode},任务{task.Id}"));
                                            }
                                            else
                                            {
                                                transaction.Rollback();
                                                return(BllResultFactory.Error($"响应站台{station.Name}位置到达失败,通知PLC失败,条码{barcode},任务{task.Id}"));
                                            }
                                        }
                                        else
                                        {
                                            return(BllResultFactory.Error($"响应站台{station.Name}位置到达请求失败,更新任务状态失败,条码{barcode},任务{task.Id}," +
                                                                          $"详情:{result.Msg}"));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        transaction?.Rollback();
                                        return(BllResultFactory.Error($"仓库{task.WarehouseCode},响应站台{station.Name}位置到达请求失败,更新任务状态失败," +
                                                                      $"条码{barcode},任务{task.Id},详情:{ex.ToString()}"));
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        return(BllResultFactory.Error($"站台{station.Name}根据条码{barcode}没有查询到任务:{taskResult.Msg}"));
                    }
                }
            }
            else
            {
                return(BllResultFactory.Error($"站台{station.Name}位置到达失败"));
            }
        }
Пример #17
0
 public override BllResult ExcuteRequest(Equipment station, List <Equipment> allEquipments, IPLC plc)
 {
     return(BllResultFactory.Error($"堆垛机接入站台{station.Name}不执行请求处理"));
 }
Пример #18
0
        public static BllResult <HslSiemensDataEntity> ParseAddress(EquipmentProp prop)
        {
            HslSiemensDataEntity entity = new HslSiemensDataEntity();

            entity.OPCAddressId = prop.Id.Value;
            string address = prop.Address;

            try
            {
                if (address[0] == 'I')
                {
                    entity.Area = SiemensArea.I;
                    return(BllResultFactory <HslSiemensDataEntity> .Error("暂时不支持I区访问"));
                }
                else if (address[0] == 'Q')
                {
                    entity.Area = SiemensArea.Q;
                    return(BllResultFactory <HslSiemensDataEntity> .Error("暂时不支持Q区访问"));
                }
                else if (address[0] == 'M')
                {
                    entity.Area       = SiemensArea.M;
                    entity.BlockIndex = 0;
                    entity.DataAmount = 1;
                    string temp = address.Substring(1);
                    if (temp.StartsWith("DINT"))
                    {
                        temp = temp.Substring(4);
                        entity.DataOffset = Convert.ToInt32(temp);
                        entity.DataType   = PLCDataType.DINT;
                    }
                    else if (temp.StartsWith("INT"))
                    {
                        temp = temp.Substring(3);
                        entity.DataOffset = Convert.ToInt32(temp);
                        entity.DataType   = PLCDataType.INT;
                    }
                    else if (temp.StartsWith("D"))
                    {
                        temp = temp.Substring(1);
                        entity.DataOffset = Convert.ToInt32(temp);
                        entity.DataType   = PLCDataType.DWORD;
                    }
                    else if (temp.StartsWith("W"))
                    {
                        temp = temp.Substring(1);
                        entity.DataOffset = Convert.ToInt32(temp);
                        entity.DataType   = PLCDataType.WORD;
                    }
                    else if (temp.StartsWith("X"))
                    {
                        temp = temp.Substring(1);
                        var adss = temp.Split('.');
                        entity.DataOffset = Convert.ToInt32(adss[0]);
                        entity.BitOffset  = Convert.ToInt32(adss[1]);
                        entity.DataType   = PLCDataType.BOOL;
                    }
                    else if (temp.StartsWith("CHAR"))
                    {
                        temp = temp.Substring(4);
                        var adss = temp.Split(',');
                        entity.DataOffset = Convert.ToInt32(adss[0]);
                        entity.DataAmount = Convert.ToInt32(adss[1]);
                        entity.DataType   = PLCDataType.CHAR;
                    }
                    else
                    {
                        return(BllResultFactory <HslSiemensDataEntity> .Error("解析错误,无效数据类型"));
                    }
                    return(BllResultFactory <HslSiemensDataEntity> .Sucess(entity));
                }
                else if (address[0] == 'D' || address.Substring(0, 2) == "DB")
                {
                    if (address[1] == 'B')
                    {
                        entity.Area = SiemensArea.DB;
                        string temp = address.Substring(2);
                        if (temp.Contains("W"))
                        {
                            var ads = temp.Split('W');
                            entity.BlockIndex = Convert.ToInt32(ads[0]);
                            entity.DataOffset = Convert.ToInt32(ads[1]);
                            entity.DataAmount = 1;
                            entity.DataType   = PLCDataType.WORD;
                        }
                        else if (temp.Contains("DINT"))
                        {
                            var ads = temp.Split(new char[] { 'D', 'I', 'N', 'T' }, StringSplitOptions.RemoveEmptyEntries);
                            entity.BlockIndex = Convert.ToInt32(ads[0]);
                            entity.DataOffset = Convert.ToInt32(ads[1]);
                            entity.DataAmount = 1;
                            entity.DataType   = PLCDataType.DINT;
                        }
                        else if (temp.Contains("INT"))
                        {
                            var ads = temp.Split(new char[] { 'I', 'N', 'T' }, StringSplitOptions.RemoveEmptyEntries);
                            entity.BlockIndex = Convert.ToInt32(ads[0]);
                            entity.DataOffset = Convert.ToInt32(ads[1]);
                            entity.DataAmount = 1;
                            entity.DataType   = PLCDataType.INT;
                        }
                        else if (temp.Contains("D"))
                        {
                            var ads = temp.Split('D');
                            entity.BlockIndex = Convert.ToInt32(ads[0]);
                            entity.DataOffset = Convert.ToInt32(ads[1]);
                            entity.DataAmount = 1;
                            entity.DataType   = PLCDataType.DWORD;
                        }
                        else if (temp.Contains("B"))
                        {
                            var ads = temp.Split('B');
                            entity.BlockIndex = Convert.ToInt32(ads[0]);
                            entity.DataOffset = Convert.ToInt32(ads[1]);
                            entity.DataAmount = 1;
                            entity.DataType   = PLCDataType.BYTE;
                        }
                        else if (temp.Contains("X"))
                        {
                            var ads = temp.Split('X');
                            entity.BlockIndex = Convert.ToInt32(ads[0]);
                            var adss = ads[1].Split('.');
                            entity.DataOffset = Convert.ToInt32(adss[0]);
                            entity.BitOffset  = Convert.ToInt32(adss[1]);
                            entity.DataAmount = 1;
                            entity.DataType   = PLCDataType.BOOL;
                        }
                        else if (temp.Contains("CHAR"))
                        {
                            var ads = temp.Split(new char[] { 'C', 'H', 'A', 'R' }, StringSplitOptions.RemoveEmptyEntries);
                            entity.BlockIndex = Convert.ToInt32(ads[0]);
                            var adss = ads[1].Split(',');
                            entity.DataOffset = Convert.ToInt32(adss[0]);
                            entity.DataAmount = Convert.ToInt32(adss[1]);
                            entity.DataType   = PLCDataType.CHAR;
                        }
                        else
                        {
                            return(BllResultFactory <HslSiemensDataEntity> .Error("解析错误,无效数据类型"));
                        }
                    }
                    else
                    {
                        return(BllResultFactory <HslSiemensDataEntity> .Error("暂时只支持DB块访问"));
                    }
                    return(BllResultFactory <HslSiemensDataEntity> .Sucess(entity));
                }
                else if (address[0] == 'T')
                {
                    entity.Area = SiemensArea.T;
                    return(BllResultFactory <HslSiemensDataEntity> .Error("暂时不支持T区访问"));
                }
                else if (address[0] == 'C')
                {
                    entity.Area = SiemensArea.C;
                    return(BllResultFactory <HslSiemensDataEntity> .Error("暂时不支持C区访问"));
                }
                else if (address[0] == 'V')
                {
                    entity.Area = SiemensArea.V;
                    return(BllResultFactory <HslSiemensDataEntity> .Error("暂时不支持V区访问"));

                    //result.Content1 = 0x84;
                    //result.Content3 = 1;
                    //result.Content2 = CalculateAddressStarted(address.Substring(1));
                }
                else
                {
                    return(BllResultFactory <HslSiemensDataEntity> .Error("未知的地址开头"));
                }
            }
            catch (Exception ex)
            {
                return(BllResultFactory <HslSiemensDataEntity> .Error(ex.Message));
            }
        }
        /// <summary>
        /// 这里只有请求信息
        /// </summary>
        /// <param name="station"></param>
        /// <param name="plc"></param>
        /// <returns></returns>
        public override BllResult ExcuteRequest(Equipment station, List <Equipment> allEquipments, IPLC plc)
        {
            //获取任务
            var taskResult = AppSession.Dal.GetCommonModelByCondition <TaskEntity>($"where  taskStatus= {TaskEntityStatus.响应堆垛机库外放货完成.GetIndexInt()} and gateway = '{station.Code}' and deleted = 0");

            if (taskResult.Success)
            {
                var tasks = taskResult.Data;
                if (taskResult.Data.Count > 1)
                {
                    return(BllResultFactory.Error($"站台{station.Name}根据任务状态{TaskEntityStatus.响应堆垛机库外放货完成}和站台编码{station.Code}查找到了多条任务,请检查数据"));
                }
                else
                {
                    var task = taskResult.Data[0];
                    if (task.TaskType == TaskType.整盘入库.GetIndexInt() || task.TaskType == TaskType.空容器入库.GetIndexInt())
                    {
                        return(BllResultFactory.Error($"站台{station.Name}不接受整盘入库和空容器入库任务"));
                    }
                    var requestNumber = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestNumber.ToString()).Value;
                    //***********************************************************************************************************************
                    // 根据托盘上一个入库性质的任务进行查找其长宽高重信息  这个其实不重要---so,what do you want?
                    var requestWeight = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestWeight.ToString()).Value;
                    var requestLength = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestLength.ToString()).Value;
                    var requestWidth  = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestWidth.ToString()).Value;
                    var requestHeight = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestHeight.ToString()).Value;
                    var tempPreResult = AppSession.Dal.GetCommonModelByCondition <TaskEntity>($" where containerCode='{task.ContainerCode}' and " +
                                                                                              $" taskStatus>={(int)task.TaskStatus}  order by Id desc");
                    if (tempPreResult.Success && tempPreResult.Data.Count > 0)
                    {
                        requestHeight = tempPreResult.Data[0].ReqHeight;
                        requestLength = tempPreResult.Data[0].ReqLength;
                        requestWeight = tempPreResult.Data[0].ReqWeight;
                        requestWidth  = tempPreResult.Data[0].ReqWidth;
                    }
                    //***********************************************************************************************************************
                    //判断是否有去向地址,没有则根据任务的出口进行判断
                    string goAddress = station.GoAddress;
                    if (string.IsNullOrWhiteSpace(goAddress) || goAddress == "0")
                    {
                        var tempEquipmentResult = AppSession.Dal.GetCommonModelByCondition <Equipment>($"where code = '{task.ToPort}' and warehouseCode = '{station.WarehouseCode}'");
                        if (!tempEquipmentResult.Success)
                        {
                            return(BllResultFactory.Error($"没有配置站台{station.Code}的去向地址,系统也找不到任务{task.Id}对应的{task.ToPort}地址"));
                        }
                        else
                        {
                            goAddress = tempEquipmentResult.Data[0].SelfAddress;
                        }
                    }

                    int tempStatus = task.TaskStatus; //记录原始状态以便回滚
                    task.TaskStatus = TaskEntityStatus.响应接出口站台请求.GetIndexInt();
                    var temp = AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                    if (temp.Success)
                    {
                        //回复地址请求
                        temp = SendAddressReplyToPlc(station, plc, StationMessageFlag.地址回复, StationLoadStatus.默认, requestNumber, task.ContainerCode,
                                                     requestWeight, requestLength, requestWidth, requestHeight, goAddress, "0");
                        if (temp.Success)
                        {
                            return(BllResultFactory.Sucess($"响应站台{station.Name}地址请求成功,条码{task.ContainerCode},任务{task.Id}"));
                        }
                        else
                        {
                            task.TaskStatus = tempStatus;
                            AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                            return(BllResultFactory.Error($"响应站台{station.Name}地址请求失败,条码{task.ContainerCode},任务{task.Id},回滚任务状态"));
                        }
                    }
                    else
                    {
                        return(BllResultFactory.Error($"站台{station.Name},响应请求时更新任务{task.Id}状态失败。"));
                    }
                }
            }
            else
            {
                string barcode = "123";
                SendBack(station, plc, barcode);
                return(BllResultFactory.Error($"站台{station.Name}根据任务状态{TaskEntityStatus.响应堆垛机库外放货完成}没有查询到任务:{taskResult.Msg}"));
            }
        }
Пример #20
0
        /// <summary>
        /// 测长缓存区地址请求:
        /// 测长缓存区域只要有物料,PLC就发送请求,ECS判断如果定长切割设备请求上料,就响应请求。
        /// PLC收到响应就从调度设备从缓存料架取走一根管子放到输送线上。
        /// </summary>
        /// <param name="lengthMeasuringCache"></param>
        /// <param name="allEquipments"></param>
        /// <param name="data"></param>
        /// <param name="plc"></param>
        /// <returns></returns>
        protected override BllResult ExcuteRequest(Equipment lengthMeasuringCache, List <Equipment> allEquipments, List <StepTrace> data, IPLC plc)
        {
            try
            {
                var RequestTaskId = lengthMeasuringCache.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == PipeLineProps.RequestTaskId.ToString());
                if (string.IsNullOrWhiteSpace(RequestTaskId.Value))
                {
                    Logger.Log($"处理工位位[{lengthMeasuringCache.StationCode}]的设备[{lengthMeasuringCache.Name}] 地址请求失败,原因:有地址请求但是没有任务号信息", LogLevel.Error);
                    return(BllResultFactory.Error());
                }
                var cutter = allEquipments.FirstOrDefault(t => t.SelfAddress == lengthMeasuringCache.GoAddress.ToString());
                //找到下个设备(定长切割)
                if (cutter == null)
                {
                    Logger.Log($"处理工位位[{lengthMeasuringCache.StationCode}]的设备[{lengthMeasuringCache.Name}] 地址请求失败,原因:测长缓存位没有设置对应的下个设备", LogLevel.Error);
                    return(BllResultFactory.Error());
                }
                var ArriveMessage = cutter.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == MachineProps.ArriveMessage.ToString());
                var WCSACKMessage = cutter.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == MachineProps.WCSACKMessage.ToString());
                var requestNumber = lengthMeasuringCache.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == PipeLineProps.RequestNumber.ToString());
                if (ArriveMessage?.Value == MachineMessageFlag.PLC自动请求上料.GetIndexString() && WCSACKMessage?.Value == MachineMessageFlag.默认.GetIndexString())
                {
                    var stationCacheCountResult = AppSession.Dal.GetCommonModelCount <StationCache>($"where status = {StationCacheStatus.使用中.GetIndexInt()}");
                    if (!stationCacheCountResult.Success)
                    {
                        Logger.Log($"处理工位位[{lengthMeasuringCache.StationCode}]的设备[{lengthMeasuringCache.Name}]地址请求 失败,统计正在切割中的管子数量失败,原因:{stationCacheCountResult.Msg}", LogLevel.Error);
                        return(BllResultFactory.Error());
                    }
                    if (stationCacheCountResult.Data > 0)
                    {
                        Logger.Log($"处理工位位[{lengthMeasuringCache.StationCode}]的设备[{lengthMeasuringCache.Name}]地址请求 失败,存在还未切割完毕的管子,请等管子切割完毕。", LogLevel.Error);
                        return(BllResultFactory.Error());
                    }
                    var stationCachesResult = AppSession.Dal.GetCommonModelByCondition <StationCache>($"where id = {RequestTaskId.Value}");
                    if (!stationCachesResult.Success)
                    {
                        Logger.Log($"处理工位位[{lengthMeasuringCache.StationCode}]的设备[{lengthMeasuringCache.Name}]地址请求 失败,根据缓存ID[{RequestTaskId.Value}]查找缓存记录失败,原因:{stationCachesResult.Msg}", LogLevel.Error);
                        return(BllResultFactory.Error());
                    }
                    var stationCache = stationCachesResult.Data[0];
                    if (stationCache.Status == StationCacheStatus.初始.GetIndexInt())
                    {
                        Logger.Log($"处理工位位[{lengthMeasuringCache.StationCode}]的设备[{lengthMeasuringCache.Name}]地址请求 失败,管子缓存标识[{RequestTaskId.Value}]对应的管子还没有套料", LogLevel.Error);
                        return(BllResultFactory.Error());
                    }
                    if (stationCache.Status > StationCacheStatus.已经套料.GetIndexInt())
                    {
                        Logger.Log($"处理工位位[{lengthMeasuringCache.StationCode}]的设备[{lengthMeasuringCache.Name}]地址请求 失败,管子缓存标识[{RequestTaskId.Value}]对应的管子已经使用过了", LogLevel.Error);
                        return(BllResultFactory.Error());
                    }
                    //将缓存的管子标记为已用
                    stationCache.Status     = StationCacheStatus.使用中.GetIndexInt();
                    stationCache.CreateTime = DateTime.Now;
                    stationCache.CreateBy   = App.User.UserCode;

                    using (IDbConnection connection = AppSession.Dal.GetConnection())
                    {
                        IDbTransaction tran = null;
                        try
                        {
                            connection.Open();
                            tran = connection.BeginTransaction();
                            connection.Update <StationCache>(stationCache, tran);
                            BllResult plcResult = SendAddressReplyToPlc(lengthMeasuringCache, plc, StationMessageFlag.地址回复, StationLoadStatus.默认, requestNumber.Value, stationCache.Id.ToString(), "", stationCache.WcsProductType.ToString(), stationCache.MaterialLength.ToString(), stationCache.Diameter.ToString(), stationCache.Thickness.ToString(), lengthMeasuringCache.GoAddress);
                            if (plcResult.Success)
                            {
                                tran?.Commit();
                                Logger.Log($"处理工位位[{lengthMeasuringCache.StationCode}]的设备[{lengthMeasuringCache.Name}]地址请求 成功", LogLevel.Success);
                            }
                            else
                            {
                                tran?.Rollback();
                                Logger.Log($"处理工位位[{lengthMeasuringCache.StationCode}]的设备[{lengthMeasuringCache.Name}]地址请求 失败,写入PLC失败:{plcResult.Msg}", LogLevel.Error);
                            }
                            return(plcResult);
                        }
                        catch (Exception ex)
                        {
                            tran?.Rollback();
                            Logger.Log($"处理工位位[{lengthMeasuringCache.StationCode}]的设备[{lengthMeasuringCache.Name}]地址请求的时候,发生异常,缓存标识:[{RequestTaskId.Value}],原因:{ex.Message}", LogLevel.Exception, ex);
                            return(BllResultFactory.Error());
                        }
                    }
                }
                return(BllResultFactory.Sucess());
            }
            catch (Exception ex)
            {
                Logger.Log($"处理工位位[{lengthMeasuringCache.StationCode}]的设备[{lengthMeasuringCache.Name}] 地址请求时候,发生异常:{ex.Message}", LogLevel.Exception, ex);
                return(BllResultFactory.Error());
            }
        }
        /// <summary>
        /// 入库请求,由电气发起  兼容 分配巷道-》分配库位   或 分配库位 两种方式
        /// 第一步:判断条码信息,核对是否正确
        /// 第二步:根据条码查找任务
        /// 第三步:入库口优先分配巷道,在分配库位(入库站台响应的时候请求分配库位)
        /// </summary>
        /// <param name="station"></param>
        /// <param name="plc"></param>
        /// <returns>日志服务会对结果进行处理</returns>
        public override BllResult ExcuteRequest(Equipment station, List <Equipment> allEquipments, IPLC plc)
        {
            var    barcode       = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestBarcode.ToString()).Value;
            var    requestNumber = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestNumber.ToString()).Value;
            var    height        = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestHeight.ToString()).Value;
            var    weight        = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestWeight.ToString()).Value;
            var    length        = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestLength.ToString()).Value;
            var    width         = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestWidth.ToString()).Value;
            string goAddress     = "";
            string backAddress   = "";

            if (string.IsNullOrWhiteSpace(barcode))
            {
                SendBack(station, plc, barcode);
                return(BllResultFactory.Error($"站台{station.Name}有地址请求但是没有条码信息"));
            }
            else
            {
                //获取任务
                var taskResult = AppSession.Dal.GetCommonModelByConditionWithZero <TaskEntity>($"where containerCode = '{barcode}' and taskStatus < {TaskEntityStatus.任务完成.GetIndexInt()} and deleted = 0");
                if (taskResult.Success)
                {
                    if (taskResult.Data.Count > 1)
                    {
                        SendBack(station, plc, barcode);
                        return(BllResultFactory.Error($"站台{station.Name}根据条码{barcode}查找到了多条任务,请检查数据"));
                    }
                    if (taskResult.Data.Count == 0)
                    {
                        return(BllResultFactory.Error($"站台{station.Name}根据条码{barcode}没有找到任务,请检查数据"));
                    }
                    else
                    {
                        var task = taskResult.Data[0];
                        if (task.TaskType == TaskType.整盘出库.GetIndexInt() || task.TaskType == TaskType.空容器出库.GetIndexInt())
                        {
                            SendBack(station, plc, barcode);
                            return(BllResultFactory.Error($"站台{station.Name}不接受整盘出库和空托盘出库任务"));
                        }
                        //检测是否有去向库位,没有则请求
                        if (task.TaskType == TaskType.换站.GetIndexInt())
                        {
                            //如果是换站任务,则port不能为此站台,否则无意义
                            if (task.ToPort == station.Code)
                            {
                                SendBack(station, plc, barcode);
                                return(BllResultFactory.Error($"托盘{task.ContainerCode}为换站任务,但是换站目的地与入口目的地相同"));
                            }
                        }
                        goAddress = station.GoAddress;
                        if (string.IsNullOrWhiteSpace(goAddress))
                        {
                            // 检测是否有去向库位或去向站台   设计逻辑:优先考虑是否分配了目标区域,没有则判断是否分配了库位
                            if (string.IsNullOrWhiteSpace(task.DestinationArea))
                            {
                                if (string.IsNullOrWhiteSpace(task.ToLocationCode))
                                {
                                    //没有分配目标区域,也没有分配库位的情况  这个时候需要请求上游系统分配目标区域或库位
                                    //hack:这里默认进行去向库位获取,按需改成获取去向区域
                                    LocationAssignReqModelInfo locationRequest = new LocationAssignReqModelInfo();
                                    locationRequest.TaskNo = task.RemoteTaskNo.ToString();
                                    locationRequest.Height = height;
                                    locationRequest.Weight = weight;
                                    locationRequest.Length = length;
                                    locationRequest.Width  = width;
                                    var result = AppSession.TaskService.GetDestinationLocationFromWMS(locationRequest);
                                    if (!result.Success)
                                    {
                                        SendBack(station, plc, barcode);
                                        return(BllResultFactory.Error($"任务{task.Id}没有去向库位,并且请求上游系统库位失败:{result.Msg}"));
                                    }
                                    Logger.Log($"任务{task.Id}请求上位系统去向库位成功,获取库位为:{result.Data.Code}", LogLevel.Success);
                                    task.DestinationArea = result.Data.DestinationArea;
                                    task.ToLocationCode  = result.Data.Code;
                                }
                                else
                                {
                                    //没有分配目标区域,分配了库位的情况
                                    // 根据库位 查找巷道
                                    var temp2 = AppSession.LocationService.GetLocationByCode(task.ToLocationCode);
                                    if (!temp2.Success)
                                    {
                                        SendBack(station, plc, barcode);
                                        return(BllResultFactory.Error($"任务{task.Id}获取去向库位{task.ToLocationCode}出错:{temp2.Msg}"));
                                    }
                                    task.DestinationArea = temp2.Data.DestinationArea;
                                }
                                //将获取到的数据进行update
                                AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                            }
                            //根据目标区域查找前进地址
                            var temp3 = AppSession.ExcuteService.GetGoAddressByDestinationArea(task.DestinationArea, station.Code, App.WarehouseCode);
                            if (!temp3.Success)
                            {
                                SendBack(station, plc, barcode);
                                return(BllResultFactory.Error($"托盘{task.ContainerCode}没有查找到对应请进地址,请核对信息是否录入维护错误"));
                            }
                            //hack:这里默认取第一个,如果有项目存在多个选择,请加逻辑进行判断
                            if (string.IsNullOrWhiteSpace(temp3.Data[0].SelfAddress))
                            {
                                SendBack(station, plc, barcode);
                                return(BllResultFactory.Error($"托盘{task.ContainerCode}查找设备{temp3.Data[0].Code}无目标地址,请核对设备信息是否配置正确"));
                            }
                            goAddress = temp3.Data[0].SelfAddress;
                        }

                        int    tempStatus = task.TaskStatus; //记录原始状态以便回滚
                        string tempArrivaEquipmentCode = task.Gateway;
                        task.TaskStatus = TaskEntityStatus.拣选台回库.GetIndexInt();
                        task.Gateway    = station.Code;
                        task.ReqHeight  = height;
                        task.ReqLength  = length;
                        task.ReqWeight  = weight;
                        task.ReqWidth   = width;
                        var temp = AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                        if (temp.Success)
                        {
                            //回复地址请求
                            temp = SendAddressReplyToPlc(station, plc, StationMessageFlag.地址回复, StationLoadStatus.默认,
                                                         requestNumber, barcode, weight, length, width, height, goAddress, backAddress);
                            if (temp.Success)
                            {
                                //发送LED
                                AppSession.BllService.SendLED(station, task);
                                return(BllResultFactory.Sucess($"响应站台{station.Name}地址请求成功,条码{barcode},任务{task.Id}"));
                            }
                            else
                            {
                                task.TaskStatus = tempStatus;
                                task.Gateway    = tempArrivaEquipmentCode;
                                AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                                SendBack(station, plc, barcode);
                                return(BllResultFactory.Error($"响应站台{station.Name}地址请求失败,条码{barcode},任务{task.Id},详情:{temp.Msg},回滚任务状态"));
                            }
                        }
                        else
                        {
                            SendBack(station, plc, barcode);
                            return(BllResultFactory.Error($"站台{station.Name},响应请求时更新任务{task.Id}状态失败。详情:{temp.Msg}"));
                        }
                    }
                }
                else
                {
                    SendBack(station, plc, barcode);
                    return(BllResultFactory.Error($"站台{station.Name}根据条码{barcode}没有查询到任务:{taskResult.Msg}"));
                }
            }
        }
Пример #22
0
        /// <summary>
        /// 具体的站台实现逻辑
        /// </summary>
        /// <param name="bevels"></param>
        /// <param name="plcs"></param>
        /// <returns></returns>
        public virtual BllResult Excute(List <Equipment> pipeLines, List <Equipment> allEquipments, IPLC plc)
        {
            try
            {
                if (pipeLines.Count == 0)
                {
                    return(BllResultFactory.Error($"没有连接到类型[{EquipmentType.Name}]的设备,所以不执行处理程序。"));
                }
                List <StepTrace> stepTraceList = new List <StepTrace>();
                if (EquipmentType.Code != "LengthMeasuringCache")
                {
                    //找出  未完成的任务
                    var stepTraceResult = AppSession.Dal.GetCommonModelByConditionWithZero <StepTrace>($"where status < {StepTraceStatus.任务完成.GetIndexInt()}");
                    if (!stepTraceResult.Success)
                    {
                        Logger.Log($"查询类型[{EquipmentType.Name}]的设备的任务出错,原因:{stepTraceResult.Msg}", LogLevel.Error);
                        return(BllResultFactory.Error());
                    }
                    else
                    {
                        stepTraceList = stepTraceResult.Data;
                    }
                }
                foreach (var pipeLine in pipeLines)
                {
                    var OperationModel = pipeLine.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == PipeLineProps.OperationModel.ToString());
                    var TotalError     = pipeLine.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == PipeLineProps.TotalError.ToString());
                    //不是 故障且联机,就不处理,跳到下个设备
                    if (OperationModel?.Value != OperationModelFlag.联机.GetIndexString() || TotalError?.Value != TotalErrorFlag.无故障.GetIndexString())
                    {
                        continue;
                    }

                    //处理位置到达
                    var ArriveMessage    = pipeLine.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == PipeLineProps.ArriveMessage.ToString());
                    var WCSACKMessage    = pipeLine.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == PipeLineProps.WCSACKMessage.ToString());
                    var WCSACKLoadStatus = pipeLine.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == PipeLineProps.WCSACKLoadStatus.ToString());
                    //PLC有位置到达,而WCSACK没有回复,则WCS还没有响应
                    if (ArriveMessage?.Value == StationMessageFlag.分拣报告.GetIndexString() && WCSACKMessage?.Value == StationMessageFlag.默认.GetIndexString())
                    {
                        ExcuteArrive(pipeLine, allEquipments, stepTraceList, plc);
                    }
                    //PLC没位置到达,而WCSACK有回复,则PLC已经响应但还没有清除
                    if (ArriveMessage?.Value == StationMessageFlag.默认.GetIndexString() && WCSACKMessage?.Value == StationMessageFlag.WCSPLCACK.GetIndexString() && WCSACKLoadStatus?.Value == StationLoadStatus.回复到达.GetIndexString())
                    {
                        ExcuteArriveClear(pipeLine, plc);
                    }

                    //处理地址请求
                    var RequestMessage  = pipeLine.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == PipeLineProps.RequestMessage.ToString());
                    var WCSReplyMessage = pipeLine.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == PipeLineProps.WCSReplyMessage.ToString());
                    //PLC有请求,但ECS没有,则ECS还没有响应
                    if (RequestMessage?.Value == StationMessageFlag.地址请求.GetIndexString() && WCSReplyMessage?.Value == StationMessageFlag.默认.GetIndexString())
                    {
                        ExcuteRequest(pipeLine, allEquipments, stepTraceList, plc);
                    }
                    //PLC没有请求,但ECS有确认信号, 就清除 ECS确认下料完成信号
                    if (RequestMessage?.Value == StationMessageFlag.默认.GetIndexString() && WCSReplyMessage?.Value == StationMessageFlag.地址回复.GetIndexString())
                    {
                        ExcuteRequestClear(pipeLine, plc);
                    }
                }
                return(BllResultFactory.Sucess());
            }
            catch (Exception ex)
            {
                Logger.Log($"处理类型[{EquipmentType.Name}]设备过程中出现异常:{ex.Message}", LogLevel.Exception, ex);
                return(BllResultFactory.Error());
            }
        }
Пример #23
0
        /// <summary>
        /// 更新库位表数据源
        /// </summary>
        /// <param name="stepTrace"></param>
        /// <param name="stations"></param>
        /// <returns></returns>
        public BllResult updateLocation(StepTrace stepTrace, List <Station> stations)
        {
            try
            {
                //var temp = stations.Where(t => t.Code.Contains("StationForFinished")).ToList();
                //if (temp.Count == 0 || temp == null)
                //{
                //    return BllResultFactory.Error("没有查询到相对应的成品下线站台数据");
                //}
                var station = stations.Find(t => t.Id == stepTrace.NextStationId);
                if (station != null)
                {
                    var locationResult = AppSession.Dal.GetCommonModelByCondition <Location>($"where srmCode = '{station.Code}'");
                    if (locationResult.Success == false)
                    {
                        return(BllResultFactory.Error($"根据{station.Code}查询库位数据失败"));
                    }
                    if (locationResult.Data.Count != 1)
                    {
                        return(BllResultFactory.Error($"根据{station.Code}查询库位数据不是1条,请核对库位基础数据"));
                    }
                    var location = locationResult.Data[0];

                    if (location.Line < 1 || location.Layer < 1)
                    {
                        location.Row   = 1;
                        location.Line  = 1;
                        location.Layer = 1;
                        return(AppSession.Dal.UpdateCommonModel <Location>(location));
                    }
                    if (location.Line == 1 && location.Layer == 1)
                    {
                        return(BllResultFactory.Sucess());
                    }
                    if (location.Line == 1)
                    {
                        location.Line  = 4;
                        location.Layer = (short)(location.Layer - 1);
                        return(AppSession.Dal.UpdateCommonModel <Location>(location));
                    }
                    if (location.Line > 1)
                    {
                        location.Line = (short)(location.Line - 1);
                        return(AppSession.Dal.UpdateCommonModel <Location>(location));
                    }
                    return(BllResultFactory.Error("更新下线站台的列层失败,存在程序未处理的情况。"));
                    //string sql_1 = $"update wcslocation set WCSLayer = @WCSLayer,WCSLine=@WCSLine where id = @id ";
                    //string sql_2 = $"update wcslocation set WCSLine=@WCSLine where id = @id ";
                    ////当前列数减一,发生异常情况实际未送过去的,
                    //int? newLine = location.Line - 1;
                    //if (newLine == 0)
                    //{
                    //    var result = AppSession.Dal.ExcuteCommonSqlForInsertOrUpdate(sql_1, new { WCSLine = 1, WCSLayer = 1, id = location.Id });
                    //    if (!result.Success)
                    //    {
                    //        return BllResultFactory.Error($"更新库位表失败{location.Id}");
                    //    }
                    //}
                    //else
                    //{
                    //    var result = AppSession.Dal.ExcuteCommonSqlForInsertOrUpdate(sql_2, new { WCSLine = newLine, id = location.Id });
                    //    if (!result.Success)
                    //    {
                    //        return BllResultFactory.Error($"更新库位表失败{location.Id}");
                    //    }

                    //}
                }
                return(BllResultFactory.Error($"更新下线站台的列层失败,因为没有找到ID[{stepTrace.NextStationId}]对应的站台"));
            }
            catch (Exception)
            {
                return(BllResultFactory.Error());
            }
        }
Пример #24
0
        /// <summary>
        /// 状态指令
        /// </summary>
        /// <param name="stocker"></param>
        /// <returns></returns>
        private BllResult SendStatusForWS(Equipment srm)
        {
            string project  = "2020040901";
            string instruct = "WS";
            string code     = srm.DestinationArea;
            //string code = "SRM001";
            var statusSRM = FilterForData(srm);

            if (statusSRM.Success)
            {
                var statusResult = AppSession.Dal.GetCommonModelByCondition <WareHouseAlarm>($"where instruct = 'WS' and  equipmentCode ='{code}' ORDER BY id DESC ");
                if (statusResult.Success && statusResult.Data.Count > 0)
                {
                    var status = statusResult.Data[0];
                    if (statusSRM.Msg != status.EquipmentStatus)
                    {
                        WareHouseAlarm wareHouseAlarm = new WareHouseAlarm();
                        wareHouseAlarm.Pn                      = project;
                        wareHouseAlarm.Instruct                = "WS";
                        wareHouseAlarm.EquipmentStatus         = statusSRM.Msg;
                        wareHouseAlarm.EquipmentCode           = code;
                        wareHouseAlarm.Created                 = DateTime.Now;
                        wareHouseAlarm.EquipmentFailureTime    = DateTime.Now;
                        wareHouseAlarm.EquipmentEndFailureTime = DateTime.Now;
                        wareHouseAlarm.CreatedBy               = "WCS";
                        var res = AppSession.Dal.InsertCommonModel <WareHouseAlarm>(wareHouseAlarm);
                        if (!res.Success)
                        {
                            string s = res.Msg;
                        }
                        var dataResult = ConversionDataForStatus(project, instruct, code, statusSRM.Msg, DateTime.Now, DateTime.Now);
                        return(BllResultFactory.Sucess(null, dataResult.Msg));
                    }
                    else
                    {
                        return(BllResultFactory.Error(null, "失败"));
                    }
                }
                else if (!statusResult.Success)
                {
                    WareHouseAlarm wareHouseAlarm = new WareHouseAlarm();
                    wareHouseAlarm.Pn                      = project;
                    wareHouseAlarm.Instruct                = "WS";
                    wareHouseAlarm.EquipmentStatus         = statusSRM.Msg;
                    wareHouseAlarm.EquipmentCode           = code;
                    wareHouseAlarm.Created                 = DateTime.Now;
                    wareHouseAlarm.EquipmentFailureTime    = DateTime.Now;
                    wareHouseAlarm.EquipmentEndFailureTime = DateTime.Now;
                    wareHouseAlarm.CreatedBy               = "WCS";
                    var res = AppSession.Dal.InsertCommonModel <WareHouseAlarm>(wareHouseAlarm);
                    if (!res.Success)
                    {
                        string s = res.Msg;
                    }
                    var dataResult = ConversionDataForStatus(project, instruct, code, statusSRM.Msg, DateTime.Now, DateTime.Now);
                    return(BllResultFactory.Sucess(null, dataResult.Msg));
                }
                else
                {
                    return(BllResultFactory.Error(null, "失败"));
                }
            }
            else
            {
                return(BllResultFactory.Error(null, "失败"));
            }
        }
Пример #25
0
 /// <summary>
 /// 处理翻转请求
 /// </summary>
 /// <param name="bevel"></param>
 /// <param name="allEquipments"></param>
 /// <param name="stepTraceList"></param>
 /// <param name="plc"></param>
 /// <returns></returns>
 public override BllResult ExcuteFlip(Equipment bevel, List <Equipment> allEquipments, List <StepTrace> stepTraceList, IPLC plc)
 {
     try
     {
         var RequestTaskId = bevel.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == MachineProps.RequestTaskId.ToString());
         var convertResult = int.TryParse(RequestTaskId.Value, out int stepTraceId);
         if (!convertResult)
         {
             Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 翻转信号失败,工序任务的id[{RequestTaskId.Value}]转化为整数失败!", LogLevel.Error);
             return(BllResultFactory.Error());
         }
         if (stepTraceId == 0)
         {
             Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 翻转信号失败,工序跟踪ID为0", LogLevel.Error);
             return(BllResultFactory.Error());
         }
         var stepTrace = stepTraceList.FirstOrDefault(t => t.Id == stepTraceId);
         if (stepTrace == null)
         {
             Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 翻转信号失败,找不到未完成的工序任务id[{stepTraceId}]", LogLevel.Error);
             return(BllResultFactory.Error());
         }
         //就生成AGV任务并且插入数据库   小车任务的状态和类型需要重新定义?
         CarTask taskCar = new CarTask();
         taskCar.StepTraceId  = stepTrace.Id;
         taskCar.CarNo        = 1;
         taskCar.Type         = CarTaskType.翻转.GetIndexInt();
         taskCar.FromLocation = bevel.Station.TrussTakeStationId.ToString();
         taskCar.ToLocation   = bevel.Station.TrussTakeStationId.ToString();
         taskCar.ReSend       = 0;
         taskCar.Status       = TaskCarStatus.Init.GetIndexInt();
         taskCar.CreateTime   = DateTime.Now;
         taskCar.EndTime      = DateTime.Now;
         taskCar.StartTime    = DateTime.Now;
         taskCar.UpdateTime   = DateTime.Now;
         //taskCar.IsFlip = Convert.ToInt32(Allow_Flip);
         var updateResult = AppSession.Dal.InsertCommonModel <CarTask>(taskCar);
         if (updateResult.Success)
         {
             var sendResult = SendFlipToPlc(bevel, plc, FlipFlag.WCS回复允许翻转);
             if (sendResult.Success)
             {
                 Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 翻转请求成功,对应的任务[{stepTrace.Id}]信息写入设备", LogLevel.Success);
             }
             else
             {
                 //PLC写入失败,就把数据改回来
                 AppSession.Dal.DeleteCommonModelByIds <CarTask>(new List <int>()
                 {
                     taskCar.Id.Value
                 });
                 Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 翻转请求失败,对应的任务[{stepTrace.Id}]信息写入PLC失败,原因:{sendResult.Msg}", LogLevel.Error);
             }
             return(sendResult);
         }
     }
     catch (Exception ex)
     {
         Logger.Log($"处理工位[{bevel.StationCode}]的设备[{bevel.Name}] 翻转信号时候,发生异常:{ex.Message}", LogLevel.Exception, ex);
         return(BllResultFactory.Error());
     }
     return(BllResultFactory.Sucess());
 }
Пример #26
0
 /// <summary>
 /// 激光打标机处理逻辑
 /// </summary>
 /// <param name="cars"></param>
 /// <param name="plc"></param>
 /// <returns></returns>
 public override BllResult Excute(Equipment marking, IPLC plc)
 {
     return(BllResultFactory.Sucess());
 }
Пример #27
0
 /// <summary>
 /// 打标机处理逻辑
 /// </summary>
 /// <param name="cars"></param>
 /// <param name="plc"></param>
 /// <returns></returns>
 public virtual BllResult Excute(Equipment marking, IPLC plc)
 {
     return(BllResultFactory.Sucess());
 }
Пример #28
0
        /// <summary>
        /// 以堆垛机状态驱动,重写堆垛机控制逻辑
        /// hack:1.注意此处改动:堆垛机任务完成不再以状态去查找任务,以堆垛机携带的任务号为准;
        /// 2.标准实现中不支持跨巷道移库
        /// </summary>
        /// <param name="srm"></param>
        /// <param name="plc"></param>
        /// <returns></returns>
        public BllResult ExcuteSingle(Equipment srm, List <Equipment> allEquipments, IPLC plc)
        {
            //联机、无故障
            if (Validate(srm).Success)
            {
                #region 对于单叉堆垛机,判断这个货叉有误故障

                if (srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1TotalError.ToString()).Value == "True")
                {
                    //如果报有故障,则返回
                    return(BllResultFactory.Error("货叉1故障"));
                }

                #endregion

                #region 堆垛机任务执行判断
                if (srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1TaskExcuteStatus.ToString()).Value == SRMTaskExcuteStatus.任务执行中.GetIndexString())
                {
                    //任务执行中就return
                    return(BllResultFactory.Sucess());
                }
                if (srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1TaskExcuteStatus.ToString()).Value == SRMTaskExcuteStatus.任务中断_出错.GetIndexString())
                {
                    //由人工处理,一般为空出和重入
                    return(BllResultFactory.Sucess());
                }
                if (srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1TaskExcuteStatus.ToString()).Value == SRMTaskExcuteStatus.发任务错误.GetIndexString())
                {
                    //由人工处理,需要重新下发任务
                    return(BllResultFactory.Sucess());
                }
                #endregion

                #region 任务,货位和本巷道的其他设备

                //找出所有未完成的任务
                var tasksResult = AppSession.Dal.GetCommonModelByConditionWithZero <TaskEntity>($"where taskStatus < {TaskEntityStatus.任务完成.GetIndexInt()} " +
                                                                                                $"and taskStatus>={TaskEntityStatus.下发任务.GetIndexInt()} and deleted = 0 and warehouseCode='{AppSession.WarehouseCode}'");
                if (!tasksResult.Success)
                {
                    //如果查找发生错误
                    return(BllResultFactory.Error(tasksResult.Msg));
                }
                //找出同巷道的库位,考虑到可能多个巷道移库,这里分别查询出所有库位和当前堆垛机所在巷道的库位
                var locationsResult = AppSession.LocationService.GetAllLocations(null, null, null, null, null, null, null, srm.WarehouseCode);
                if (!locationsResult.Success)
                {
                    return(BllResultFactory.Error(locationsResult.Msg));
                }
                //所有库位
                var allLocations = locationsResult.Data;
                //本巷道库位
                var locationsRoadWay = allLocations.Where(t => t.RoadWay == srm.RoadWay).ToList();
                //找出本巷道的所有设备
                var equipmentsRoadWay = allEquipments.Where(t => t.RoadWay == srm.RoadWay && t.WarehouseCode == srm.WarehouseCode).ToList();

                //获取当前堆垛机可以到达的列
                var minProp   = srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.ManageSmallColumn.ToString());
                var maxProp   = srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.ManageBigColumn.ToString());
                int minColumn = Convert.ToInt32(minProp.Value);
                int maxColumn = Convert.ToInt32(maxProp.Value);
                //可用的可出站台
                //hack:注意,此处针对每个巷道均需要配置StationStatusMonitor!如果没有配置,则可出站台为空集合;
                var stationOutStatusMonitor = equipmentsRoadWay.Find(a => a.EquipmentType.Code == "StationStatusMonitor");
                var availableOutStation     = stationOutStatusMonitor == null ? new List <Equipment>() : equipmentsRoadWay.Where(t => t.EquipmentType.Code.Contains("Station") &&
                                                                                                                                 stationOutStatusMonitor.EquipmentProps.
                                                                                                                                 Count(b => b.EquipmentTypeTemplateCode == t.StationIndex.ToString() && b.Value == StationTaskLimit.可出.GetIndexString()) > 0).ToList();
                //筛选可出站台,可出站台得在堆垛机的最大列和最小列之间且目标区域与堆垛机
                //hack:这里按需选择是否判断站台的区域与堆垛机的区域是否相同
                availableOutStation = availableOutStation.Where(t => t.ColumnIndex >= minColumn && t.ColumnIndex <= maxColumn).ToList();

                //筛选任务,任务的范围得在堆垛机的最大列和最小列之间
                var tasks = tasksResult.Data.Where(t =>
                {
                    if (t.TaskType != (int)TaskType.换站)
                    {
                        //hack:这里筛选本巷道或关联到本巷道的任务,规则为起始或目标库位,所以,当将来出现跨巷道移库时,需要特别处理跨巷道移库任务
                        //兼容转轨,这里需要对两个库位是否在当前堆垛机可以到达的列做个判断,如果超出,则不执行
                        var tempLocations = locationsRoadWay.Where(a => a.Code == t.FromLocationCode || a.Code == t.ToLocationCode).ToList();
                        if (tempLocations.Count > 0)
                        {
                            return(tempLocations.Exists(a =>
                            {
                                return a.RoadWay == srm.RoadWay && (a.Line >= minColumn && a.Line <= maxColumn);
                            }));
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        //如果是换站,则toPort必须在本巷道中
                        var temp = AppSession.ExcuteService.GetOutStationByPort(srm.DestinationArea, t.ToPort, App.WarehouseCode);
                        if (temp.Success)
                        {
                            if (temp.Data.Exists(a => a.RoadWay != srm.RoadWay))
                            {
                                return(false);
                            }
                            else
                            {
                                return(true);
                            }
                        }
                        else
                        {
                            return(false);
                        }
                    }
                }).ToList();

                //筛选任务,任务的前置任务如果存在,则其前置任务需要大于完成状态
                tasks = tasks.Where(t =>
                {
                    if (t.PreTaskId != 0)
                    {
                        var tempResult = AppSession.Dal.GetCommonModelByCondition <TaskEntity>($"where id = {t.PreTaskId}");
                        if (tempResult.Success)
                        {
                            var innerTask = tempResult.Data[0];
                            if (innerTask.TaskStatus >= (int)TaskEntityStatus.任务完成)
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            Logger.Log($"未找到任务{t.Id},远程任务号:{t.RemoteTaskNo}的前置远程任务:{t.PreRemoteTaskNo},前置内部任务号:{t.PreTaskId},该任务不允许执行。如果要执行,请取消其前置任务号", LogLevel.Warning);
                            return(false);
                        }
                    }
                    else
                    {
                        return(true);
                    }
                }).ToList();

                #endregion

                //货叉1待机情况下
                if (srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1TaskExcuteStatus.ToString()).Value == SRMTaskExcuteStatus.待机.GetIndexString())
                {
                    //货叉任务待机时,可执行放和取任务,同时当执行完成时,交互后货叉1会从任务完成更新为待机
                    EquipmentProp fork1TaskFlag = srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.WCSFork1TaskFlag.ToString());
                    if (fork1TaskFlag.Value == SRMForkTaskFlag.任务完成.GetIndexString())
                    {
                        return(ClearWCSData(srm, plc));
                    }
                    else if (fork1TaskFlag.Value == SRMForkTaskFlag.除任务.GetIndexString())
                    {
                        return(ClearWCSData(srm, plc));
                    }
                    //货叉无任务且货叉在中心
                    else if (srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.WCSFork1TaskFlag.ToString()).Value == SRMForkTaskFlag.无任务.GetIndexString() && srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1Center.ToString()).Value == "True")
                    {
                        #region 优先处理重新下发的任务,此处可按需去除有货无货的校验

                        //库内取,要求货叉1无货
                        var taskForResend = tasks.FirstOrDefault(t => t.TaskStatus == TaskEntityStatus.发堆垛机库内取货.GetIndexInt() && locationsRoadWay.Count(a => a.Code == t.FromLocationCode) > 0 && t.SendAgain == 1);
                        if (taskForResend != null && srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1HasPallet.ToString()).Value == "False")
                        {
                            var locationForResend = locationsRoadWay.Find(t => t.Code == taskForResend.FromLocationCode);
                            return(ReSendTask(srm, plc, locationForResend.SrmCode == srm.Code ? locationForResend.RowIndex1.ToString() : locationForResend.RowIndex2.ToString(), locationForResend.Line.ToString(), locationForResend.Layer.ToString(), "0", taskForResend, SRMForkTaskFlag.库内取货));
                        }

                        //库内放货时,任务标记已在当前堆垛机上,校验之,要求货叉有货
                        taskForResend = tasks.FirstOrDefault(t => t.TaskStatus == TaskEntityStatus.发堆垛机库内放货.GetIndexInt() && locationsRoadWay.Count(a => a.Code == t.ToLocationCode) > 0 && t.SendAgain == 1 && t.Gateway == srm.Code);
                        if (taskForResend != null && srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1HasPallet.ToString()).Value == "True")
                        {
                            var locationForResend = locationsRoadWay.Find(t => t.Code == taskForResend.ToLocationCode);
                            return(ReSendTask(srm, plc, locationForResend.SrmCode == srm.Code ? locationForResend.RowIndex1.ToString() : locationForResend.RowIndex2.ToString(), locationForResend.Line.ToString(), locationForResend.Layer.ToString(), "0", taskForResend, SRMForkTaskFlag.库内放货));
                        }

                        //库外取货时,此站台得在本巷道内,要求货叉无货
                        //hack:一般情况下不存在同个巷道多个重新下发的任务,如果存在,此处需要特别处理
                        taskForResend = tasks.FirstOrDefault(t => t.TaskStatus == TaskEntityStatus.发堆垛机库外取货.GetIndexInt() &&
                                                             equipmentsRoadWay.Count(a => a.Code == t.Gateway) > 0 &&
                                                             t.SendAgain == 1);
                        if (taskForResend != null && srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1HasPallet.ToString()).Value == "False")
                        {
                            //使用task的ArrivaEquipmentCode来记录task对应托盘当前或上一次所在的口,则此处通过ArrivaEquipmentCode来查找当前task所在的口
                            var stationResult = equipmentsRoadWay.First(t => t.Code == taskForResend.Gateway);
                            return(ReSendTask(srm, plc, stationResult.RowIndex1.ToString(), stationResult.RowIndex1.ToString(), "0", stationResult.StationIndex.ToString(), taskForResend, SRMForkTaskFlag.库外取货));
                        }
                        //库外放货,要求货叉有货,要求站台可出
                        taskForResend = tasks.FirstOrDefault(t => t.TaskStatus == TaskEntityStatus.发堆垛机库外放货.GetIndexInt() && t.Gateway == srm.Code && t.SendAgain == 1);
                        if (taskForResend != null && srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1HasPallet.ToString()).Value == "True")
                        {
                            var stationsResult = AppSession.ExcuteService.GetOutStationByPort(srm.DestinationArea, taskForResend.ToPort, App.WarehouseCode);
                            if (!stationsResult.Success)
                            {
                                return(BllResultFactory.Error($"重新下发任务出错:{stationsResult.Msg}"));
                            }
                            //这些站台要在可用的站台列表中并选取离堆垛机最近的一个站台
                            var station = stationsResult.Data.Where(t => availableOutStation.Exists(a => a.Code == t.Code)).OrderBy(t => CurrentColumn - t.ColumnIndex).FirstOrDefault();
                            if (station == null)
                            {
                                Logger.Log($"堆垛机{srm.Name}当前没有可用的站台可以放货,任务:{taskForResend.Id}", LogLevel.Warning);
                                return(BllResultFactory.Error());
                            }
                            else
                            {
                                return(ReSendTask(srm, plc, station.RowIndex1.ToString(), "0", "0", station.StationIndex.ToString(), taskForResend, SRMForkTaskFlag.库外放货));
                            }
                        }

                        #endregion

                        //判断堆垛机货叉上是不是有货,有货就只能接受放货任务,无货就可以接受取货任务
                        if (srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1HasPallet.ToString()).Value == "True")
                        {
                            //有货,则查找同巷道的取货任务完成状态的任务,同一个堆垛机,单叉情况下最多一条
                            #region 判断是否超出一条
                            if (tasks.Count(t => (t.TaskStatus == TaskEntityStatus.响应堆垛机库内取货完成.GetIndexInt() || t.TaskStatus == TaskEntityStatus.响应堆垛机库外取货完成.GetIndexInt()) && t.Gateway == srm.Code) > 1)
                            {
                                Logger.Log($"堆垛机{srm.Name}显示货叉上有货,但是对应的任务超过1条,请检查状态为{TaskEntityStatus.响应堆垛机库内取货完成}" +
                                           $"和{TaskEntityStatus.响应堆垛机库外取货完成}的任务", LogLevel.Error);
                                return(BllResultFactory.Error());
                            }
                            #endregion

                            //添加任务号进行判断
                            int taskNo = int.Parse(srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1TaskNo.ToString()).Value);
                            //先找库内取货完成的任务
                            var task = tasks.FirstOrDefault(t => t.TaskStatus == TaskEntityStatus.响应堆垛机库内取货完成.GetIndexInt() && t.Gateway == srm.Code);
                            if (task == null)
                            {
                                //如果没有就找库外取货完成的任务,此任务以ArrivaEquipmentCode去查找堆垛机任务
                                task = tasks.FirstOrDefault(t => t.TaskStatus == TaskEntityStatus.响应堆垛机库外取货完成.GetIndexInt() && t.Gateway == srm.Code);
                            }
                            if (task == null)
                            {
                                //如果还是没有找到任务,那就说明的确没有这条任务,或是人为原因导致的,但此时又显示货叉有货,所以这里是有问题的,做个日志
                                Logger.Log($"堆垛机{srm.Name}显示货叉上有货,但是没有对应的任务", LogLevel.Error);
                                return(BllResultFactory.Error());
                            }
                            else
                            {
                                if (task.Id != taskNo)
                                {
                                    Logger.Log($"堆垛机{srm.Name}显示货叉上有货,并且找到对应的任务:{task.Id},但是和堆垛机对应的任务号:{taskNo},出现偏差请核对", LogLevel.Error);
                                    return(BllResultFactory.Error());
                                }
                                //判断任务类型
                                //移库
                                if (task.TaskType == TaskType.移库.GetIndexInt())
                                {
                                    //是否同巷道
                                    var tempLocation = locationsRoadWay.FirstOrDefault(t => t.Code == task.ToLocationCode);
                                    if (tempLocation != null)
                                    {
                                        //同一个巷道,则直接下发库内放货
                                        return(SendTaskToLocation(srm, plc, task, tempLocation, TaskEntityStatus.发堆垛机库内放货, SRMForkTaskFlag.库内放货, task.TaskStatus));
                                    }
                                    else
                                    {
                                        //hack:默认不支持巷道间的移库,如需要则请按实际情况自行实现
                                        Logger.Log($"任务:{task.Id}对应去向货位{task.ToLocationCode}不在本巷道中,请检查任务数据", LogLevel.Error);
                                        return(BllResultFactory.Error());
                                    }
                                }
                                else if (task.TaskType == TaskType.整盘出库.GetIndexInt() || task.TaskType == TaskType.空容器出库.GetIndexInt() || task.TaskType == TaskType.换站.GetIndexInt())
                                {
                                    //整出任务,空盘出库和换站,都是奔着port去的:
                                    var stationsResult = AppSession.ExcuteService.GetOutStationByPort(srm.DestinationArea, task.ToPort, App.WarehouseCode);
                                    if (!stationsResult.Success)
                                    {
                                        Logger.Log($"未找到可出站台:" + stationsResult.Msg, LogLevel.Error);
                                        return(BllResultFactory.Error(stationsResult.Msg));
                                    }
                                    var station = stationsResult.Data.Where(t => availableOutStation.Exists(a => a.Code == t.Code)).OrderBy(t => CurrentColumn - t.ColumnIndex).FirstOrDefault();
                                    if (station == null)
                                    {
                                        Logger.Log($"堆垛机{srm.Name}当前没有可用的站台可以放货,任务:{task.Id}", LogLevel.Warning);
                                        return(BllResultFactory.Error());
                                    }
                                    else
                                    {
                                        return(SendTaskToStation(srm, plc, task, TaskEntityStatus.发堆垛机库外放货, SRMForkTaskFlag.库外放货, station, task.TaskStatus));
                                    }
                                }
                                else if (task.TaskType == TaskType.整盘入库.GetIndexInt() || task.TaskType == TaskType.空容器入库.GetIndexInt())
                                {
                                    //整盘入库、空盘入库:当前目的货位与堆垛机是否在同一个巷道,在,则下发库内放货任务;不在,报错;
                                    var tempLocation = locationsRoadWay.FirstOrDefault(t => t.Code == task.ToLocationCode);
                                    if (tempLocation != null)
                                    {
                                        //同一个巷道,则直接下发库内放货
                                        return(SendTaskToLocation(srm, plc, task, tempLocation, TaskEntityStatus.发堆垛机库内放货, SRMForkTaskFlag.库内放货, task.TaskStatus));
                                    }
                                    else
                                    {
                                        Logger.Log($"任务:{task.Id}对应去向货位{task.ToLocationCode}不在本巷道中,请检查任务数据", LogLevel.Error);
                                        return(BllResultFactory.Error());
                                    }
                                }
                                else if (task.TaskType == TaskType.出库查看.GetIndexInt() || task.TaskType == TaskType.分拣出库.GetIndexInt() ||
                                         task.TaskType == TaskType.盘点.GetIndexInt() || task.TaskType == TaskType.补充入库.GetIndexInt())
                                {
                                    //补充入库、分拣出库、盘点、出库查看:需要判断任务阶段来决定是出还是入
                                    //判断任务阶段
                                    if (task.Stage == TaskStageFlag.入.GetIndexInt())
                                    {
                                        //判断目标货位是否在当前巷道
                                        var tempLocation = locationsRoadWay.FirstOrDefault(t => t.Code == task.ToLocationCode);
                                        if (tempLocation != null)
                                        {
                                            //同一个巷道,则直接下发库内放货
                                            return(SendTaskToLocation(srm, plc, task, tempLocation, TaskEntityStatus.发堆垛机库内放货, SRMForkTaskFlag.库内放货, task.TaskStatus));
                                        }
                                        else
                                        {
                                            Logger.Log($"任务:{task.Id}对应去向货位{task.ToLocationCode}不在本巷道中,请检查任务数据", LogLevel.Error);
                                            return(BllResultFactory.Error());
                                        }
                                    }
                                    else
                                    {
                                        //出
                                        var stationsResult = AppSession.ExcuteService.GetOutStationByPort(srm.DestinationArea, task.ToPort, App.WarehouseCode);
                                        if (!stationsResult.Success)
                                        {
                                            return(BllResultFactory.Error(stationsResult.Msg));
                                        }
                                        var station = stationsResult.Data.Where(t => availableOutStation.Exists(a => a.Code == t.Code)).OrderBy(t => CurrentColumn - t.ColumnIndex).FirstOrDefault();
                                        if (station == null)
                                        {
                                            Logger.Log($"堆垛机{srm.Name}当前没有可用的站台可以放货,任务:{task.Id}", LogLevel.Warning);
                                            return(BllResultFactory.Error());
                                        }
                                        else
                                        {
                                            return(SendTaskToStation(srm, plc, task, TaskEntityStatus.发堆垛机库外放货, SRMForkTaskFlag.库外放货, station, task.TaskStatus));
                                        }
                                    }
                                }
                                else
                                {
                                    //报警,未知的任务类型
                                    Logger.Log($"堆垛机{srm.Name}对应的任务{task.Id}为未知的任务类型", LogLevel.Error);
                                    return(BllResultFactory.Error());
                                }
                            }
                        }
                        else
                        {
                            //无货,说明完全处在空闲状态
                            var tempTasks = tasks;
                            if (tempTasks.Count == 0)
                            {
                                return(BllResultFactory.Error());
                            }
                            else
                            {
                                //完全空闲的堆垛机实际只执行取货任务,则为库外取与库内取两种
                                //找出下发状态的待取的离堆垛机最近的任务,并且对应站台口需要可用
                                var task1s = tempTasks.Where(t => t.TaskStatus == TaskEntityStatus.发任务.GetIndexInt() &&
                                                             (t.TaskType == TaskType.出库查看.GetIndexInt() ||
                                                              t.TaskType == TaskType.分拣出库.GetIndexInt() ||
                                                              t.TaskType == TaskType.整盘出库.GetIndexInt() ||
                                                              t.TaskType == TaskType.盘点.GetIndexInt() ||
                                                              t.TaskType == TaskType.空容器出库.GetIndexInt() ||
                                                              t.TaskType == TaskType.补充入库.GetIndexInt() ||
                                                              t.TaskType == TaskType.移库.GetIndexInt()) &&
                                                             locationsRoadWay.Exists(a => a.Code == t.FromLocationCode)).ToList();
                                task1s.ForEach(t =>
                                {
                                    t.FromLocation    = locationsRoadWay.First(a => a.Code == t.FromLocationCode);
                                    t.ToPortEquipment = equipmentsRoadWay.FirstOrDefault(a => a.Code == t.ToPort);
                                });
                                //任务过滤条件,任务port对应的station要可用
                                task1s = task1s.Where(t => t.TaskType == (int)TaskType.移库 || (availableOutStation.Exists(a => AppSession.ExcuteService.GetOutStationByPort(srm.DestinationArea, t.ToPort, App.WarehouseCode).Data?.Exists(b => b.Code == a.Code) == true))).ToList();


                                //库内取货的任务
                                var task1 = task1s.OrderByDescending(t => t.Priority).ThenBy(t => Math.Abs((int)t.FromLocation.Line - CurrentColumn)).FirstOrDefault();

                                //本巷道接入口的任务
                                var task2s = tempTasks.Where(t => t.TaskStatus == TaskEntityStatus.响应接入站台到达.GetIndexInt() && equipmentsRoadWay.Exists(a => a.Code == t.Gateway)).ToList();
                                task2s.ForEach(t => t.ArrivaEquipment = equipmentsRoadWay.Find(a => a.Code == t.Gateway));
                                //按优先级以及站台与现有堆垛机的距离优先做调度,注意,接入的站台必须要在堆垛机可以到达的列之间
                                var task2 = task2s.Where(t => t.ArrivaEquipment.ColumnIndex >= minColumn && t.ArrivaEquipment.ColumnIndex <= maxColumn).OrderByDescending(t => t.Priority).ThenBy(t => Math.Abs(t.ArrivaEquipment.ColumnIndex - CurrentColumn)).FirstOrDefault();
                                if (task1 == null && task2 == null)
                                {
                                    //说明当前没有可以被执行的任务
                                    return(BllResultFactory.Sucess());
                                }
                                if (task2 != null)
                                {
                                    //说明库外取货任务不为空,则下发接入任务
                                    return(SendTaskToStation(srm, plc, task2, TaskEntityStatus.发堆垛机库外取货, SRMForkTaskFlag.库外取货, equipmentsRoadWay.Find(t => t.Code == task2.Gateway), task2.TaskStatus));
                                }
                                if (task1 != null)
                                {
                                    //说明库内取货任务不为空
                                    return(SendTaskToLocation(srm, plc, task1, task1.FromLocation, TaskEntityStatus.发堆垛机库内取货, SRMForkTaskFlag.库内取货, task1.TaskStatus));
                                }

                                //当两种任务均存在时,此处设置两种模式,出库优先与均衡模式(按堆垛机位置进行)
                                var configResult = AppSession.BllService.GetAllConfig();
                                var config       = configResult.Data?.FirstOrDefault(t => t.Code == ConfigStrings.OutFirst.ToString());
                                if (config == null || config.Value != "1")
                                {
                                    //均衡模式
                                    var dis1 = Math.Abs((int)task1.FromLocation.Line - CurrentColumn);
                                    var dis2 = Math.Abs(task2.ArrivaEquipment.RowIndex1 - CurrentColumn);
                                    if (dis1 <= dis2)
                                    {
                                        return(SendTaskToLocation(srm, plc, task1, task1.FromLocation, TaskEntityStatus.发堆垛机库内取货, SRMForkTaskFlag.库内取货, task1.TaskStatus));
                                    }
                                    else
                                    {
                                        return(SendTaskToStation(srm, plc, task2, TaskEntityStatus.发堆垛机库外取货, SRMForkTaskFlag.库外取货, equipmentsRoadWay.First(t => t.Code == task2.Gateway), task2.TaskStatus));
                                    }
                                }
                                else
                                {
                                    //出库优先模式
                                    return(SendTaskToLocation(srm, plc, task1, task1.FromLocation, TaskEntityStatus.发堆垛机库内取货, SRMForkTaskFlag.库内取货, task1.TaskStatus));
                                }
                            }
                        }
                    }
                    else
                    {
                        //hack:其他情况1-库内取货,2-库内放货,3-库外入库,4库外出库, 5重新分配入库地址,暂时不做处理,这里也应不需要处理这些情况
                    }
                }
                else if (srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1TaskExcuteStatus.ToString()).Value == SRMTaskExcuteStatus.任务完成.GetIndexString() &&
                         srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.WCSFork1TaskFlag.ToString()).Value != SRMForkTaskFlag.任务完成.GetIndexString())
                {
                    //一共4种完成情况
                    //根据任务号和货叉类型进行任务完成处理
                    int taskNo     = int.Parse(srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1TaskNo.ToString()).Value);
                    int forkType   = int.Parse(srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1TaskType.ToString()).Value);
                    var taskResult = AppSession.Dal.GetCommonModelByCondition <TaskEntity>($"where id = {taskNo}");
                    if (!taskResult.Success)
                    {
                        Logger.Log($"根据堆垛机任务号{taskNo}未找到任务:{taskResult.Msg}", LogLevel.Error);
                        return(BllResultFactory.Error());
                    }
                    var task        = taskResult.Data[0];
                    var tempStatus  = task.TaskStatus;
                    var tempGateWay = task.Gateway;
                    //库内取货完成
                    if (forkType == SRMForkTaskFlag.库内取货.GetIndexInt())
                    {
                        //更新任务状态
                        task.TaskStatus = TaskEntityStatus.响应堆垛机库内取货完成.GetIndexInt();
                        task.Gateway    = srm.Code; //标记当前堆垛机到任务
                        var tempResult = AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                        if (tempResult.Success)
                        {
                            //标记交换区地址,任务完成10
                            var prop = srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.WCSFork1TaskFlag.ToString());
                            prop.Value = SRMForkTaskFlag.任务完成.GetIndexString();
                            var sendResult = plc.Writes(new List <EquipmentProp> {
                                prop
                            });
                            if (sendResult.Success)
                            {
                                Logger.Log($"堆垛机{srm.Name}完成库内取货成功,任务:{task.Id}", LogLevel.Success);
                                return(BllResultFactory.Sucess());
                            }
                            else
                            {
                                Logger.Log($"堆垛机{srm.Name}完成库内取货失败,任务:{task.Id},原因:{sendResult.Msg}", LogLevel.Error);
                                task.TaskStatus = tempStatus;
                                task.Gateway    = tempGateWay;
                                AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                                return(BllResultFactory.Error());
                            }
                        }
                        else
                        {
                            Logger.Log($"完成堆垛机{srm.Name}库内取货时,更新任务{task.Id}状态失败:{tempResult.Msg}", LogLevel.Error);
                            return(BllResultFactory.Error($"完成堆垛机{srm.Name}库内取货时,更新任务{task.Id}状态失败:{tempResult.Msg}"));
                        }
                    }

                    //库内放货完成
                    else if (forkType == SRMForkTaskFlag.库内放货.GetIndexInt())
                    {
                        //本地完成任务,然后进行回传
                        var tempResult = AppSession.TaskService.CompleteTask(task.Id.Value, App.User.UserCode);
                        if (!tempResult.Success)
                        {
                            Logger.Log($"完成堆垛机{srm.Name}库内放货失败:{tempResult.Msg}", LogLevel.Error);
                            return(BllResultFactory.Error($"完成堆垛机{srm.Name}库内放货失败:{tempResult.Msg}"));
                        }
                        else
                        {
                            //标记交换区地址,任务完成10
                            var prop = srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.WCSFork1TaskFlag.ToString());
                            prop.Value = SRMForkTaskFlag.任务完成.GetIndexString();
                            var sendResult = plc.Writes(new List <EquipmentProp> {
                                prop
                            });
                            if (sendResult.Success)
                            {
                                Logger.Log($"堆垛机{srm.Name}完成库内放货成功,任务:{task.Id}", LogLevel.Success);
                                return(BllResultFactory.Sucess());
                            }
                            else
                            {
                                Logger.Log($"堆垛机{srm.Name}完成库内放货失败,请人工处理任务:{task.Id},原因:{sendResult.Msg}", LogLevel.Error);
                                return(BllResultFactory.Error());
                            }
                        }
                    }
                    //库外取货完成时
                    else if (forkType == SRMForkTaskFlag.库外取货.GetIndexInt())
                    {
                        //更新任务状态
                        task.TaskStatus = TaskEntityStatus.响应堆垛机库外取货完成.GetIndexInt();
                        task.Gateway    = srm.Code; //标记当前堆垛机到任务
                        var tempResult = AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                        if (tempResult.Success)
                        {
                            //标记交换区地址,任务完成10
                            var prop = srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.WCSFork1TaskFlag.ToString());
                            prop.Value = SRMForkTaskFlag.任务完成.GetIndexString();
                            var sendResult = plc.Writes(new List <EquipmentProp> {
                                prop
                            });
                            if (sendResult.Success)
                            {
                                Logger.Log($"堆垛机{srm.Name}完成库外取货成功,任务:{task.Id}", LogLevel.Success);
                                return(BllResultFactory.Sucess());
                            }
                            else
                            {
                                Logger.Log($"堆垛机{srm.Name}完成库外取货失败,任务:{task.Id},原因:{sendResult.Msg}", LogLevel.Error);
                                task.TaskStatus = tempStatus;
                                task.Gateway    = tempGateWay;
                                AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                                return(BllResultFactory.Error());
                            }
                        }
                        else
                        {
                            Logger.Log($"完成堆垛机{srm.Name}库外取货时,更新任务{task.Id}状态失败:{tempResult.Msg}", LogLevel.Error);
                            return(BllResultFactory.Error($"完成堆垛机{srm.Name}库外取货时,更新任务{task.Id}状态失败:{tempResult.Msg}"));
                        }
                    }
                    //库外放货完成时
                    else if (forkType == SRMForkTaskFlag.库外放货.GetIndexInt())
                    {
                        //库外放货时,堆垛机会携带站台Index,找到放货站台并更新到任务;
                        var currentStation = srm.EquipmentProps.FirstOrDefault(t => t.EquipmentTypeTemplateCode == SRMProps.CurrentStation.ToString());
                        if (currentStation == null)
                        {
                            Logger.Log($"未找到堆垛机{srm.Name}对应的出入口属性", LogLevel.Error);
                            return(BllResultFactory.Error());
                        }
                        var station = equipmentsRoadWay.FirstOrDefault(t => t.StationIndex?.ToString() == currentStation.Value && t.WarehouseCode == srm.WarehouseCode && t.DestinationArea == srm.DestinationArea);
                        if (station == null)
                        {
                            Logger.Log($"未找到堆垛机{srm.Name}对应的出入口{currentStation.Value}", LogLevel.Error);
                            return(BllResultFactory.Error());
                        }

                        //更新任务状态
                        task.TaskStatus = TaskEntityStatus.响应堆垛机库外放货完成.GetIndexInt();
                        //注意此处对应放货的具体接出站台
                        task.Gateway = station.Code;
                        var tempResult = AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                        if (tempResult.Success)
                        {
                            //标记交换区地址,任务完成10
                            var prop = srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.WCSFork1TaskFlag.ToString());
                            prop.Value = SRMForkTaskFlag.任务完成.GetIndexString();
                            var sendResult = plc.Writes(new List <EquipmentProp> {
                                prop
                            });
                            if (sendResult.Success)
                            {
                                Logger.Log($"堆垛机{srm.Name}完成库外放货成功,任务:{task.Id}", LogLevel.Success);
                                return(BllResultFactory.Sucess());
                            }
                            else
                            {
                                Logger.Log($"堆垛机{srm.Name}完成库外放货失败,任务:{task.Id},原因:{sendResult.Msg}", LogLevel.Error);
                                task.TaskStatus = tempStatus;
                                task.Gateway    = tempGateWay;
                                AppSession.Dal.UpdateCommonModel <TaskEntity>(task);
                                return(BllResultFactory.Error());
                            }
                        }
                        else
                        {
                            Logger.Log($"完成堆垛机{srm.Name}库外放货时,更新任务{task.Id}状态失败:{tempResult.Msg}", LogLevel.Error);
                            return(BllResultFactory.Error($"完成堆垛机{srm.Name}库外放货时,更新任务{task.Id}状态失败:{tempResult.Msg}"));
                        }
                    }
                    return(BllResultFactory.Sucess());
                }
                else
                {
                    //未知情况
                    Logger.Log($"堆垛机{srm.Name}执行中,执行状态为:{srm.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == SRMProps.Fork1TaskExcuteStatus.ToString()).Value};可能由于WCS还未处理造成", LogLevel.Warning);
                    return(BllResultFactory.Sucess());
                }
            }
            return(BllResultFactory.Sucess());
        }
        /// <summary>
        /// 请求
        /// </summary>
        /// <param name="station"></param>
        /// <param name="allEquipments"></param>
        /// <param name="plc"></param>
        /// <returns></returns>
        public override BllResult ExcuteRequest(Equipment station, List <Equipment> allEquipments, IPLC plc)
        {
            var    barcode       = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestBarcode.ToString()).Value;
            var    requestNumber = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestNumber.ToString()).Value;
            var    height        = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestHeight.ToString()).Value;
            var    weight        = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestWeight.ToString()).Value;
            var    length        = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestLength.ToString()).Value;
            var    width         = station.EquipmentProps.Find(t => t.EquipmentTypeTemplateCode == StationProps.RequestWidth.ToString()).Value;
            string goAddress     = "";
            string backAddress   = "";

            if (string.IsNullOrWhiteSpace(barcode))
            {
                SendBack(station, plc, barcode);
                return(BllResultFactory.Error($"站台{station.Code}{station.Name}有地址请求但是没有条码信息"));
            }
            else
            {
                //获取任务
                var stepTraces = AppSession.Dal.GetCommonModelByConditionWithZero <StepTrace>($"where id = {barcode}");
                if (stepTraces.Success)
                {
                    if (stepTraces.Data.Count > 1)
                    {
                        SendBack(station, plc, barcode);
                        return(BllResultFactory.Error($"站台{station.Code}{station.Name}根据条码{barcode}查找到了多条任务,请检查任务数据"));
                    }
                    if (stepTraces.Data.Count == 0)
                    {
                        return(BllResultFactory.Error($"站台{station.Code}{station.Name}根据条码{barcode}没有找到任务,请检查任务数据"));
                    }
                    else
                    {
                        var stepTrace = stepTraces.Data[0];
                        goAddress = station.GoAddress;
                        if (string.IsNullOrWhiteSpace(goAddress))
                        {
                            return(BllResultFactory.Error($"站台{station.Code}{station.Name}去向地址为空,请检查设备基础数据"));
                        }
                        else
                        {
                            if (stepTrace.Status > StepTraceStatus.设备开始生产.GetIndexInt())
                            {
                                SendAddressReplyToPlc(station, plc, StationMessageFlag.地址回复, StationLoadStatus.默认, requestNumber, barcode, weight, length, width, height, goAddress, backAddress);
                                Logger.Log($"站台{station.Code}{station.Name}根据id[{barcode}]请求任务的任务状态大于 {StepTraceStatus.设备开始生产},直接回复请求", LogLevel.Success);
                                return(BllResultFactory.Error());
                            }
                            var nextEquipment = allEquipments.FirstOrDefault(t => t.SelfAddress == goAddress);
                            if (nextEquipment != null)
                            {
                                //var stationId = stepTrace.StationId;
                                //stepTrace.StationId = nextEquipment.StationId;
                                //var updateResult = AppSession.Dal.UpdateCommonModel<StepTrace>(stepTrace);
                                //if (updateResult.Success)
                                //{
                                var temp = SendAddressReplyToPlc(station, plc, StationMessageFlag.地址回复, StationLoadStatus.默认,
                                                                 requestNumber, barcode, weight, length, width, height, goAddress, backAddress);
                                if (temp.Success)
                                {
                                    return(BllResultFactory.Sucess($"响应站台{station.Code}{station.Name}地址请求成功,条码{barcode},任务{stepTrace.Id}"));
                                }
                                else
                                {
                                    //stepTrace.StationId = stationId;
                                    //AppSession.Dal.UpdateCommonModel<StepTrace>(stepTrace);
                                    return(BllResultFactory.Error($"响应站台{station.Code}{station.Name}地址请求失败,条码{barcode},任务{stepTrace.Id},写入PLC失败:{temp.Msg}"));
                                }
                                //}
                                //else
                                //{
                                //    return BllResultFactory.Error($"响应站台{station.Code}{station.Name}地址请求失败,更新当前站台失败,任务{stepTrace.Id},原因:{updateResult.Msg}");
                                //}
                            }
                            else
                            {
                                return(BllResultFactory.Error($"站台{station.Code}{station.Name}去向地址没有对应的设备,请检设备查数据"));
                            }
                        }
                    }
                }
                else
                {
                    SendBack(station, plc, barcode);
                    return(BllResultFactory.Error($"站台{station.Code}{station.Name}根据条码{barcode}没有查询到任务:{stepTraces.Msg}"));
                }
            }
        }
 public override BllResult ExcuteRequest(Equipment station, List <Equipment> allEquipments, IPLC plc)
 {
     Logger.Log($"堆垛机接入站台{station.Code}{station.Name}不执行请求处理", LogLevel.Error);
     return(BllResultFactory.Error());
 }