From 48d66a079c307356997fb400d27907ff6d363b7b Mon Sep 17 00:00:00 2001
From: liudl <673013083@qq.com>
Date: 星期一, 20 一月 2025 08:35:37 +0800
Subject: [PATCH] 修改2楼分拣和1楼拆垛时获取拆垛信息接口

---
 Admin.NET/WCS.Application/PLC/PLCTaskAction.cs |  421 ++++++++++++++++++++++++++++++++++++++++++++--------
 1 files changed, 356 insertions(+), 65 deletions(-)

diff --git a/Admin.NET/WCS.Application/PLC/PLCTaskAction.cs b/Admin.NET/WCS.Application/PLC/PLCTaskAction.cs
index 47c28e2..311e7ce 100644
--- a/Admin.NET/WCS.Application/PLC/PLCTaskAction.cs
+++ b/Admin.NET/WCS.Application/PLC/PLCTaskAction.cs
@@ -1,6 +1,10 @@
 锘縰sing Admin.NET.Core.Service;
+using DocumentFormat.OpenXml.Drawing;
 using Furion.Logging;
 using Microsoft.AspNetCore.SignalR;
+using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
+using System;
+//using WCS.Application.Util;
 
 namespace WCS.Application;
 public static class PLCTaskAction
@@ -11,61 +15,102 @@
     public static bool boOffline = false;
     //鑷埛鏂�
     public static bool boRefresh = false;
+    //婕旂ず妯″紡
+    public static bool boDemo = false;
+    //婊氱瓛鍙嶈浆
+    public static bool boDrumReversal = false;
+    //鍑哄簱閿佸畾
+    public static bool boOutLock = false;
+    //鍏ュ簱閿佸畾
+    public static bool boEnterLock = false;
+
+    public static List<PlcPositionInfo> listPositionInfo = new List<PlcPositionInfo>();
 
     private static readonly ISqlSugarClient _db = SqlSugarSetup.ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
     private static readonly SysCacheService sysCacheService = App.GetRequiredService<SysCacheService>();
-    private static readonly IHubContext<PlcHub, IPlcHub> _plcHubContext;
+    private static readonly SysConfigService _sysConfigService = App.GetService<SysConfigService>();
 
-    private static List<WcsPlc> listPlc;
-    private static List<WcsDevice> listPlcDevice;
-    private static List<WcsPosition> listPlcStation;
+    private static List<WcsPlc> listPlc = new List<WcsPlc>();
+    private static List<WcsDevice> listPlcDevice = new List<WcsDevice>();
+    private static List<WcsPosition> listPlcPosition = new List<WcsPosition>();
+    private static List<WcsAlarmInfo> listAlarmInfo = new List<WcsAlarmInfo>();
 
     private static List<PLCUtil> listPlcUtil = new List<PLCUtil>();
