Ver Fonte

up date

林豪 左 há 3 anos atrás
pai
commit
8337f1b255

+ 6 - 6
DBHelper-SqlSugar/DB.cs

@@ -63,7 +63,7 @@ namespace DBHelper_SqlSugar
         /// <summary>
         /// 默认链接
         /// </summary>
-        public SqlSugarClient Default
+        public SqlSugarScope Default
         {
             get
             {
@@ -78,11 +78,11 @@ namespace DBHelper_SqlSugar
         /// </summary>
         /// <param name="type"></param>
         /// <returns></returns>
-        public static SqlSugarClient CreateContext(ConnectionConfig config, string key)
+        public static SqlSugarScope CreateContext(ConnectionConfig config, string key)
         {
             var ctx = _contexts.FirstOrDefault(v => v.Key == key);
             if (ctx != null) return ctx.Client;
-            ctx = new ContextList(key, new SqlSugarClient(new ConnectionConfig()
+            ctx = new ContextList(key, new SqlSugarScope(new ConnectionConfig()
             {
                 ConnectionString = config.ConnectionString,
                 DbType = config.DbType,
@@ -93,7 +93,7 @@ namespace DBHelper_SqlSugar
             return ctx.Client;
         }
 
-        public SqlSugarClient Context(string key)
+        public SqlSugarScope Context(string key)
         {
             var ctx = _contexts.FirstOrDefault(v => v.Key == key);
             if (ctx == null) throw new Exception("没有对应的链接,请先调用创建");
@@ -107,7 +107,7 @@ namespace DBHelper_SqlSugar
     public class ContextList
 
     {
-        public ContextList(string key, SqlSugarClient client, ConnectionConfig connectionConfig)
+        public ContextList(string key, SqlSugarScope client, ConnectionConfig connectionConfig)
         {
             this.Key = key;
             Client = client;
@@ -116,7 +116,7 @@ namespace DBHelper_SqlSugar
 
         public string Key { get; set; }
 
-        public SqlSugarClient Client { get; set; }
+        public SqlSugarScope Client { get; set; }
 
         public ConnectionConfig ConnectionConfig { get; set; }
     }

BIN
DLL/PLC.Siemens.dll


+ 57 - 1
Projects/永冠OPP/WCS.Service/Extensions/TypeExtension.cs

@@ -1,4 +1,8 @@
-using System;
+using SqlSugar;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
 
 namespace WCS.Service.Extensions
 {
@@ -63,5 +67,57 @@ namespace WCS.Service.Extensions
         {
             return value.Replace("G", "").ToShort();
         }
+
+        /// <summary>
+        /// 数据映射
+        /// </summary>
+        /// <typeparam name="D"></typeparam>
+        /// <typeparam name="S"></typeparam>
+        /// <param name="s"></param>
+        /// <returns></returns>
+        public static D Mapper<D, S>(S s)
+        {
+            D d = Activator.CreateInstance<D>();
+
+            var sType = s.GetType();
+            var dType = typeof(D);
+            foreach (PropertyInfo sP in sType.GetProperties())
+            {
+                foreach (PropertyInfo dP in dType.GetProperties())
+                {
+                    if (dP.Name == sP.Name)
+                    {
+                        dP.SetValue(d, sP.GetValue(s));
+                        break;
+                    }
+                }
+            }
+            return d;
+        }
+
+        /// <summary>
+        ///
+        /// </summary>
+        /// <typeparam name="T1"></typeparam>
+        /// <typeparam name="T2"></typeparam>
+        /// <typeparam name="T3"></typeparam>
+        /// <param name="t3"></param>
+        /// <returns></returns>
+        public static Dictionary<string, object> EntityClassToDictionary<T>(T t)
+        {
+            Type type = typeof(SugarColumn);
+            Dictionary<string, object> d = new Dictionary<string, object>();
+
+            var sType = t.GetType();
+            foreach (PropertyInfo sP in sType.GetProperties())
+            {
+                if (sP.CustomAttributes.Any(v => v.AttributeType == type) && sP.Name != "VER" && sP.Name != "ID")
+                {
+                    d.Add(sP.Name, sP.GetValue(t));
+                }
+            }
+
+            return d;
+        }
     }
 }

+ 13 - 12
Projects/永冠OPP/WCS.Service/Handlers/DataClearHandler.cs

@@ -1,8 +1,10 @@
 using DBHelper_SqlSugar;
+using SqlSugar;
 using System;
 using System.ComponentModel;
 using WCS.Core;
 using WCS.Entity;
+using WCS.Service.Extensions;
 
 namespace WCS.Service
 {
@@ -22,7 +24,8 @@ namespace WCS.Service
             last = DateTime.Now;
             Db.Do(db =>
             {
-                db.Default.Ado.UseStoredProcedure().ExecuteCommand("delete WCS_EXCEPTION where datediff(dd, UPDATETIME, getdate()) > 7");
+                db.Default.Deleteable<WCS_EXCEPTION>().Where(v => SqlFunc.DateDiff(DateType.Day, v.UPDATETIME, SqlFunc.GetDate()) > 7).AddQueue();
+                //db.Default.Ado.UseStoredProcedure().ExecuteCommand("DELETE FROM wcs_exception WHERE TIMESTAMPDIFF(DAY,UPDATETIME,NOW()) > 7");
 
                 var ps = db.Default.GetType().GetProperties();
                 foreach (var p in ps)
@@ -32,21 +35,19 @@ namespace WCS.Service
                     var tType = p.PropertyType.GenericTypeArguments[0];
                     if (!tType.IsSubclassOf(typeof(WCS_PROTOCOLDATA)))
                         continue;
-                    var sSql = $"Delete {tType.Name} where datediff(dd,Frame,getdate())>7";
+                    var sSql = $"Delete FROM {tType.Name} where TIMESTAMPDIFF(DAY,Frame,NOW())>7";
                     db.Default.Ado.UseStoredProcedure().ExecuteCommand(sSql);
                     DBHelper.DbLog.DB_CLEAN(sSql);
                 }
+                var taskList = db.Default.Queryable<WCS_TASK>().Where(v => SqlFunc.DateDiff(DateType.Day, v.UPDATETIME, SqlFunc.GetDate()) > 3 && v.STATUS >= TaskStatus.已完成).ToList();
 
-                var copySql = @"INSERT INTO WCS_TASK_OLD (ID,BARCODE,TYPE,STATUS,ADDRFROM,ADDRTO,ADDRNEXT,TUNNEL,FLOOR,
-                                DEVICE,SRMSTATION,CREATETIME,STARTTIME,ENDTIME,DOCID,PALLETTYPE,PRODLINE,FULLQTY,HEIGHT,
-                                WMSTASK,TaskGroupKey,UPLOADED,AgvTask,Priority,ManualRemarks,ENABLED,UPDATEUSER,UPDATETIME,
-                                Length,MaterialCode) SELECT
-                                ID,BARCODE,TYPE,STATUS,ADDRFROM,ADDRTO,ADDRNEXT,TUNNEL,FLOOR,DEVICE,SRMSTATION,CREATETIME,
-                                STARTTIME,ENDTIME,DOCID,PALLETTYPE,PRODLINE,FULLQTY,HEIGHT,WMSTASK,TaskGroupKey,UPLOADED,AgvTask,
-                                Priority,ManualRemarks,ENABLED,UPDATEUSER,UPDATETIME,Length,MaterialCode FROM WCS_TASK WHERE STATUS >=99 AND UPDATETIME < DATEADD(DAY, -3, GETDATE())";
-                db.Default.Ado.UseStoredProcedure().ExecuteCommand(copySql);
-                var clearSql = "DELETE FROM WCS_TASK WHERE STATUS >=99 AND UPDATETIME < DATEADD(DAY, -3, GETDATE())";
-                db.Default.Ado.UseStoredProcedure().ExecuteCommand(clearSql);
+                foreach (var task in taskList)
+                {
+                    var taskOld = TypeExtension.Mapper<WCS_TASK_OLD, WCS_TASK>(task);
+                    db.Default.Insertable(taskOld).AddQueue();
+                    db.Default.Deleteable(task).AddQueue();
+                }
+                db.Default.SaveQueues();
             });
         }
     }

+ 1 - 1
Projects/永冠OPP/WCS.Service/Handlers/WorkHandler.cs

@@ -30,6 +30,7 @@ namespace WCS.Service.Handlers
                         return false;
                     return attr.Handler == this.GetType();
                 });
+            //TODO:加一层关于仓库的管控,通过
             var works = arr.Select(v => Activator.CreateInstance(v) as Work).Select(v =>
             {
                 var attr = v.GetType().GetCustomAttribute<WorkTitleAttribute>();
@@ -119,7 +120,6 @@ namespace WCS.Service.Handlers
                 {
                     Ltc.Log(ex.GetBaseException().Message);
                 }
-
                 if (ex.REPORTWMS)
                 {
                     Configs.UploadException?.Invoke(p.ToString(), ex.GetBaseException().Message);

+ 21 - 8
Projects/永冠OPP/WCS.Service/PLCAccessors/SiemensS7PLC.cs

@@ -1,9 +1,11 @@
 using HslCommunication.Profinet.Siemens;
-using System;
+using Virtual_PLC;
+using WCS.Core;
+using WCS.Core.DataTrans;
 
 namespace WCS.Service.PLCAccessors
 {
-    public class SiemensS7PLC : SiemensS7Net
+    public class SiemensS7PLC : SiemensS7Net, IPlcAccessor
     {
         private SiemensS7Net plc;
 
@@ -21,21 +23,32 @@ namespace WCS.Service.PLCAccessors
             plc = new SiemensS7Net((SiemensPLCS)type, ip);
         }
 
-        public byte[] ReadBytes(ushort db, ushort address, ushort length)
+        public byte[] ReadBytes(ushort db, ushort address, ushort length, ushort dataLength)
         {
+            if (Configs.Any(SystemMode.虚拟PLC))
+            {
+                return PlcData.Read(new PLCData { IP = plc.IpAddress, DB = db, Length = length, DataLength = dataLength });
+            }
+
             var addr = "DB" + db + "." + address;
             var res = plc.Read(addr, length);
             if (res.IsSuccess)
                 return res.Content;
-            throw new Exception("读取PLC数据失败:" + res.Message);
+            throw new WarnException("读取PLC数据失败:" + res.Message);
         }
 
         public void WriteBytes(ushort db, ushort address, byte[] data)
         {
-            var start = db + address / 2;
-            var res = plc.Write("D" + start, data);
-            if (!res.IsSuccess)
-                throw new Exception("写入PLC数据失败:" + res.Message);
+            if (Configs.Any(SystemMode.虚拟PLC))
+            {
+                PlcData.Write(new PLCData { IP = plc.IpAddress, DB = db }, address, data);
+            }
+            else
+            {
+                var res = plc.Write("D" + address, data);
+                if (!res.IsSuccess)
+                    throw new WarnException("写入PLC数据失败:" + res.Message);
+            }
         }
     }
 }

+ 2 - 0
Projects/永冠OPP/WCS.Service/Program.cs

@@ -5,6 +5,7 @@ using System;
 using System.Runtime.InteropServices;
 using System.Threading;
 using System.Threading.Tasks;
+using WCS.Core;
 
 namespace WCS.Service
 {
@@ -19,6 +20,7 @@ namespace WCS.Service
             using var mt = new Mutex(true, "WCS");
             if (mt.WaitOne())
             {
+                Configs.AddSystemMode(SystemMode.ÐéÄâPLC);
                 CreateHostBuilder(args).Build().Run(); mt.ReleaseMutex();
             }
             else

+ 22 - 19
Projects/永冠OPP/WCS.Service/ProtocolProxy.cs

@@ -2,6 +2,7 @@
 using FreeRedis;
 using MessagePack;
 using MessagePack.Resolvers;
+using SqlSugar;
 using System;
 using System.Collections.Concurrent;
 using System.Collections.Generic;
@@ -13,7 +14,7 @@ using WCS.Core;
 using WCS.Core.DataTrans;
 using WCS.Entity;
 using WCS.Entity.Protocol;
-using DbContext = Microsoft.EntityFrameworkCore.DbContext;
+using WCS.Service.Extensions;
 
 namespace WCS.Service
 {
@@ -23,7 +24,7 @@ namespace WCS.Service
 
         public ProtocolProxy(string id, WCS_DATABLOCK db, ushort start, WCS_DEVICEPROTOCOL protocol) : base(id, db, start, protocol)
         {
-            _setMethod = typeof(DbContext).GetMethod("Set", new Type[] { })?.MakeGenericMethod(this.ProtocolDataType);
+            _setMethod = typeof(SqlSugarScope).GetMethod("Queryable", new Type[] { })?.MakeGenericMethod(this.ProtocolDataType);
         }
 
         private static readonly ConcurrentDictionary<Type, object[]> LastDatas = new();
@@ -32,19 +33,14 @@ namespace WCS.Service
         {
             if (!LastDatas.ContainsKey(this.ProtocolDataType))
             {
-                dynamic q = _setMethod.Invoke(db.Default, null);
-                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;
+                LastDatas[this.ProtocolDataType] = db.Default.Queryable<dynamic>().AS($"{this.ProtocolDataType.Name}", "it").Where("ISLAST=0").OrderBy("ID").ToArray();
             }
             dynamic datas = LastDatas[this.ProtocolDataType];
             var list = new List<WCS_PROTOCOLDATA>();
             foreach (var data in datas)
             {
-                if (data.Code == Protocol.DEVICE.CODE)
-                    list.Add(data.Data);
+                if (data.DEVICECOD == Protocol.DEVICE.CODE)
+                    list.Add(data);
             }
 
             if (list.Count > 1)
@@ -68,18 +64,25 @@ namespace WCS.Service
 
             if (last != null)
             {
-                db.Default.Insertable((object)last).ExecuteCommand();
+                var dc = TypeExtension.EntityClassToDictionary((object)last);
+                db.Default.Insertable(dc).AS($"{last.GetType().Name}").ExecuteCommand();
                 last.ISLAST = false;
             }
 
-            db.Default.Storageable(Protocol.DEVICE).ExecuteCommand();
-
-            newobj.DEVICE = Protocol.DEVICE;
+            var a = db.Default.Storageable(Protocol.DEVICE).ExecuteCommand();
+            newobj.DEVICECOD = Protocol.DEVICE.CODE;
             newobj.ISLAST = true;
             newobj.UPDATETIME = DateTime.Now;
             newobj.UPDATEUSER = user;
             newobj.FRAME = LogicHandler.Frame;
-            db.Default.Insertable((object)newobj).ExecuteCommand();
+            var typeName = newobj.GetType().Name;
+            if (!typeName.Contains("SRM") && !typeName.Contains("RGV"))
+            {
+                var f = 0;
+            }
+
+            var dc1 = TypeExtension.EntityClassToDictionary((object)newobj);
+            db.Default.Insertable(dc1).AS($"{typeName}").ExecuteCommand();
             return newobj;
         }
 
@@ -91,7 +94,7 @@ namespace WCS.Service
         static ProtocolProxy()
         {
             MessagePackSerializer.DefaultOptions = StandardResolver.Options.WithCompression(MessagePackCompression.Lz4Block);
-            Redis = new RedisClient("212.64.66.35,database=10");
+            Redis = new RedisClient("127.0.0.1,database=2");
             Redis.Serialize = obj =>
             {
                 var bytes = MessagePackSerializer.Serialize(obj);
@@ -103,9 +106,9 @@ namespace WCS.Service
                 return obj;
             };
 
-            Yg150Redis = new RedisClient("192.168.249.150,password=123456,database=1");
-            Ygwms150Redis = new RedisClient("192.168.249.150,password=123456,database=0");
-            Ygwcs150Redis = new RedisClient("192.168.249.150,password=123456,database=10");
+            Yg150Redis = new RedisClient("127.0.0.1,database=1");
+            Ygwms150Redis = new RedisClient("127.0.0.1,database=0");
+            Ygwcs150Redis = new RedisClient("127.0.0.1,database=3");
             Ygwcs150Redis.Serialize = obj =>
             {
                 var bytes = MessagePackSerializer.Serialize(obj);

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

@@ -38,14 +38,16 @@
     <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
     <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.6" />
     <PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.1" />
-    <PackageReference Include="WCS.Core" Version="1.0.0.3" />
   </ItemGroup>
 
   <ItemGroup>
     <ProjectReference Include="..\..\..\DBHelper-SqlSugar\DBHelper-SqlSugar.csproj" />
     <ProjectReference Include="..\..\..\Logs\Logs.csproj" />
     <ProjectReference Include="..\..\..\Virtual_PLC\Virtual_PLC.csproj" />
+    <ProjectReference Include="..\..\..\WCS.Core\WCS.Core.csproj" />
     <ProjectReference Include="..\..\..\WCS.Entity\WCS.Entity.csproj" />
     <ProjectReference Include="..\WCS.Entity.Protocol\WCS.Entity.Protocol.csproj" />
   </ItemGroup>
+
+  <ProjectExtensions><VisualStudio><UserProperties appsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions>
 </Project>

+ 1 - 0
Projects/永冠OPP/WCS.Service/WebApi/WMS/WMS.cs

@@ -241,6 +241,7 @@ namespace WCS.Service
 
         public static void UploadDevInfo()
         {
+            return;
             try
             {
                 var res = APICaller.CallApi<I_WCS_PutDevInfoResponse>(Url + "/api/Task/I_WCS_PutDevInfo", DevInfoList);

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

@@ -56,7 +56,7 @@ namespace WCS.Service
             Db.CreateContext(new ConnectionConfig()
             {
                 ConnectionString = AppSettings.Config.GetConnectionString("WCSDB"),
-                DbType = DbType.MySql
+                DbType = DbType.SqlServer
             }, "WCSDB");
             Db.SetDefaultDbContextType("WCSDB");
             Db.Do(db =>
@@ -142,12 +142,19 @@ namespace WCS.Service
                     items.Select(v => v.Data()).ToArray();
                     LogicHandler.AllObjects.AddRange(items);
 
-                    var devices = db.Default.Queryable<WCS_DEVICE>().Includes(v => v.ROUTES).Includes(v => v.PATHS).Includes(v => v.DEVICEGROUP).ToArray();
+                    var devices = db.Default.Queryable<WCS_DEVICE>()
+                                            .Includes(v => v.ROUTES)
+                                            .Includes(v => v.PATHS)
+                                            .Includes(v => v.DEVICEGROUP)
+                                            .Includes(v => v.DEVICEPROTOCOLS, p => p.DB, c => c.PLC)
+                                            .Includes(v => v.DEVICEPROTOCOLS, p => p.DEVICE)
+                                            .ToList();
                     LogicHandler.AllObjects.AddRange(devices);
                 });
 
                 #region 设备扩展数据配置
 
+                //TODO:通过配置使用switch
                 Device.AddFlag(DF.一楼RGV放货, "G1035", "G1044", "G1053", "G1062");
                 Device.AddFlag(DF.SRM, "SRM1", "SRM2", "SRM3", "SRM4", "SRM5", "SRM6", "SRM7", "SRM8");
                 Device.AddFlag(DF.月台, "G1469", "G1561", "G1538", "G1574", "G1509");

+ 1 - 0
Projects/永冠OPP/WCS.Service/Works/SRM/SRMWork.cs

@@ -22,6 +22,7 @@ namespace WCS.Service.Works.SRM
 
         protected override void Do(Device<ISRM520, ISRM521, ISRM537> obj)
         {
+            obj.Data2.RES14_2 = 15467;
         }
 
         protected override bool SelectDevice(WCS_DEVICE dev)

+ 3 - 0
Projects/永冠OPP/WCS.Service/Works/Station/一楼入库.cs

@@ -6,6 +6,9 @@ using WCS.Service.Handlers;
 
 namespace WCS.Service.Works.Station
 {
+    /// <summary>
+    /// 
+    /// </summary>
     [WorkTitle(typeof(ProductHandler), "扫码入库")]
     internal class 扫码入库 : DeviceWork<Device<IStation520, IStation521, IStation523>>
     {

+ 1 - 0
Projects/永冠OPP/WCS.Service/Works/Station/涂布入库.cs

@@ -62,6 +62,7 @@ namespace WCS.Service.Works.Station
     {
         protected override void Do(Device<IStation520, IStation521, IStation523> obj)
         {
+
         }
 
         protected override bool SelectDevice(WCS_DEVICE dev)

+ 5 - 3
Projects/永冠OPP/WCS.Service/appsettings.json

@@ -9,7 +9,9 @@
   "ConnectionStrings": {
     //"WCSDB": "Data Source=192.168.251.12;User ID=sa;Password=abc.123;Initial Catalog=WCS_MW;Integrated Security=False"
     //"WCSDB": "Data Source=192.168.249.120;User ID=sa;Password=password@123$%^;Initial Catalog=WCS_MW;Integrated Security=False;"
-    "WCSDB": "server=localhost;Database=wcs;Uid=root;Pwd=123456;AllowLoadLocalInfile=true"
-    //"WMSDB": "Data Source=192.168.249.151;User ID=sa;Password=Password@123;Initial Catalog=yongguanwms_opp;Integrated Security=False;"
+    //本地数据库
+    "WCSDB": "Data Source=LAPTOP-D9OEIS1K\\SQLEXPRESS;User ID=sa;Password=7166766;Initial Catalog=wcs;Integrated Security=False;"
+    //MySql
+    //"WCSDB": "server=localhost;Database=wcs;Uid=root;Pwd=123456;AllowLoadLocalInfile=true"
   }
-}
+}

+ 16 - 2
Virtual_PLC/PlcData.cs

@@ -10,6 +10,11 @@ namespace Virtual_PLC
     {
         private static RedisClient Redis { get; set; }
 
+        /// <summary>
+        /// 数据结构缓存
+        /// </summary>
+        private static List<PLCData> PLCDatas { get; set; } = new List<PLCData>();
+
         /// <summary>
         /// redis 链接字符串
         /// </summary>
@@ -35,6 +40,10 @@ namespace Virtual_PLC
         /// <param name="pLCData">一个PLC</param>
         public void InitPlcData(PLCData pLCData)
         {
+            if (!PLCDatas.Contains(pLCData))
+            {
+                PLCDatas.Add(pLCData);
+            }
             //用总长度除以数据长度,再以每断数据的起始位置、IP、DB组成Key
             var mun = pLCData.Length / pLCData.DataLength;
             int addstart = 0;
@@ -95,9 +104,14 @@ namespace Virtual_PLC
         /// <summary>
         ///
         /// </summary>
-        public static void Write(PLCData pLCData, int startLength, byte[] bytes)
+        public static void Write(PLCData pLCData, int startLength, byte[] value)
         {
-            Redis.Set($"{pLCData.IP}:{pLCData.DB}:{startLength}", bytes);
+            var data = PLCDatas.Find(v => v.IP == pLCData.IP && v.DB == pLCData.DB);
+            var start = startLength < data.DataLength ? 0 : (data.DataLength - startLength) + startLength;
+            //获取原有数据
+            var bytes = System.Text.Encoding.Default.GetBytes(Redis.Get($"{pLCData.IP}:{pLCData.DB}:{start}"));
+            value.CopyTo(bytes, startLength - 1);
+            Redis.Set($"{pLCData.IP}:{pLCData.DB}:{start}", bytes);
         }
     }
 

+ 27 - 2
WCS.Core/Configs.cs

@@ -7,11 +7,29 @@ namespace WCS.Core
 {
     public static class Configs
     {
+        public static Type ProtocolProxyBaseType { get; set; }
+
+        private static List<SystemMode> SystemModes { get; set; } = new List<SystemMode>();
+
         /// <summary>
-        /// 设置协议通讯代理类的基类,继承至DataObject,IBaseType
+        /// 添加一种模式
         /// </summary>
-        public static Type ProtocolProxyBaseType { get; set; }
+        /// <param name="mode"></param>
+        public static void AddSystemMode(SystemMode mode)
+        {
+            if (SystemModes.Contains(mode)) return;
+            SystemModes.Add(mode);
+        }
 
+        /// <summary>
+        /// 是否有
+        /// </summary>
+        /// <param name="mode"></param>
+        /// <returns></returns>
+        public static bool Any(SystemMode mode)
+        {
+            return SystemModes.Contains(mode);
+        }
 
         public static Encoding StringEncoding { get; set; }
 
@@ -27,6 +45,13 @@ namespace WCS.Core
         }
 
         public static Action<string, string> UploadException { get; set; }
+    }
 
+    /// <summary>
+    /// 系统模式
+    /// </summary>
+    public enum SystemMode
+    {
+        虚拟PLC = 1,
     }
 }

+ 1 - 1
WCS.Core/DataTrans/DataBlock.cs

@@ -48,7 +48,7 @@ namespace WCS.Core
                 lock (Entity.PLC)
                 {
                     sw.Start();
-                    data = Entity.PLC.Ex().Accessor.ReadBytes((ushort)Entity.NO, 0, (ushort)Entity.LENGTH);
+                    data = Entity.PLC.Ex().Accessor.ReadBytes((ushort)Entity.NO, 0, (ushort)Entity.LENGTH, (ushort)Entity.DATALENGTH);
                     sw.Stop();
                 }
 

+ 1 - 1
WCS.Core/DataTrans/IPLCAccessor.cs

@@ -12,7 +12,7 @@ namespace WCS.Core.DataTrans
     {
         void WriteBytes(ushort db, ushort address, byte[] data);
 
-        byte[] ReadBytes(ushort db, ushort address, ushort length);
+        byte[] ReadBytes(ushort db, ushort address, ushort length, ushort dataLength);
     }
 
     public class PlcAccessor : EntityEx<WCS_PLC>

+ 3 - 3
WCS.Core/DataTrans/ProtocolProxyBase.cs

@@ -27,12 +27,12 @@ namespace WCS.Core.DataTrans
         /// <summary>
         /// 起始便宜量,按字节算
         /// </summary>
-        private readonly ushort _start;
+        public readonly ushort _start;
 
         /// <summary>
         /// 长度,按字节算
         /// </summary>
-        private readonly ushort _length;
+        public readonly ushort _length;
 
         public WCS_DATABLOCK Db;
 
@@ -40,7 +40,7 @@ namespace WCS.Core.DataTrans
 
         protected ProtocolProxyBase(string id, WCS_DATABLOCK db, ushort start, WCS_DEVICEPROTOCOL deviceItem)
         {
-            var type = this.GetType();
+           var type = this.GetType();
             if (!LockObjs.ContainsKey(type))
                 LockObjs[type] = new object();
 

+ 6 - 7
WCS.Core/LogicHandler.cs

@@ -2,6 +2,7 @@
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
+using System.Diagnostics;
 using System.Linq;
 using System.Threading;
 using System.Threading.Tasks;
@@ -124,8 +125,10 @@ namespace WCS.Core
 
             while (true)
             {
-                var dd = DateTime.Now;
+                var time = new Stopwatch();
+                time.Start();
                 Frame = DateTime.Now;
+
                 Parallel.ForEach(arr, db =>
                 {
                     try
@@ -138,7 +141,7 @@ namespace WCS.Core
                         Console.WriteLine("更新" + db.NAME + "数据失败:" + ex.Message);
                     }
                 });
-                var dbTimes = (DateTime.Now - dd).TotalMilliseconds;
+                time.Stop();
 
                 var total = (DateTime.Now - _last).TotalMilliseconds;
                 var s = (int)(600 - total);
@@ -147,7 +150,7 @@ namespace WCS.Core
                 total = (DateTime.Now - _last).TotalMilliseconds;
                 Console.ForegroundColor = ConsoleColor.Blue;
                 //此处打印的logicTimes实际是上一个周期的业务处理时长
-                Console.WriteLine("------刷新DB块数据耗时:" + ((int)dbTimes).ToString().PadRight(4, ' ') + ";业务逻辑耗时:" + ((int)_logicTimes).ToString().PadRight(4, ' ') + ";周期总耗时" + ((int)total).ToString().PadRight(4, ' ') + "");
+                Console.WriteLine("------刷新DB块数据耗时:" + time.ElapsedMilliseconds + ";业务逻辑耗时:" + _logicTimes.ToString().PadRight(4, ' ') + ";周期总耗时" + ((int)total).ToString().PadRight(4, ' ') + "");
                 Console.ResetColor();
                 _last = DateTime.Now;
 
@@ -365,8 +368,4 @@ namespace WCS.Core
 
         public abstract void Execute(object obj);
     }
-
-   
-
-   
 }

+ 1 - 1
WCS.Core/WCS.Core.csproj

@@ -16,13 +16,13 @@
   </ItemGroup>
 
   <ItemGroup>
-    <PackageReference Include="DBHelper-SqlSugar" Version="1.0.0.1" />
     <PackageReference Include="FreeRedis" Version="0.3.5" />
     <PackageReference Include="HslCommunication" Version="6.2.2" />
     <PackageReference Include="Logs" Version="1.0.0.1" />
   </ItemGroup>
 
   <ItemGroup>
+    <ProjectReference Include="..\DBHelper-SqlSugar\DBHelper-SqlSugar.csproj" />
     <ProjectReference Include="..\WCS.Entity\WCS.Entity.csproj" />
   </ItemGroup>
 

+ 1 - 3
WCS.Entity/OBJ.cs

@@ -1,6 +1,5 @@
 using SqlSugar;
 using System;
-using System.ComponentModel.DataAnnotations;
 using System.ComponentModel.DataAnnotations.Schema;
 
 namespace WCS.Entity
@@ -45,8 +44,7 @@ namespace WCS.Entity
         /// <summary>
         /// 版本号
         /// </summary>
-        [SugarColumn(ColumnDescription = "版本号")]
-        [Timestamp]
+        [SugarColumn(ColumnDescription = "版本号", ColumnDataType = "timestamp", IsNullable = true, IsOnlyIgnoreInsert = true, IsOnlyIgnoreUpdate = true)]
         public byte[] VER { get; set; }
 
         /// <summary>

+ 5 - 5
WCS.Entity/WCS_DEVICE.cs

@@ -29,26 +29,26 @@ namespace WCS.Entity
         /// <summary>
         /// 设备可用协议集合
         /// </summary>
-        [Navigate(NavigateType.OneToMany, nameof(WCS_DEVICEPROTOCOL.DATABLOCKCODE))]
-        public List<WCS_DEVICEPROTOCOL> DEVICEPROTOCOLS { get; set; } = new List<WCS_DEVICEPROTOCOL>();
+        [Navigate(NavigateType.OneToMany, nameof(WCS_DEVICEPROTOCOL.DEVICECODE))]
+        public List<WCS_DEVICEPROTOCOL> DEVICEPROTOCOLS { get; set; }
 
         /// <summary>
         /// 设备可用路由集合
         /// </summary>
         [Navigate(NavigateType.OneToMany, nameof(WCS_ROUTE.DEVICECODE))]
-        public List<WCS_ROUTE> ROUTES { get; set; } = new List<WCS_ROUTE>();
+        public List<WCS_ROUTE> ROUTES { get; set; }
 
         /// <summary>
         /// 设备可用路径集合
         /// </summary>
         [Navigate(NavigateType.OneToMany, nameof(WCS_PATH.STARTCODE))]
-        public List<WCS_PATH> PATHS { get; set; } = new List<WCS_PATH>();
+        public List<WCS_PATH> PATHS { get; set; }
 
         /// <summary>
         /// 设备对应设备组信息
         /// </summary>
         [Navigate(NavigateType.OneToMany, nameof(WCS_GROUPMEMBER.GROUPCODE))]
-        public List<WCS_GROUPMEMBER> DEVICEGROUP { get; set; } = new List<WCS_GROUPMEMBER>();
+        public List<WCS_GROUPMEMBER> DEVICEGROUP { get; set; }
 
         public override string ToString()
         {

+ 5 - 5
WCS.Entity/WCS_PLC.cs

@@ -34,31 +34,31 @@ namespace WCS.Entity
         /// <summary>
         /// 端口
         /// </summary>
-        [SugarColumn(ColumnDescription = "端口", Length = 20)]
+        [SugarColumn(ColumnDescription = "端口")]
         public int PORT { get; set; } = 102;
 
         /// <summary>
         /// 插槽号
         /// </summary>
-        [SugarColumn(ColumnDescription = "插槽号", Length = 20)]
+        [SugarColumn(ColumnDescription = "插槽号")]
         public int SLOT { get; set; }
 
         /// <summary>
         /// 机架号
         /// </summary>
-        [SugarColumn(ColumnDescription = "机架号", Length = 20)]
+        [SugarColumn(ColumnDescription = "机架号")]
         public int RACK { get; set; }
 
         /// <summary>
         /// 厂商
         /// </summary>
-        [SugarColumn(ColumnDescription = "厂商", Length = 20)]
+        [SugarColumn(ColumnDescription = "厂商")]
         public PLCType TYPE { get; set; }
 
         /// <summary>
         /// 型号
         /// </summary>
-        [SugarColumn(ColumnDescription = "型号", Length = 10)]
+        [SugarColumn(ColumnDescription = "型号")]
         public PLCMODEL MODEL { get; set; }
     }