Browse Source

Migrate new requrirment and fixes from ELK02

Zixuan 1 month ago
parent
commit
a424a856ca

File diff suppressed because it is too large
+ 415 - 1
Configs/ConfigFile/IOList/Mini8-1.json


+ 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();
 }

+ 59 - 30
DataBase/SqlSugarORM/SqlSugarCustom.cs

@@ -201,18 +201,18 @@ public class SqlSugarCustom : IORM
             return false;
 
         return await Task<bool>.Factory.StartNew(() =>
+        {
+            try
             {
-                try
-                {
-                    results?.Invoke(this._Client.Queryable<T>().Where(expression).ToList());
-                }
-                catch
-                {
-                    _logQueue?.Enqueue(new($"Query {typeof(T)} Failed", DateTime.Now, LogLevel.Error));
-                    return false;
-                }
-                return true;
-            });
+                results?.Invoke(this._Client.Queryable<T>().Where(expression).ToList());
+            }
+            catch
+            {
+                _logQueue?.Enqueue(new($"Query {typeof(T)} Failed", DateTime.Now, LogLevel.Error));
+                return false;
+            }
+            return true;
+        });
     }
 
     async Task<bool> IORM.Query<T>(string tableName, Expression<Func<T, bool>> expression, Action<List<T>> results)
@@ -221,25 +221,25 @@ public class SqlSugarCustom : IORM
             return false;
 
         return await Task<bool>.Factory.StartNew(() =>
-          {
-              try
-              {
-                  if (string.IsNullOrEmpty(tableName))
-                      results?.Invoke(this._Client.Queryable<T>().Where(expression).ToList());
-                  else
-                      results?.Invoke(this._Client.Queryable<T>().AS(tableName).Where(expression).ToList());
-              }
-              catch
-              {
-                  if (string.IsNullOrEmpty(tableName))
-                      _logQueue?.Enqueue(new($"Query {typeof(T)} Failed", DateTime.Now, LogLevel.Error));
-                  else
-                      _logQueue?.Enqueue(new($"Query {typeof(T)} from Table {tableName} Failed", DateTime.Now, LogLevel.Error));
-                  return false;
-              }
-
-              return true;
-          });
+        {
+            try
+            {
+                if (string.IsNullOrEmpty(tableName))
+                    results?.Invoke(this._Client.Queryable<T>().Where(expression).ToList());
+                else
+                    results?.Invoke(this._Client.Queryable<T>().AS(tableName).Where(expression).ToList());
+            }
+            catch
+            {
+                if (string.IsNullOrEmpty(tableName))
+                    _logQueue?.Enqueue(new($"Query {typeof(T)} Failed", DateTime.Now, LogLevel.Error));
+                else
+                    _logQueue?.Enqueue(new($"Query {typeof(T)} from Table {tableName} Failed", DateTime.Now, LogLevel.Error));
+                return false;
+            }
+
+            return true;
+        });
     }
 
     bool IORM.Delete<T>(string tableName, Expression<Func<T, bool>> expression)
@@ -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)
     {

+ 6 - 10
HistoryUI/ViewModels/AlarmViewModel.cs

@@ -24,21 +24,17 @@ public partial class AlarmViewModel(Hardwares hardwares, IORM orm) : BaseViewMod
 
     private void QueryResult(List<DBWarning> results)
     {
+        results = [.. results.OrderBy(t => t.DateTime)];
         App.Current.Dispatcher?.Invoke(() =>
         {
-            base.Results ??= [];
-            base.Results?.Clear();
-        });
-        Task.Factory.StartNew(() =>
-        {
-            results = [.. results.OrderBy(t => t.DateTime)];
+            base.Results = null;
+            Dictionary<int, DBWarning> temp = [];
+
             for (int i = 1; i <= results.Count; i++)
             {
-                App.Current.Dispatcher?.Invoke(() =>
-                {
-                    base.Results!.Add(i, results[i - 1]);
-                });
+                temp.Add(i, results[i - 1]);
             }
+            base.Results = temp;
         });
     }
 }

+ 1 - 1
HistoryUI/ViewModels/BaseViewModel.cs

@@ -36,7 +36,7 @@ public partial class BaseViewModel<T_ResultType> : ObservableObject
     private Hardwares _Hardwares;
 
     [ObservableProperty]
-    private ObservableDictionary<int, T_ResultType>? _Results;
+    private Dictionary<int, T_ResultType>? _Results;
 
     [ObservableProperty]
     private KeyValuePair<byte, Mini8Data>? _SelectedMini8;