-    private static CancellationTokenSource cts;//鍙栨秷绾跨▼鏍囪瘑
-
+    private static CancellationTokenSource cts = new CancellationTokenSource();//鍙栨秷绾跨▼鏍囪瘑
+    //瀵瑰鍏竷杩炴帴鐘舵��
+    public static List<PLCUtil> listPlcConn
+    {
+        get { return listPlcUtil; }
+    }
+    // 浜や簰鐐归泦鍚�
+    public static List<WcsDevice> plcDevices
+    {
+        get { return listPlcDevice; }
+    }
+    public static List<WcsPosition> plcPositions
+    {
+        get { return listPlcPosition; }
+    }
     public static event EventHandler DeviceValueChangeEvent;
     static PLCTaskAction()
     {
         //璁㈤槄浜嬩欢
         DeviceValueChangeEvent += PLCService.OnChangeEvent;
-
-        listPlc = _db.Queryable<WcsPlc>().ToList();
-        listPlcDevice = _db.Queryable<WcsDevice>().ToList();
-        listPlcStation = _db.Queryable<WcsPosition>().ToList();
+        boRunningState = _sysConfigService.GetConfigValue<bool>("sys_RunningState").Result;
+        boOffline = _sysConfigService.GetConfigValue<bool>("sys_Offline").Result;
+        boRefresh = _sysConfigService.GetConfigValue<bool>("sys_Refresh").Result;
+        boDemo = _sysConfigService.GetConfigValue<bool>("sys_demo").Result;
+        boDrumReversal = _sysConfigService.GetConfigValue<bool>("sys_DrumReversal").Result;
+        boOutLock = _sysConfigService.GetConfigValue<bool>("sys_BoOutLock").Result;
+        boEnterLock = _sysConfigService.GetConfigValue<bool>("sys_BoEnterLock").Result;
     }
     /// <summary>
     /// 鍒濆鍖朠LC杩炴帴
     /// </summary>
     public static void Init()
     {
-        if (listPlcUtil.Count != 0)
+        // var strMsg = new HttpService().RequestPackWcs("LN000001");
+        cts.Cancel();
+        listPlc = _db.Queryable<WcsPlc>()
+            .Where(s => s.Type == PLCTypeEnum.StackingMachine || s.Type == PLCTypeEnum.ConveyorLine || s.Type == PLCTypeEnum.BoxConveyorLine || s.Type == PLCTypeEnum.StackingRobot)
+            .Where(s => s.Enable == YesNoEnum.Y)
+            .ToList();
+        listPlcDevice = _db.Queryable<WcsDevice>().ToList();
+        listPlcPosition = _db.Queryable<WcsPosition>().ToList();
+        listAlarmInfo = _db.Queryable<WcsAlarmInfo>().ToList();
+        //绛夊緟鍑犵閽燂紝鎶婂凡鏈夌嚎绋嬪彇娑堟帀鍐嶈繛鎺�
+        //Thread.Sleep(5000);
+        foreach (var modPlcUtil in listPlcUtil)
         {
-            cts.Cancel();
-            listPlc = _db.Queryable<WcsPlc>().Where(s => s.Type == PLCTypeEnum.StackingMachine || s.Type == PLCTypeEnum.ConveyorLine || s.Type == PLCTypeEnum.BoxConveyorLine).ToList();
-            listPlcDevice = _db.Queryable<WcsDevice>().ToList();
-            listPlcStation = _db.Queryable<WcsPosition>().ToList();
-            //绛夊緟鍑犵閽燂紝鎶婂凡鏈夌嚎绋嬪彇娑堟帀鍐嶈繛鎺�
-            Thread.Sleep(5000);
-            foreach (var modPlcUtil in listPlcUtil)
-            {
-                modPlcUtil.Close();
-            }
-            listPlcUtil.Clear();
+            modPlcUtil.Close();
         }
+        listPlcUtil.Clear();
         foreach (var modPlc in listPlc)
         {
             var plc = new PLCUtil(modPlc);
             listPlcUtil.Add(plc);
         }
-        cts = new CancellationTokenSource();
-        boRunningState = true;
-        StartRead();
+        HubUtil.UpdateService(new PLCServiceModel()
+        {
+            BoRunningState = boRunningState,
+            BoOffline = boOffline,
+            BoRefresh = boRefresh
+        });
+        if (boRunningState)
+        {
+            cts = new CancellationTokenSource();
+            StartRead();
+            ConnectionStatus();
+            StartWatchAlarm();
+            StartWatchPosition();
+        }
     }
     /// <summary>
     /// 寮�鍚鍙杙lc绾跨▼
     /// </summary>
     public static void StartRead()
     {
+        Console.WriteLine("寮�鍚鍙杙lc绾跨▼");
         foreach (var modPlc in listPlc)
         {
             Task.Run(() =>
@@ -78,47 +123,67 @@
                     {
                         foreach (var modPlcUtil in listPlcUtil)
                         {
-                            modPlcUtil.Close();
+                            if (modPlcUtil != null && modPlcUtil.Connected)
+                                modPlcUtil.Close();
                         }
-                        throw new OperationCanceledException();
+                        break;
+                        //throw new OperationCanceledException();
                     }
                     try
                     {
-                        var modPlcUtil = listPlcUtil.FirstOrDefault(s => s.PlcId == modPlc.Id);
+                        var modPlcUtil = listPlcUtil.FirstOrDefault(s => s != null && s.PlcId == modPlc.Id);
                         if (modPlcUtil == null)
                         {
+                            Console.WriteLine($"杩炴帴plc{modPlc.IP}");
                             modPlcUtil = new PLCUtil(modPlc);
                             listPlcUtil.Add(modPlcUtil);
+                            if (modPlcUtil.Connected)
+                                Console.WriteLine($"杩炴帴plc{modPlc.IP}鎴愬姛");
                         }
-                        var listDevice = listPlcDevice.Where(s => s.PlcId == _modplc.Id).ToList();
+                        if (!modPlcUtil.Connected)
+                        {
+                            Thread.Sleep(1000);
+                            modPlcUtil.Open();
+                            continue;
+                        }
+                        var listDevice = listPlcDevice
+                            .Where(s => s.PlcId == _modplc.Id && s.DeviceType == DeviceTypeEnum.Business)
+                            .WhereIF(modPlc.Type == PLCTypeEnum.ConveyorLine, s => s.Level == DeviceLevelEnum.Station)
+                            .WhereIF(modPlc.Type == PLCTypeEnum.StackingMachine, s => s.Level == DeviceLevelEnum.DB)
+                            .ToList();
+
                         //寰幆璇昏澶�
-                        foreach (var modDevice in listDevice.Where(s => s.Level == DeviceLevelEnum.DB))
+                        foreach (var modDevice in listDevice)
                         {
                             var (result, value) = modPlcUtil.GetPlcDBValue(modDevice.PosType, modDevice.DbNumber, modDevice.PlcPos);
+                            //if (!result.IsSucceed)
+                            //    Console.WriteLine($"{modPlc.IP}閿欒{modDevice.DbNumber}.{modDevice.PlcPos}锛�"+result.Err);
                             if (result.IsSucceed)
                             {
+                                //Console.WriteLine($"{modPlc.IP}璇诲彇{modDevice.DbNumber}.{modDevice.PlcPos}鐨勫�间负锛歿value}");
                                 //鏃犳祦绋嬭烦鍑�
-                                if (value == 0)
+                                if (value == 0)// && modPlc.Type!= PLCTypeEnum.BoxConveyorLine
                                     continue;
                                 var dto = modDevice.Adapt<WcsDeviceDto>();
                                 dto.Value = value;
                                 dto.Type = _modplc.Type;
                                 dto.PLCUtil = modPlcUtil;
-                                dto.listStation = listPlcStation.Where(s => s.DeviceId == modDevice.Id).ToList();
-                                dto.listDevice = listDevice.Where(s => s.StationNum == modDevice.StationNum).ToList();
+                                dto.listStation = listPlcPosition.Where(s => s.DeviceId == modDevice.Id).ToList();
+                                dto.listDevice = listDevice.Where(s => s.StationNum == modDevice.StationNum && s.Level == DeviceLevelEnum.Station).ToList();
                                 //杩欓噷瑙﹀彂鍊煎彉鏇翠簨浠�
                                 DeviceValueChangeEvent?.Invoke(dto, EventArgs.Empty);
                             }
-                            else
+                            else if (!modPlcUtil.Connected)
                             {
-                                //鍒犻櫎褰撳墠杩炴帴 涓嬩竴娆″惊鐜噸鏂拌繛鎺�
-                                Console.WriteLine("杩炴帴鏂紑...");
-                                modPlcUtil.Close();
-                                listPlcUtil.Remove(modPlcUtil);
+                                //Console.WriteLine($"杩炴帴鏂紑...{modPlc.IP}");
+                                //閲嶆柊鎵撳紑杩炴帴
+                                modPlcUtil.Open();
+                                //if (modPlcUtil.Connected)
+                                //    Console.WriteLine($"閲嶈繛鎴愬姛...{modPlc.IP}");
                             }
                         }
 
-                        Thread.Sleep(3000);
+                        Thread.Sleep(1000);
                     }
                     catch (OperationCanceledException)
                     {
@@ -126,7 +191,7 @@
                     }
                     catch (Exception ex)
                     {
-                        Log.Error(ex.Message, ex);
+                        Log.Error("璇诲彇PLC绾跨▼鍙戠敓寮傚父", ex);
                     }
                 }
             }, cts.Token);
