DbJSonLoader.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. using AutoMapper;
  2. using Edge.Core.Configuration;
  3. using Edge.Core.Database;
  4. using Edge.Core.Database.Configuration.Models;
  5. using Edge.Core.Parser.BinaryParser;
  6. using Edge.Core.Processor.Communicator;
  7. using Edge.Core.Processor.Dispatcher.Attributes;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.Extensions.Logging;
  10. using Microsoft.Extensions.Logging.Abstractions;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Reflection;
  16. using System.Text;
  17. using System.Text.Json;
  18. using System.Threading.Tasks;
  19. namespace Edge.Core.Processor.Dispatcher
  20. {
  21. public class DbJSonLoader : IProcessorLoader, IProcessorMetaConfigAccessor
  22. {
  23. protected IServiceProvider services;
  24. protected static ILogger mainLogger = NullLogger.Instance;
  25. private Dictionary<IProcessor, ProcessorMetaConfig> processorInstanceAndMetaConfigDic
  26. = new Dictionary<IProcessor, ProcessorMetaConfig>();
  27. public DbJSonLoader(IServiceProvider services)
  28. {
  29. this.services = services;
  30. var loggerFactory = services.GetRequiredService<ILoggerFactory>();
  31. mainLogger = loggerFactory.CreateLogger("Main");
  32. }
  33. protected virtual IEnumerable<ProcessorMetaConfig> LoadProcessorMetaConfigs()
  34. {
  35. string json = @"[
  36. {
  37. ""Id"": 16,
  38. ""Name"": ""HengshanPaymentTerminal.HengshanPayTerminal.Hengs_938d2e2bd48b45ba_8"",
  39. ""Description"": """",
  40. ""Type"": 0,
  41. ""Parts"": [
  42. {
  43. ""Id"": 38,
  44. ""Type"": 1,
  45. ""FullTypeString"": ""HengshanPaymentTerminal.HengshanPayTermHandler, HengshanPaymentTerminal, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"",
  46. ""ParametersJsonArrayStr"": ""[{\""pumpIds\"":\""1,2,3,4\"",\""pumpSubAddresses\"":[{\""PumpId\"":1,\""SubAddress\"":1},{\""PumpId\"":2,\""SubAddress\"":2},{\""PumpId\"":3,\""SubAddress\"":3},{\""PumpId\"":4,\""SubAddress\"":4}],\""pumpNozzleLogicIds\"":[{\""PumpId\"":1,\""LogicIds\"":\""1\""},{\""PumpId\"":2,\""LogicIds\"":\""1\""},{\""PumpId\"":3,\""LogicIds\"":\""1\""},{\""PumpId\"":4,\""LogicIds\"":\""1\""}],\""pumpSiteNozzleNos\"":[{\""PumpId\"":1,\""SiteNozzleNos\"":\""1\""},{\""PumpId\"":2,\""SiteNozzleNos\"":\""2\""},{\""PumpId\"":3,\""SiteNozzleNos\"":\""3\""},{\""PumpId\"":4,\""SiteNozzleNos\"":\""4\""}],\""nozzleLogicIds\"":[{\""NozzleNo\"":1,\""LogicId\"":1},{\""NozzleNo\"":2,\""LogicId\"":1},{\""NozzleNo\"":3,\""LogicId\"":1},{\""NozzleNo\"":4,\""LogicId\"":1}]}]""
  47. },
  48. {
  49. ""Id"": 40,
  50. ""Type"": 0,
  51. ""FullTypeString"": ""Edge.Core.Processor.GenericDeviceProcessor`2, Edge.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"",
  52. ""ParametersJsonArrayStr"": ""[]""
  53. },
  54. {
  55. ""Id"": 41,
  56. ""Type"": 5,
  57. ""FullTypeString"": ""Edge.Core.Processor.Communicator.TcpServerCommunicator`1, Edge.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"",
  58. ""ParametersJsonArrayStr"": ""[23456, 30, \""enabled\"", \""enabled\"", \""2\""]""
  59. }
  60. ],
  61. ""Activated"": true
  62. }
  63. ]";
  64. IEnumerable<ProcessorMetaConfig> configs = JsonSerializer.Deserialize<IEnumerable<ProcessorMetaConfig>>(json);
  65. return configs;
  66. //using (var scope = this.services.CreateScope())
  67. //{
  68. //var dbContext = scope.ServiceProvider.GetRequiredService<SqliteDbContext>();
  69. //var mapper = services.GetRequiredService<IMapper>();
  70. //var processorMetaConfigs =
  71. //mapper.Map<IEnumerable<ProcessorMetaConfig>>(
  72. // dbContext.ProcessorMetaConfigs.Include(i => i.Parts).OrderByDescending(mc => mc.TimeStamp));
  73. //}
  74. // now only for App
  75. //var systemInternalComponentEndPointTypes = new List<Type>();
  76. //foreach (var loadedAss in ObjectInstanceCreator.CurrentDomainAssemblies)
  77. //{
  78. // try
  79. // {
  80. // systemInternalComponentEndPointTypes.AddRange(loadedAss.GetTypes().Where(t =>
  81. // // if already loaded via db metaconfig, then don't load again even IsSystemInternalComponent
  82. // !processorMetaConfigs.SelectMany(mc => mc.Parts).Any(p => p.FullTypeString != t.AssemblyQualifiedName) &&
  83. // !t.IsInterface && !t.IsAbstract &&
  84. // (
  85. // //t.GetInterfaces().Any(ti =>ti.Name == typeof(IDeviceHandler<,>).Name)
  86. // //||
  87. // typeof(IAppProcessor).IsAssignableFrom(t)
  88. // ) &&
  89. // t.GetCustomAttributes<MetaPartsDescriptor>().Any(att => att.IsSystemInternalComponent)
  90. // )
  91. // );
  92. // }
  93. // catch
  94. // { }
  95. //}
  96. //var processorMetaConfigFromAir = systemInternalComponentEndPointTypes.Select(t => new ProcessorMetaConfig()
  97. //{
  98. // Id = new Random().Next(1000, int.MaxValue),
  99. // Activated = true,
  100. // Description = "SystemInternalComponent",
  101. // Name = "SystemInternalComponent_" + t.Name,
  102. // Type = ProcessorTypeEnum.AppProcessor,
  103. // Parts = new List<ProcessorMetaPartsConfig>()
  104. // {
  105. // new ProcessorMetaPartsConfig()
  106. // {
  107. // Id = new Random().Next(1000, int.MaxValue),
  108. // FullTypeString = t.AssemblyQualifiedName,
  109. // Type = ProcessorMetaPartsTypeEnum.App,
  110. // ParametersJsonArrayStr = "["+
  111. // t.GetCustomAttributes<MetaPartsDescriptor>().First(att=>att.IsSystemInternalComponent).DefaultCtorParamsJsonStrings.Aggregate((acc,n)=>acc+","+n)+"]",
  112. // }
  113. // }
  114. //});
  115. //return processorMetaConfigs.Concat(processorMetaConfigFromAir);
  116. }
  117. public IEnumerable<ProcessorInstanceOperatingResult> CreateAll()
  118. {
  119. this.processorInstanceAndMetaConfigDic.Clear();
  120. mainLogger.LogInformation("Use DbJSonLoader for Processor Meta Config.");
  121. mainLogger.LogInformation("==============Instantiate Processors (by DbJSonLoader)==============");
  122. Console.WriteLine();
  123. Console.WriteLine("==============Instantiate Processors (by DbJSonLoader)==============");
  124. var processorMetaConfigs = this.LoadProcessorMetaConfigs().Where(c => c.Activated);
  125. if (processorMetaConfigs == null || !processorMetaConfigs.Any())
  126. {
  127. //mainLogger.LogInformation("Found IDeviceHandler or IAppProcessor type: " + t.FullName + " but there's no meta config defined for it, will skip it");
  128. mainLogger.LogInformation("Found empty MetaConfig in db");
  129. mainLogger.LogInformation("==============Instantiate Processors End==============");
  130. Console.WriteLine("==============Instantiate Processors End==============");
  131. return Enumerable.Empty<ProcessorInstanceOperatingResult>();
  132. }
  133. var createResults = new List<ProcessorInstanceOperatingResult>();
  134. processorMetaConfigs.ToList().ForEach(mc =>
  135. {
  136. mainLogger.LogInformation("constructing [id:" + mc.Id + "]: " + mc.Name + ", type: " + mc.Type);// + ", from: " + t.Assembly.FullName + ", assemblyPath: " + t.Assembly.Location);
  137. Console.WriteLine("[id:" + mc.Id + "]: " + mc.Name);// + " from: " + t.Assembly.GetName().Name);
  138. try
  139. {
  140. var p = ObjectInstanceCreator.CreateProcessor<IProcessor>(mc, new object[] { this.services });
  141. createResults.Add(new ProcessorInstanceOperatingResult()
  142. {
  143. Succeed = true,
  144. ProcessorInstance = p,
  145. HostVersion = Assembly.GetAssembly(p.GetType()).GetName().Version.ToString(),
  146. CoreVersion = Assembly.GetAssembly(typeof(IProcessor)).GetName().Version.ToString(),
  147. MetaConfig = mc,
  148. });
  149. this.processorInstanceAndMetaConfigDic.Add(p, mc);
  150. }
  151. catch (Exception exxxxx)
  152. {
  153. createResults.Add(new ProcessorInstanceOperatingResult()
  154. {
  155. Succeed = false,
  156. MetaConfig = mc,
  157. CoreVersion = Assembly.GetAssembly(typeof(IProcessor)).GetName().Version.ToString(),
  158. FailedReason = exxxxx.ToString()
  159. });
  160. mainLogger.LogError(" - Failed for instantiate: " + "[id:" + mc.Id + "]: " + mc.Name + ", type: " + mc.Type
  161. //+ ", from: " + t.Assembly.FullName + ", assemblyPath: " + t.Assembly.Location
  162. + Environment.NewLine + " " + exxxxx.ToString());
  163. Console.BackgroundColor = ConsoleColor.Red;
  164. Console.ForegroundColor = ConsoleColor.Black;
  165. Console.WriteLine(" - Failed for instantiate: " + "[id:" + mc.Id + "]: " + mc.Name + Environment.NewLine + " " + exxxxx.ToString().Substring(0, 90) + "...");
  166. Console.ResetColor();
  167. }
  168. });
  169. mainLogger.LogInformation("==============Instantiate Processors End==============");
  170. Console.WriteLine("==============Instantiate Processors End==============");
  171. return createResults;
  172. }
  173. public IProcessor Create(string configName)
  174. {
  175. if (string.IsNullOrEmpty(configName)) throw new ArgumentException(nameof(configName));
  176. //ignore the IsActivated
  177. var processorMetaConfig = this.LoadProcessorMetaConfigs().First(mc => mc.Name == configName);
  178. var p = ObjectInstanceCreator.CreateProcessor<IProcessor>(processorMetaConfig, new object[] { this.services });
  179. return p;
  180. }
  181. public async Task<ProcessorMetaPartsConfig> GetMetaPartsMetaConfigAsync(
  182. IProcessor processor, ProcessorMetaPartsTypeEnum metaPartsType)
  183. {
  184. if (!this.processorInstanceAndMetaConfigDic.TryGetValue(processor, out ProcessorMetaConfig pMetaConfig))
  185. return null;
  186. using (var scope = this.services.CreateScope())
  187. {
  188. return null;
  189. }
  190. }
  191. public async Task<ProcessorMetaPartsConfig> UpdateMetaPartsMetaConfigAsync(
  192. IProcessor processor, ProcessorMetaPartsTypeEnum metaPartsType, object[] parameters)
  193. {
  194. if (!this.processorInstanceAndMetaConfigDic.TryGetValue(processor, out ProcessorMetaConfig pMetaConfig))
  195. return null;
  196. using (var scope = this.services.CreateScope())
  197. {
  198. return null;
  199. }
  200. }
  201. public async Task<bool> RemoveMetaPartsMetaConfigAsync(IProcessor processor, int processorMetaPartsConfigId)
  202. {
  203. if (!this.processorInstanceAndMetaConfigDic.TryGetValue(processor, out ProcessorMetaConfig pMetaConfig))
  204. return false;
  205. using (var scope = this.services.CreateScope())
  206. {
  207. return false;
  208. }
  209. }
  210. public async Task<IEnumerable<ProcessorMetaConfig>> GetMetaConfigAsync()
  211. {
  212. return await this.GetMetaConfigAsync(null);
  213. }
  214. /// <summary>
  215. /// Get the meta configs by its linked sourceEndpointFullTypeStr with *sql likes* input parameter.
  216. /// </summary>
  217. /// <param name="sourceEndpointFullTypeStr"></param>
  218. /// <returns></returns>
  219. public async Task<IEnumerable<ProcessorMetaConfig>> GetMetaConfigAsync(string sourceEndpointFullTypeStr)
  220. {
  221. return null;
  222. }
  223. public async Task<ProcessorMetaConfig> UpsertMetaConfigAsync(ProcessorMetaConfig metaConfig)
  224. {
  225. return null;
  226. }
  227. public async Task<bool> RemoveMetaConfigAsync(int metaConfigId)
  228. {
  229. return false;
  230. }
  231. }
  232. }