林豪 左 3 år sedan
förälder
incheckning
1b9cd6725f

+ 34 - 46
Projects/永冠OPP/WCS.Service/ProtocolProxy.cs

@@ -1,8 +1,7 @@
-using DBHelper;
+using DBHelper_SqlSugar;
 using FreeRedis;
 using MessagePack;
 using MessagePack.Resolvers;
-using Microsoft.EntityFrameworkCore;
 using System;
 using System.Collections.Concurrent;
 using System.Collections.Generic;
@@ -11,8 +10,10 @@ using System.Linq;
 using System.Linq.Dynamic.Core;
 using System.Reflection;
 using WCS.Core;
+using WCS.Core.DataTrans;
 using WCS.Entity;
 using WCS.Entity.Protocol;
+using DbContext = Microsoft.EntityFrameworkCore.DbContext;
 
 namespace WCS.Service
 {
@@ -27,41 +28,33 @@ namespace WCS.Service
 
         private static ConcurrentDictionary<Type, object[]> LastDatas = new ConcurrentDictionary<Type, object[]>();
 
-        protected override WCS_PROTOCOLDATA GetLastData(DB db)
+        protected override WCS_PROTOCOLDATA GetLastData(Db db)
         {
             if (!LastDatas.ContainsKey(this.ProtocolDataType))
             {
                 dynamic q = SetMethod.Invoke(db.Default, null);
-                try
-                {
-                    q = DynamicQueryableExtensions.Where(q, "ISLAST==@0", true);
-                    q = DynamicQueryableExtensions.OrderBy(q, "ID");
-                    q = DynamicQueryableExtensions.Select(q, "new(it.DEVICE.CODE as Code,it as Data)");
-                    var arr = Enumerable.ToArray(q);
-                    LastDatas[this.ProtocolDataType] = arr;
-                }
-                catch (Exception ex)
-                {
-                    throw;
-                }
+                q = DynamicQueryableExtensions.Where(q, "ISLAST==@0", true);
+                q = DynamicQueryableExtensions.OrderBy(q, "ID");
+                q = DynamicQueryableExtensions.Select(q, "new(it.DEVICE.CODE as Code,it as Data)");
+                var arr = Enumerable.ToArray(q);
+                LastDatas[this.ProtocolDataType] = arr;
             }
             dynamic datas = LastDatas[this.ProtocolDataType];
             var list = new List<WCS_PROTOCOLDATA>();
             foreach (var data in datas)
             {
-                if (data.Code == PROTOCOL.DEVICE.CODE)
+                if (data.Code == Protocol.DEVICE.CODE)
                     list.Add(data.Data);
             }
 
             if (list.Count > 1)
             {
-                for (int i = 0; i < list.Count - 1; i++)
+                for (var i = 0; i < list.Count - 1; i++)
                 {
                     var obj = list[i];
-                    db.Default.Attach(obj);
+                    db.Default.Insertable((object)obj).ExecuteCommand();
                     obj.ISLAST = false;
                 }
-                db.Default.SaveChanges();
             }
             var res = Enumerable.LastOrDefault(list);
             return res;
@@ -69,25 +62,24 @@ namespace WCS.Service
 
         private static int total;
 
-        protected override WCS_PROTOCOLDATA SaveNewData(DB db, WCS_PROTOCOLDATA last, WCS_PROTOCOLDATA newobj, string user)
+        protected override WCS_PROTOCOLDATA SaveNewData(Db db, WCS_PROTOCOLDATA last, WCS_PROTOCOLDATA newobj, string user)
         {
             total++;
 
             if (last != null)
             {
-                db.Default.Attach(last);
+                db.Default.Insertable((object)last).ExecuteCommand();
                 last.ISLAST = false;
             }
 
-            db.Default.Attach(PROTOCOL.DEVICE);
+            db.Default.Storageable(Protocol.DEVICE).ExecuteCommand();
 
-            newobj.DEVICE = PROTOCOL.DEVICE;
+            newobj.DEVICE = Protocol.DEVICE;
             newobj.ISLAST = true;
             newobj.UPDATETIME = DateTime.Now;
             newobj.UPDATEUSER = user;
             newobj.FRAME = LogicHandler.Frame;
-            db.Default.Add(newobj);
-            db.Default.SaveChanges();
+            db.Default.Insertable((object)newobj).ExecuteCommand();
             return newobj;
         }
 
@@ -156,19 +148,18 @@ namespace WCS.Service
                     if (!Datas.ContainsKey(code))
                         Datas[code] = new StationData { Code = code };
                 }
-                if (Datas.ContainsKey(code))
+
+                if (!Datas.ContainsKey(code)) return;
+                var data = Datas[code];
+                data.Frame = LogicHandler.Frame;
+                var p = data.GetType().GetProperties().FirstOrDefault(v => v.PropertyType == obj.GetType());
+                if (p == null)
+                {
+                    Console.WriteLine("类型" + data.GetType().Name + "不包含类型为" + obj.GetType().Name + "的属性");
+                }
+                else
                 {
-                    var data = Datas[code];
-                    data.Frame = LogicHandler.Frame;
-                    var p = data.GetType().GetProperties().Where(v => v.PropertyType == obj.GetType()).FirstOrDefault();
-                    if (p == null)
-                    {
-                        Console.WriteLine("类型" + data.GetType().Name + "不包含类型为" + obj.GetType().Name + "的属性");
-                    }
-                    else
-                    {
-                        p.SetValue(data, obj);
-                    }
+                    p.SetValue(data, obj);
                 }
             }
             catch (Exception ex)