@@ -142,35 +207,47 @@
         {
             try
             {
-                //鍙栨秷绾跨▼ 鍏抽棴PLC杩炴帴
-                if (cts.Token.IsCancellationRequested)
+                Console.WriteLine("杩炴帴鐘舵�佺嚎绋�");
+                while (true)
                 {
-                    foreach (var modPlcUtil in listPlcUtil)
+                    //鍙栨秷绾跨▼ 鍏抽棴PLC杩炴帴
+                    if (cts.Token.IsCancellationRequested)
                     {
-                        modPlcUtil.Close();
-                    }
-                    throw new OperationCanceledException();
-                }
-                //鑾峰彇姣忎釜PLC杩炴帴鐘舵��
-                foreach (var modPlc in listPlc)
-                {
-                    var modPlcUtil = listPlcUtil.FirstOrDefault(s => s.PlcId == modPlc.Id);
-                    if (modPlcUtil == null)
-                        modPlc.IsConn = false;
-                    else
-                        modPlc.IsConn = modPlcUtil.Connected;
-                    if (sysCacheService.ExistKey("PLCCONN" + modPlc.Id))
-                    {
-                        var cachePlc = sysCacheService.Get<WcsPlc>("PLCCONN" + modPlc.Id);
-                        if (cachePlc.IsConn != modPlc.IsConn)
+                        foreach (var modPlcUtil in listPlcUtil)
                         {
-                            //杩炴帴鐘舵�佸彉鏇� 閫氱煡鍓嶇
-                            _plcHubContext.Clients.All.PublicPlcConn(modPlc);
+                            if (modPlcUtil != null && modPlcUtil.Connected)
+                                modPlcUtil.Close();
+                        }
+                        break;
+                        //throw new OperationCanceledException();
+                    }
+                    //鑾峰彇姣忎釜PLC杩炴帴鐘舵��
+                    foreach (var modPlc in listPlc)
+                    {
+                        var modPlcUtil = listPlcUtil.FirstOrDefault(s => s.PlcId == modPlc.Id);
+                        if (modPlcUtil == null)
+                            modPlc.IsConn = false;
+                        else
+                            modPlc.IsConn = modPlcUtil.Connected;
+                        if (sysCacheService.ExistKey("PLCCONN:" + modPlc.Id))
+                        {
+                            var cachePlc = sysCacheService.Get<WcsPlc>("PLCCONN:" + modPlc.Id);
+                            if (cachePlc.IsConn != modPlc.IsConn)
+                            {
+                                //杩炴帴鐘舵�佸彉鏇� 閫氱煡鍓嶇
+                                Console.WriteLine($"閫氱煡鍓嶇鍙樻洿{modPlc.Text} {modPlc.IsConn}");
+                                HubUtil.PublicPlcConn(modPlc);
+                            }
+                            sysCacheService.Set("PLCCONN:" + modPlc.Id, modPlc);
+                        }
+                        else
+                        {
+                            sysCacheService.Set("PLCCONN:" + modPlc.Id, modPlc);
+                            HubUtil.PublicPlcConn(modPlc);
                         }
                     }
-                    sysCacheService.Set("PLCCONN" + modPlc.Id, modPlc);
+                    Thread.Sleep(10000);
                 }
-                Thread.Sleep(3000);
             }
             catch (OperationCanceledException)
             {
@@ -179,12 +256,226 @@
             }
             catch (Exception ex)
             {
-                Log.Error(ex.Message, ex);
+                Log.Error("杩炴帴鐘舵�佺嚎绋嬪彂鐢熷紓甯�", ex);
             }
 
-        });
+        }, cts.Token);
 
     }
