ContainerManager.cs 18.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
using Asa;
using HalconDotNet;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace OnlineStore.DeviceLibrary
{
    public class ContainerManager
    {
        public static int mTimeOut = 200;
        public static int StopDTime = 2000;
        /// <summary>
        /// 容器集合,key=容器编号,value=托盘详细信息
        /// </summary>
        private static ConcurrentDictionary<string, ContainerInfo> containerInfoMap = new ConcurrentDictionary<string, ContainerInfo>();

        /// <summary>
        /// 容器错误消息
        /// </summary>
        public static string TrayErrorMsg = "";
        /// <summary>
        /// 容器错误的设备ID
        /// </summary>
        public static string ErrorContainerId = "";

        static ContainerManager()
        {
        }
        public static List<ContainerInfo> getTrayList()
        {
            return new List<ContainerInfo>(containerInfoMap.Values);
        }
        /// <summary>
        /// 在线体上的料箱数量
        /// </summary>
        /// <returns></returns>
        public static int CntofContainerOnLine()
        {
            try
            {
              List<ContainerInfo> containers=  getTrayList().FindAll(s=>(s.Status.Equals(TaskStatus.IN_ON_LINE) || s.Status.Equals(TaskStatus.OUT_ON_LINE)));
                if(containers!=null)
                {
                    return containers.Count;
                }
            }
            catch (Exception ex)
            {
                LogUtil.error($"CntofContainerOnLine", ex);
            }
            return 0;
        }
        /// <summary>
        ///处理未发送AGV任务的容器
        /// </summary>
        /// <returns></returns>
        public static void HandlePendingTask()
        {
            List<ContainerInfo> outstores = getTrayList().FindAll(s => s.Status.Equals(TaskStatus.WAIT) && s.InOrOutStore.Equals(ContainerType.OutStore));
            List<ContainerInfo> instores = getTrayList().FindAll(
                    s => s.InOrOutStore.Equals(ContainerType.InStore) && s.Status.Equals(TaskStatus.WAIT));
            if (outstores != null && outstores.Count > 0)
            {
                SServerManager.CreateOutStoreOrder(outstores);
            }
            if (instores != null && instores.Count > 0)
            {
                SServerManager.CreateInStoreOrder(instores);
            }
        }
        public static void UpdateContainerStatus()
        {
            foreach (var item in getTrayList())
            {
                bool rtn = SServerManager.UpdateLocInfo("ContainerManager", item.ContainerValidCode, item.Status, item.CurLoc);
                if (rtn)
                {
                    if (item.Status.Equals(TaskStatus.ERROR))
                    {
                        bool res = containerInfoMap.TryRemove(item.ContainerValidCode, out ContainerInfo containerInfo);
                        LogUtil.info($"因任务异常,自动删除该任务【{res}】:【{JsonHelper.SerializeObject(containerInfo)}】");
                    }
                    else if (item.Status.Equals(TaskStatus.FINISHED))
                    {
                        bool res = containerInfoMap.TryRemove(item.ContainerValidCode, out ContainerInfo containerInfo);
                        LogUtil.info($"任务完成【{res}】:【{JsonHelper.SerializeObject(containerInfo)}】");
                    }
                }
            }
        }
        public static ContainerInfo GetTrayInfo(string trayNum)
        {

            if (containerInfoMap.ContainsKey(trayNum))
            {
                return containerInfoMap[trayNum];
            }
            return null;
        }
        /// <summary>
        /// 获取在线体上的出库箱子
        /// </summary>
        /// <param name="boxId"></param>
        /// <returns>true,存在</returns>
        public static bool GetOutStoreBox(string boxId)
        {
            ContainerInfo container = GetTrayInfo(boxId);
            try
            {
                if (container != null)
                {
                    if (container.InOrOutStore.Equals(ContainerType.OutStore))//&& (container.Status.Equals(TaskStatus.OUT_ON_LINE) || container.Status.Equals(TaskStatus.NEED_AWAY))
                    {
                        return true;
                    }
                }
                else
                {
                    //LogUtil.error($"未找到容器信息: {boxId}");
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogUtil.error($"GetOutStoreBox {boxId}", ex);
            }
            return false;
        }
        /// <summary>
        /// 站点是否有箱子准备进入
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        internal static bool StationHasInTask(int deviceId, out InOutParam inOutParam)
        {
            inOutParam = new InOutParam();
            int cnt = ContainerManager.GetInTaskCnt(deviceId);
            if (deviceId == 5)
            {
                if ((IOManager.IOValue(IO_Type.FrontStop_BoxCheck, deviceId).Equals(IO_VALUE.HIGH) ||
                    IOManager.IOValue(IO_Type.Stop_BoxCheck, deviceId).Equals(IO_VALUE.HIGH)))
                    return true;
            }
            else
            {
                if (cnt > 0 && (IOManager.IOValue(IO_Type.FrontStop_BoxCheck, deviceId).Equals(IO_VALUE.HIGH) ||
                        IOManager.IOValue(IO_Type.Stop_BoxCheck, deviceId).Equals(IO_VALUE.HIGH)))
                    return true;
            }


            return false;
        }
        /// <summary>
        /// 站点是否有箱子准出去
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="inOutParam"></param>
        /// <returns></returns>
        internal static bool StationHasOutTask(int deviceId, out InOutParam inOutParam)
        {
            inOutParam = new InOutParam();
            if (GetOutTaskCnt(deviceId, out ContainerInfo containerInfo))
            {
                inOutParam.Containercode = containerInfo.ContainerValidCode;
                return true;
            }
            return false;
        }
        /// <summary>
        /// 获取该工位需要出去的箱子
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        internal static int GetOutTaskCnt(int deviceId)
        {
            List<ContainerInfo> containerInfos = getTrayList().FindAll(s => s.InOrOutStore.Equals(ContainerType.InStore)
            && s.InoutParam.DeviceId.Equals(deviceId) && (s.Status.Equals(TaskStatus.EXECUTING) || s.Status.Equals(TaskStatus.WAIT)));
            return containerInfos?.Count ?? 0;
        }
        internal static bool GetOutTaskCnt(int deviceId, out ContainerInfo containerInfo)
        {
            containerInfo = getTrayList().Find(s => s.InOrOutStore.Equals(ContainerType.InStore) && s.InoutParam.DeviceId.Equals(deviceId) && s.Status.Equals(TaskStatus.EXECUTING));
            return containerInfo != null;
        }
        /// <summary>
        /// 获取属于该工位的箱子
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        internal static int GetInTaskCnt(int deviceId)
        {
            List<ContainerInfo> containerInfos = getTrayList().FindAll(s => s.InOrOutStore.Equals(ContainerType.OutStore) && s.InoutParam.DeviceId.Equals(deviceId));
            return containerInfos?.Count ?? 0;
        }

        static List<string> stationNames = new List<string> { "s1", "s2", "s3", "s4", "s5" };
        /// <summary>
        /// 站点有入库任务
        /// </summary>
        /// <param name="barcode"></param>
        /// <returns></returns>
        public static bool HasInstore(ContainerTarget containerTarget, out string slotCode)
        {
            slotCode = "";
            //deviceId = 0;
            if (containerTarget != null)
            {
                if (stationNames.Contains(containerTarget.slotCode))//有出库的料
                {

                }
                else if (containerTarget.slotCode.Equals("s0"))//站点分拣台已有容器
                {

                }
                else //有入库的料
                {
                    slotCode = containerTarget.slotCode;
                    //int.TryParse(slotCode.Substring(1), out deviceId);
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 站点有出库任务
        /// </summary>
        /// <param name="devicename">s+站点编号</param>
        /// <param name="barcode"></param>
        /// <returns></returns>
        public static bool HasOutstore(ContainerTarget containerTarget, out int deviceId)
        {
            deviceId = 0;
            if (containerTarget != null)
            {
                if (stationNames.Contains(containerTarget.slotCode))//有出库的料
                {
                    bool rtn = int.TryParse(containerTarget.slotCode.Substring(1), out deviceId);
                    return rtn;
                }
                else if (containerTarget.slotCode.Equals("s0"))//站点分拣台已有容器
                {
                    return true;
                }
                else //有入库的料
                {

                }
            }
            return false;
        }
        /// <summary>
        /// 工作台已有箱子
        /// </summary>
        /// <param name="devicename"></param>
        /// <param name="barcode"></param>
        /// <returns></returns>
        public static bool HasBoxInStation(ContainerTarget containerTarget)
        {
            if (containerTarget != null)
            {
                if (stationNames.Contains(containerTarget.slotCode))//有出库的料
                {

                }
                else if (containerTarget.slotCode.Equals("s0"))//站点分拣台已有容器
                {
                    return true;
                }
                else //有入库的料
                {

                }
            }
            return false;
        }
        
        public static void AddOrUpdateContainerInfo(string containerCode)
        {
            if (string.IsNullOrEmpty(containerCode)) return;
            if (containerCode.EndsWith("A") || containerCode.EndsWith("B"))
            {
                containerCode = containerCode.Substring(0, containerCode.Length - 1);
            }
            if (containerInfoMap.ContainsKey(containerCode))
            {
                //不更新
                return;
            }
            else
            {
                //获取服务端数据并添加容器信息
                ContainerTarget containerTarget = SServerManager.GetContainerTarget("AddOrUpdateContainerInfo", containerCode);
                if (containerTarget != null)
                {
                    if (containerTarget.slotCode.Equals("0") || containerTarget.barcode.Equals(""))
                    {
                        UpdateContainerNumError(containerCode, "容器无目的地信息,请检查");
                        return;
                    }
                    UpdateContainerNumError("", "");
                    int deviceId = 0;
                    ContainerType containerType = ContainerType.None;
                    if (HasInstore(containerTarget, out string slotCode))
                    {
                        containerType = ContainerType.InStore;
                    }
                    else if (HasOutstore(containerTarget, out deviceId))
                    {
                        containerType = ContainerType.OutStore;

                    }
                    else if (HasBoxInStation(containerTarget))
                    {
                        return;
                    }
                    ContainerInfo info = new ContainerInfo(containerTarget.barcode, containerType, slotCode, deviceId);
                    containerInfoMap.TryAdd(containerTarget.barcode, info);
                }
                SaveMapToFile();
            }
        }
        public static void AddOrUpdateContainerInfo(string stationName, string containerCode)
        {
            if (string.IsNullOrEmpty(containerCode)) return;
            if (containerCode.EndsWith("A") || containerCode.EndsWith("B"))
            {
                containerCode = containerCode.Substring(0, containerCode.Length - 1);
            }
            if (containerInfoMap.ContainsKey(containerCode))
            {
                //不更新
                return;
            }
            else
            {
                //获取服务端数据并添加容器信息
                ContainerTarget containerTarget = SServerManager.GetContainerTarget("AddOrUpdateContainerInfo", containerCode);
                if (containerTarget != null)
                {
                    if (containerTarget.slotCode.Equals("0") || containerTarget.barcode.Equals(""))
                    {
                        UpdateContainerNumError(containerCode, $"容器目的地信息异常:{containerTarget.slotCode},请检查");
                        return;
                    }
                    UpdateContainerNumError("", "");
                    int deviceId = 0;
                    ContainerType containerType = ContainerType.None;
                    if (HasInstore(containerTarget, out string slotCode))
                    {
                        containerType = ContainerType.InStore;
                        int.TryParse(stationName.Substring(1), out deviceId);
                    }
                    else if (HasOutstore(containerTarget, out deviceId))
                    {
                        containerType = ContainerType.OutStore;

                    }
                    else if (HasBoxInStation(containerTarget))
                    {
                        return;
                    }
                    ContainerInfo info = new ContainerInfo(containerTarget.barcode, containerType, slotCode, deviceId);
                    containerInfoMap.TryAdd(containerTarget.barcode, info);
                }
                SaveMapToFile();
            }
        }
        /// <summary>
        /// 更新任务状态
        /// </summary>
        /// <param name="barcode"></param>
        /// <param name="status"></param>
        public static void UpdateTaskStatus(string barcode, string status, string loc = "")
        {
            if (containerInfoMap.ContainsKey(barcode))
            {
                LogUtil.info($"已有缓存,更新容器状态:【{barcode}】【{status}】");
                containerInfoMap[barcode].UpdateStatus(status, loc);
            }
            else
            {
                LogUtil.info($"更新容器状态:【{barcode}】【{status}】");
                AddOrUpdateContainerInfo(barcode);
                UpdateTaskStatus(barcode, status);
            }
            SaveMapToFile();
        }
        /// <summary>
        /// 是否存在容器编码
        /// </summary>
        /// <param name="barcode"></param>
        /// <returns></returns>
        public static bool CheckContainerCode(string barcode)
        {
            return containerInfoMap.ContainsKey(barcode);
        }
        internal static void UpdateContainerNumError(string containerId, string errorMsg)
        {
            TrayErrorMsg = errorMsg;
            ErrorContainerId = containerId;
        }

        public static void ClearTrayInfo()
        {
            LogUtil.info("---------点击:清空容器,清空前打印容器信息----------");
            List<ContainerInfo> tray = ContainerManager.getTrayList();
            foreach (ContainerInfo t in tray)
            {
                LogUtil.info(t.ToStr());
            }
            containerInfoMap = new ConcurrentDictionary<string, ContainerInfo>();
            SaveMapToFile();
            LogUtil.info("---------点击:清空容器,容器内容已清空----------");
            MessageBox.Show("所有容器内容已清空");
        }


        private static string FilePath = "";
        public static void InitFileData()
        {
            containerInfoMap = new ConcurrentDictionary<string, ContainerInfo>();
            FilePath = Application.StartupPath + ConfigAppSettings.GetValue(Setting_Init.ConfigPath_TrayList);
            if (File.Exists(FilePath))
            {
                LogUtil.info("开始加载容器缓存信息:" + FilePath);
                string[] lines = FileEncoding.GetFileLines(FilePath);
                foreach (string line in lines)
                {
                    ContainerInfo tray = JsonHelper.DeserializeJsonToObject<ContainerInfo>(line);
                    if (tray != null && !string.IsNullOrEmpty(tray.ContainerValidCode))
                    {
                        LogUtil.info("加载到缓存容器:" + tray.ToStr());
                        containerInfoMap.TryAdd(tray.ContainerValidCode, tray);
                    }
                }
                LogUtil.info("容器缓存信息加载完成");
            }
        }
        static object saveObj = new object();
        static void SaveMapToFile()
        {
            LogUtil.info("SaveMapToFile");
            if (Monitor.TryEnter(saveObj, 500))
            {
                try
                {
                    List<ContainerInfo> trayList = new List<ContainerInfo>(containerInfoMap.Values);
                    List<string> lineList = new List<string>();
                    foreach (ContainerInfo tray in trayList)
                    {
                        string line = JsonHelper.SerializeObject(tray);
                        if (!string.IsNullOrEmpty(line))
                        {
                            lineList.Add(line);
                        }
                    }
                    FileEncoding.WritteFile(FilePath, lineList.ToArray());
                }
                catch (Exception ex)
                {
                    LogUtil.error("SaveContainerToFile出错:" + ex.ToString());
                }
                finally
                {
                    Monitor.Exit(saveObj);
                }
            }
        }
    }
}