@@ -207,7 +198,7 @@ namespace WCS.Service
                     var etype = g.Key;
                     var type = typeof(DeviceDataCollection<>).MakeGenericType(etype);
                     var coll = Activator.CreateInstance(type, LogicHandler.Frame, value);
-                    var p = pack.GetType().GetProperties().Where(v => v.PropertyType == type).First();
+                    var p = pack.GetType().GetProperties().First(v => v.PropertyType == type);
                     p.SetValue(pack, coll);
                 }
 
@@ -234,13 +225,10 @@ namespace WCS.Service
                 {
                     // LastInfo[data.Key] = data.Value.Info;
                     data.Value.Info = "";
-                    if (data.Value is ProdLineData)
-                    {
-                        var pld = data.Value as ProdLineData;
-                        pld.TaskList.Clear();
-                        pld.Frame = LogicHandler.Frame;
-                        pld.Code = data.Key;
-                    }
+                    if (data.Value is not ProdLineData pld) continue;
+                    pld.TaskList.Clear();
+                    pld.Frame = LogicHandler.Frame;
+                    pld.Code = data.Key;
                 }
             }
             catch (Exception ex)
@@ -256,4 +244,4 @@ namespace WCS.Service
 
         public byte[] Data { get; set; }
     }
-}
+}

+ 1 - 1
Projects/永冠OPP/WCS.Service/WCS.Service.csproj

@@ -33,7 +33,7 @@
   </ItemGroup>
 
   <ItemGroup>
-    <ProjectReference Include="..\..\..\DBHelper\DBHelper.csproj" />
+    <ProjectReference Include="..\..\..\DBHelper-SqlSugar\DBHelper-SqlSugar.csproj" />
     <ProjectReference Include="..\..\..\Logs\Logs.csproj" />
     <ProjectReference Include="..\..\..\WCS.Core\WCS.Core.csproj" />
     <ProjectReference Include="..\..\..\WCS.Entity\WCS.Entity.csproj" />

+ 9 - 11
Projects/永冠OPP/WCS.Service/Worker.cs

@@ -1,6 +1,5 @@
-using DBHelper;
+using DBHelper_SqlSugar;
 using Logs;
-using Microsoft.EntityFrameworkCore;
 using Microsoft.Extensions.Hosting;
 using Microsoft.Extensions.Logging;
 using Newtonsoft.Json;
@@ -44,7 +43,7 @@ namespace WCS.Service
             Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
             Configs.StringEncoding = Encoding.UTF8;
 
-            DB.SetDefaultDbContextType<WCSDB>();
+            Db.SetDefaultDbContextType("WCSDB");
 
             //日志发布事件
             Configs.PublishEvent += () =>
