FspWebRun.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. using Applications.FDC;
  2. using Edge.Core.Database;
  3. using Edge.Core.Processor;using Edge.Core.IndustryStandardInterface.Pump;
  4. using FdcServerHost;
  5. using FspWebApp.Entity.Client;
  6. using FspWebApp.Entity.Service;
  7. using Microsoft.AspNetCore;
  8. using Microsoft.AspNetCore.Hosting;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Microsoft.Extensions.Logging;
  11. using Microsoft.Extensions.Logging.Abstractions;
  12. using Newtonsoft.Json;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using Wayne.FDCPOSLibrary;
  19. using Edge.Core.Configuration;
  20. namespace FspWebApp
  21. {
  22. public class FspWebRun : IAppProcessor
  23. {
  24. #region Properties
  25. public string MetaConfigName { get; set; }
  26. public static string LocalServiceUrl { get; set; }
  27. public string AuthServiceBaseUrl { get; set; }
  28. public string TransactionServiceBaseUrl { get; set; }
  29. #endregion
  30. #region Fields
  31. private ILogger logger = NullLogger.Instance;
  32. private object lockTransactionMonitor = new object();
  33. private Dictionary<(int, int), int> nozzles = new Dictionary<(int, int), int>();
  34. private FdcServerHostApp fdcServerHostApp;
  35. #endregion
  36. #region Constructor
  37. public FspWebRun(string otherParameter, string localServiceUrl, string authServiceBaseUrl, string transactionServiceBaseUrl, IServiceProvider services)
  38. {
  39. if (services != null)
  40. {
  41. var loggerFactory = services.GetRequiredService<ILoggerFactory>();
  42. this.logger = loggerFactory.CreateLogger("FspWebApp");
  43. }
  44. string[] args = { };
  45. LocalServiceUrl = localServiceUrl;
  46. AuthServiceBaseUrl = authServiceBaseUrl;
  47. TransactionServiceBaseUrl = transactionServiceBaseUrl;
  48. ThreadPool.QueueUserWorkItem(RunWeb, args);
  49. //var ts = new Test(36);
  50. }
  51. #endregion
  52. #region Init
  53. private void RunWeb(object state)
  54. {
  55. CreateWebHostBuilder(state as string[]).Build().Run();
  56. }
  57. private static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
  58. WebHost.CreateDefaultBuilder(args).UseUrls(LocalServiceUrl).UseStartup<Startup>()
  59. .ConfigureLogging(logging =>
  60. {
  61. logging.ClearProviders();
  62. });
  63. //IApplication method implementation
  64. public void Init(IEnumerable<IProcessor> processors)
  65. {
  66. InfoLog("FspWebApp Init begins...");
  67. try
  68. {
  69. fdcServerHostApp = processors.OfType<FdcServerHostApp>().FirstOrDefault();
  70. if (fdcServerHostApp == null)
  71. throw new ArgumentNullException("Can't find the FdcServerHostApp from processors");
  72. FuelProduct.onChangeFuelPrice = new ChangeFuel(FdcServerHostApp_OnChangeFuelPrice);
  73. FuelProduct.onChangeFuelProduct = new ChangeFuel(FdcServerHostApp_OnChangeFuelProduct);
  74. FuelProduct.onGetAuthToken = new CommonDelegate(FdcServerHostApp_OnGetAuthToken);
  75. var sino = Configurator.Default.DeviceProcessorConfiguration.Processor.Find(i => i.Parameter.Find(p => p.Name == "rawProductNameToPosProductNameStr") != null);
  76. string[] productNames = sino.Parameter.Find(i => i.Name == "rawProductNameToPosProductNameStr").Value.Split(';', StringSplitOptions.RemoveEmptyEntries);
  77. foreach (string pn in productNames)
  78. {
  79. string[] bcpn = pn.Split(':', StringSplitOptions.RemoveEmptyEntries);
  80. int barcode = int.Parse(bcpn[0]);
  81. DevicesConfig.fuelProducts[barcode] = new FuelProduct()
  82. {
  83. Barcode = barcode,
  84. FuelName = bcpn[1],
  85. CurrentPrice = 0.0,
  86. CurrentNozzles = new HashSet<int>()
  87. };
  88. }
  89. nozzles.Clear();
  90. InfoLog("(PumpId, Nozzle.LogicalId) => Site nozzle number");
  91. IEnumerable<NozzleExtraInfo> nozzleProductConfig = Configurator.Default.NozzleExtraInfoConfiguration.Mapping;
  92. foreach (NozzleExtraInfo np in nozzleProductConfig)
  93. {
  94. InfoLog($"({np.PumpId}, {np.NozzleLogicalId}) => {np.SiteLevelNozzleId}");
  95. nozzles.Add((np.PumpId, np.NozzleLogicalId), np.SiteLevelNozzleId ?? 0);
  96. DevicesConfig.fuelProducts[np.ProductBarcode].CurrentNozzles.Add(np.SiteLevelNozzleId ?? 0);
  97. }
  98. InitPumpData(fdcServerHostApp.FdcPumpControllers);
  99. DevicesConfig.pumpDatas = DevicesConfig.pumpDatas.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
  100. DevicesConfig.fuelProducts = DevicesConfig.fuelProducts.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
  101. }
  102. catch (Exception ex)
  103. {
  104. logger.LogError($"Init Exception: {ex}");
  105. }
  106. InfoLog("FspWebApp init ends...");
  107. }
  108. #endregion
  109. #region IProcessor implementation
  110. public async Task<bool> Start()
  111. {
  112. InfoLog("FspWebApp Start begins...");
  113. fdcServerHostApp.OnStateChange += FdcPumpController_OnStateChange;
  114. fdcServerHostApp.OnCurrentFuellingStatusChange += FdcPumpController_OnCurrentFuellingStatusChange;
  115. fdcServerHostApp.OnFdcFuelSaleTransactinStateChange += FdcPumpController_OnFdcFuelSaleTransactinStateChange;
  116. InfoLog("FspWebApp Start ends...");
  117. return true;
  118. }
  119. public async Task<bool> Stop()
  120. {
  121. return true;
  122. }
  123. private async Task<int> TransactionMonitor(int pumpId, byte logicalId)
  124. {
  125. try
  126. {
  127. var fuelPointTotals = await fdcServerHostApp.GetFuelPointTotalsAsync(pumpId, logicalId);
  128. lock (lockTransactionMonitor)
  129. {
  130. DevicesConfig.pumpDatas[nozzles[(pumpId, logicalId)]].VolumeTotalizer = fuelPointTotals.Item2;
  131. }
  132. }
  133. catch (Exception ex)
  134. {
  135. logger.LogError($"TransactionMonitor Exception: {ex}");
  136. }
  137. return 0;
  138. }
  139. #endregion
  140. #region Init pump data
  141. /// <summary>
  142. /// Set up the site nozzles, in particular the nozzle number
  143. /// Strategy:
  144. /// 1. Sort the Pumps by id
  145. /// 2. Sort the nozzles by logical id
  146. /// 3. The site nozzle number then will be (Pump id, Logical nozzle id) => site nozzle number
  147. /// e.g. (1, 1) => 1, (1, 2) => 2, (2, 1) => 3, (3, 1) => 4, (3, 2) => 5, (4, 1) => 6 ...
  148. /// </summary>
  149. /// <param name="fdcPumpControllers">The Fdc pump instance collection.</param>
  150. private async void InitPumpData(IEnumerable<IFdcPumpController> fdcPumpControllers)
  151. {
  152. var pumps = fdcPumpControllers.OrderBy(c => c.PumpId);
  153. var payableSaleTrxs = await fdcServerHostApp.GetAvailableFuelSaleTrxsWithDetailsAsync(-1);
  154. foreach (var pump in pumps)
  155. {
  156. var pumpNozzles = pump.Nozzles.OrderBy(n => n.LogicalId);
  157. foreach (var nozzle in pumpNozzles)
  158. {
  159. int nozzleNo = nozzles[(pump.PumpId, nozzle.LogicalId)];
  160. var fuelPointTotals = await fdcServerHostApp.GetFuelPointTotalsAsync(pump.PumpId, nozzle.LogicalId);
  161. DevicesConfig.pumpDatas[nozzleNo] = new PumpData()
  162. {
  163. SiteNozzleNumber = nozzleNo,
  164. PumpState = "Disconnected",
  165. VolumeTotalizer = fuelPointTotals.Item2,
  166. PayableTrxsCount = payableSaleTrxs.Where(t => t.PumpId == pump.PumpId && t.LogicalNozzleId == nozzle.LogicalId).Count()
  167. };
  168. }
  169. }
  170. }
  171. #endregion
  172. #region Event handlers
  173. private string FdcServerHostApp_OnGetAuthToken(object value)
  174. {
  175. var user = JsonConvert.DeserializeObject<User>(value.ToString());
  176. var tokenTask = Client.Default.GetAuthToken(AuthServiceBaseUrl + "token", user.userName, user.password);
  177. return tokenTask.Result;
  178. }
  179. private bool FdcServerHostApp_OnChangeFuelPrice(object value)
  180. {
  181. var fuelProducts = JsonConvert.DeserializeObject<Dictionary<int, FuelProduct>>(value.ToString());
  182. var succeedNozzles = new List<LogicalNozzle>();
  183. foreach (FuelProduct val in fuelProducts.Values)
  184. {
  185. if (val.NewPrice != null)
  186. {
  187. string deviceSn = "V105182A51890";
  188. var posItem = new PosItem();
  189. posItem.IsFuelItem = true;
  190. posItem.BarCode = val.Barcode.ToString();
  191. posItem.ItemId = posItem.BarCode;
  192. posItem.ItemName = val.FuelName;
  193. posItem.Price = decimal.Parse(val.NewPrice.ToString());
  194. var response = Client.Default.ChangeFuelPrice(TransactionServiceBaseUrl + "api/products/fuelgrades", deviceSn, posItem);
  195. int barcode = val.Barcode;
  196. double newPriceWithDecimalPoints = (double)val.NewPrice;
  197. var logicalNozzles = fdcServerHostApp.ChangeFuelPriceAsync(barcode, newPriceWithDecimalPoints);
  198. if (logicalNozzles.Result != null)
  199. succeedNozzles.AddRange(logicalNozzles.Result);
  200. //var pumps = fdcServerHostApp.FdcPumpControllers.OrderBy(c => c.PumpId);
  201. //foreach (var pump in pumps)
  202. //{
  203. // if (pump.GetType().FullName == "Global_Pump_Fdc.PumpHandler")
  204. // {
  205. // pump.ChangeFuelPriceAsync((int)(newPriceWithDecimalPoints * 1000 + 10000), (byte)barcode);
  206. // break;
  207. // }
  208. //}
  209. }
  210. }
  211. string result = succeedNozzles.Aggregate(
  212. "(PumpId, LogicalId) =>" + Environment.NewLine,
  213. (str, item) => str += ("(" + item.PumpId + ", " + item.LogicalId + ")-"),
  214. str => str.Substring(0, str.Length - 1)
  215. );
  216. InfoLog($"The successfully price changed nozzle: {result}");
  217. return succeedNozzles.Count > 0;
  218. }
  219. private bool FdcServerHostApp_OnChangeFuelProduct(object value)
  220. {
  221. var succeedNozzles = new List<LogicalNozzle>();
  222. //Client.Default.UploadDataAsync(null, null, AuthServiceBaseUrl);
  223. return false;
  224. }
  225. private void FdcPumpController_OnStateChange(object sender, FdcPumpControllerOnStateChangeEventArg e)
  226. {
  227. var currentPump = sender as IFdcPumpController;
  228. if (currentPump != null)
  229. {
  230. try
  231. {
  232. switch (e.NewPumpState)
  233. {
  234. case LogicalDeviceState.FDC_OFFLINE:
  235. foreach (var noz in currentPump.Nozzles)
  236. {
  237. DevicesConfig.pumpDatas[nozzles[(currentPump.PumpId, noz.LogicalId)]].PumpState = "Disconnected";
  238. }
  239. break;
  240. case LogicalDeviceState.FDC_READY:
  241. if (e.StateChangedNozzles != null)
  242. {
  243. break;
  244. }
  245. foreach (var noz in currentPump.Nozzles)
  246. {
  247. DevicesConfig.pumpDatas[nozzles[(currentPump.PumpId, noz.LogicalId)]].PumpState = "Idle";
  248. }
  249. break;
  250. case LogicalDeviceState.FDC_CALLING:
  251. if (e.StateChangedNozzles != null)
  252. {
  253. DevicesConfig.pumpDatas[nozzles[(currentPump.PumpId, e.StateChangedNozzles.First().LogicalId)]].PumpState = "Calling";
  254. }
  255. break;
  256. case LogicalDeviceState.FDC_AUTHORISED:
  257. if (e.StateChangedNozzles != null)
  258. {
  259. DevicesConfig.pumpDatas[nozzles[(currentPump.PumpId, e.StateChangedNozzles.First().LogicalId)]].PumpState = "Authorised";
  260. break;
  261. }
  262. foreach (var noz in currentPump.Nozzles)
  263. {
  264. DevicesConfig.pumpDatas[nozzles[(currentPump.PumpId, noz.LogicalId)]].PumpState = "Authorised";
  265. }
  266. break;
  267. case LogicalDeviceState.FDC_FUELLING:
  268. if (e.StateChangedNozzles != null)
  269. {
  270. DevicesConfig.pumpDatas[nozzles[(currentPump.PumpId, e.StateChangedNozzles.First().LogicalId)]].PumpState = "Fueling";
  271. }
  272. break;
  273. default:
  274. return;
  275. }
  276. }
  277. catch (Exception ex)
  278. {
  279. ErrorLog(currentPump.PumpId, $"Exception: {ex}");
  280. }
  281. }
  282. else
  283. {
  284. InfoLog($"Sender is not an IFdcPumpController, PumpStateChange, New State: {e.NewPumpState}");
  285. return;
  286. }
  287. }
  288. private async void FdcPumpController_OnCurrentFuellingStatusChange(object sender, FdcServerTransactionDoneEventArg e)
  289. {
  290. var currentPump = sender as IFdcPumpController;
  291. if (currentPump != null)
  292. {
  293. try
  294. {
  295. int key = nozzles[(currentPump.PumpId, e.Transaction.Nozzle.LogicalId)];
  296. if (e.Transaction.Finished)
  297. {
  298. DevicesConfig.pumpDatas[key].PumpState = "Idle";
  299. DevicesConfig.pumpDatas[key].Amount = e.Transaction.Amount / Math.Pow(10, currentPump.AmountDecimalDigits);
  300. DevicesConfig.pumpDatas[key].Volumn = e.Transaction.Volumn / Math.Pow(10, currentPump.VolumeDecimalDigits);
  301. DevicesConfig.fuelProducts[e.Transaction.Barcode].CurrentPrice = e.Transaction.Price / Math.Pow(10, currentPump.PriceDecimalDigits);
  302. DevicesConfig.pumpDatas[key].PayableTrxsCount++;
  303. await TransactionMonitor(currentPump.PumpId, e.Transaction.Nozzle.LogicalId);
  304. }
  305. else
  306. {
  307. DevicesConfig.pumpDatas[key].PumpState = "Fueling";
  308. DevicesConfig.pumpDatas[key].Amount = e.Transaction.Amount / Math.Pow(10, currentPump.AmountDecimalDigits);
  309. DevicesConfig.pumpDatas[key].Volumn = e.Transaction.Volumn / Math.Pow(10, currentPump.VolumeDecimalDigits);
  310. }
  311. }
  312. catch (Exception ex)
  313. {
  314. ErrorLog(currentPump.PumpId, $"Exception: {ex}");
  315. }
  316. }
  317. else
  318. {
  319. InfoLog($"Sender is not an IFdcPumpController, FuellingStateChange, New State: {e.Transaction}");
  320. return;
  321. }
  322. }
  323. public void FdcPumpController_OnFdcFuelSaleTransactinStateChange(object sender, FdcFuelSaleTransactinStateChangeEventArg e)
  324. {
  325. try
  326. {
  327. if (e.State == Edge.Core.Database.Models.FuelSaleTransactionState.Paid)
  328. {
  329. DevicesConfig.pumpDatas[nozzles[(e.Transaction.PumpId, e.Transaction.LogicalNozzleId)]].PayableTrxsCount--;
  330. }
  331. }
  332. catch (Exception ex)
  333. {
  334. logger.LogError($"OnFdcFuelSaleTransactinStateChange Exception: {ex}");
  335. }
  336. }
  337. #endregion
  338. #region Log methods
  339. private void InfoLog(string log)
  340. {
  341. if (logger.IsEnabled(LogLevel.Information))
  342. logger.LogInformation(log);
  343. }
  344. private void InfoLog(int pumpId, string log)
  345. {
  346. if (logger.IsEnabled(LogLevel.Information))
  347. logger.LogInformation($"Pump {pumpId}, {log}");
  348. }
  349. private void DebugLog(int pumpId, string log)
  350. {
  351. if (logger.IsEnabled(LogLevel.Debug))
  352. logger.LogDebug($"Pump {pumpId}, {log}");
  353. }
  354. private void ErrorLog(int pumpId, string log)
  355. {
  356. if (logger.IsEnabled(LogLevel.Error))
  357. logger.LogError($"Pump {pumpId}, {log}");
  358. }
  359. #endregion
  360. }
  361. public class Test
  362. {
  363. int len = 0;
  364. int[] trxs = { 4, 3, 2, 1, 0 };
  365. string[] states = { "Fueling", "Disconnected", "Idle", "Calling", "Authorised" };
  366. double[] amounts = { 116, 116.8, 116.98, 18, 0 };
  367. double[] volumeTotalizers = { 1169869, 1169869.8, 1169869.98, 18, 0 };
  368. public Test(int length)
  369. {
  370. len = length;
  371. for (int i = 1; i <= len; i++)
  372. {
  373. DevicesConfig.pumpDatas[i] = new PumpData()
  374. {
  375. SiteNozzleNumber = i,
  376. PumpState = "Disconnected"
  377. };
  378. }
  379. var timer = new System.Timers.Timer(1000);
  380. timer.Elapsed += new System.Timers.ElapsedEventHandler(TransactionFileMonitor_newTableEvent);
  381. timer.Start();
  382. }
  383. void TransactionFileMonitor_newTableEvent(object sender, EventArgs e)
  384. {
  385. var ran = new Random();
  386. for (int i = 1; i <= len; i++)
  387. {
  388. int randKey = ran.Next(0, 5);
  389. DevicesConfig.pumpDatas[i].PayableTrxsCount = trxs[randKey];
  390. DevicesConfig.pumpDatas[i].PumpState = states[randKey];
  391. DevicesConfig.pumpDatas[i].Amount = amounts[randKey];
  392. DevicesConfig.pumpDatas[i].VolumeTotalizer = volumeTotalizers[randKey];
  393. }
  394. //var timer = sender as System.Timers.Timer;
  395. //timer.Stop();
  396. //Trace.WriteLine(DateTime.Now);
  397. }
  398. }
  399. }