App.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. using Edge.Core.Processor;
  2. using Edge.Core.IndustryStandardInterface.Pump;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Threading.Tasks;
  6. using System.Linq;
  7. using Edge.Core.IndustryStandardInterface.ATG;
  8. using Microsoft.Extensions.Logging.Abstractions;
  9. using Microsoft.Extensions.Logging;
  10. using Microsoft.Extensions.DependencyInjection;
  11. using Edge.Core.Database;
  12. using AutoMapper;
  13. using Edge.Core.UniversalApi;
  14. using System.Text.Json;
  15. using Microsoft.EntityFrameworkCore;
  16. using System.Text.RegularExpressions;
  17. using Application.ATG_Classic_App.Model;
  18. using System.Diagnostics.CodeAnalysis;
  19. using System.Timers;
  20. using System.Threading;
  21. using Edge.Core.Processor.Dispatcher.Attributes;
  22. namespace Application.ATG_Classic_App
  23. {
  24. [UniversalApi(Name = "OnStateChange", EventDataType = typeof(AtgStateChangeEventArg), Description = "will fire on Atg state changed")]
  25. [UniversalApi(Name = "OnAlarm", EventDataType = typeof(AtgAlarmEventArg), Description = "will fire on Atg alarms detected")]
  26. [MetaPartsDescriptor(
  27. "lang-zh-cn:Pro-gauge 液位仪lang-en-us:Pro-gauge ATG",
  28. "lang-zh-cn:用于总控所有连入此系统的 Pro-gauge 探棒,并提供液位仪控制台功能lang-en-us:Used for overall control all Pro-gauge probes connected in the system, and providing functions of the ATG console",
  29. new[] { "lang-zh-cn:液位仪lang-en-us:ATG" })]
  30. public class App : IAppProcessor, IAutoTankGaugeController
  31. {
  32. private ILogger logger = NullLogger.Instance;
  33. private System.Timers.Timer polling_fast_TankReadingTimer;
  34. /// <summary>
  35. /// DO NOT lower down this value unless you understand the consequence.
  36. /// </summary>
  37. public int polling_fast_TankReadingTimer_Internval = 500;
  38. private int polling_fast_TankReadingTimer_Buffer_MaxLength_By_Second = 60 * 60 * 3;
  39. /// <summary>
  40. /// for track last Inventory saved to db time, and compare to current polling fast timer, if inventory sampling
  41. /// interval time reached, then start a new db saving.
  42. /// </summary>
  43. private DateTime lastInventoriesSavedIntoDatabaseTime = DateTime.MinValue;
  44. private IServiceProvider services;
  45. private IEnumerable<IProbeHandler> probeHandlers;
  46. private IEnumerable<RichTankInfo> richTankInfos = null;
  47. public string MetaConfigName { get; set; }
  48. public int DeviceId { get; }
  49. public IEnumerable<Tank> Tanks => this.richTankInfos.Select(c => c.Tank);
  50. public SystemUnit SystemUnit { get; }
  51. public event EventHandler<AtgStateChangeEventArg> OnStateChange;
  52. public event EventHandler<AtgAlarmEventArg> OnAlarm;
  53. #region UniversalApi - Config
  54. [UniversalApi(Description = "Get the TankOverallConfig, and all TankConfigs.")]
  55. public async Task<Tuple<TankOverallConfig, IEnumerable<TankConfig>>> GetConfigAsync()
  56. {
  57. var dbContext = this.DbContextFactory.CreateDbContext<AppDbContext>();
  58. var tankOverallConfig = await dbContext.TankOverallConfigs
  59. .OrderByDescending(c => c.ModifiedTimeStamp)
  60. .ThenByDescending(c => c.CreatedTimeStamp).FirstOrDefaultAsync();
  61. var haveToDoThisToMakeInMemoryDbUsedInUnitTestToWork = await dbContext.TankConfigs
  62. .Include(tc => tc.TankLimitConfig)
  63. .Include(tc => tc.ProbeConfig)
  64. .Include(tc => tc.ProductConfig)
  65. .Include(tc => tc.TankProfileDatas).ToListAsync();
  66. var tankConfigs = haveToDoThisToMakeInMemoryDbUsedInUnitTestToWork.GroupBy(tc => tc.TankNumber)
  67. .Select(tcGp => tcGp.OrderByDescending(c => c.ModifiedTimeStamp)
  68. .ThenByDescending(c => c.CreatedTimeStamp).FirstOrDefault());
  69. //var tankConfigs = await dbContext.TankConfigs
  70. // .Include(tc => tc.TankLimitConfig)
  71. // .Include(tc => tc.ProbeConfig)
  72. // .Include(tc => tc.ProductConfig)
  73. // .GroupBy(tc => tc.TankNumber)
  74. // .Select(tcGp => tcGp.OrderByDescending(c => c.ModifiedTimeStamp)
  75. // .ThenByDescending(c => c.CreatedTimeStamp).FirstOrDefault()).ToListAsync();
  76. return new Tuple<TankOverallConfig, IEnumerable<TankConfig>>(tankOverallConfig, tankConfigs);
  77. }
  78. [UniversalApi(Description = "Udpate or insert the config, the input and sample could be either of-> </br>" +
  79. "<b>TankOverallConfig:</b> " + "{\"TcReference\":25,\"InventorySamplingInterval\":5000,\"DeliveryMode\":0,\"Id\":0}, </br>" +
  80. "<b>TankConfig:</b> " + "{\"TankNumber\":1,\"Label\":\"I\u0027m Tank with Number 1\",\"Diameter\":1000,\"ThermalCoefficient\":0,\"DeliveryDelay\":0,\"TankProfileDatas\":null,\"ProductConfigId\":null,\"ProductConfig\":{\"ProductCode\":\"91\",\"ProductLabel\":\"91#\",\"Id\":0,\"CreatedTimeStamp\":\"0001-01-01T00:00:00\",\"ModifiedTimeStamp\":null},\"TankLimitConfigId\":null,\"TankLimitConfig\":{\"MaxVolume\":1100,\"FullVolume\":1200,\"HighProduct\":900,\"LowProduct\":100,\"HighWaterWarning\":10,\"HighWaterAlarm\":40,\"FuelTemperatureLowLimit\":1,\"FuelTemperatureHighLimit\":2,\"Id\":0,\"CreatedTimeStamp\":\"0001-01-01T00:00:00\",\"ModifiedTimeStamp\":null},\"ProbeConfigId\":null,\"ProbeConfig\":{\"DeviceId\":1,\"ProbeOffset\":0,\"WaterOffset\":0,\"Id\":0,\"CreatedTimeStamp\":\"0001-01-01T00:00:00\",\"ModifiedTimeStamp\":null},\"Id\":0,\"CreatedTimeStamp\":\"0001-01-01T00:00:00\",\"ModifiedTimeStamp\":null}" + ", </br>" +
  81. "<b>TankLimitConfig:</b> " + "{\"MaxVolume\":4400,\"FullVolume\":4800,\"HighProduct\":3600,\"LowProduct\":400,\"HighWaterWarning\":40,\"HighWaterAlarm\":160,\"FuelTemperatureLowLimit\":4,\"FuelTemperatureHighLimit\":8,\"Id\":0,\"CreatedTimeStamp\":\"0001-01-01T00:00:00\",\"ModifiedTimeStamp\":null}" + ", </br>" +
  82. "<b>ProbeConfig:</b> " + "{\"DeviceId\":4,\"ProbeOffset\":0,\"WaterOffset\":0,\"Id\":0,\"CreatedTimeStamp\":\"0001-01-01T00:00:00\",\"ModifiedTimeStamp\":null}" + ", </br>" +
  83. "<b>ProductConfig:</b> " + "{\"ProductCode\":\"94\",\"ProductLabel\":\"94#\",\"Id\":0,\"CreatedTimeStamp\":\"0001-01-01T00:00:00\",\"ModifiedTimeStamp\":null}")]
  84. public async Task<BaseConfig> UpsertConfigAsync(BaseConfig inputConfig)
  85. {
  86. /*update or insert a db row*/
  87. if (inputConfig == null) throw new ArgumentException(nameof(inputConfig));
  88. //BaseConfig inputConfig = null;
  89. var options = new JsonSerializerOptions
  90. {
  91. PropertyNameCaseInsensitive = true,
  92. };
  93. //switch (input.Parameters.First().Name)
  94. //{
  95. // case "TankOverallConfig":
  96. // {
  97. // inputConfig = JsonSerializer.Deserialize<TankOverallConfig>(input.Parameters.First().Value, options);
  98. // break;
  99. // }
  100. // case "TankConfig":
  101. // {
  102. // inputConfig = JsonSerializer.Deserialize<TankConfig>(input.Parameters.First().Value, options);
  103. // break;
  104. // }
  105. // case "TankLimitConfig":
  106. // {
  107. // inputConfig = JsonSerializer.Deserialize<TankLimitConfig>(input.Parameters.First().Value, options);
  108. // break;
  109. // }
  110. // case "ProbeConfig":
  111. // {
  112. // inputConfig = JsonSerializer.Deserialize<ProbeConfig>(input.Parameters.First().Value, options);
  113. // break;
  114. // }
  115. // case "ProductConfig":
  116. // {
  117. // inputConfig = JsonSerializer.Deserialize<ProductConfig>(input.Parameters.First().Value, options);
  118. // break;
  119. // }
  120. // default:
  121. // throw new InvalidOperationException("Unknown Config name: " + (input.Parameters.First().Name ?? ""));
  122. //}
  123. var dbContext = this.DbContextFactory.CreateDbContext<AppDbContext>();// new SqliteDbContext();
  124. if (inputConfig.Id == 0)
  125. {
  126. /*create one in db*/
  127. inputConfig.CreatedTimeStamp = DateTime.Now;
  128. inputConfig.ModifiedTimeStamp = null;
  129. dbContext.Add(inputConfig);
  130. var effectedRowCount = await dbContext.SaveChangesAsync();
  131. }
  132. else
  133. {
  134. /*udpate one in db*/
  135. inputConfig.ModifiedTimeStamp = DateTime.Now;
  136. dbContext.Entry(inputConfig).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
  137. dbContext.Entry(inputConfig).Property(c => c.CreatedTimeStamp).IsModified = false;
  138. //dbContext.Entry(inputTankOverallConfig).Property(c => c.ModifiedTimeStamp).IsModified = true;
  139. await dbContext.SaveChangesAsync();
  140. }
  141. var haveToDoThisToMakeInMemoryDbUsedInUnitTestToWork = await dbContext.TankConfigs
  142. .Include(tc => tc.TankLimitConfig)
  143. .Include(tc => tc.ProbeConfig)
  144. .Include(tc => tc.ProductConfig)
  145. .Include(tc => tc.TankProfileDatas).ToListAsync();
  146. var tankConfigs = haveToDoThisToMakeInMemoryDbUsedInUnitTestToWork.GroupBy(tc => tc.TankNumber)
  147. .Select(tcGp => tcGp.OrderByDescending(c => c.ModifiedTimeStamp)
  148. .ThenByDescending(c => c.CreatedTimeStamp).FirstOrDefault());
  149. var tankOverallConfig = await dbContext.Set<TankOverallConfig>()//.TankOverallConfigs
  150. .OrderByDescending(c => c.ModifiedTimeStamp)
  151. .ThenByDescending(c => c.CreatedTimeStamp).FirstOrDefaultAsync();
  152. this.richTankInfos = this.TryReCreateRichTankInfos(tankConfigs, tankOverallConfig, this.probeHandlers);
  153. if (this.richTankInfos == null)
  154. {
  155. this.State = AtgState.Inoperative_MissingConfig;
  156. var onStateChangeEventArg = new AtgStateChangeEventArg(this.State,
  157. "Necessary tank configs were missed or invalid after the UpsertConfigAsync(...), fix them and wait for notify.");
  158. this.OnStateChange?.Invoke(this, onStateChangeEventArg);
  159. var universalApiHub = this.services.GetRequiredService<UniversalApiHub>();
  160. await universalApiHub.FireEvent(this, "OnStateChange", onStateChangeEventArg);
  161. return inputConfig;
  162. }
  163. else
  164. {
  165. this.State = AtgState.Idle;
  166. var onStateChangeEventArg = new AtgStateChangeEventArg(AtgState.TanksReloaded, "All tanks reloaded due to Config updated");
  167. this.OnStateChange?.Invoke(this, onStateChangeEventArg);
  168. var universalApiHub = this.services.GetRequiredService<UniversalApiHub>();
  169. await universalApiHub.FireEvent(this, "OnStateChange", onStateChangeEventArg);
  170. return inputConfig;
  171. }
  172. }
  173. [UniversalApi(Description = "add a profile data for a tank.", InputParametersExampleJson = "[1,\"Height0:Volume0,Height1:Volume1,Height2:Volume2...\"]")]
  174. public async Task<object> AddTankProfileDataAsync(byte targetTankNumber, string profileData)
  175. {
  176. /*Add new datas and delete the old datas*/
  177. if (string.IsNullOrEmpty(profileData)) throw new ArgumentException("must provide profileData");
  178. //dataStr format is: "Height0:Volume0,Height1:Volume1,Height2:Volume2..."}
  179. //do a format check
  180. if (!Regex.IsMatch(profileData, @"^(\d+(\.\d+)?:\s?\d+(\.\d+)?,\s?)+\d+(\.\d+)?:\d+(\.\d+)?$"))
  181. throw new ArgumentException("Data string content format is not correct");
  182. string batchLabel = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  183. var dbContext = this.DbContextFactory.CreateDbContext<AppDbContext>(); //new SqliteDbContext();
  184. var targetTankConfig = dbContext.Set<TankConfig>()//.TankConfigs
  185. .First(tc => tc.TankNumber == targetTankNumber);
  186. var tankProfileDatas = profileData.Split(',').Select(part =>
  187. new TankProfileData()
  188. {
  189. TankConfig = targetTankConfig,
  190. Height = double.Parse(part.Split(':')[0]),
  191. Volume = double.Parse(part.Split(':')[1]),
  192. BatchLabel = batchLabel,
  193. });
  194. dbContext.Set<TankProfileData>()//.TankProfileDatas
  195. .AddRange(tankProfileDatas);
  196. var deleting = dbContext.Set<TankProfileData>()//.TankProfileDatas
  197. .Where(d => d.TankConfigId == targetTankConfig.Id && d.BatchLabel != batchLabel);
  198. dbContext.Set<TankProfileData>()//.TankProfileDatas
  199. .RemoveRange(deleting);
  200. await dbContext.SaveChangesAsync();
  201. var haveToDoThisToMakeInMemoryDbUsedInUnitTestToWork = await dbContext.TankConfigs
  202. .Include(tc => tc.TankLimitConfig)
  203. .Include(tc => tc.ProbeConfig)
  204. .Include(tc => tc.ProductConfig)
  205. .Include(tc => tc.TankProfileDatas).ToListAsync();
  206. var tankConfigs = haveToDoThisToMakeInMemoryDbUsedInUnitTestToWork.GroupBy(tc => tc.TankNumber)
  207. .Select(tcGp => tcGp.OrderByDescending(c => c.ModifiedTimeStamp)
  208. .ThenByDescending(c => c.CreatedTimeStamp).FirstOrDefault());
  209. var tankOverallConfig = await dbContext.Set<TankOverallConfig>()//.TankOverallConfigs
  210. .OrderByDescending(c => c.ModifiedTimeStamp)
  211. .ThenByDescending(c => c.CreatedTimeStamp).FirstOrDefaultAsync();
  212. this.richTankInfos = this.TryReCreateRichTankInfos(tankConfigs, tankOverallConfig, this.probeHandlers);
  213. if (this.richTankInfos == null)
  214. {
  215. this.State = AtgState.Inoperative_MissingConfig;
  216. var onStateChangeEventArg = new AtgStateChangeEventArg(this.State,
  217. "Necessary tank configs were missed or invalid after the AddTankProfileData(...), fix them and wait for notify.");
  218. this.OnStateChange?.Invoke(this, onStateChangeEventArg);
  219. var universalApiHub = this.services.GetRequiredService<UniversalApiHub>();
  220. await universalApiHub.FireEvent(this, "OnStateChange", onStateChangeEventArg);
  221. return false;
  222. }
  223. else
  224. {
  225. this.State = AtgState.Idle;
  226. var onStateChangeEventArg = new AtgStateChangeEventArg(AtgState.TanksReloaded, "All tanks reloaded due to TankProfileData updated");
  227. this.OnStateChange?.Invoke(this, onStateChangeEventArg);
  228. var universalApiHub = this.services.GetRequiredService<UniversalApiHub>();
  229. await universalApiHub.FireEvent(this, "OnStateChange", onStateChangeEventArg);
  230. return true;
  231. }
  232. }
  233. [UniversalApi(Description = "start or stop a manual delivery", InputParametersExampleJson = "[1,\"start\"]")]
  234. public async Task<TankReading> StartOrStopManualDeliveryAsync(byte targetTankNumber, string operation)
  235. {
  236. if (operation.ToLower() != "start" && operation.ToLower() != "stop") throw new ArgumentException("must provide valid operation string 'start' or 'stop'");
  237. Tuple<DateTime, TankReading> mostRecentReading = null;
  238. if (this.tankReadings_fast_buffer.TryGetValue(targetTankNumber, out List<Tuple<DateTime, TankReading>> readings))
  239. {
  240. mostRecentReading = readings.LastOrDefault();
  241. if (mostRecentReading == null ||
  242. // max tolerance is 4 cycles of fast polling missing.
  243. DateTime.Now.Subtract(mostRecentReading.Item1).TotalMilliseconds >= this.polling_fast_TankReadingTimer_Internval * 4)
  244. throw new InvalidOperationException("Could not get most recent tank reading for target tank, may retry later?");
  245. if (mostRecentReading.Item2.Volume == null || mostRecentReading.Item2.WaterVolume == null)
  246. throw new InvalidOperationException("Most recent tank reading for target tank is invalid, may retry later?");
  247. }
  248. var dbContext = this.DbContextFactory.CreateDbContext<AppDbContext>();
  249. var lastDeliveryRecord = await dbContext.Deliveries.Where(d => d.TankNumber == targetTankNumber)
  250. .OrderByDescending(d => d.StartingDateTime).FirstOrDefaultAsync();
  251. var targetTank = this.Tanks?.FirstOrDefault(t => t.TankNumber == targetTankNumber);
  252. if (targetTank == null) throw new InvalidOperationException("Could not find tank with tankNumber: " + targetTankNumber);
  253. if (operation.ToLower() == "start")
  254. {
  255. // last delivery still in open.
  256. if (lastDeliveryRecord != null && lastDeliveryRecord.EndingDateTime == null)
  257. throw new InvalidOperationException($"Previous Delivery(started " +
  258. $"from: {lastDeliveryRecord.StartingDateTime.ToString("yyyy-MM-dd HH:mm:ss")}) " +
  259. $"is still opening, close that and retry");
  260. var openDelivery = new Model.Delivery()
  261. {
  262. TankNumber = targetTankNumber,
  263. StartingDateTime = DateTime.Now,
  264. StartingFuelHeight = mostRecentReading.Item2.Height ?? -1,
  265. StartingFuelVolume = mostRecentReading.Item2.Volume ?? -1,
  266. StartingFuelTCVolume = mostRecentReading.Item2.TcVolume ?? -1,
  267. StartingTemperture = mostRecentReading.Item2.Temperature ?? double.MinValue,
  268. StartingWaterHeight = mostRecentReading.Item2.Water ?? -1,
  269. StartingWaterVolume = mostRecentReading.Item2.WaterVolume ?? -1,
  270. };
  271. dbContext.Deliveries.Add(openDelivery);
  272. await dbContext.SaveChangesAsync();
  273. targetTank.State = TankState.Delivering;
  274. var onStateChangeEventArg = new AtgStateChangeEventArg(
  275. targetTank,
  276. this.State,
  277. $"Manual delivery is starting on Tank with TankNumber: {targetTankNumber} with " +
  278. $"StartingFuelVolume: {openDelivery.StartingFuelVolume}");
  279. this.OnStateChange?.Invoke(this, onStateChangeEventArg);
  280. var universalApiHub = this.services.GetRequiredService<UniversalApiHub>();
  281. await universalApiHub.FireEvent(this, "OnStateChange", onStateChangeEventArg);
  282. }
  283. else if (operation.ToLower() == "stop")
  284. {
  285. // last open delivery does not exists.
  286. if (lastDeliveryRecord == null)
  287. throw new InvalidOperationException($"There's no start delivery record exists.");
  288. if (lastDeliveryRecord.EndingDateTime != null)
  289. throw new InvalidOperationException($"The last Delivery record is not opened.");
  290. lastDeliveryRecord.TankNumber = targetTankNumber;
  291. lastDeliveryRecord.EndingDateTime = DateTime.Now;
  292. lastDeliveryRecord.EndingFuelHeight = mostRecentReading.Item2.Height ?? -1;
  293. lastDeliveryRecord.EndingFuelVolume = mostRecentReading.Item2.Volume ?? -1;
  294. lastDeliveryRecord.EndingFuelTCVolume = mostRecentReading.Item2.TcVolume ?? -1;
  295. lastDeliveryRecord.EndingTemperture = mostRecentReading.Item2.Temperature ?? double.MinValue;
  296. lastDeliveryRecord.EndingWaterHeight = mostRecentReading.Item2.Water ?? -1;
  297. lastDeliveryRecord.EndingWaterVolume = mostRecentReading.Item2.WaterVolume ?? -1;
  298. dbContext.Deliveries.Update(lastDeliveryRecord);
  299. await dbContext.SaveChangesAsync();
  300. targetTank.State = TankState.Idle;
  301. var onStateChangeEventArg = new AtgStateChangeEventArg(
  302. targetTank,
  303. this.State,
  304. $"Manual delivery has finished on Tank with TankNumber: {targetTankNumber} with " +
  305. $"EndingFuelVolume: {lastDeliveryRecord.EndingFuelVolume}");
  306. this.OnStateChange?.Invoke(this, onStateChangeEventArg);
  307. var universalApiHub = this.services.GetRequiredService<UniversalApiHub>();
  308. await universalApiHub.FireEvent(this, "OnStateChange", onStateChangeEventArg);
  309. }
  310. else
  311. {
  312. throw new ArgumentException("unknown operationStr");
  313. }
  314. return mostRecentReading.Item2;
  315. }
  316. #endregion
  317. #region UniversalApi - Service
  318. /// <summary>
  319. /// first parameter name must be 'tanknumber', and value is the tank number, like 1, 2, 3...
  320. /// </summary>
  321. /// <param name="input"></param>
  322. /// <returns></returns>
  323. [UniversalApi(Description = "", InputParametersExampleJson = "[1]")]
  324. public async Task<TankReading> GetTankReadingAsync(int tankNumber)
  325. {
  326. //return this.InternalGetTankReadingAsync(tankNumber);
  327. TankReading mostRecentCachedTankReading = null;
  328. if (this.tankReadings_fast_buffer.TryGetValue(tankNumber, out List<Tuple<DateTime, TankReading>> cachedReadings))
  329. {
  330. var mostRecentReading = cachedReadings.LastOrDefault();
  331. if (mostRecentReading == null ||
  332. // max tolerance is 4 cycles of fast polling missing.
  333. DateTime.Now.Subtract(mostRecentReading.Item1).TotalMilliseconds >= this.polling_fast_TankReadingTimer_Internval * 2)
  334. throw new InvalidOperationException("Could not get most recent tank reading for target tank, may retry later?");
  335. if (mostRecentReading.Item2.Volume == null || mostRecentReading.Item2.WaterVolume == null)
  336. throw new InvalidOperationException("Most recent tank reading for target tank is invalid, may retry later?");
  337. mostRecentCachedTankReading = mostRecentReading.Item2;
  338. }
  339. var mapper = services.GetRequiredService<IMapper>();
  340. return mapper.Map<TankReading>(mostRecentCachedTankReading);
  341. }
  342. [UniversalApi(Description = "", InputParametersExampleJson = "[1,8,0,\"2020-04-01T18:25:43.511Z\"]")]
  343. public async Task<IEnumerable<Edge.Core.IndustryStandardInterface.ATG.Delivery>> GetTankDeliveryAsync(int tankNumber, int pageRowCount = 10, int pageIndex = 0, DateTime? filterTimestamp = null)
  344. {
  345. var dbContext = this.DbContextFactory.CreateDbContext<AppDbContext>();
  346. var mostRecentDeliveries = await dbContext.Deliveries.Where(d => d.TankNumber == tankNumber)
  347. .Where(d => d.StartingDateTime >= (filterTimestamp ?? DateTime.MinValue))
  348. .OrderByDescending(d => d.StartingDateTime).Skip(pageRowCount * pageIndex).Take(pageRowCount).ToListAsync();
  349. var mapper = services.GetRequiredService<IMapper>();
  350. return mapper.Map<IEnumerable<Edge.Core.IndustryStandardInterface.ATG.Delivery>>(mostRecentDeliveries);
  351. }
  352. [UniversalApi(Description = "", InputParametersExampleJson = "[1,8,0,\"2020-04-01T18:25:43.511Z\"]")]
  353. public async Task<IEnumerable<Edge.Core.IndustryStandardInterface.ATG.Alarm>> GetTankAlarmAsync(int tankNumber, int pageRowCount = 10, int pageIndex = 0, DateTime? filterTimestamp = null)
  354. {
  355. var mapper = services.GetRequiredService<IMapper>();
  356. var dbContext = this.DbContextFactory.CreateDbContext<AppDbContext>();
  357. var dbAlarms = await dbContext.Alarms.Where(al => al.TankNumber == tankNumber)
  358. .Where(d => d.CreatedTimeStamp >= (filterTimestamp ?? DateTime.MinValue))
  359. .OrderByDescending(d => d.CreatedTimeStamp).Skip(pageRowCount * pageIndex).Take(pageRowCount).ToArrayAsync();
  360. var alarms = mapper.Map<IEnumerable<Edge.Core.IndustryStandardInterface.ATG.Alarm>>(dbAlarms);
  361. return alarms;
  362. }
  363. [UniversalApi(Description = "", InputParametersExampleJson = "[1,8,0,\"2020-04-01T18:25:43.511Z\"]")]
  364. public async Task<IEnumerable<Edge.Core.IndustryStandardInterface.ATG.Inventory>> GetTankInventoryAsync(int tankNumber, int pageRowCount = 10, int pageIndex = 0, DateTime? filterTimestamp = null)
  365. {
  366. var mapper = services.GetRequiredService<IMapper>();
  367. var dbContext = this.DbContextFactory.CreateDbContext<AppDbContext>();
  368. var results = await dbContext.Inventories.Where(i => i.TankNumber == tankNumber)
  369. .Where(d => d.TimeStamp >= (filterTimestamp ?? DateTime.MinValue))
  370. .OrderByDescending(d => d.TimeStamp).Skip(pageRowCount * pageIndex).Take(pageRowCount).ToArrayAsync();
  371. return mapper.Map<IEnumerable<Edge.Core.IndustryStandardInterface.ATG.Inventory>>(results);
  372. }
  373. [UniversalApi()]
  374. public Task<IEnumerable<Tank>> GetTanksAsync()
  375. {
  376. return Task.FromResult(this.richTankInfos?.Select(c => c.Tank));
  377. }
  378. #endregion
  379. private SpinLock spinLock_GuardGetTankReading = new SpinLock();
  380. private async Task<TankReading> InternalGetTankReadingAsync(int tankNumber)
  381. {
  382. bool lockTaken = false;
  383. try
  384. {
  385. this.spinLock_GuardGetTankReading.Enter(ref lockTaken);
  386. var targetRichTankInfo = this.richTankInfos.FirstOrDefault(ti => ti.Tank.TankNumber == tankNumber);
  387. var targetProbeHandler = this.probeHandlers.FirstOrDefault(ph => ph.Probe.DeviceId == targetRichTankInfo.TankConfig.ProbeConfig.DeviceId);
  388. if (targetProbeHandler == null) throw new ArgumentException("Could not find ProbeHandler which bound to Tank with tankNumber: " + tankNumber);
  389. var probeReading = await targetProbeHandler.GetProbeReadingAsync();
  390. var volumeCaculator = new HeightToVolumeCaculator(targetRichTankInfo.TankConfig.TankProfileDatas);
  391. var tcCaculator = new TemperatureCompensationCaculator(targetRichTankInfo.TankConfig.ThermalCoefficient);
  392. var tankReading = new TankReading()
  393. {
  394. Density = probeReading.Density,
  395. Water = probeReading.Water,
  396. Height = probeReading.Height,
  397. Temperature = probeReading.Temperature.FirstOrDefault(),
  398. Volume = volumeCaculator.GetVolume(probeReading.Height ?? 0) - volumeCaculator.GetVolume(probeReading.Water ?? 0),
  399. WaterVolume = volumeCaculator.GetVolume(probeReading.Water ?? 0),
  400. TcVolume = tcCaculator.CaculateCompensatedVolume(
  401. targetRichTankInfo.TankOverallConfig.TcReference,
  402. volumeCaculator.GetVolume(probeReading.Height ?? 0) - volumeCaculator.GetVolume(probeReading.Water ?? 0),
  403. probeReading.Temperature.FirstOrDefault()),
  404. Ullage = volumeCaculator.GetVolume(targetRichTankInfo.TankConfig.TankProfileDatas.Max(p => p.Height))
  405. - volumeCaculator.GetVolume(probeReading.Height ?? 0)
  406. };
  407. var alarms = this.ExtractTankAlarms(tankReading, targetRichTankInfo.TankConfig.TankLimitConfig);
  408. if (alarms.Any())
  409. {
  410. await this.UpsertAlarmsInDatabase(alarms);
  411. this.OnAlarm?.Invoke(this, new AtgAlarmEventArg(tankNumber, alarms));
  412. }
  413. return tankReading;
  414. }
  415. finally
  416. {
  417. if (lockTaken) this.spinLock_GuardGetTankReading.Exit(false);
  418. }
  419. }
  420. private IEnumerable<Edge.Core.IndustryStandardInterface.ATG.Alarm> ExtractTankAlarms(TankReading tankReading, TankLimitConfig tankLimitConfig)
  421. {
  422. if (tankReading == null || tankLimitConfig == null) throw new ArgumentNullException(nameof(tankReading) + nameof(tankLimitConfig));
  423. var alarms = new List<Edge.Core.IndustryStandardInterface.ATG.Alarm>();
  424. if (tankLimitConfig.FuelTemperatureHighLimit <= tankReading.Temperature.Value)
  425. {
  426. alarms.Add(new Edge.Core.IndustryStandardInterface.ATG.Alarm(AlarmPriority.Alarm, AlarmType.TankHighTemperatureWarning));
  427. }
  428. if (tankLimitConfig.FuelTemperatureLowLimit >= tankReading.Temperature.Value)
  429. {
  430. alarms.Add(new Edge.Core.IndustryStandardInterface.ATG.Alarm(AlarmPriority.Alarm, AlarmType.TankColdTemperatureWarning));
  431. }
  432. if (tankLimitConfig.MaxVolume * tankLimitConfig.HighProduct <= tankReading.Volume.Value)
  433. {
  434. alarms.Add(new Edge.Core.IndustryStandardInterface.ATG.Alarm(AlarmPriority.Alarm, AlarmType.TankHighProductAlarm));
  435. }
  436. if (tankLimitConfig.LowProduct >= tankReading.Volume)
  437. {
  438. alarms.Add(new Edge.Core.IndustryStandardInterface.ATG.Alarm(AlarmPriority.Alarm, AlarmType.TankLowProductAlarm));
  439. }
  440. if (tankLimitConfig.HighWaterAlarm <= tankReading.Water)
  441. {
  442. alarms.Add(new Edge.Core.IndustryStandardInterface.ATG.Alarm(AlarmPriority.Alarm, AlarmType.TankHighWaterAlarm));
  443. }
  444. if (tankLimitConfig.HighWaterWarning <= tankReading.Water)
  445. {
  446. alarms.Add(new Edge.Core.IndustryStandardInterface.ATG.Alarm(AlarmPriority.Warning, AlarmType.TankHighWaterWarning));
  447. }
  448. return alarms;
  449. }
  450. /// <summary>
  451. /// tank number: <TankReadingsWithTimeStamp>
  452. /// </summary>
  453. private Dictionary<int, List<Tuple<DateTime, TankReading>>> tankReadings_fast_buffer
  454. = new Dictionary<int, List<Tuple<DateTime, TankReading>>>();
  455. public IDbContextFactory DbContextFactory { get; set; }
  456. public AtgState State { get; private set; }
  457. private bool skipDatabaseMigration = false;
  458. public App(IServiceProvider services, int id, bool skipDatabaseMigration)
  459. {
  460. this.skipDatabaseMigration = skipDatabaseMigration;
  461. this.services = services;
  462. var loggerFactory = services.GetRequiredService<ILoggerFactory>();
  463. this.logger = loggerFactory.CreateLogger("Application");
  464. this.DbContextFactory = new DefaultDbContextFactory();
  465. this.DbContextFactory.AddProvider(new ClassicAtgDbContextProvider());
  466. //set a fast polling for better real time experience.
  467. this.polling_fast_TankReadingTimer = new System.Timers.Timer(this.polling_fast_TankReadingTimer_Internval);
  468. this.polling_fast_TankReadingTimer.Elapsed += async (_, __) =>
  469. {
  470. if (this.richTankInfos == null || !this.richTankInfos.Any()) return;
  471. try
  472. {
  473. this.polling_fast_TankReadingTimer.Stop();
  474. foreach (var richTankInfo in this.richTankInfos)
  475. {
  476. var tankReading = await this.InternalGetTankReadingAsync(richTankInfo.Tank.TankNumber);
  477. if (this.tankReadings_fast_buffer.TryGetValue(richTankInfo.Tank.TankNumber, out List<Tuple<DateTime, TankReading>> readings))
  478. {
  479. var d = new Tuple<DateTime, TankReading>(DateTime.Now, tankReading);
  480. readings.Add(d);
  481. readings.RemoveAll(i => DateTime.Now.Subtract(i.Item1).TotalSeconds > this.polling_fast_TankReadingTimer_Buffer_MaxLength_By_Second);
  482. }
  483. else
  484. {
  485. this.tankReadings_fast_buffer.Add(richTankInfo.Tank.TankNumber,
  486. new List<Tuple<DateTime, TankReading>>() {
  487. new Tuple<DateTime, TankReading>(DateTime.Now,tankReading)
  488. });
  489. }
  490. }
  491. // check if Inventory sampling interval cycle ellapsed, if yes, save one inventory into db.
  492. if (DateTime.Now.Subtract(this.lastInventoriesSavedIntoDatabaseTime).TotalMilliseconds
  493. >= (this.richTankInfos.FirstOrDefault()?.TankOverallConfig.InventorySamplingInterval ?? 60000))
  494. {
  495. try
  496. {
  497. foreach (var data in this.tankReadings_fast_buffer)
  498. {
  499. var dbContext = this.DbContextFactory.CreateDbContext<AppDbContext>();
  500. dbContext.Inventories.Add(Model.Inventory.From(data.Key, data.Value.Last().Item2, data.Value.Last().Item1));
  501. await dbContext.SaveChangesAsync();
  502. }
  503. }
  504. finally
  505. {
  506. this.lastInventoriesSavedIntoDatabaseTime = DateTime.Now;
  507. }
  508. }
  509. }
  510. finally
  511. {
  512. this.polling_fast_TankReadingTimer.Start();
  513. }
  514. };
  515. this.OnStateChange += (_, evtArg) =>
  516. {
  517. if (evtArg.State == AtgState.TanksReloaded)
  518. {
  519. this.tankReadings_fast_buffer.Clear();
  520. }
  521. };
  522. }
  523. public App(IServiceProvider services, int id) : this(services, id, false)
  524. {
  525. }
  526. public void Init(IEnumerable<IProcessor> processors)
  527. {
  528. var probeHandlers = processors.WithHandlerOrApp<IProbeHandler>().SelectHandlerOrAppThenCast<IProbeHandler>();
  529. if (probeHandlers.GroupBy(p => p.Probe.DeviceId).Any(g => g.Count() > 1)) throw new ArgumentException("Duplicate Id in Probe handlers");
  530. this.probeHandlers = probeHandlers;
  531. }
  532. public async Task<bool> Start()
  533. {
  534. if (!this.skipDatabaseMigration)
  535. {
  536. this.logger.LogInformation("Migrating database...");
  537. var migrateDbContext = this.DbContextFactory.CreateDbContext<AppDbContext>();
  538. try
  539. {
  540. migrateDbContext.Database.Migrate();
  541. }
  542. catch (Exception exx)
  543. {
  544. string migrationsStr = "";
  545. string pendingMigrationsStr = "";
  546. string appliedMigrationsStr = "";
  547. try
  548. {
  549. migrationsStr = migrateDbContext.Database?.GetMigrations()?.Aggregate((acc, n) => acc + ", " + n) ?? "";
  550. pendingMigrationsStr = migrateDbContext.Database?.GetPendingMigrations()?.Aggregate((acc, n) => acc + ", " + n) ?? "";
  551. appliedMigrationsStr = migrateDbContext.Database?.GetAppliedMigrations()?.Aggregate((acc, n) => acc + ", " + n) ?? "";
  552. }
  553. catch
  554. {
  555. this.logger.LogError("ATG_Classic_App Exceptioned when Migrating the database, detail: " + exx + System.Environment.NewLine +
  556. "migrations are: " + migrationsStr + System.Environment.NewLine +
  557. ", pendingMigrations are: " + pendingMigrationsStr + System.Environment.NewLine +
  558. ", appliedMigrations are: " + appliedMigrationsStr);
  559. }
  560. throw new InvalidOperationException("failed for migrating the database");
  561. }
  562. this.logger.LogInformation(" Migrate database finished.");
  563. }
  564. await this.PurgeDatabase();
  565. var configs = await this.GetConfigAsync();
  566. this.richTankInfos = this.TryReCreateRichTankInfos(configs.Item2, configs.Item1, this.probeHandlers);
  567. if (this.richTankInfos == null || !this.richTankInfos.Any())
  568. {
  569. this.State = AtgState.Inoperative_MissingConfig;
  570. this.OnStateChange?.Invoke(this,
  571. new AtgStateChangeEventArg(this.State,
  572. "Necessary tank configs were missed, add configs and wait for notify"));
  573. }
  574. else
  575. {
  576. this.State = AtgState.Idle;
  577. this.OnStateChange?.Invoke(this, new AtgStateChangeEventArg(AtgState.TanksReloaded, "All tanks reloaded due to application started"));
  578. }
  579. this.polling_fast_TankReadingTimer.Start();
  580. return true;
  581. }
  582. private IEnumerable<RichTankInfo> TryReCreateRichTankInfos(
  583. IEnumerable<TankConfig> tankConfigs, TankOverallConfig tankOverallConfig, IEnumerable<IProbeHandler> probeHandlers)
  584. {
  585. if (tankConfigs == null || tankOverallConfig == null || probeHandlers == null
  586. || !tankConfigs.Any()
  587. || tankConfigs.Any(tc => tc.ProbeConfig == null
  588. || tc.ProductConfig == null || tc.TankLimitConfig == null
  589. || tc.TankProfileDatas == null))
  590. return null;
  591. try
  592. {
  593. richTankInfos = tankConfigs.Select(tc =>
  594. {
  595. var rti = new RichTankInfo(
  596. this.services, tc, tankOverallConfig,
  597. this.probeHandlers.FirstOrDefault(ph => ph.Probe.DeviceId == tc.ProbeConfig.DeviceId));
  598. return rti;
  599. });
  600. return richTankInfos;
  601. }
  602. catch
  603. {
  604. return null;
  605. }
  606. }
  607. public async Task<bool> Stop()
  608. {
  609. this.tankReadings_fast_buffer.Clear();
  610. this.polling_fast_TankReadingTimer.Stop();
  611. return true;
  612. }
  613. private async Task PurgeDatabase()
  614. {
  615. #region let's do some purge work here... only keep 2 years data, no special reason.
  616. int maxKeepDays = 365 * 2;
  617. DateTime keepHistoryFrom = DateTime.Now.Subtract(new TimeSpan(maxKeepDays, 0, 0, 0));
  618. var dbContext = this.DbContextFactory.CreateDbContext<AppDbContext>();
  619. var deletingInventories = dbContext.Inventories.Where(i => i.TimeStamp < keepHistoryFrom);
  620. dbContext.RemoveRange(deletingInventories);
  621. var deletingAlarms = dbContext.Alarms.Where(a => a.CreatedTimeStamp < keepHistoryFrom);
  622. dbContext.RemoveRange(deletingAlarms);
  623. var deletingDelieveries = dbContext.Deliveries.Where(d => d.StartingDateTime < keepHistoryFrom);
  624. dbContext.RemoveRange(deletingDelieveries);
  625. await dbContext.SaveChangesAsync();
  626. #endregion
  627. }
  628. private class AlarmEqualityComparer : IEqualityComparer<Edge.Core.IndustryStandardInterface.ATG.Alarm>
  629. {
  630. public bool Equals([AllowNull] Edge.Core.IndustryStandardInterface.ATG.Alarm x, [AllowNull] Edge.Core.IndustryStandardInterface.ATG.Alarm y)
  631. {
  632. if (x == null && y == null) return false;
  633. if ((x == null && y != null) || (x != null && y == null)) return false;
  634. if (x.TankNumber == y.TankNumber && x.Type == y.Type
  635. && x.Priority == y.Priority && x.Description == y.Description)
  636. return true;
  637. return false;
  638. }
  639. public int GetHashCode([DisallowNull] Edge.Core.IndustryStandardInterface.ATG.Alarm obj)
  640. {
  641. return (int)obj.TankNumber ^ (int)obj.Type
  642. ^ (int)obj.Priority;
  643. }
  644. }
  645. /// <summary>
  646. /// Update or insert alarms into database.
  647. /// Searching all active alarms in database:
  648. /// for each active alarms:
  649. /// if same type real time alarm disappeared-> mark alarm as cleared.
  650. /// if same type real time alarm existed as well-> did nothing.
  651. /// if same type real time alarm does not exists->
  652. /// Add realTime alarm into database.
  653. /// </summary>
  654. /// <param name="realTimeAlarms"></param>
  655. /// <returns></returns>
  656. protected virtual async Task UpsertAlarmsInDatabase(IEnumerable<Edge.Core.IndustryStandardInterface.ATG.Alarm> realTimeAlarms)
  657. {
  658. var mapper = services.GetRequiredService<IMapper>();
  659. foreach (var g in realTimeAlarms.GroupBy(a => a.TankNumber))
  660. {
  661. var dbContext = this.DbContextFactory.CreateDbContext<AppDbContext>();
  662. var dbActiveAlarms = mapper.Map<IEnumerable<Edge.Core.IndustryStandardInterface.ATG.Alarm>>(
  663. dbContext.Set<Model.Alarm>()//.Alarms
  664. .Where(al => al.ClearedTimeStamp == null
  665. && al.TankNumber == g.Key
  666. // only searching latest 30 days alarms, for performance wise?
  667. && DateTime.Now.Subtract(al.CreatedTimeStamp).TotalDays <= 30)
  668. );
  669. var clearedAlarms = mapper.Map<IEnumerable<Model.Alarm>>(
  670. dbActiveAlarms.Except(g, new AlarmEqualityComparer()));
  671. clearedAlarms.ToList().ForEach(c => c.ClearedTimeStamp = DateTime.Now);
  672. var addedAlarms = mapper.Map<IEnumerable<Model.Alarm>>(
  673. realTimeAlarms.Except(dbActiveAlarms, new AlarmEqualityComparer()));
  674. if (clearedAlarms != null && clearedAlarms.Any())
  675. dbContext.UpdateRange(clearedAlarms);
  676. if (addedAlarms != null && addedAlarms.Any())
  677. await dbContext.AddRangeAsync(addedAlarms);
  678. await dbContext.SaveChangesAsync();
  679. }
  680. }
  681. public Task<IEnumerable<TankReading>> GetTanksReadingAsync()
  682. {
  683. throw new NotImplementedException();
  684. }
  685. }
  686. }