@@ -70,16 +69,16 @@ namespace WCS.Service
             PLCAccessor.Creater = new PLCAccessors.PLCAccessorsCreater();
             try
             {
-                DB.Do(db =>
+                Db.Do(db =>
                 {
-                    var items = db.Default.Set<WCS_DEVICEPROTOCOL>()
-                   .Include(v => v.DEVICE.ROUTES)
-                   .Include(v => v.DEVICE.PATHS)
-                   .Include(v => v.DB.PLC).ToArray();
-                    items.Select(v => v.Data()).ToArray();
+                    var items = db.Default.Queryable<WCS_DEVICEPROTOCOL>()
+                   .Includes(v => v.DEVICE.ROUTES)
+                   .Includes(v => v.DEVICE.PATHS)
+                   .Includes(v => v.DB.PLC).ToArray();
+                    var objects = items.Select(v => v.Data()).ToArray();
                     LogicHandler.AllObjects.AddRange(items);
 
-                    var devices = db.Default.Set<WCS_DEVICE>().Include(v => v.ROUTES).Include(v => v.PATHS).Include(v => v.DEVICEGROUP).ToArray();
+                    var devices = db.Default.Queryable<WCS_DEVICE>().Includes(v => v.ROUTES).Includes(v => v.PATHS).Includes(v => v.DEVICEGROUP).ToArray();
                     LogicHandler.AllObjects.AddRange(devices);
                 });
 
@@ -108,7 +107,6 @@ namespace WCS.Service
                 Device.AddFlag(DF.涂布RGV取货站台, "1285", "1286", "1294", "1295", "1303", "1304", "1312", "1313");
                 Device.AddFlag(DF.涂布RGV取货站台, "1391", "1392", "1399", "1400");
                 Device.AddFlag(DF.BOPPRGV, "RGV1", "RGV2", "RGV3", "RGV4", "RGV5", "RGV6", "RGV7");
-                //Device.AddFlag(DF.BOPPRGV取货设备组, "G17", "G18", "G19", "G20", "G21", "G22", "G23");
                 Device.AddFlag(DF.BOPPRGV取货设备组, "G19", "G23");
                 Device.AddFlag(DF.BOPPRGV放货设备组, "G12", "G13", "G14", "G15", "G16");
 

+ 5 - 4
WCS.Core/DataTrans/DataBlock.cs

@@ -1,5 +1,4 @@
 using DBHelper_SqlSugar;
-using SqlSugar;
 using System;
 using System.Collections;
 using System.Collections.Generic;
@@ -20,7 +19,7 @@ namespace WCS.Core
 
         private List<PlcItem> Values = new List<PlcItem>();
 
-        internal event Action<SqlSugarScope, byte[]> DataChanged;
+        internal event Action<Db, byte[]> DataChanged;
 
         /// <summary>
         /// 是否失败,默认成功
@@ -53,12 +52,14 @@ namespace WCS.Core
                     sw.Stop();
                 }
 
-                //var changed = DataServer.Refresh(Entity);
                 failed = false;
                 if (Data != null && data.SequenceEqual(Data)) return;
                 Data = data;
 
-                DataChanged?.Invoke(DbContext.Db, Data);
+                Db.Do(db =>
+                {
+                    DataChanged?.Invoke(db, Data);
+                });
             }
             catch (Exception)
             {

+ 2 - 1
WCS.Core/DataTrans/Extentions.cs

@@ -5,6 +5,7 @@ using System.Linq;
 using System.Reflection;
 using System.Runtime.InteropServices;
 using System.Text;
+using WCS.Core.DataTrans;
 using WCS.Entity;
 
 namespace WCS.Core
@@ -531,7 +532,7 @@ namespace WCS.Core
 
         public static WCS_DEVICEPROTOCOL PROTOCOL(this IProtocol obj)
         {
-            return (obj as ProtocolProxyBase).PROTOCOL;
+            return (obj as ProtocolProxyBase).Protocol;
         }
 
         public static T Create<T>(this WCS_DEVICE source)

+ 47 - 64
WCS.Core/DataTrans/ProtocolProxyBase.cs

@@ -1,14 +1,13 @@
-using DBHelper;
+using DBHelper_SqlSugar;
 using System;
 using System.Collections.Generic;
 using System.ComponentModel.DataAnnotations;
 using System.Linq;
 using System.Reflection;
 using System.Runtime.InteropServices;
-using DBHelper_SqlSugar;
 using WCS.Entity;
 
-namespace WCS.Core
+namespace WCS.Core.DataTrans
 {
     /// <summary>
     /// IL动态生成的类型所继承的基类
@@ -19,29 +18,27 @@ namespace WCS.Core
 
         public static Func<WCS_PROTOCOLDATA, string, WCS_PROTOCOLDATA> DataChanged;
 
-        private Dictionary<string, PlcItem> Items = new Dictionary<string, PlcItem>();
+        private readonly Dictionary<string, PlcItem> _items = new Dictionary<string, PlcItem>();
 
-        //public ushort Start;
-        //public string Name;
         public string Id { get; set; }
 
-        public WCS_DEVICEPROTOCOL PROTOCOL { get; private set; }
+        public WCS_DEVICEPROTOCOL Protocol { get; private set; }
 
         /// <summary>
         /// 起始便宜量,按字节算
         /// </summary>
-        private ushort Start;
+        private readonly ushort _start;
 
         /// <summary>
         /// 长度,按字节算
         /// </summary>
-        private ushort Length;
+        private readonly ushort _length;
 
         public WCS_DATABLOCK Db;
 
-        private static Dictionary<Type, object> LockObjs = new Dictionary<Type, object>();
+        private static readonly Dictionary<Type, object> LockObjs = new Dictionary<Type, object>();
 
-        public ProtocolProxyBase(string id, WCS_DATABLOCK db, ushort start, WCS_DEVICEPROTOCOL deviceItem)
+        protected ProtocolProxyBase(string id, WCS_DATABLOCK db, ushort start, WCS_DEVICEPROTOCOL deviceItem)
         {
             var type = this.GetType();
             if (!LockObjs.ContainsKey(type))
@@ -49,12 +46,10 @@ namespace WCS.Core
 
             this.Db = db;
             db.Ex().DataChanged += PLCData_DataChanged;
-            this.Start = start;
+            this._start = start;
             var bitStart = start * 8;//偏移量,按位算
             this.Id = id;
-            this.PROTOCOL = deviceItem;
-            //this.Start = start;
-            //PlcDB db = new PlcDB(null, 50, 100);
+            this.Protocol = deviceItem;
             var lst = this.GetType().GetInterfaces().ToList();
 
             var ps = lst.SelectMany(v => v.GetProperties()).ToArray();
@@ -110,44 +105,44 @@ namespace WCS.Core
                 var m = typeof(DataBlock).GetMethod("Regist");
                 m = m.MakeGenericMethod(p.PropertyType);
                 var item = m.Invoke(db.Ex(), new object[] { this.Id, p.Name, bitStart, arrlen, strLen }) as PlcItem;
-                Items.Add(p.Name, item);
+                _items.Add(p.Name, item);
                 bitStart += item.DataSizeOfBits;
-                Length += item.DataSize;
+                _length += item.DataSize;
             }
-            ProtocolType = this.PROTOCOL.DB.GetProtocolType();
+            ProtocolType = this.Protocol.DB.GetProtocolType();
             ProtocolDataType = ProtocolType.Assembly.GetTypes().Where(v => v.IsClass).First(v => v.GetInterface(ProtocolType.Name) != null && v != this.GetType());
         }
 
         private byte[] Data = null;
-        private static object locobj = new object();
+        private static object _locobj = new object();
 
         private void InvokeUpdate(string user, Db db)
         {
             SaveChangs(user, db);
         }
 
-        private WCS_PROTOCOLDATA last = null;
+        private WCS_PROTOCOLDATA _last = null;
 
         public DateTime UpdateTime;
 
         protected virtual void SaveChangs(string user, Db db)
         {
             var obj = Copy(this, ProtocolDataType) as WCS_PROTOCOLDATA;
-            obj.WCSVERSION = this.WCSVersion;
-            if (last == null)
+            obj!.WCSVERSION = this.WcsVersion;
+            if (_last == null)
             {
-                Publish(this.PROTOCOL.DEVICE.CODE, obj);
-                last = GetLastData(db);
+                Publish(this.Protocol.DEVICE.CODE, obj);
+                _last = GetLastData(db);
             }
-            if (last != null)
+            if (_last != null)
             {
-                if (Equals(obj, last, ProtocolType))
+                if (Equals(obj, _last, ProtocolType))
                     return;
             }
             this.UpdateTime = DateTime.Now;
 
-            Publish(this.PROTOCOL.DEVICE.CODE, obj);
-            last = SaveNewData(db, last, obj, user);
+            Publish(this.Protocol.DEVICE.CODE, obj);
+            _last = SaveNewData(db, _last, obj, user);
         }
 
         public virtual void Publish(string code, WCS_PROTOCOLDATA obj)
@@ -160,7 +155,7 @@ namespace WCS.Core
 
         private void PLCData_DataChanged(Db db, byte[] data)
         {
-            var temp = data.Skip(Start).Take(Length).ToArray();
+            var temp = data.Skip(_start).Take(_length).ToArray();
             try
             {
                 if (Data != null && Data.SequenceEqual(temp))
@@ -168,12 +163,11 @@ namespace WCS.Core
                 var d1 = DateTime.Now;
                 InvokeUpdate("PLC", db);
                 var d = (DateTime.Now - d1).TotalMilliseconds;
-                //Console.WriteLine("DB " + d);
             }
             finally { Data = temp; }
         }
 
-        private object Copy(object obj, Type type)
+        private static object Copy(object obj, Type type)
         {
             var res = Activator.CreateInstance(type);
             foreach (var p in type.GetProperties())
@@ -187,7 +181,7 @@ namespace WCS.Core
             return res;
         }
 
-        private bool Equals(object a, object b, Type type)
+        private static bool Equals(object a, object b, Type type)
         {
             foreach (var p in type.GetProperties())
             {
@@ -199,18 +193,15 @@ namespace WCS.Core
                 {
                     if (attr.IgnoreValueRange == 0)
                         continue;
-                    else
+                    try
                     {
-                        try
-                        {
-                            var d = Math.Abs((decimal.Parse(v1.ToString())) - (decimal.Parse(v2.ToString())));
-                            if (d < attr.IgnoreValueRange)
-                                continue;
-                        }
-                        catch
-                        {
-                            Console.WriteLine("IgnoreValueRange属性只能用于数字类型");
-                        }
+                        var d = Math.Abs((decimal.Parse(v1.ToString())) - (decimal.Parse(v2.ToString())));
+                        if (d < attr.IgnoreValueRange)
+                            continue;
+                    }
+                    catch
+                    {
+                        Console.WriteLine("IgnoreValueRange属性只能用于数字类型");
                     }
                 }
 
@@ -222,14 +213,14 @@ namespace WCS.Core
                 if (p.PropertyType.IsArray)
                 {
                     var m = typeof(Enumerable).GetMethods().Where(v => v.Name == nameof(Enumerable.SequenceEqual)).First(v => v.GetParameters().Length == 2);
-                    m = m.MakeGenericMethod(p.PropertyType.GetElementType());
-                    var res = (bool)m.Invoke(null, new object[] { v1, v2 });
+                    m = m.MakeGenericMethod(p.PropertyType.GetElementType()!);
+                    var res = (bool)m.Invoke(null, new[] { v1, v2 })!;
                     if (!res)
                         return false;
                 }
                 else
                 {
-                    if (!v1.Equals(v2))
+                    if (!v1!.Equals(v2))
                         return false;
                 }
             }
@@ -263,15 +254,15 @@ namespace WCS.Core
         /// <summary>
         /// 版本号,WCS每修改一次数据,版本号变化一次
         /// </summary>
-        public int WCSVersion { get; private set; }
+        public int WcsVersion { get; private set; }
 
         public void Set<T>(string propertyName, T value)
         {
-            var str = PROTOCOL.DEVICE.CODE + "." + ProtocolType.Name + "." + propertyName;
+            var str = Protocol.DEVICE.CODE + "." + ProtocolType.Name + "." + propertyName;
             try
             {
                 str += " = " + (value == null ? "null" : value.ToString());
-                var item = Items[propertyName] as PlcItem<T>;
+                var item = _items[propertyName] as PlcItem<T>;
                 item.Value = value;
                 DBHelper_SqlSugar.Db.Do(db =>
                 {
@@ -279,7 +270,7 @@ namespace WCS.Core
                 });
 
                 Data = null;
-                WCSVersion++;
+                WcsVersion++;
                 str += " 写入成功";
             }
             catch
@@ -295,7 +286,7 @@ namespace WCS.Core
 
         public void Update(string prop, object value, string user)
         {
-            var item = Items[prop];
+            var item = _items[prop];
             item.Value = value;
             DBHelper_SqlSugar.Db.Do(db =>
             {
@@ -305,15 +296,15 @@ namespace WCS.Core
             Data = null;
             if (user == "PLC")
                 return;
-            WCSVersion++;
+            WcsVersion++;
         }
 
         public T Get<T>(string propertyName)
         {
-            var str = PROTOCOL.DEVICE.CODE + "." + ProtocolType.Name + "." + propertyName;
+            var str = Protocol.DEVICE.CODE + "." + ProtocolType.Name + "." + propertyName;
             try
             {
-                var item = Items[propertyName] as PlcItem<T>;
+                var item = _items[propertyName] as PlcItem<T>;
                 var res = item.Value;
                 str += " : " + (res == null ? "null" : res.ToString());
                 return res;
@@ -323,10 +314,6 @@ namespace WCS.Core
                 str += " 读取失败";
                 throw;
             }
-            finally
-            {
-                //Ltc.Log(str);
-            }
         }
 
         public T CallReturn<T>(string methodName, params object[] args)
@@ -355,12 +342,8 @@ namespace WCS.Core
         public override string ToString()
 
         {
-            var str = "";
-            foreach (var p in this.GetType().GetProperties())
-            {
-                str += p.Name + ":" + p.GetValue(this, null).ToString() + ",";
-            }
-            str = str.Substring(0, str.Length - 1);
+            var str = this.GetType().GetProperties().Aggregate("", (current, p) => current + (p.Name + ":" + p.GetValue(this, null)!.ToString() + ","));
+            str = str[..^1];
             return str;
         }
     }