Преглед изворни кода

Optimize Modbus_Tcp SlaveAddress
Move Hareware config to database

Zixuan пре 6 дана
родитељ
комит
602324fafd

+ 4 - 4
CommunicationProtocols/ModBusTcp/Modbus_Tcp.cs

@@ -62,7 +62,7 @@ public class Modbus_Tcp : IModBus<byte[]?>
         {
             lock (this)
             {
-                Span<byte> bytes = this._master.ReadHoldingRegisters(0x00, index, count);
+                Span<byte> bytes = this._master.ReadHoldingRegisters(slaveAddress, index, count);
                 if (bytes == null)
                     return null;
                 return bytes.ToArray();
@@ -91,7 +91,7 @@ public class Modbus_Tcp : IModBus<byte[]?>
         try
         {
             lock (this)
-                this._master.WriteMultipleRegisters(0x00, (int)index, bytes);
+                this._master.WriteMultipleRegisters(slaveAddress, (int)index, bytes);
         }
         catch
         {
@@ -125,7 +125,7 @@ public class Modbus_Tcp : IModBus<byte[]?>
         try
         {
             lock (this)
-                this._master.WriteMultipleRegisters(0x00, (int)index, bytes);
+                this._master.WriteMultipleRegisters(slaveAddress, (int)index, bytes);
         }
         catch
         {
@@ -144,7 +144,7 @@ public class Modbus_Tcp : IModBus<byte[]?>
         try
         {
             lock (this)
-                this._master.WriteSingleRegister(0x00, index, result);
+                this._master.WriteSingleRegister(slaveAddress, index, result);
         }
         catch
         {

+ 1 - 0
DataBase/ORM/IORM.cs

@@ -28,6 +28,7 @@ public interface IORM : IDisposable
     Task<bool> Query<T>(string tableName, Action<List<T>> results) where T : class, new();
     Task<bool> Query<T>(Expression<Func<T, bool>> expression, Action<List<T>> results) where T : class, new();
     Task<bool> Query<T>(string tableName, Expression<Func<T, bool>> expression, Action<List<T>> results) where T : class, new();
+    bool AddOrUpdate<T>(string tableName, T data, Expression<Func<T, bool>> expression) where T : class, new();
 
     bool Delete<T>(string tableName, Expression<Func<T, bool>> expression) where T : class, new();
 }

+ 29 - 0
DataBase/SqlSugarORM/SqlSugarCustom.cs

@@ -257,6 +257,35 @@ public class SqlSugarCustom : IORM
         return true;
     }
 
+    bool IORM.AddOrUpdate<T>(string tableName, T data, Expression<Func<T, bool>> expression)
+    {
+        if (this._Client is null)
+            return false;
+
+        try
+        {
+            if (string.IsNullOrEmpty(tableName))
+            {
+                if (this._Client.Updateable(data).Where(expression).ExecuteCommand() == 0)
+                    return (this as IORM).Insert(data);
+            }
+            else
+            {
+                if (this._Client.Updateable(data).Where(expression).AS(tableName).ExecuteCommand() == 0)
+                    return (this as IORM).Insert(tableName,data);
+            }
+        }
+        catch
+        {
+            if (string.IsNullOrEmpty(tableName))
+                _logQueue?.Enqueue(new($"Update {data.ToString} Failed", DateTime.Now, LogLevel.Error));
+            else
+                _logQueue?.Enqueue(new($"Update {data.ToString} to table {tableName} Failed", DateTime.Now, LogLevel.Error));
+            return false;
+        }
+        return true;
+    }
+
     #region Disopse
     protected virtual void Dispose(bool disposing)
     {

+ 4 - 3
MinicsConsole/Business/HardwareOperator.cs

@@ -5,7 +5,8 @@ namespace MinicsConsole.Business;
 public class HardwareOperator(
     Hardwares hardwares,
     HardWareMonitor hardWareMonitor,
-    HardwareFileLoader hardwareFileLoader, 
+    //HardwareFileLoader hardwareFileLoader, 
+    HardwareDBLoader hardwareDBLoader,
     UISender uIConnector,ILog log)
 {
     public Task QueryHardwares()
@@ -113,7 +114,7 @@ public class HardwareOperator(
             EnableChannel(mini8Index, channelIndex, Inhibit.Disable);
 
         uIConnector.UpdateSingleChannel(mini8Index, channelIndex, channel);
-        hardwareFileLoader.SaveSingleMini8(mini8Index);
+        hardwareDBLoader.SaveSingleMini8(mini8Index);
 
         log.Info($"HardwareHub - SwitchChannelMode  Mini8-{mini8Index} Channel-{channelIndex} ChannelMode-{channelMode}");
 
@@ -164,7 +165,7 @@ public class HardwareOperator(
             uIConnector.UpdateMini8(mini8Index, mini8);
         }
 
-        hardwareFileLoader.SaveSingleMini8(mini8Index);
+        hardwareDBLoader.SaveSingleMini8(mini8Index);
         log.Info($"HardwareHub - EnableDisableDevice  Mini8-{mini8Index}  isEnable-{isEnable}");
 
         return Task.CompletedTask;

+ 4 - 3
MinicsConsole/Helper/ConfigUpdater.cs

@@ -134,6 +134,7 @@ public class ConfigUpdater(Hardwares hardwares, ConfigFiles configFiles, HardWar
 
                 if (!channels.TryGetValue(channelRealTime.Key, out var hardwareChannel) || hardwareChannel is null)
                     continue;
+
                 //Take ChannelMode from Hareware configruation
                 channelConfig.ChannelMode = hardwareChannel.ChannelMode;
             }
@@ -142,13 +143,13 @@ public class ConfigUpdater(Hardwares hardwares, ConfigFiles configFiles, HardWar
         });
 
 
-        if (hardWareMonitor.GetCurrentLimit() is not IEnumerable<(byte channelIndex, Dictionary<byte, Mini8Limit>? limits)> limitGroups)
+        if (hardWareMonitor.GetCurrentLimit() is not IDictionary<byte, Dictionary<byte, Mini8Limit>?> limitGroups)
             goto final;
 
         Parallel.ForEach(limitGroups, (t) =>
         {
-            byte mini8Index = t.channelIndex;
-            Dictionary<byte, Mini8Limit>? data = t.limits;
+            byte mini8Index = t.Key;
+            Dictionary<byte, Mini8Limit>? data = t.Value;
 
             if (data is null)
                 return;

+ 99 - 0
MinicsConsole/Helper/HardwareDBLoader.cs

@@ -0,0 +1,99 @@
+namespace MinicsConsole.Helper;
+
+public class HardwareDBLoader(OrmCollections ormCollections, Hardwares hardwares)
+{
+    public bool Load()
+    {
+        if (ormCollections == null || ormCollections.MainORM is null)
+            return false;
+
+        IORM orm = ormCollections.MainORM;
+
+        var result = orm.Query<Mini8Data>("Mini8Config", (mini8s) =>
+        {
+            foreach (Mini8Data mini8 in mini8s)
+                hardwares.Mini8s[mini8.Index] = mini8;
+
+        }).Result;
+
+        result &= orm.Query<ChannelData>("ChannelConfigConfig", (channelDatas) =>
+        {
+            foreach (ChannelData channelData in channelDatas)
+            {
+                if (!hardwares.Mini8Channels.TryGetValue(channelData.Mini8Index, out ConcurrentDictionary<byte, ChannelData>? channels) || channels is null)
+                {
+                    channels = [];
+                    hardwares.Mini8Channels[channelData.Mini8Index] = channels;
+                }
+                channels[channelData.ChannelIndex] = channelData;
+            }
+        }).Result;
+
+        if (hardwares.Mini8s is null || hardwares.Mini8s.IsEmpty)
+            return false;
+
+        if (hardwares.Mini8Channels is null || hardwares.Mini8Channels.IsEmpty)
+            return false;
+
+        return result;
+    }
+
+    public bool Save()
+    {
+        if (ormCollections == null || ormCollections.MainORM is null)
+            return false;
+
+        IORM orm = ormCollections.MainORM;
+        orm.CreateTable<Mini8Data>("Mini8Config");
+        orm.CreateTable<ChannelData>("ChannelConfigConfig");
+
+        foreach (var mini8 in hardwares.Mini8s.Values)
+        {
+            if (!orm.AddOrUpdate("Mini8Config", mini8, t => t.Index == mini8.Index))
+                return false;
+        }
+
+        foreach (var channels in hardwares.Mini8Channels.Values)
+        {
+            foreach (var channel in channels)
+            {
+                ChannelData channelData = channel.Value;
+
+                if (!orm.AddOrUpdate("ChannelConfigConfig", channelData, t => t.Mini8Index == channelData.Mini8Index && t.ChannelIndex == channelData.ChannelIndex))
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    public bool SaveSingleMini8(byte mini8Index)
+    {
+        if (ormCollections == null || ormCollections.MainORM is null)
+            return false;
+
+        IORM orm = ormCollections.MainORM;
+        orm.CreateTable<Mini8Data>("Mini8Config");
+        orm.CreateTable<ChannelData>("ChannelConfigConfig");
+
+        if (!hardwares.Mini8s.TryGetValue(mini8Index, out Mini8Data? mini8) || mini8 is null)
+            return false;
+
+        if (!hardwares.Mini8Channels.TryGetValue(mini8Index, out ConcurrentDictionary<byte, ChannelData>? channels) || channels is null)
+            return false;
+
+        if (!orm.AddOrUpdate("Mini8Config", mini8, t => t.Index == mini8.Index))
+            return false;
+
+        foreach (var channel in channels)
+        {
+            ChannelData channelData = channel.Value;
+
+            if (!orm.AddOrUpdate("ChannelConfigConfig", channelData, t => t.Mini8Index == channelData.Mini8Index && t.ChannelIndex == channelData.ChannelIndex))
+                return false;
+        }
+
+        return true;
+    }
+
+}

+ 13 - 4
MinicsConsole/Helper/HarewareMonitors.cs

@@ -152,13 +152,22 @@ public class HardWareMonitor(HardwareAddress address, Hardwares hardwares, Mini8
         return list;
     }
 
-    public IEnumerable<(byte channelIndex, Dictionary<byte, Mini8Limit>? limits)> GetCurrentLimit()
+    public IDictionary<byte, Dictionary<byte, Mini8Limit>?> GetCurrentLimit()
     {
-        List<(byte channelIndex, Dictionary<byte, Mini8Limit>? limits)> list = [];
+        Dictionary<byte, Dictionary<byte, Mini8Limit>?> list = [];
         foreach (KeyValuePair<byte, IMini8Communicator> communicator in this.Mini8Communicators)
         {
-            communicator.Value.GetRealtimeLimit(out Dictionary<byte, Mini8Limit>? output);
-            list.Add((communicator.Key, output));
+            for (int i = 0; i < 10; i++)
+            {
+                if (!communicator.Value.GetRealtimeLimit(out Dictionary<byte, Mini8Limit>? output) || output is null)
+                {
+                    Thread.Sleep(200);
+                    continue;
+                }
+
+                list[communicator.Key] = output;
+                break;
+            }
         }
         return list;
     }

+ 15 - 10
MinicsConsole/HostLifetime.cs

@@ -2,6 +2,7 @@
 
 class HostLifetime(
         HardwareFileLoader hardwareFileLoader,
+        HardwareDBLoader hardwareDBLoader,
         ConfigFileLoader configFileLoader,
         AddressFileLoader addressFileLoader,
         HardWareMonitor hardWareMonitor,
@@ -22,8 +23,21 @@ class HostLifetime(
     async Task IHostedService.StartAsync(CancellationToken cancellationToken)
     {
         log.Initialize("General");
+        //Connect to DataBase Server
+        ormCollections.MainORM = new SqlSugarCustom();
+        if (string.IsNullOrEmpty(basicInfo.DBConnectionString) ||
+            !ormCollections.MainORM.Initialize() ||
+            !ormCollections.MainORM.Open(basicInfo.DBConnectionString, DbType.PostgreSQL))
+        {
+            log.Fatal($"Connect DB Failed");
+            Environment.Exit(0);
+        }
 
-        hardwareFileLoader.Load();
+        if (!hardwareDBLoader.Load())
+        {
+            hardwareFileLoader.Load();
+            hardwareDBLoader.Save();
+        }
         configFileLoader.Load();
         addressFileLoader.Load();
         addressFileLoader.LoadPLC();
@@ -47,15 +61,6 @@ class HostLifetime(
         dataDispatcher.TryAddNotifier("RT", rtNotifer);
         dataDispatcher.TryAddNotifier("Kanban", kanbanNotifier);
 
-        //Connect to DataBase Server
-        ormCollections.MainORM = new SqlSugarCustom();
-        if (string.IsNullOrEmpty(basicInfo.DBConnectionString) ||
-            !ormCollections.MainORM.Initialize() ||
-            !ormCollections.MainORM.Open(basicInfo.DBConnectionString, DbType.PostgreSQL))
-        {
-            log.Fatal($"Connect DB Failed");
-            Environment.Exit(0);
-        }
 
 
         log.Info($"Start RT Server  {basicInfo.RTServerAddress}:{basicInfo.RTServerPort} success");

+ 1 - 0
MinicsConsole/Program.cs

@@ -62,6 +62,7 @@ internal class Program
 
         //DataBase
         builder.Services.AddSingleton<OrmCollections>();
+        builder.Services.AddSingleton<HardwareDBLoader>();
 
         //Businesses
         builder.Services.AddSingleton<UserOperator>();

+ 1 - 1
MinicsUI/Connector/HubSender.cs

@@ -27,7 +27,7 @@ public class HubSender(HubReceiver receiver, Hardwares hardwares) : SenderBase,
         temp.On<int, DateTime>("UpdateDataBaseInfo", receiver.UpdateDataBaseInfo);
         temp.On<byte, byte, ChannelData>("ChannelDataUpdate", receiver.ChannelDataUpdate);
 
-        temp.ServerTimeout = TimeSpan.FromSeconds(5.0);
+        //temp.ServerTimeout = TimeSpan.FromSeconds(5.0);
 
 
         for (int i = 1; i <= retry; i++)