PumpHandler.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using HengShan_Pump_NonIC_Plus.MessageEntity;
  5. using Edge.Core.Processor;
  6. using Edge.Core.IndustryStandardInterface.Pump;
  7. using Wayne.FDCPOSLibrary;
  8. using Edge.Core.Database.Models;
  9. using System.Threading.Tasks;
  10. using Edge.Core.Parser.BinaryParser.MessageEntity;
  11. using static HengShan_Pump_NonIC_Plus.MessageEntity.GetNozzleStatusResponse;
  12. using static HengShan_Pump_NonIC_Plus.MessageEntity.NonICMessageTemplateResponseBase;
  13. using System.Xml;
  14. using Microsoft.Extensions.Logging;
  15. namespace HengShan_Pump_NonIC_Plus
  16. {
  17. public class PumpHandler : IFdcPumpController, IDisposable
  18. {
  19. public event EventHandler<FdcPumpControllerOnStateChangeEventArg> OnStateChange;
  20. /// <summary>
  21. /// fired on fueling process is on going, the fuel amount should keep changing.
  22. /// </summary>
  23. public event EventHandler<FdcTransactionDoneEventArg> OnCurrentFuellingStatusChange;
  24. protected IContext<byte[], MessageTemplateBase> context;
  25. private ILogger logger = null;
  26. /// <summary>
  27. /// when first time connected with physical pump , in some case, the pump will not report any status actively,
  28. /// so need send a status query from FC.
  29. /// From then on, pump will actively notify FC when state changes, no need to send query anymore from FC.
  30. /// </summary>
  31. private bool initialPumpStatueEverRetrieved = false;
  32. private PumpStatus lastLogicalDeviceState = PumpStatus.未运行;
  33. /// <summary>
  34. /// Indicator for OnFdcServiceInit function called, the Process() will be called eariler that this function,
  35. /// </summary>
  36. protected bool isOnFdcServerInitCalled = false;
  37. private Guid uniqueId = Guid.NewGuid();
  38. private PumpGroupHandler parent;
  39. private int pumpId = -1;
  40. protected List<LogicalNozzle> nozzles = new List<LogicalNozzle>();
  41. private byte liftNozzleId = 0;
  42. private int amountDecimalDigits;
  43. private int volumeDecimalDigits;
  44. private int priceDecimalDigits;
  45. private int volumeTotalizerDecimalDigits;
  46. private int previousPolledHandlerIndex = 0;
  47. /// <summary>
  48. /// this type of pump state change is detected by FC actively polling, then state is always delay reported, so there's a corner case that in a fueling process,
  49. /// the attendants put back and pull out nozzle very quickly and it happened exactly in the middle of a polling, meanwhile,
  50. /// an auth request was done to auth the pump again(most likely the autoAuthCallingPump set with True),
  51. /// then the pump state returned from physical pump will still be read as a fueling state, but actually the
  52. /// 2nd fueling process is started, so detect the pump state is not enough, need detect if the fueling seq number reset to null(if place back nozzle detected) or not.
  53. /// </summary>
  54. protected GetNozzleStatusResponse previousUnfinishedFuelingNozzleStatus;
  55. public IEnumerable<LogicalNozzle> Nozzles => this.nozzles;
  56. protected void FireOnStateChangeEvent(LogicalDeviceState state)
  57. {
  58. var safe = this.OnStateChange;
  59. safe?.Invoke(this, new FdcPumpControllerOnStateChangeEventArg(state, this.nozzles.First()));
  60. }
  61. protected void FireOnCurrentFuellingStatusChangeEvent(FdcTransaction trx)
  62. {
  63. var safe = this.OnCurrentFuellingStatusChange;
  64. safe?.Invoke(this, new FdcTransactionDoneEventArg(trx));
  65. }
  66. public PumpHandler(PumpGroupHandler parent, int pumpId,
  67. int amountDecimalDigits, int volumeDecimalDigits,
  68. int priceDecimalDigits, int volumeTotalizerDecimalDigits,
  69. string pumpXmlConfiguration, ILogger logger)
  70. {
  71. this.parent = parent;
  72. this.pumpId = pumpId;
  73. this.amountDecimalDigits = amountDecimalDigits;
  74. this.volumeDecimalDigits = volumeDecimalDigits;
  75. this.priceDecimalDigits = priceDecimalDigits;
  76. this.volumeTotalizerDecimalDigits = volumeTotalizerDecimalDigits;
  77. this.logger = logger;
  78. // sample of pumpXmlConfiguration
  79. // <Pump pumpId='1' physicalId='1'>
  80. // <Nozzles>
  81. // <Nozzle logicalId='1' physicalId='1' defaultNoDecimalPointPriceIfNoHistoryPriceReadFromDb='2345'/>
  82. // <Nozzle logicalId='2' physicalId='2' defaultNoDecimalPointPriceIfNoHistoryPriceReadFromDb='2345'/>
  83. // <Nozzle logicalId='3' physicalId='3' defaultNoDecimalPointPriceIfNoHistoryPriceReadFromDb='2345'/>
  84. // </Nozzles>
  85. // </Pump>
  86. var xmlDocument = new XmlDocument();
  87. xmlDocument.LoadXml(pumpXmlConfiguration);
  88. //var physicalPumpAddressConfiguratedInPump =
  89. // byte.Parse(xmlDocument.SelectSingleNode("/Pump").Attributes["physicalId"].Value);
  90. //if (physicalPumpAddressConfiguratedInPump > 0x20)
  91. // throw new ArgumentOutOfRangeException("HSC+ pump only accept pump address range from 1 to 32, make sure this value is correctly configurated in physical pump mother board");
  92. foreach (var nozzleElement in xmlDocument.GetElementsByTagName("Nozzle").Cast<XmlNode>())
  93. {
  94. var nozzlePhysicalId = byte.Parse(nozzleElement.Attributes["physicalId"].Value);
  95. var nozzleLogicalId = byte.Parse(nozzleElement.Attributes["logicalId"].Value);
  96. var nozzleRawDefaultPriceWithoutDecimal = nozzleElement.Attributes["defaultNoDecimalPointPriceIfNoHistoryPriceReadFromDb"].Value;
  97. //if (nozzlePhysicalId < 1 || nozzlePhysicalId > 8) throw new ArgumentOutOfRangeException("HSC+ pump only accept nozzle physical id range in config from 1 to 8");
  98. this.nozzles.Add(new LogicalNozzle(pumpId, nozzlePhysicalId, nozzleLogicalId, null) { ExpectingPriceOnFcSide = int.Parse(nozzleRawDefaultPriceWithoutDecimal) });
  99. logger.LogInformation("Pump: " + this.pumpId
  100. + ", created a nozzle with logicalId: " + nozzleLogicalId + ", physicalId: " + nozzlePhysicalId
  101. + ", default raw price without decimal points: " + nozzleRawDefaultPriceWithoutDecimal);
  102. }
  103. }
  104. public NonICMessageTemplateBase GetRequest()
  105. {
  106. if (this.liftNozzleId != 0)
  107. return new GetNozzleStatusRequest(this.liftNozzleId);
  108. if (this.nozzles.Count <= previousPolledHandlerIndex)
  109. previousPolledHandlerIndex = 0;
  110. var target = this.nozzles[previousPolledHandlerIndex++];
  111. return new GetNozzleStatusRequest(target.PhysicalId);
  112. }
  113. public void Init(IContext<byte[], MessageTemplateBase> context)
  114. {
  115. this.context = context;
  116. this.context.Incoming.OnLongTimeNoSeeMessage += (_, __) =>
  117. {
  118. if (this.lastLogicalDeviceState != PumpStatus.未运行)
  119. {
  120. this.lastLogicalDeviceState = PumpStatus.未运行;
  121. logger.LogInformation("Pump: " + this.pumpId + ", " + " State switched to FDC_OFFLINE due to long time no see pump data incoming");
  122. var safe0 = this.OnStateChange;
  123. safe0?.Invoke(this, new FdcPumpControllerOnStateChangeEventArg(LogicalDeviceState.FDC_OFFLINE));
  124. logger.LogTrace("Pump: " + this.pumpId + ", " + " OnStateChange event fired and back");
  125. }
  126. };
  127. this.context.Incoming.LongTimeNoSeeMessageTimeout = 3000;
  128. }
  129. public async Task Process(IContext<byte[], MessageTemplateBase> context)
  130. {
  131. if (!isOnFdcServerInitCalled)
  132. return;
  133. this.context = context;
  134. if (context.Incoming.Message is GetNozzleStatusResponse getNozzleStatusResponse)
  135. {
  136. var latestStatus = (PumpStatus)getNozzleStatusResponse.Status;
  137. var safe = this.OnStateChange;
  138. string prefix = "Pump: " + this.pumpId + ", " + "Nozzle: " + getNozzleStatusResponse.Nozzle + ", ";
  139. if (this.lastLogicalDeviceState == PumpStatus.未运行 && latestStatus != PumpStatus.未运行)
  140. {
  141. logger.LogInformation(prefix + "Recevied an Pump Msg in FDC_OFFLINE state, " +
  142. "indicates the underlying connection is established, switch to FDC_READY");
  143. if (latestStatus == PumpStatus.空闲态)
  144. this.lastLogicalDeviceState = latestStatus;
  145. safe?.Invoke(this, new FdcPumpControllerOnStateChangeEventArg(LogicalDeviceState.FDC_READY));
  146. logger.LogTrace(prefix + " OnStateChange event fired and back");
  147. }
  148. // put the price by reading the real price.
  149. if (0 != getNozzleStatusResponse.Nozzle)
  150. this.nozzles.First(n => n.PhysicalId == getNozzleStatusResponse.Nozzle).RealPriceOnPhysicalPump = getNozzleStatusResponse.单价;
  151. if (latestStatus == PumpStatus.空闲态)
  152. {
  153. //在加油结束后,交易信息跟随加油状态主动上报给后台
  154. //if (this.lastLogicalDeviceState == PumpStatus.正在加油 || this.lastLogicalDeviceState == PumpStatus.暂停加油 ||
  155. // latestStatus == PumpStatus.暂停开始 || latestStatus == PumpStatus.暂停加油)
  156. //{
  157. //}
  158. this.liftNozzleId = 0;
  159. this.lastLogicalDeviceState = PumpStatus.空闲态;
  160. safe?.Invoke(this, new FdcPumpControllerOnStateChangeEventArg(LogicalDeviceState.FDC_READY, this.nozzles.First(n => n.PhysicalId == getNozzleStatusResponse.Nozzle)));
  161. }
  162. else if (latestStatus == PumpStatus.提枪)
  163. {
  164. this.liftNozzleId = getNozzleStatusResponse.Nozzle;
  165. logger.LogDebug(prefix + "收到状态: " + latestStatus.ToString() + ", switch to FDC_CALLING");
  166. this.lastLogicalDeviceState = PumpStatus.提枪;
  167. safe?.Invoke(this, new FdcPumpControllerOnStateChangeEventArg(LogicalDeviceState.FDC_CALLING, this.nozzles.First(n => n.PhysicalId == liftNozzleId)));
  168. }
  169. else if (latestStatus == PumpStatus.授权)
  170. {
  171. this.liftNozzleId = getNozzleStatusResponse.Nozzle;
  172. logger.LogDebug(prefix + "收到状态: " + latestStatus.ToString() + ", switch to FDC_AUTHORISED");
  173. lastLogicalDeviceState = PumpStatus.授权;
  174. safe?.Invoke(this, new FdcPumpControllerOnStateChangeEventArg(LogicalDeviceState.FDC_AUTHORISED, this.nozzles.First(n => n.PhysicalId == liftNozzleId)));
  175. }
  176. else if (latestStatus == PumpStatus.开始加油 || latestStatus == PumpStatus.正在加油)
  177. {
  178. this.liftNozzleId = getNozzleStatusResponse.Nozzle;
  179. logger.LogDebug(prefix + "收到状态: " + latestStatus.ToString() + ", switch to FDC_FUELLING");
  180. lastLogicalDeviceState = latestStatus;
  181. safe?.Invoke(this, new FdcPumpControllerOnStateChangeEventArg(LogicalDeviceState.FDC_FUELLING, this.nozzles.First(n => n.PhysicalId == liftNozzleId)));
  182. }
  183. else if (latestStatus == PumpStatus.暂停开始 || latestStatus == PumpStatus.暂停加油)
  184. {
  185. this.liftNozzleId = getNozzleStatusResponse.Nozzle;
  186. logger.LogDebug(prefix + "收到状态: " + latestStatus.ToString() + ", switch to FDC_SUSPENDED_FUELLING");
  187. lastLogicalDeviceState = latestStatus;
  188. safe?.Invoke(this, new FdcPumpControllerOnStateChangeEventArg(LogicalDeviceState.FDC_SUSPENDED_FUELLING, this.nozzles.First(n => n.PhysicalId == liftNozzleId)));
  189. }
  190. else if (latestStatus == PumpStatus.未运行 || latestStatus == PumpStatus.关闭)
  191. {
  192. this.lastLogicalDeviceState = latestStatus;
  193. }
  194. else
  195. {
  196. this.lastLogicalDeviceState = PumpStatus.未运行;
  197. logger.LogDebug(prefix + "收到未知状态: " + getNozzleStatusResponse.ToLogString() + ", \r\n switch to FDC_ERRORSTATE");
  198. }
  199. }
  200. else if (context.Incoming.Message is ActivePushTransactionResponse trx)
  201. {
  202. logger.LogDebug($"Pump: {this.pumpId}, Nozzle: {trx.Nozzle}, {trx.ToLogString()}");
  203. byte targetNozzlePhysicalId = trx.Nozzle;
  204. var lastFillTrx = new FdcTransaction()
  205. {
  206. Nozzle = this.nozzles.First(n => n.PhysicalId == targetNozzlePhysicalId),
  207. Amount = trx.加油金额,
  208. Volumn = trx.加油量,
  209. Price = this.nozzles.First(n => n.PhysicalId == targetNozzlePhysicalId).RealPriceOnPhysicalPump ?? 0,
  210. SequenceNumberGeneratedOnPhysicalPump = trx.SequenceNo,
  211. VolumeTotalizer = (int)trx.升累计,
  212. Finished = true,
  213. };
  214. FireOnCurrentFuellingStatusChangeEvent(lastFillTrx);
  215. byte result = (byte)EnumResult.成功;
  216. await this.context.Outgoing.WriteAsync(new AckActivePushTransactionRequest(targetNozzlePhysicalId) { HandleResult = result }, null, 1);
  217. }
  218. else
  219. {
  220. logger.LogDebug("Pump: " + this.pumpId + ", " + "收到: " + context.Incoming.Message.ToLogString());
  221. }
  222. }
  223. public virtual async Task<LogicalDeviceState> QueryStatusAsync()
  224. {
  225. switch (this.lastLogicalDeviceState)
  226. {
  227. case PumpStatus.空闲态:
  228. return LogicalDeviceState.FDC_OFFLINE;
  229. default:
  230. return LogicalDeviceState.FDC_OFFLINE;
  231. }
  232. }
  233. public string Name => this.GetType().FullName;
  234. public Guid Id => this.uniqueId;
  235. /// <summary>
  236. /// Gets the Identification of the pump for the system. Is the logical number of the pump
  237. /// </summary>
  238. public int PumpId => this.pumpId;
  239. /// <summary>
  240. /// this pump have no way to share same comport since this HengShan protocol content does not contains
  241. /// any id info, so always static 0 here.
  242. /// 地址面地址
  243. /// </summary>
  244. public int PumpPhysicalId => 0;
  245. public int AmountDecimalDigits => this.amountDecimalDigits;
  246. public int VolumeDecimalDigits => this.volumeDecimalDigits;
  247. public int PriceDecimalDigits => this.priceDecimalDigits;
  248. public int VolumeTotalizerDecimalDigits => this.volumeTotalizerDecimalDigits;
  249. /// <summary>
  250. ///
  251. /// </summary>
  252. /// <returns>MoneyTotalizer:VolumnTotalizer</returns>
  253. public async Task<Tuple<int, int>> QueryTotalizerAsync(byte logicalNozzleId)
  254. {
  255. var result = new Tuple<int, int>(-1, -1);
  256. logger.LogInformation("Pump: " + this.pumpId + ", " + " Start QueryTotalizer for logicalNozzle: " + logicalNozzleId);
  257. if (this.lastLogicalDeviceState == PumpStatus.未运行)
  258. {
  259. logger.LogInformation("Pump: " + this.pumpId + ", " + " Pump is in state FDC_CLOSED or FDC_OFFLINE, will return -1, -1");
  260. return result;
  261. }
  262. byte nozzleId = this.nozzles.First(n => n.LogicalId == logicalNozzleId).PhysicalId;
  263. var response = await this.context.Outgoing.WriteAsync(new GetAccumulateRequest(nozzleId),
  264. (request, testResponse) => testResponse is GetAccumulateResponse, 3000);
  265. if (response == null)
  266. {
  267. logger.LogInformation("Pump: " + this.pumpId + ", " + "QueryTotalizer timed out");
  268. return result;
  269. }
  270. else
  271. {
  272. var accumResponse = response as GetAccumulateResponse;
  273. logger.LogDebug($"Pump: {this.pumpId}, {accumResponse.ToLogString()}");
  274. result = new Tuple<int, int>((int)accumResponse.金额累计, (int)accumResponse.升累计);
  275. }
  276. return result;
  277. }
  278. public virtual async Task<bool> ChangeFuelPriceAsync(int newPriceWithoutDecimalPoint, byte logicalNozzleId)
  279. {
  280. logger.LogInformation("Pump: " + this.pumpId + ", " + " Start ChangeFuelPrice for logicalNozzle: " + logicalNozzleId + " with new price(without decimalPoints): " + newPriceWithoutDecimalPoint);
  281. if (this.lastLogicalDeviceState == PumpStatus.未运行)
  282. {
  283. logger.LogInformation("Pump: " + this.pumpId + ", " + " Pump is in state FDC_CLOSED or FDC_OFFLINE, ChangeFuelPrice will return false");
  284. return false;
  285. }
  286. byte nozzleId = this.nozzles.First(n => n.LogicalId == logicalNozzleId).PhysicalId;
  287. var response = await this.context.Outgoing.WriteAsync(new SetFuelPriceRequest(nozzleId) { FuelPrice = newPriceWithoutDecimalPoint },
  288. (request, testResponse) => testResponse is SetFuelPriceResponse, 3000);
  289. if (response == null)
  290. {
  291. logger.LogInformation("Pump: " + this.pumpId + ", " + "ChangeFuelPrice timed out");
  292. return false;
  293. }
  294. else
  295. {
  296. var priceChangeResponse = response as SetFuelPriceResponse;
  297. if (priceChangeResponse.Result != EnumResult.成功)
  298. {
  299. logger.LogInformation("Pump: " + this.pumpId + ", " + "ChangeFuelPriceResponse is NOT Result.成功");
  300. return false;
  301. }
  302. else
  303. {
  304. logger.LogInformation("Pump: " + this.pumpId + ", " + "ChangeFuelPriceResponse succeed");
  305. return true;
  306. }
  307. }
  308. }
  309. public virtual async Task<bool> ChangePumpClockAsync(DateTime datetime, byte logicalNozzleId)
  310. {
  311. logger.LogInformation("Pump: " + this.pumpId + ", " + " Start ChangePumpClockAsync");
  312. if (this.lastLogicalDeviceState == PumpStatus.未运行)
  313. {
  314. logger.LogInformation("Pump: " + this.pumpId + ", " + " Pump is in state FDC_CLOSED or FDC_OFFLINE, ChangePumpClockAsync will return false");
  315. return false;
  316. }
  317. var response = await this.context.Outgoing.WriteAsync(new SetClockRequest(logicalNozzleId, datetime),
  318. (request, testResponse) => testResponse is SetClockResponse, 3000);
  319. if (response == null)
  320. {
  321. logger.LogInformation("Pump: " + this.pumpId + ", " + "ChangePumpClock timed out");
  322. return false;
  323. }
  324. else
  325. {
  326. var setClockResponse = response as SetClockResponse;
  327. if (setClockResponse.Result != EnumResult.成功)
  328. {
  329. logger.LogInformation("Pump: " + this.pumpId + ", " + "SetClockResponse is NOT Result.成功");
  330. return false;
  331. }
  332. else
  333. {
  334. logger.LogInformation("Pump: " + this.pumpId + ", " + "SetClockResponse succeed");
  335. return true;
  336. }
  337. }
  338. }
  339. /// <summary>
  340. ///
  341. /// </summary>
  342. /// <param name="logicalNozzleId">useless for this type of pump, it always one pump one nozzle</param>
  343. /// <returns></returns>
  344. public virtual async Task<bool> AuthorizeAsync(byte logicalNozzleId)
  345. {
  346. logger.LogDebug("Pump: " + this.pumpId + ", " + "Start Authorize for logicalNozzle: " + this.liftNozzleId);
  347. var response = await this.context.Outgoing.WriteAsync(new StartRequest(this.liftNozzleId),
  348. (request, testResponse) => testResponse is StartResponse, 3000);
  349. if (response == null)
  350. {
  351. logger.LogInformation("Pump: " + this.pumpId + ", " + "Authorize timed out");
  352. return false;
  353. }
  354. else
  355. {
  356. var startResponse = response as StartResponse;
  357. string prefix = "Pump: " + this.pumpId + ", " + "Nozzle: " + startResponse.Nozzle + ", ";
  358. if (startResponse.Result != EnumResult.成功)
  359. {
  360. logger.LogInformation(prefix + "Authorize (StartResponse) is NOT Result.成功");
  361. return false;
  362. }
  363. else
  364. {
  365. logger.LogDebug(prefix + "Authorize (StartResponse) succeed");
  366. return true;
  367. }
  368. }
  369. }
  370. /// <summary>
  371. ///
  372. /// </summary>
  373. /// <param name="moneyAmount"></param>
  374. /// <param name="logicalNozzleId">useless for this type of pump, it always one pump one nozzle</param>
  375. /// <returns></returns>
  376. public virtual async Task<bool> AuthorizeWithAmountAsync(int moneyAmountWithoutDecimalPoint, byte logicalNozzleId)
  377. {
  378. //return await AuthorizeWithVolumeAsync(moneyAmountWithoutDecimalPoint, logicalNozzleId);
  379. logger.LogDebug("Pump: " + this.pumpId + ", " + "Start AuthorizeWithAmount for logicalNozzle: " + this.liftNozzleId + " with money(without decimalPoint): " + moneyAmountWithoutDecimalPoint);
  380. var response = await this.context.Outgoing.WriteAsync(new AuthPumpWithAmountRequest(this.liftNozzleId) { Amount = moneyAmountWithoutDecimalPoint },
  381. (request, testResponse) => testResponse is AuthPumpWithAmountResponse, 3000);
  382. if (response == null)
  383. {
  384. logger.LogInformation("Pump: " + this.pumpId + ", " + "AuthorizeWithAmount timed out");
  385. return false;
  386. }
  387. else
  388. {
  389. var presetResponse = response as AuthPumpWithAmountResponse;
  390. if (presetResponse.Result != EnumResult.成功)
  391. {
  392. logger.LogInformation("Pump: " + this.pumpId + ", " + "AuthPumpWithAmountResponse is NOT Result.成功");
  393. return false;
  394. }
  395. else
  396. {
  397. logger.LogDebug("Pump: " + this.pumpId + ", " + "Authorize (StartResponse) succeed");
  398. return true;
  399. }
  400. }
  401. }
  402. /// <summary>
  403. ///
  404. /// </summary>
  405. /// <param name="volumn"></param>
  406. /// <param name="logicalNozzleId">useless for this type of pump, it always one pump one nozzle</param>
  407. /// <returns></returns>
  408. public virtual async Task<bool> AuthorizeWithVolumeAsync(int volumnWithoutDecimalPoint, byte logicalNozzleId)
  409. {
  410. logger.LogDebug("Pump: " + this.pumpId + ", " + "Start AuthorizeWithVolumn for logicalNozzle: " + this.liftNozzleId + " with vol(without decimalPoint): " + volumnWithoutDecimalPoint);
  411. var response = await this.context.Outgoing.WriteAsync(new AuthPumpWithGallonRequest(this.liftNozzleId) { Gallon = volumnWithoutDecimalPoint },
  412. (request, testResponse) => testResponse is AuthPumpWithGallonResponse, 3000);
  413. if (response == null)
  414. {
  415. logger.LogInformation("Pump: " + this.pumpId + ", " + "AuthPumpWithGallonRequest timed out");
  416. return false;
  417. }
  418. else
  419. {
  420. var presetResponse = (AuthPumpWithGallonResponse)response;
  421. if (presetResponse.Result != EnumResult.成功)
  422. {
  423. logger.LogInformation("Pump: " + this.pumpId + ", " + "AuthorizeWithVolumnResponse is NOT Result.成功");
  424. return false;
  425. }
  426. else
  427. {
  428. logger.LogDebug("Pump: " + this.pumpId + ", " + "Authorize (StartResponse) succeed");
  429. return true;
  430. }
  431. }
  432. }
  433. public virtual async Task<bool> GetTransactionAsync(int sequenceNo, byte logicalNozzleId)
  434. {
  435. logger.LogInformation("Pump: " + this.pumpId + ", " + "Start Get transaction for sequenceNo: " + sequenceNo);
  436. var response = await this.context.Outgoing.WriteAsync(new GetTransactionRequest(logicalNozzleId) { SequenceNo = sequenceNo },
  437. (request, testResponse) => (testResponse is GetTransactionResponse || testResponse is GetTransactionFailureResponse), 3000);
  438. if (response == null)
  439. {
  440. logger.LogInformation("Pump: " + this.pumpId + ", " + "GetTransactionRequest timed out");
  441. return false;
  442. }
  443. else
  444. {
  445. if (response is GetTransactionFailureResponse)
  446. {
  447. logger.LogInformation("Pump: " + this.pumpId + ", " + "不存在该流水");
  448. return false;
  449. }
  450. else
  451. {
  452. var trxResponse = response as GetTransactionResponse;
  453. logger.LogInformation($"Pump: {this.pumpId}, {trxResponse.ToLogString()}");
  454. return true;
  455. }
  456. }
  457. }
  458. public virtual async Task<bool> GetVersionAsync(byte logicalNozzleId)
  459. {
  460. logger.LogInformation("Pump: " + this.pumpId + ", " + "Start Get version");
  461. var response = await this.context.Outgoing.WriteAsync(new GetVersionRequest(logicalNozzleId),
  462. (request, testResponse) => (testResponse is GetVersionResponse), 3000);
  463. if (response == null)
  464. {
  465. logger.LogInformation("Pump: " + this.pumpId + ", " + "GetVersionRequest timed out");
  466. return false;
  467. }
  468. else
  469. {
  470. var versionResponse = response as GetVersionResponse;
  471. logger.LogInformation($"Pump: {this.pumpId}, {versionResponse.ToLogString()}");
  472. return true;
  473. }
  474. }
  475. public virtual async Task<bool> ErrorPromptAsync(string errorMessage, byte logicalNozzleId)
  476. {
  477. logger.LogInformation("Pump: " + this.pumpId + ", " + "Start Error message prompt.");
  478. var response = await this.context.Outgoing.WriteAsync(new ErrorPromptRequest(logicalNozzleId, errorMessage),
  479. (request, testResponse) => testResponse is ErrorPromptResponse, 3000);
  480. if (response == null)
  481. {
  482. logger.LogInformation("Pump: " + this.pumpId + ", " + "Error message prompt timed out");
  483. return false;
  484. }
  485. else
  486. {
  487. var errorResponse = response as ErrorPromptResponse;
  488. if (errorResponse.Result != EnumResult.成功)
  489. {
  490. logger.LogInformation("Pump: " + this.pumpId + ", " + "ErrorPromptResponse is NOT Result.成功");
  491. return false;
  492. }
  493. else
  494. {
  495. logger.LogInformation("Pump: " + this.pumpId + ", " + "Error message prompt succeed");
  496. return true;
  497. }
  498. }
  499. }
  500. public virtual async Task<bool> CancelRationAsync(byte logicalNozzleId)
  501. {
  502. logger.LogInformation("Pump: " + this.pumpId + ", " + "Start Cancel ration.");
  503. var response = await this.context.Outgoing.WriteAsync(new CancelRationRequest(logicalNozzleId),
  504. (request, testResponse) => testResponse is CancelRationResponse, 3000);
  505. if (response == null)
  506. {
  507. logger.LogInformation("Pump: " + this.pumpId + ", " + "Cancel ration timed out");
  508. return false;
  509. }
  510. else
  511. {
  512. var rationResponse = response as CancelRationResponse;
  513. if (rationResponse.Result != EnumResult.成功)
  514. {
  515. logger.LogInformation("Pump: " + this.pumpId + ", " + "CancelRationResponse is NOT Result.成功");
  516. return false;
  517. }
  518. else
  519. {
  520. logger.LogInformation("Pump: " + this.pumpId + ", " + "Cancel ration succeed");
  521. return true;
  522. }
  523. }
  524. }
  525. public virtual async Task<bool> FuelingRoundUpByAmountAsync(int amount)
  526. {
  527. logger.LogInformation("Pump: " + this.pumpId + ", " + " Start FuelingRoundUpByAmount, amount: " + amount + " will be ignored due to hardware limit");
  528. return await Task.FromResult(false);
  529. }
  530. #region not implemented
  531. public async Task<bool> UnAuthorizeAsync(byte logicalNozzleId)
  532. {
  533. throw new NotImplementedException();
  534. }
  535. public async Task<bool> SuspendFuellingAsync()
  536. {
  537. throw new NotImplementedException();
  538. }
  539. public async Task<bool> ResumeFuellingAsync()
  540. {
  541. throw new NotImplementedException();
  542. }
  543. public async Task<bool> FuelingRoundUpByVolumeAsync(int volume)
  544. { throw new NotImplementedException(); }
  545. #endregion
  546. /// <summary>
  547. /// </summary>
  548. protected Dictionary<byte, FuelSaleTransaction> logicalNozzleIdToLastFuelSaleTrxMapping = new Dictionary<byte, FuelSaleTransaction>();
  549. public void OnFdcServerInit(Dictionary<string, object> parameters)
  550. {
  551. if (parameters.ContainsKey("LastPriceChange"))
  552. {
  553. }
  554. /* Load Last sale(from db) for void the case of FC accidently disconnect from Pump in fueling,
  555. and may cause a fueling trx gone from FC control */
  556. if (parameters.ContainsKey("LastFuelSaleTrx"))
  557. {
  558. // nozzle logical id:lastSale
  559. var lastFuelSaleTrxes = parameters["LastFuelSaleTrx"] as Dictionary<byte, FuelSaleTransaction>;
  560. foreach (var lastFuelSaleTrx in lastFuelSaleTrxes)
  561. {
  562. logger.LogInformation("Pump: " + this.pumpId + ", OnFdcServerInit, load last fuel sale " +
  563. "on logical nozzle: " + lastFuelSaleTrx.Key + " with value: " + lastFuelSaleTrx.Value);
  564. this.logicalNozzleIdToLastFuelSaleTrxMapping.Remove(lastFuelSaleTrx.Key);
  565. this.logicalNozzleIdToLastFuelSaleTrxMapping.Add(lastFuelSaleTrx.Key, lastFuelSaleTrx.Value);
  566. }
  567. }
  568. this.isOnFdcServerInitCalled = true;
  569. }
  570. public async Task<bool> LockNozzleAsync(byte logicalNozzleId)
  571. {
  572. return false;
  573. }
  574. public async Task<bool> UnlockNozzleAsync(byte logicalNozzleId)
  575. {
  576. return false;
  577. }
  578. public void Dispose()
  579. {
  580. //this.retryReadLastFillTimer?.Stop();
  581. //this.retryReadLastFillTimer?.Dispose();
  582. }
  583. }
  584. }