FairbanksRealTimeDataApp.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. using Applications.FDC;
  2. using AutoMapper;
  3. using Edge.Core.Database;
  4. using Edge.Core.Processor;
  5. using Edge.Core.IndustryStandardInterface.ATG;
  6. using Edge.Core.UniversalApi;
  7. using Dfs.WayneChina.FairbanksRTData.Support;
  8. using Dfs.WayneChina.FairbanksRTData.UniversalApiModels;
  9. using FdcServerHost;
  10. using Microsoft.Extensions.DependencyInjection;
  11. using Microsoft.Extensions.Logging;
  12. using Microsoft.Extensions.Logging.Abstractions;
  13. using System;
  14. using System.Collections.Concurrent;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.IO.Compression;
  18. using System.Linq;
  19. using System.Reflection;
  20. using System.Text;
  21. using System.Text.Json;
  22. using System.Text.RegularExpressions;
  23. using System.Threading;
  24. using System.Threading.Tasks;
  25. using System.Timers;
  26. using Edge.Core.Database.Models;
  27. using Edge.Core.Processor.Dispatcher.Attributes;
  28. namespace Dfs.WayneChina.FairbanksRTData
  29. {
  30. [MetaPartsDescriptor(
  31. "lang-zh-cn:Fairbanks实时数据上传应用lang-en-us:Fairbank real time data App",
  32. "lang-zh-cn:用于传输加油站实时数据,如:加油、液位仪、告警等数据到Fairbanks服务器" +
  33. "lang-en-us:Used for uploading real time data in specified format to Fairbanks server",
  34. new[] { "lang-zh-cn:Fairbankslang-en-us:Fairbanks" })]
  35. public class FairbanksRealTimeDataApp : IAppProcessor
  36. {
  37. #region Fields
  38. public string MetaConfigName { get; set; }
  39. private ILogger appLogger = NullLogger.Instance;
  40. private IServiceProvider services;
  41. private FdcServerHostApp fdcServer;
  42. private System.Timers.Timer tankReadTimer;
  43. private System.Timers.Timer uploadTimer;
  44. private string host;
  45. private int port;
  46. private string username;
  47. private string password;
  48. private string deviceId;
  49. private string siteName;
  50. private int tankReadInterval;
  51. private int uploadInterval;
  52. private string hostUploadFolder;
  53. private IEnumerable<IAutoTankGaugeController> autoTankGaugeControllers;
  54. private string transactionsFileName = "transactions";
  55. private string transactionsFilePath;
  56. private string tankReadingFileName = "stockLevels";
  57. private string stockLevelsFilePath;
  58. private string alarmsFileName = "alarms";
  59. private string alarmsFilePath;
  60. private string deliveriesFileName = "deliveries";
  61. private string deliveriesFilePath;
  62. private string requiredFolder;
  63. private string tempFolder;
  64. private string uploadedFilesFolder;
  65. private string folderSeperator = "/";
  66. private FairbanksSftpClient fbSftpClient;
  67. // Persistence
  68. private IMapper objMapper;
  69. private readonly SqliteDbContext dbContext;
  70. private AppConfig appConfig;
  71. private DbHelper dbHelper;
  72. private ConcurrentQueue<string> csvFileQueue = new ConcurrentQueue<string>();
  73. private ReaderWriterLockSlim fileLocker = new ReaderWriterLockSlim();
  74. private int sortToken = 0;
  75. #endregion
  76. #region Tank State Dictionary
  77. private Dictionary<int, TankState> tankStateDict = new Dictionary<int, TankState>();
  78. #endregion
  79. #region Logger
  80. NLog.Logger logger = NLog.LogManager.LoadConfiguration("NLog.config").GetLogger("Fairbanks");
  81. #endregion
  82. #region Constructor
  83. [ParamsJsonSchemas("appCtorParamsJsonSchema")]
  84. public FairbanksRealTimeDataApp(IServiceProvider services, FairbanksAppConfigV1 config)
  85. {
  86. this.services = services;
  87. var loggerFactory = services.GetRequiredService<ILoggerFactory>();
  88. appLogger = loggerFactory.CreateLogger("Application");
  89. objMapper = services.GetRequiredService<IMapper>();
  90. dbContext = services.GetRequiredService<SqliteDbContext>();
  91. if (services != null)
  92. dbHelper = new DbHelper(services);
  93. host = config.Host;
  94. port = config.Port;
  95. username = config.Username;
  96. password = config.Password;
  97. deviceId = config.DeviceId;
  98. siteName = config.SiteName;
  99. tankReadInterval = config.Interval;
  100. uploadInterval = config.UploadInterval;
  101. hostUploadFolder = config.HostUploadFolder;
  102. fbSftpClient = new FairbanksSftpClient(host, username, password);
  103. }
  104. public FairbanksRealTimeDataApp(IServiceProvider services, string host, int port, string username, string password,
  105. string deviceId, string siteName, int interval, int uploadInterval, string hostUploadFolder)
  106. {
  107. this.services = services;
  108. var loggerFactory = services.GetRequiredService<ILoggerFactory>();
  109. appLogger = loggerFactory.CreateLogger("Application");
  110. objMapper = services.GetRequiredService<IMapper>();
  111. dbContext = services.GetRequiredService<SqliteDbContext>();
  112. if (services != null)
  113. dbHelper = new DbHelper(services);
  114. this.host = host;
  115. this.port = port;
  116. this.username = username;
  117. this.password = password;
  118. this.deviceId = deviceId;
  119. this.siteName = siteName;
  120. this.tankReadInterval = interval;
  121. this.uploadInterval = uploadInterval;
  122. this.hostUploadFolder = hostUploadFolder;
  123. fbSftpClient = new FairbanksSftpClient(host, username, password);
  124. }
  125. #endregion
  126. #region Init
  127. public void Init(IEnumerable<IProcessor> processors)
  128. {
  129. //get the FdcServer instance during init
  130. foreach (dynamic processor in processors)
  131. {
  132. if (processor is IAppProcessor)
  133. {
  134. FdcServerHostApp fdcServer = processor as FdcServerHostApp;
  135. if (fdcServer != null)
  136. {
  137. logger.Info("FdcServerHostApp retrieved as an IApplication instance!");
  138. this.fdcServer = processor;
  139. }
  140. continue;
  141. }
  142. }
  143. if (fdcServer != null)
  144. logger.Info("Fdc Server instance alive");
  145. var atgControllers = processors.WithHandlerOrApp<IAutoTankGaugeController>()
  146. .Select(p => p.ProcessorDescriptor().DeviceHandlerOrApp)
  147. .Cast<IAutoTankGaugeController>();
  148. autoTankGaugeControllers = atgControllers;
  149. if (autoTankGaugeControllers != null)
  150. {
  151. foreach (var controller in autoTankGaugeControllers)
  152. {
  153. controller.OnStateChange += Controller_OnStateChange;
  154. controller.OnAlarm += Controller_OnAlarm;
  155. }
  156. }
  157. }
  158. #region Alarms
  159. private async void Controller_OnAlarm(object sender, AtgAlarmEventArg e)
  160. {
  161. logger.Info("Incoming alarm");
  162. var currentGauge = sender as IAutoTankGaugeController;
  163. if (currentGauge != null)
  164. {
  165. var alarms = new List<FbAlarm>();
  166. foreach (var alarm in e.Alarms)
  167. {
  168. logger.Info($"Gauge: {currentGauge.DeviceId}");
  169. logger.Info($" tank number: {alarm.TankNumber}, description: {alarm.Description}");
  170. logger.Info($" alarm id: {alarm.Id}, priority: {alarm.Priority}, type: {alarm.Type}");
  171. logger.Info($" created time: {alarm.CreatedTimeStamp}, cleared time: {alarm.ClearedTimeStamp}");
  172. var fbAlarm = new FbAlarm();
  173. fbAlarm.ibank = deviceId;
  174. fbAlarm.DateTime = alarm.CreatedTimeStamp;
  175. fbAlarm.CodedAlarm = "1";
  176. fbAlarm.Category = "TLS_ALARM";
  177. fbAlarm.Type = ""; // can be left blank or null
  178. fbAlarm.AlarmCode = string.Concat("TLS_", "02_", ((byte)alarm.Type).ToString().PadLeft(2, '0'));
  179. fbAlarm.TankAlarm = "1"; //1=tank alarm, 0=other device alarm or things
  180. fbAlarm.Tank = alarm.TankNumber;
  181. fbAlarm.State = 0; // active = 0, cleared = 1
  182. fbAlarm.Note = alarm.Description;
  183. alarms.Add(fbAlarm);
  184. }
  185. await RecordAlarmsAsync(alarms);
  186. }
  187. }
  188. private async Task RecordAlarmsAsync(IEnumerable<FbAlarm> alarms)
  189. {
  190. try
  191. {
  192. fileLocker.TryEnterReadLock(500);
  193. SetAlarmsFile(requiredFolder);
  194. }
  195. catch (Exception ex)
  196. {
  197. logger.Error(ex.ToString());
  198. }
  199. finally
  200. {
  201. fileLocker.ExitReadLock();
  202. }
  203. if (!File.Exists(alarmsFilePath))
  204. {
  205. logger.Info("Creating alarms file path");
  206. await WriteCsvAsync(new List<FbAlarm>(), alarmsFilePath);
  207. }
  208. logger.Info("Writing alarms info into file");
  209. await WriteCsvAsync(alarms, alarmsFilePath);
  210. }
  211. #endregion
  212. #region Fuel deliveries
  213. private async void Controller_OnStateChange(object sender, AtgStateChangeEventArg e)
  214. {
  215. if (e.State == AtgState.TanksReloaded)
  216. {
  217. logger.Info("Tank reloaded, ready for use");
  218. }
  219. if (e.TargetTank != null)
  220. {
  221. if (e.TargetTank.State == TankState.Delivering)
  222. {
  223. logger.Info("Delivering fuel...");
  224. if (!tankStateDict.ContainsKey(e.TargetTank.TankNumber))
  225. {
  226. logger.Info($"Adding tank {e.TargetTank.TankNumber.ToString()} to the tank state dict");
  227. tankStateDict.Add(e.TargetTank.TankNumber, e.TargetTank.State);
  228. }
  229. }
  230. else if (e.TargetTank.State == TankState.Idle)
  231. {
  232. logger.Info("Tank state: Idle");
  233. var currentTankState = tankStateDict[e.TargetTank.TankNumber];
  234. if (currentTankState == TankState.Delivering && e.TargetTank.State == TankState.Idle)
  235. {
  236. logger.Info($"Tank {e.TargetTank.TankNumber.ToString()} state changed, Delivering -> Idle, check fuel delivery");
  237. tankStateDict[e.TargetTank.TankNumber] = TankState.Idle;
  238. var currentAtg = sender as IAutoTankGaugeController;
  239. if (currentAtg != null)
  240. {
  241. await RecordFuelDelivery(currentAtg, e.TargetTank.TankNumber);
  242. }
  243. }
  244. }
  245. }
  246. }
  247. private async Task RecordFuelDelivery(IAutoTankGaugeController autoTankGauge, int tankNumber)
  248. {
  249. var deliveries = await autoTankGauge.GetTankDeliveryAsync(tankNumber);
  250. var fbFuelDeliveries = new List<FbFuelDelivery>();
  251. foreach (var delivery in deliveries)
  252. {
  253. logger.Info($"Tank: {delivery.TankNumber}, FuelHeight, start: {delivery.StartingFuelHeight}, end: {delivery.EndingFuelHeight}");
  254. logger.Info($" Fuel TC Volume, start: {delivery.StartingFuelTCVolume}, end: {delivery.EndingFuelTCVolume}");
  255. logger.Info($" Fuel Volume, start: {delivery.StartingFuelVolume}, end: {delivery.EndingFuelVolume}");
  256. var fbFuelDelivery = new FbFuelDelivery();
  257. fbFuelDelivery.ibank = deviceId;
  258. fbFuelDelivery.Tank = delivery.TankNumber;
  259. fbFuelDelivery.StartDateTime = delivery.StartingDateTime;
  260. fbFuelDelivery.StartVolume = (decimal)delivery.StartingFuelVolume;
  261. fbFuelDelivery.StartWater = (decimal)delivery.StartingWaterHeight;
  262. fbFuelDelivery.StartTemperature = (decimal)delivery.StartingTemperture;
  263. fbFuelDelivery.EndDateTime = (DateTime)delivery.EndingDateTime;
  264. fbFuelDelivery.EndVolume = (decimal)delivery.EndingFuelVolume;
  265. fbFuelDelivery.EndWater = (decimal)delivery.EndingWaterHeight;
  266. fbFuelDelivery.EndTemperature = (decimal)delivery.EndingTemperture;
  267. fbFuelDelivery.Quantity = 0m;
  268. fbFuelDelivery.ConfirmedQuantity = 0m;
  269. fbFuelDeliveries.Add(fbFuelDelivery);
  270. }
  271. try
  272. {
  273. fileLocker.TryEnterReadLock(500);
  274. SetDeliveriesFile(requiredFolder);
  275. }
  276. catch (Exception ex)
  277. {
  278. logger.Error(ex.ToString());
  279. }
  280. finally
  281. {
  282. fileLocker.ExitReadLock();
  283. }
  284. if (!File.Exists(deliveriesFilePath))
  285. {
  286. logger.Info("Creating deliveries file path");
  287. await WriteCsvAsync(new List<FbFuelDelivery>(), deliveriesFilePath);
  288. }
  289. logger.Info("Writing deliveries info into file");
  290. await WriteCsvAsync(fbFuelDeliveries, deliveriesFilePath);
  291. }
  292. #endregion
  293. #endregion
  294. #region Folder and file name handling
  295. private void EnsureFolder()
  296. {
  297. string path = Directory.GetCurrentDirectory();
  298. requiredFolder = path + folderSeperator + "RealTimeData";
  299. if (!Directory.Exists(requiredFolder))
  300. Directory.CreateDirectory(requiredFolder);
  301. tempFolder = requiredFolder + folderSeperator + "temp";
  302. if (!Directory.Exists(requiredFolder + folderSeperator + "temp"))
  303. {
  304. Directory.CreateDirectory(tempFolder);
  305. }
  306. uploadedFilesFolder = requiredFolder + folderSeperator + "archives";
  307. if (!Directory.Exists(uploadedFilesFolder))
  308. Directory.CreateDirectory(uploadedFilesFolder);
  309. SetAlarmsFile(requiredFolder);
  310. SetDeliveriesFile(requiredFolder);
  311. SetTransactionFile(requiredFolder);
  312. SetTankReadingFile(requiredFolder);
  313. }
  314. private string CreateFileNameWithoutExt(string fileTypeName, string dateSection, string hourSection)
  315. {
  316. return string.Concat(requiredFolder, folderSeperator, /*deviceId, "_",*/ fileTypeName, "_", dateSection, "_", hourSection);
  317. }
  318. private void SetAlarmsFile(string requiredFolder)
  319. {
  320. var dateSection = DateTime.Now.Date.ToString("yyyy-MM-dd");
  321. var hourSection = DateTime.Now.Hour.ToString("D2");
  322. var fileNameWithoutExtension = CreateFileNameWithoutExt(alarmsFileName, dateSection, hourSection);
  323. logger.Debug($"FileNameWithoutExt: {fileNameWithoutExtension}");
  324. var filesInProcessing = csvFileQueue.Where(f => f.Contains(dateSection + "_" + hourSection)).ToList();
  325. foreach (var file in filesInProcessing)
  326. {
  327. logger.Debug($" Alarms files in queue: {file}");
  328. }
  329. var candidateFiles = GetMatchingFilesFromFolder(alarmsFileName, uploadedFilesFolder)
  330. .Concat(filesInProcessing);
  331. foreach (var cf in candidateFiles)
  332. {
  333. logger.Debug($"\tcdi: {cf}");
  334. }
  335. if (candidateFiles.Any(f => f.Contains('[')))
  336. {
  337. Interlocked.Increment(ref sortToken);
  338. var currentSortToken = sortToken;
  339. logger.Info($"Sort [{currentSortToken}] the candidates to find last Alarms file name");
  340. var lastFile = candidateFiles.OrderBy(f => f, new FileNameSuffixComparer()).Last();
  341. logger.Info($"Sort [{currentSortToken}] done, Last alarms file full name: {lastFile}");
  342. int startIndex = lastFile.IndexOf('[');
  343. int endIndex = lastFile.IndexOf(']');
  344. int number = Convert.ToInt32(lastFile.Substring(startIndex + 1, endIndex - startIndex - 1));
  345. alarmsFilePath = fileNameWithoutExtension + "[" + Convert.ToString(number + 1) + "]" + ".csv";
  346. logger.Debug($"Expected new alarms file: {alarmsFilePath}");
  347. }
  348. else if (candidateFiles.Any(f => Path.GetFileNameWithoutExtension(f) == Path.GetFileNameWithoutExtension(fileNameWithoutExtension)
  349. || Path.GetFileNameWithoutExtension(f) == Path.GetFileNameWithoutExtension(fileNameWithoutExtension + ".csv")))
  350. {
  351. logger.Info("Found a alarms file in `processing file`");
  352. alarmsFilePath = fileNameWithoutExtension + "[0]" + ".csv";
  353. }
  354. else
  355. {
  356. logger.Info("No previous alarms file");
  357. alarmsFilePath = fileNameWithoutExtension + ".csv";
  358. }
  359. if (csvFileQueue.Count > 5)
  360. {
  361. string dqFile;
  362. if (csvFileQueue.TryDequeue(out dqFile))
  363. logger.Info($"Dequeued alarms file: {dqFile}");
  364. }
  365. }
  366. private void SetDeliveriesFile(string requiredFolder)
  367. {
  368. //It's not possible that within an hour there are multiple fuel deliveries, is it?
  369. var dateSection = DateTime.Now.Date.ToString("yyyy-MM-dd");
  370. var hourSection = DateTime.Now.Hour.ToString("D2");
  371. var fileNameWithoutExtension = requiredFolder + folderSeperator + /*deviceId + "_" +*/ deliveriesFileName + "_" + dateSection + "_" + hourSection;
  372. deliveriesFilePath = fileNameWithoutExtension + ".csv";
  373. }
  374. private void SetTransactionFile(string requiredFolder)
  375. {
  376. var dateSection = DateTime.Now.Date.ToString("yyyy-MM-dd");
  377. var hourSection = DateTime.Now.Hour.ToString("D2");
  378. var fileNameWithoutExtension = requiredFolder + folderSeperator + /*deviceId + "_" +*/ transactionsFileName + "_" + dateSection + "_" + hourSection;
  379. logger.Debug($"FileNameWithoutExt: {fileNameWithoutExtension}");
  380. var filesInProcessing = csvFileQueue.Where(f => f.Contains(dateSection + "_" + hourSection)).ToList();
  381. foreach (var file in filesInProcessing)
  382. {
  383. logger.Debug($" Transaction files in queue: {file}");
  384. }
  385. var candidateFiles = GetMatchingFilesFromFolder(transactionsFileName, uploadedFilesFolder)
  386. .Concat(filesInProcessing);
  387. foreach (var cf in candidateFiles)
  388. {
  389. logger.Debug($"\tcdi: {cf}");
  390. }
  391. if (candidateFiles.Any(f => f.Contains('[')))
  392. {
  393. Interlocked.Increment(ref sortToken);
  394. var currentSortToken = sortToken;
  395. logger.Info($"Sort [{currentSortToken}] the candidates to find last transaction file name");
  396. var lastFile = candidateFiles.OrderBy(f => f, new FileNameSuffixComparer()).Last();
  397. logger.Info($"Sort [{currentSortToken}] done, Last transaction file full name: {lastFile}");
  398. int startIndex = lastFile.IndexOf('[');
  399. int endIndex = lastFile.IndexOf(']');
  400. int number = Convert.ToInt32(lastFile.Substring(startIndex + 1, endIndex - startIndex - 1));
  401. transactionsFilePath = fileNameWithoutExtension + "[" + Convert.ToString(number + 1) + "]" + ".csv";
  402. logger.Debug($"Expected new transaction file: {stockLevelsFilePath}");
  403. }
  404. else if (candidateFiles.Any(f => Path.GetFileNameWithoutExtension(f) == Path.GetFileNameWithoutExtension(fileNameWithoutExtension)
  405. || Path.GetFileNameWithoutExtension(f) == Path.GetFileNameWithoutExtension(fileNameWithoutExtension + ".csv")))
  406. {
  407. logger.Info("Found a transaction file in `processing file`");
  408. transactionsFilePath = fileNameWithoutExtension + "[0]" + ".csv";
  409. }
  410. else
  411. {
  412. logger.Info("No previous transaction file");
  413. transactionsFilePath = fileNameWithoutExtension + ".csv";
  414. }
  415. if (csvFileQueue.Count > 5)
  416. {
  417. string dqFile;
  418. if (csvFileQueue.TryDequeue(out dqFile))
  419. logger.Info($"Dequeued transaction file: {dqFile}");
  420. }
  421. }
  422. private void SetTankReadingFile(string folder)
  423. {
  424. logger.Debug($"Determining TankReading file name, operating folder is: {folder}");
  425. var dateSection = DateTime.Now.Date.ToString("yyyy-MM-dd");
  426. var hourSection = DateTime.Now.Hour.ToString("D2");
  427. var fileNameWithoutExtension = folder + folderSeperator + /*deviceId + "_" +*/ tankReadingFileName + "_" + dateSection + "_" + hourSection;
  428. logger.Debug($"FileNameWithoutExt: {fileNameWithoutExtension}");
  429. var filesInProcessing = csvFileQueue.Where(f => f.Contains(dateSection + "_" + hourSection)).ToList();
  430. foreach (var file in filesInProcessing)
  431. {
  432. logger.Debug($" file in queue: {file}");
  433. }
  434. var candidateFiles = GetMatchingFilesFromFolder(tankReadingFileName, uploadedFilesFolder).Concat(filesInProcessing);
  435. foreach (var cf in candidateFiles)
  436. {
  437. logger.Debug($"\tcdi: {cf}");
  438. }
  439. if (candidateFiles.Any(f => f.Contains('[')))
  440. {
  441. Interlocked.Increment(ref sortToken);
  442. var currentSortToken = sortToken;
  443. logger.Info($"Sort [{currentSortToken}] the candidates to find last stock reading file name");
  444. var lastFile = candidateFiles.OrderBy(f => f, new FileNameSuffixComparer()).Last();
  445. logger.Info($"Sort [{currentSortToken}] done, Last stock reading file full name: {lastFile}");
  446. int startIndex = lastFile.IndexOf('[');
  447. int endIndex = lastFile.IndexOf(']');
  448. int number = Convert.ToInt32(lastFile.Substring(startIndex + 1, endIndex - startIndex - 1));
  449. stockLevelsFilePath = fileNameWithoutExtension + "[" + Convert.ToString(number + 1) + "]" + ".csv";
  450. logger.Debug($"Expected new stock reading file: {stockLevelsFilePath}");
  451. }
  452. else if (candidateFiles.Any(f => Path.GetFileNameWithoutExtension(f) == Path.GetFileNameWithoutExtension(fileNameWithoutExtension)
  453. || Path.GetFileNameWithoutExtension(f) == Path.GetFileNameWithoutExtension(fileNameWithoutExtension + ".csv")))
  454. {
  455. logger.Info("Found an in processing file");
  456. stockLevelsFilePath = fileNameWithoutExtension + "[0]" + ".csv";
  457. }
  458. else
  459. {
  460. logger.Info("No previous tank reading file");
  461. stockLevelsFilePath = fileNameWithoutExtension + ".csv";
  462. }
  463. if (csvFileQueue.Count > 5)
  464. {
  465. string dqFile;
  466. if (csvFileQueue.TryDequeue(out dqFile))
  467. logger.Info($"Dequeued file: {dqFile}");
  468. }
  469. }
  470. private void CleanOldFiles(string folder, string fileName)
  471. {
  472. var di = new DirectoryInfo(folder);
  473. var files = di.GetFiles().Where(f => f.Name.Contains(fileName)).OrderByDescending(f => f.LastAccessTime);
  474. var oldFiles = files.Skip(10);
  475. foreach (var file in oldFiles)
  476. {
  477. logger.Debug($"Deleting file: {file.FullName}");
  478. file.Delete();
  479. }
  480. }
  481. private List<string> GetMatchingFilesFromFolder(string fileName, string folder)
  482. {
  483. logger.Info($"Finding matching {fileName} in folder: {folder}");
  484. var dateSection = DateTime.Now.Date.ToString("yyyy-MM-dd");
  485. var hourSection = DateTime.Now.Hour.ToString("D2");
  486. CleanOldFiles(folder, fileName);
  487. var archivedFiles = Directory.GetFiles(folder, "*.zip");
  488. logger.Info($"Archived files count = {archivedFiles.Length}");
  489. var matchedFileNames = archivedFiles
  490. .Where(f => f.Contains(dateSection + "_" + hourSection) && f.Contains(fileName)
  491. && Regex.IsMatch(Path.GetFileNameWithoutExtension(f), @"[a-zA-Z]{11}_\d{4}-\d{2}-\d{2}_\d{2}\[(.*?)\]"));
  492. logger.Info($"Matched files count = {matchedFileNames.Count()}");
  493. if (!matchedFileNames.Any())
  494. {
  495. var fileNameWithoutExtension = folder + folderSeperator + fileName + "_" + dateSection + "_" + hourSection;
  496. if (File.Exists(fileNameWithoutExtension + ".zip"))
  497. return new List<string> { fileNameWithoutExtension };
  498. }
  499. return matchedFileNames.ToList();
  500. }
  501. private List<string> GetMatchingTransactionFilesFromFolder(string fileName, string folder)
  502. {
  503. logger.Info($"Finding matching {fileName} in folder: {folder}");
  504. var dateSection = DateTime.Now.Date.ToString("yyyy-MM-dd");
  505. var hourSection = DateTime.Now.Hour.ToString("D2");
  506. CleanOldFiles(folder, fileName);
  507. var archivedFiles = Directory.GetFiles(folder, "*.zip");
  508. logger.Info($"Archived files count = {archivedFiles.Length}");
  509. var matchedFileNames = archivedFiles
  510. .Where(f => f.Contains(dateSection + "_" + hourSection) && f.Contains(fileName)
  511. && Regex.IsMatch(Path.GetFileNameWithoutExtension(f), @"[a-zA-Z]{11}_\d{4}-\d{2}-\d{2}_\d{2}\[(.*?)\]"));
  512. logger.Info($"Matched files count = {matchedFileNames.Count()}");
  513. if (!matchedFileNames.Any())
  514. {
  515. var fileNameWithoutExtension = folder + folderSeperator + transactionsFileName + "_" + dateSection + "_" + hourSection;
  516. if (File.Exists(fileNameWithoutExtension + ".zip"))
  517. return new List<string> { fileNameWithoutExtension };
  518. }
  519. return matchedFileNames.ToList();
  520. }
  521. #endregion
  522. #region Start
  523. public Task<bool> Start()
  524. {
  525. EnsureFolder();
  526. if (fdcServer != null)
  527. fdcServer.OnCurrentFuellingStatusChange += FdcServer_OnCurrentFuellingStatusChange;
  528. uploadTimer = new System.Timers.Timer();
  529. uploadTimer.Interval = uploadInterval * 60 * 1000;
  530. uploadTimer.Elapsed += Timer_Elapsed;
  531. uploadTimer.Enabled = true;
  532. tankReadTimer = new System.Timers.Timer();
  533. tankReadTimer.Interval = tankReadInterval * 1000;
  534. tankReadTimer.Elapsed += TankReadTimer_Elapsed;
  535. tankReadTimer.Enabled = true;
  536. logger.Info("\n");
  537. logger.Info("Fairbanks real time data client started");
  538. var config = GetAppConfig();
  539. RefreshConfig(config);
  540. return Task.FromResult(true);
  541. }
  542. #endregion
  543. #region Process records
  544. //Tank reading
  545. private async void TankReadTimer_Elapsed(object sender, ElapsedEventArgs e)
  546. {
  547. if (autoTankGaugeControllers != null)
  548. {
  549. var readings = new List<FbTankReading>();
  550. var atgController = autoTankGaugeControllers.First();
  551. if (atgController.Tanks == null)
  552. return;
  553. foreach (var tank in atgController.Tanks)
  554. {
  555. try
  556. {
  557. var inventory = await atgController.GetTankInventoryAsync(tank.TankNumber, 1);
  558. if (inventory != null)
  559. {
  560. var record = inventory.First();
  561. logger.Info($"Tank No: {record.TankNumber}, Time stamp: {record.TimeStamp}, " +
  562. $"Fuel Volume: {record.FuelVolume}, Fuel TCVolume: {record.FuelTCVolume}, " +
  563. $"Fuel Height: {record.FuelHeight}, Temperature: {record.Temperture}," +
  564. $"Water Height: {record.WaterHeight}, Fuel Height: {record.FuelHeight}");
  565. var reading = new FbTankReading();
  566. reading.ibank = deviceId;
  567. reading.DateTime = record.TimeStamp;
  568. reading.Tank = record.TankNumber;
  569. reading.QTY = Math.Round(Convert.ToDecimal(record.FuelVolume), 2);
  570. reading.Temperature = Math.Round(Convert.ToDecimal(record.Temperture), 2);
  571. reading.Water = Math.Round(Convert.ToDecimal(record.WaterHeight), 2);
  572. reading.Height = Math.Round(Convert.ToDecimal(record.FuelHeight), 2);
  573. readings.Add(reading);
  574. }
  575. }
  576. catch (Exception ex)
  577. {
  578. logger.Error($"Exception in getting tank inventory on Tank {tank.TankNumber}, ex: " + ex.ToString());
  579. }
  580. }
  581. if (readings.Count > 0)
  582. {
  583. await AddTankReadingsAsync(readings);
  584. }
  585. }
  586. }
  587. //Fuelling transactions
  588. private async void FdcServer_OnCurrentFuellingStatusChange(object sender, FdcServerTransactionDoneEventArg e)
  589. {
  590. if (e.Transaction.Finished)
  591. {
  592. logger.Info("A finished filling arrived and block the upload timer");
  593. await AddFillingTransactionAsync(e);
  594. }
  595. }
  596. private async Task AddTankReadingsAsync(List<FbTankReading> readings)
  597. {
  598. try
  599. {
  600. fileLocker.TryEnterReadLock(500);
  601. SetTankReadingFile(requiredFolder);
  602. }
  603. catch (Exception ex)
  604. {
  605. logger.Error(ex.ToString());
  606. }
  607. finally
  608. {
  609. fileLocker.ExitReadLock();
  610. }
  611. if (!File.Exists(stockLevelsFilePath))
  612. await WriteCsvAsync(new List<FbTankReading>(), stockLevelsFilePath);
  613. await WriteCsvAsync(readings, stockLevelsFilePath);
  614. }
  615. private async Task AddFillingTransactionAsync(FdcServerTransactionDoneEventArg e)
  616. {
  617. var filling = new FbFillingTransaction();
  618. filling.ibank = deviceId;
  619. filling.StartDateTime = DateTime.Now;
  620. filling.EndDateTime = e.FuelingEndTime.HasValue ? e.FuelingEndTime.Value : DateTime.Now;
  621. filling.Pump = e.Transaction.Nozzle.PumpId;
  622. filling.Nozzle = e.Transaction.Nozzle.LogicalId;
  623. filling.QTY = Convert.ToDecimal(e.Transaction.Volumn) / 100;
  624. var fillings = new List<FbFillingTransaction>();
  625. fillings.Add(filling);
  626. logger.Info("Converted fueling transaction");
  627. try
  628. {
  629. fileLocker.TryEnterReadLock(500);
  630. SetTransactionFile(requiredFolder);
  631. }
  632. catch (Exception ex)
  633. {
  634. logger.Error("Exception in adding filling transaction, ex: " + ex.ToString());
  635. }
  636. finally
  637. {
  638. fileLocker.ExitReadLock();
  639. }
  640. if (!File.Exists(transactionsFilePath))
  641. await WriteCsvAsync(new List<FbFillingTransaction>(), transactionsFilePath);
  642. await WriteCsvAsync(fillings, transactionsFilePath);
  643. }
  644. public async Task WriteCsvAsync<T>(IEnumerable<T> objInstances, string fileName)
  645. {
  646. logger.Debug($"Started to write record to file, File name: {fileName}");
  647. Type itemType = typeof(T);
  648. var props = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  649. using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write))
  650. using (var writer = new StreamWriter(fs, Encoding.UTF8))
  651. {
  652. if (objInstances.Count() == 0)
  653. {
  654. logger.Debug($"Formatting Header");
  655. await writer.WriteLineAsync(string.Join(",", props.Select(p => p.Name)));
  656. }
  657. else
  658. {
  659. foreach (var obj in objInstances)
  660. {
  661. var propertyValues = props.Select(p => p.GetValue(obj, null)).ToList();
  662. StringBuilder sb = new StringBuilder();
  663. for (int i = 0; i < propertyValues.Count(); i++)
  664. {
  665. if (propertyValues[i] is DateTime)
  666. sb.Append(((DateTime)propertyValues[i]).ToString("yyyy-MM-dd HH:mm:ss"));
  667. else
  668. sb.Append(propertyValues[i]);
  669. if (i <= propertyValues.Count() - 2)
  670. sb.Append(",");
  671. }
  672. //sb.Append("\r");
  673. await writer.WriteLineAsync(sb.ToString());
  674. }
  675. }
  676. }
  677. logger.Debug("Writing done");
  678. }
  679. private async void Timer_Elapsed(object sender, ElapsedEventArgs e)
  680. {
  681. List<string> files = new List<string>();
  682. try
  683. {
  684. fileLocker.TryEnterReadLock(500);
  685. files = Directory.GetFiles(requiredFolder, "*.csv").ToList();
  686. foreach (var file in files)
  687. {
  688. if (!csvFileQueue.Contains(file))
  689. {
  690. logger.Debug($" Enqueuing CSV file: {file}");
  691. csvFileQueue.Enqueue(file);
  692. }
  693. }
  694. }
  695. catch (Exception ex)
  696. {
  697. logger.Error(ex.ToString());
  698. }
  699. finally
  700. {
  701. fileLocker.ExitReadLock();
  702. }
  703. var fileCount = files.Count();
  704. logger.Debug($"File count: {fileCount}");
  705. fbSftpClient.Connect();
  706. foreach (var currentFile in files)
  707. {
  708. logger.Info($"File full name: {currentFile}");
  709. File.Move(currentFile, tempFolder + folderSeperator + Path.GetFileName(currentFile));
  710. var zippedFileName = Path.GetFileNameWithoutExtension(currentFile) + ".zip";
  711. ZipFile.CreateFromDirectory(tempFolder, requiredFolder + folderSeperator + zippedFileName);
  712. File.Delete(tempFolder + folderSeperator + Path.GetFileName(currentFile));
  713. var sendResult = fbSftpClient.UploadSingleFile(requiredFolder + folderSeperator + zippedFileName, hostUploadFolder);
  714. await SaveUploadHistory(zippedFileName, sendResult);
  715. ArchiveFile(requiredFolder + folderSeperator + zippedFileName);
  716. }
  717. fbSftpClient.Disconnect();
  718. }
  719. private void ArchiveFile(string currentFile)
  720. {
  721. logger.Info($"Archiving file: {currentFile}");
  722. try
  723. {
  724. File.Move(currentFile, uploadedFilesFolder + folderSeperator + Path.GetFileName(currentFile));
  725. }
  726. catch (IOException ex)
  727. {
  728. logger.Error("Error in archiving file: " + currentFile + "\n" + ex.ToString());
  729. }
  730. }
  731. #endregion
  732. #region Upload history
  733. [UniversalApi(Description = "Leave input <b>null</b> to retrieve latest Day's(24 hours) upload history" +
  734. "</br>input parameters are as follows, " +
  735. "</br>para.Name==\"startTime\", format should be yyyyMMddHHmmss")]
  736. public async Task<IEnumerable<UploadRecord>> GetUploadHistoryAsync(ApiData input)
  737. {
  738. if (input == null || (input?.IsEmpty() ?? false))
  739. {
  740. return await dbHelper.GetLatestUploadHistoryAsync(DateTime.Now.Subtract(new TimeSpan(24, 0, 0)));
  741. }
  742. else
  743. {
  744. var startTime = input.Get("starttime", DateTime.Now.Subtract(new TimeSpan(24, 0, 0)));
  745. return await dbHelper.GetLatestUploadHistoryAsync(startTime);
  746. }
  747. }
  748. #endregion
  749. #region Stop
  750. public Task<bool> Stop()
  751. {
  752. return Task.FromResult(true);
  753. }
  754. #endregion
  755. #region Config handling
  756. [UniversalApi(Description = "Leave input <b>null</b> to retrieve Fairbanks related Config" +
  757. "</br>First para.Name==\"template\" will return an sample Config for reference.")]
  758. public async Task<object> GetAppConfigAsync(ApiData input)
  759. {
  760. var uploadingConfig = new AppConfig();
  761. if (input?.Get("template") != null)
  762. {
  763. logger.Info($"GetAppConfigAsync with template");
  764. }
  765. else
  766. {
  767. uploadingConfig = GetAppConfig();
  768. }
  769. logger.Info($"GetConfigAsync, Fairbanks app config: {uploadingConfig.ToString()}");
  770. return await Task.FromResult(new[] { new { Name = "FairbanksAppConfig", Value = uploadingConfig } });
  771. }
  772. [UniversalApi(Description = "First para.Name is the updating config name, such as: FairbanksAppConfig, " +
  773. "</br>First para.Value is the new config's json serialized string value")]
  774. public async Task<object> PutConfigAsync(ApiData input)
  775. {
  776. //Check input
  777. if (input == null || input.Parameters == null || !input.Parameters.Any())
  778. {
  779. throw new ArgumentException(nameof(input));
  780. }
  781. try
  782. {
  783. AppConfig appConfig = GetConfig(input.Parameters.First().Name, input.Parameters.First().Value, new JsonSerializerOptions
  784. {
  785. PropertyNameCaseInsensitive = true,
  786. });
  787. bool appConfigExists = objMapper
  788. .Map<IEnumerable<AppConfig>>(dbContext.GenericDatas
  789. .Where(gd => gd.Type == AutoMapperProfile.UploadConfig && gd.Owner == AutoMapperProfile.AppDataOwner))
  790. .FirstOrDefault() != null;
  791. if (!appConfigExists)
  792. {
  793. //Create the config record
  794. await SaveDbAsync(appConfig);
  795. logger.Info($"PutConfigAsync created config type: {appConfig.GetType().Name}, details: {appConfig.ToString()}");
  796. }
  797. else
  798. {
  799. //Update the config record
  800. await UpdateDbAsync(appConfig);
  801. logger.Info($"PutConfigAsync updated config type: {appConfig.GetType().Name}, details: {appConfig.ToString()}");
  802. }
  803. RefreshConfig(appConfig);
  804. }
  805. catch (Exception ex)
  806. {
  807. logger.Error(ex.ToString());
  808. return await Task.FromResult(new { Name = "FairbanksAppConfig", Value = false });
  809. }
  810. return await Task.FromResult(new { Name = "FairbanksAppConfig", Value = true });
  811. }
  812. static AppConfig GetConfig(string name, string value, JsonSerializerOptions options) => name switch
  813. {
  814. "FairbanksAppConfig" => JsonSerializer.Deserialize<AppConfig>(value, options),
  815. _ => throw new InvalidOperationException("Unknown Config name: " + (name ?? ""))
  816. };
  817. public AppConfig GetAppConfig()
  818. {
  819. return objMapper
  820. .Map<IEnumerable<AppConfig>>(dbContext.GenericDatas
  821. .Where(d => d.Type == AutoMapperProfile.UploadConfig && d.Owner == AutoMapperProfile.AppDataOwner))
  822. .FirstOrDefault() ?? new AppConfig
  823. {
  824. DeviceId = this.deviceId,
  825. Host = this.host,
  826. Port = this.port,
  827. UserName = this.username,
  828. Password = this.password,
  829. SiteId = this.siteName,
  830. TankReadInterval = this.tankReadInterval,
  831. UploadInterval = this.uploadInterval
  832. };
  833. }
  834. #endregion
  835. #region Private methods
  836. private void RefreshConfig(AppConfig config)
  837. {
  838. if (config == null)
  839. return;
  840. logger.Info("Refreshing config");
  841. deviceId = config.DeviceId;
  842. siteName = config.SiteId;
  843. tankReadTimer.Stop();
  844. tankReadTimer.Interval = config.TankReadInterval * 1000;
  845. tankReadTimer.Start();
  846. uploadTimer.Stop();
  847. uploadTimer.Interval = config.UploadInterval * 60 * 1000;
  848. uploadTimer.Start();
  849. fbSftpClient.RefreshConfig(config.Host, config.UserName, config.Password);
  850. }
  851. private async Task SaveUploadHistory(string fileName, bool status)
  852. {
  853. var currentUploadRecord = new UploadRecord();
  854. currentUploadRecord.TimeStamp = DateTime.Now;
  855. currentUploadRecord.FileName = fileName;
  856. currentUploadRecord.Status = status ? "成功" : "失败";
  857. currentUploadRecord.Remark = dbHelper.RecordUploadTried(fileName) ? "重试" : "首次上传";
  858. await SaveDbAsync(currentUploadRecord);
  859. }
  860. private async Task SaveDbAsync<T>(T data)
  861. {
  862. var dbModel = objMapper.Map<GenericData>(data);
  863. dbContext.GenericDatas.Add(dbModel);
  864. await dbContext.SaveChangesAsync();
  865. }
  866. private async Task UpdateDbAsync<T>(T data)
  867. {
  868. var dbModel = objMapper.Map<GenericData>(data);
  869. dbContext.GenericDatas.Update(dbModel);
  870. await dbContext.SaveChangesAsync();
  871. }
  872. #endregion
  873. }
  874. public class FairbanksAppConfigV1
  875. {
  876. /// <summary>
  877. /// FTP host
  878. /// </summary>
  879. public string Host { get; set; }
  880. /// <summary>
  881. /// FTP port
  882. /// </summary>
  883. public int Port { get; set; }
  884. /// <summary>
  885. /// FTP user name
  886. /// </summary>
  887. public string Username { get; set; }
  888. /// <summary>
  889. /// FTP user password
  890. /// </summary>
  891. public string Password { get; set; }
  892. /// <summary>
  893. /// Device ID
  894. /// </summary>
  895. public string DeviceId { get; set; }
  896. /// <summary>
  897. /// Site name
  898. /// </summary>
  899. public string SiteName { get; set; }
  900. /// <summary>
  901. /// Tank reading interval, in seconds.
  902. /// </summary>
  903. public int Interval { get; set; }
  904. /// <summary>
  905. /// Upload interval, in minutes.
  906. /// </summary>
  907. public int UploadInterval { get; set; }
  908. /// <summary>
  909. /// Host folder path
  910. /// </summary>
  911. public string HostUploadFolder { get; set; }
  912. }
  913. }