+
+    /// <summary>
+    /// 寮�鍚姤璀︾洃鎺�
+    /// </summary>
+    public static void StartWatchAlarm()
+    {
+        Task.Run(() =>
+        {
+            var listPlc = listAlarmInfo.GroupBy(s => new { s.PlcIP, s.PlcPort }).ToList();
+            List<PLCUtil> listPlcUtil = new List<PLCUtil>();
+            int i = 0;
+            foreach (var modPlc in listPlc)
+            {
+                listPlcUtil.Add(new PLCUtil(new WcsPlc() { Id = i++, IP = modPlc.Key.PlcIP, Port = modPlc.Key.PlcPort, PLCType = PLCEnum.S7_1500 }));
+            }
+            while (true)
+            {
+                //鍙栨秷绾跨▼ 鍏抽棴PLC杩炴帴
+                if (cts.Token.IsCancellationRequested)
+                {
+                    foreach (var modPlcUtil in listPlcUtil)
+                    {
+                        if (modPlcUtil != null && modPlcUtil.Connected)
+                            modPlcUtil.Close();
+                    }
+                    break;
+                    //throw new OperationCanceledException();
+                }
+                foreach (var modUtil in listPlcUtil)
+                {
+                    try
+                    {
+                        //鎶ヨ鐐逛綅
+                        var listAlarm = listAlarmInfo.Where(s => s.PlcIP == modUtil.PlcIP.ToString()).ToList();
+                        var listaddress = new Dictionary<string, PLCDataTypeEnum>();
+                        foreach (var modAlarm in listAlarm)
+                        {
+                            listaddress.Add(modAlarm.AlarmCode, PLCDataTypeEnum.Bit);
+                        }
+                        var result = modUtil.GetPlcBatchDBValue(listaddress);
+                        var listPulish = new List<WcsAlarmInfo>();
+                        foreach (var item in result.Value)
+                        {
+                            var value = Convert.ToBoolean(item.Value);
+                            var modAlarm = listAlarm.FirstOrDefault(s => s.AlarmCode == item.Key);
+                            var stationNum = modAlarm.StationNum;
+                            if (value && modAlarm.Status == YesNoEnum.N)
+                            {
+                                //淇敼鎶ヨ鐘舵�佸悓鏃惰褰曟姤璀︽棩蹇�
+                                modAlarm.AlarmTime = DateTime.Now;
+                                modAlarm.Status = YesNoEnum.Y;
+                                listPulish.Add(modAlarm);
+                            }
+                            //鍙栨秷鎶ヨ
+                            else if (!value && modAlarm.Status == YesNoEnum.Y)
+                            {
+                                modAlarm.AlarmTime = null;
+                                modAlarm.Status = YesNoEnum.N;
+                                listPulish.Add(modAlarm);
+                            }
+                        }
+                        if (listPulish.Count > 0)
+                        {
+                            _db.Updateable(listPulish).ExecuteCommand();
+                            var listLog = new List<WcsAlarmLog>();
+                            foreach (var mod in listPulish.Where(s => s.Status == YesNoEnum.Y))
+                            {
+                                WcsAlarmLog modLog = mod.Adapt<WcsAlarmLog>();
+                                modLog.Id = 0;
+                                listLog.Add(modLog);
+                            }
+                            if (listLog.Count >= 0)
+                                _db.Insertable(listLog).ExecuteCommand();
+                            HubUtil.PublicAlarm(listPulish);
+                        }
+                    }
+                    catch (Exception ex)
+                    {
+                        Log.Error("鎶ヨ鐩戞帶鍙戠敓寮傚父", ex);
+                    }
+
+                }
+                Thread.Sleep(10000);
+            }
+        }, cts.Token);
+    }
+    /// <summary>
+    /// 寮�鍚綅缃洃鎺�
+    /// </summary>
+    public static void StartWatchPosition()
+    {
+        Console.WriteLine("寮�鍚綅缃洃鎺�");
+        Task.Run(() =>
+        {
+            while (true)
+            {
+                //鍙栨秷绾跨▼ 鍏抽棴PLC杩炴帴
+                if (cts.Token.IsCancellationRequested)
+                {
+                    foreach (var modPlcUtil in listPlcUtil)
+                    {
+                        if (modPlcUtil != null && modPlcUtil.Connected)
+                            modPlcUtil.Close();
+                    }
+                    break;
+                    //throw new OperationCanceledException();
+                }
+                try
+                {
+                    foreach (var modPlcUtil in listPlcUtil)
+                    {
+                        if (modPlcUtil == null)
+                            continue;
+                        var plcIp = modPlcUtil.PlcIP;
+                        var listDevice = listPlcDevice.Where(s => s.PlcId == modPlcUtil.PlcId && s.DeviceType == DeviceTypeEnum.Show).ToList();
+                        var modPlc = listPlc.FirstOrDefault(s => s.Id == modPlcUtil.PlcId);
+                        var listaddress = new Dictionary<string, PLCDataTypeEnum>();
+                        foreach (var modDevice in listDevice)
+                        {
+                            listaddress.Add(modDevice.DbNumber + "." + modDevice.PlcPos, modDevice.PosType);
+                        }
+                        //鎵归噺璇�
+                        var result = modPlcUtil.GetPlcBatchDBValue(listaddress);
+                        //娴嬭瘯鐢�
+                        //foreach (var modDevice in listDevice)
+                        //{
+                        //    if (modPlc.Type == PLCTypeEnum.StackingMachine)
+                        //        result.Value.Add(modDevice.DbNumber + "." + modDevice.PlcPos, new Random().Next(790000));
+                        //    else if (modPlc.Type == PLCTypeEnum.ConveyorLine)
+                        //        result.Value.Add(modDevice.DbNumber + "." + modDevice.PlcPos, new Random().Next(2) == 0);
+                        //}
+                        foreach (var item in result.Value)
+                        {
+                            var modDevice = listDevice.FirstOrDefault(s => item.Key == (s.DbNumber + "." + s.PlcPos));
+                            if (modDevice == null)
+                                continue;
+                            switch (modPlc.Type)
+                            {
+                                case PLCTypeEnum.StackingMachine:
+                                    {
+                                        var value = Convert.ToInt32(item.Value);
+                                        var height = Math.Round(value / 790000d * 200).ToInt();
+                                        var modPosition = listPlcPosition.FirstOrDefault(s => s.DeviceId == modDevice.Id && s.Text == "鐩殑宸ヤ綅");
+                                        string EndLocat = "";
+                                        if (modPosition != null)
+                                        {
+                                            var (result2, value2) = modPlcUtil.GetPlcDBValue(modPosition.PosType, modDevice.DbNumber, modPosition.PlcPos);
+                                            if (result2.IsSucceed)
+                                                EndLocat = Convert.ToString(value2);
+                                        }
+                                        if (modDevice.BoxHeight != height || modDevice.EndLocat != EndLocat)
+                                        {
+                                            modDevice.EndLocat = EndLocat;
+                                            modDevice.BoxHeight = Math.Round(value / 790000d * 200).ToInt();
+                                            var modInfo = new PlcPositionInfo()
+                                            {
+                                                Type = modPlc.Type,
+                                                StationNum = modDevice.StationNum,
+                                                BoxHeight = modDevice.BoxHeight,
+                                                EndLocat = EndLocat,
+                                            };
+                                            HubUtil.PublicPosition(modInfo);
+                                            UpdatePosition(modInfo);
+                                        }
+                                    }
+                                    break;
+                                case PLCTypeEnum.ConveyorLine:
+                                    {
+                                        var bl = false;
+                                        int value = Convert.ToInt32(item.Value);
+                                        if (value <= 30)
+                                        {
+                                            bl = false;
+                                        }
+                                        else
+                                        {
+                                            bl = true;
+                                        }
+
+                                        if (bl != modDevice.BoHaveItem)
+                                        {
+                                            modDevice.BoHaveItem = bl;
+                                            var modInfo = new PlcPositionInfo() { Type = modPlc.Type, StationNum = modDevice.StationNum.PadLeft(3, '0'), BoHaveItem = bl };
+                                            HubUtil.PublicPosition(modInfo);
+                                            UpdatePosition(modInfo);
+                                        }
+                                    }
+                                    break;
+                                default:
+                                    break;
+                            }
+                        }
+                    }
+                    Thread.Sleep(3000);
+                }
+                catch (Exception ex)
+                {
+                    Log.Error("浣嶇疆鐩戞帶鍙戠敓寮傚父", ex);
+                }
+            }
+        });
+    }
+    private static void UpdatePosition(PlcPositionInfo modInfo)
+    {
+        var modTemp = listPositionInfo.FirstOrDefault(s => s.StationNum == modInfo.StationNum && modInfo.Type == s.Type);
+        if (modTemp == null)
+        {
+            listPositionInfo.Add(modInfo);
+        }
+        else
+        {
+            modTemp.BoHaveItem = modInfo.BoHaveItem;
+        }
+    }
     /// <summary>
     /// 鍋滄鏈嶅姟
     /// </summary>

--
Gitblit v1.8.0