+ 4 - 3
HistoryUI/ViewModels/StatusViewModel.cs

@@ -265,10 +265,11 @@ public partial class StatusViewModel : BaseViewModel<DBFormat>
 
     private void RefreshDataTable(List<DBFormat> results)
     {
-        this.Results ??= [];
-        this.Results.Clear();
+        Dictionary<int, DBFormat> temp = [];
+        this.Results = null;
         for (int i = 0; i < results.Count; i++)
-            this.Results.Add(i, results[i]);
+            temp.Add(i, results[i]);
+        this.Results = temp;
     }
 
     private void RefreshPlot()

+ 8 - 8
HistoryUI/Views/MainWindow.xaml.cs

@@ -41,15 +41,15 @@ public partial class MainWindow : Window
             }
             else
             {
-                //this.Left = -1920;
-                //this.Top = 0;
-                //this.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
-                //this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
+                this.Left = 0;
+                this.Top = 0;
+                this.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
+                this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
 
-                this.Left = -1024;
-                this.Top = 0.0;
-                this.Width = 1024;
-                this.Height = 768;
+                //this.Left = -1024;
+                //this.Top = 0.0;
+                //this.Width = 1024;
+                //this.Height = 768;
             }
 
             this.Content = StartSetting.Content switch

+ 3 - 3
MinicsConsole/Helper/ConfigUpdater.cs

@@ -142,13 +142,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;
+    }
+
+}

+ 24 - 4
MinicsConsole/Helper/HarewareMonitors.cs

@@ -152,13 +152,33 @@ public class HardWareMonitor(HardwareAddress address, Hardwares hardwares, Mini8
         return list;
     }
 
-    public IEnumerable<(byte channelIndex, Dictionary<byte, Mini8Limit>? limits)> GetCurrentLimit()
+    //public IEnumerable<(byte channelIndex, Dictionary<byte, Mini8Limit>? limits)> GetCurrentLimit()
+    //{
+    //    List<(byte channelIndex, Dictionary<byte, Mini8Limit>? limits)> list = [];
+    //    foreach (KeyValuePair<byte, IMini8Communicator> communicator in this.Mini8Communicators)
+    //    {
+    //        communicator.Value.GetRealtimeLimit(out Dictionary<byte, Mini8Limit>? output);
+    //        list.Add((communicator.Key, output));
+    //    }
+    //    return list;
+    //}
+
+    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;
     }

+ 19 - 12
MinicsConsole/HostLifetime.cs

@@ -2,6 +2,7 @@
 
 class HostLifetime(
         HardwareFileLoader hardwareFileLoader,
+        HardwareDBLoader hardwareDBLoader,
         ConfigFileLoader configFileLoader,
         AddressFileLoader addressFileLoader,
         HardWareMonitor hardWareMonitor,
@@ -23,7 +24,21 @@ class HostLifetime(
     {
         log.Initialize("General");
 
-        hardwareFileLoader.Load();
+        //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);
+        }
+
+        if (!hardwareDBLoader.Load())
+        {
+            hardwareFileLoader.Load();
+            hardwareDBLoader.Save();
+        }
         configFileLoader.Load();
         addressFileLoader.Load();
         addressFileLoader.LoadPLC();
@@ -36,6 +51,7 @@ class HostLifetime(
         }
         dataDispatcher.TryAddNotifier("PLC", plcNotifier);
         dataDispatcher.TryAddNotifier("UI", uiNotifier);
+
         //Start RT Server
         if (string.IsNullOrEmpty(basicInfo.RTServerAddress) ||
             !rtNotifer.Initialize(tlvProvider) ||
@@ -44,20 +60,10 @@ class HostLifetime(
             log.Fatal($"Open RT Server {basicInfo.RTServerAddress}:{basicInfo.RTServerPort} Failed");
             Environment.Exit(0);
         }
+
         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");
 
         //Connect to Mini8s
@@ -71,6 +77,7 @@ class HostLifetime(
         //Start Collecting Mini8s Realtime Data
         hardWareMonitor.ParallelStartDataCollecion();
 
+        //Start Daily Routine Work
         dailyRoutinHelper.AddorUpdateRoutinWork("CleanDataBase", dataBaseCleaner.CleanDB);
         dailyRoutinHelper.AddorUpdateRoutinWork("CleanLogFile", ((LogSender)log).CleanLog);
         dailyRoutinHelper.StartService(TimeSpan.FromDays(1));

+ 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>();