LonWorksPumpHandler.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. using Edge.Core.Database;
  2. using Edge.Core.Processor;
  3. using Edge.Core.IndustryStandardInterface.Pump;
  4. using HengShan_Pump_TQC_IFSF.MessageEntity;
  5. using HengShan_Pump_TQC_IFSF.MessageEntity.Incoming;
  6. using HengShan_Pump_TQC_IFSF.MessageEntity.Outgoing;
  7. using Edge.Core.Parser.BinaryParser.Util;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using System.Xml;
  16. using Wayne.FDCPOSLibrary;
  17. using Timer = System.Timers.Timer;
  18. using Edge.Core.Configuration;
  19. using static HengShan_Pump_TQC_IFSF.LonWorksPumpGroupHandler;
  20. namespace HengShan_Pump_TQC_IFSF
  21. {
  22. public class LonWorksPumpHandler : IFdcPumpController//, IDeviceHandler<byte[], IfsfMessageBase>
  23. {
  24. private object syncObject = new object();
  25. private IEnumerable<NozzleExtraInfo> nozzleExtraInfos = null;
  26. //protected static ILog logger = log4net.LogManager.GetLogger("PumpHandler");
  27. protected static NLog.Logger logger = NLog.LogManager.LoadConfiguration("nlog.config").GetLogger("PumpHandler");
  28. protected IContext<byte[], IfsfMessageBase> context;
  29. /// <summary>
  30. /// default to first nozzle
  31. /// </summary>
  32. protected byte currentCallingNozzleLogicalId = 1;
  33. protected LogicalDeviceState lastLogicalDeviceState = LogicalDeviceState.FDC_CLOSED;
  34. private DateTime lastLogicalDeviceStateReceivedTime;
  35. // by seconds
  36. public const int lastLogicalDeviceStateExpiredTime = 6;
  37. private Guid uniqueId = Guid.NewGuid();
  38. private TqcPumpGroupInitializer initor;
  39. protected int pumpId = -1;
  40. protected List<LogicalNozzle> nozzles = new List<LogicalNozzle>();
  41. private byte recipientSubnet = 1;
  42. private byte recipientNode = 1;
  43. private byte ifsfFuelPointId;
  44. Func<byte> msgTokenGenerator;
  45. public DateTime? LastIncomingMsgReceivedTime { get; set; }
  46. public LonWorksPumpHandler(TqcPumpGroupInitializer initor, int pumpId, byte ifsfFuelPointId,
  47. byte recipientSubnet, byte recipientNode,
  48. List<IfsfNozzleConfig> ifsfNozzleConfigs, Func<byte> msgTokenGenerator)
  49. {
  50. //sample of nozzlesXmlConfiguration
  51. // <Pump id='3'>
  52. // <Nozzles>
  53. // <Nozzle logicalId='1' physicalId='0x11' />
  54. // <Nozzle logicalId='2' physicalId='0x12' />
  55. // </Nozzles>
  56. // </Pump>
  57. this.pumpId = pumpId;
  58. this.initor = initor;
  59. this.ifsfFuelPointId = ifsfFuelPointId;
  60. this.recipientSubnet = recipientSubnet;
  61. this.recipientNode = recipientNode;
  62. this.msgTokenGenerator = msgTokenGenerator;
  63. if (ifsfNozzleConfigs.Any(nzConfig => nzConfig.PhysicalId < 0x11 || nzConfig.PhysicalId > 0x18))
  64. throw new ArgumentException("ifsf nozzle id must be range from 0x11 to 0x18");
  65. this.nozzles.AddRange(ifsfNozzleConfigs.Select(nc => new LogicalNozzle(pumpId, nc.PhysicalId, nc.LogicalId, null)));
  66. }
  67. public string Name => this.GetType().FullName;
  68. public int PumpId => this.pumpId;
  69. /// <summary>
  70. /// range from 0x21 to 0x24 since it's a IFSF pump
  71. /// </summary>
  72. public int PumpPhysicalId => this.ifsfFuelPointId;
  73. public IEnumerable<LogicalNozzle> Nozzles => this.nozzles;
  74. public int AmountDecimalDigits => 2;
  75. public int VolumeDecimalDigits => 2;
  76. public int PriceDecimalDigits => 2;
  77. public int VolumeTotalizerDecimalDigits => 2;
  78. public Guid Id => this.uniqueId;
  79. public event EventHandler<FdcPumpControllerOnStateChangeEventArg> OnStateChange;
  80. public event EventHandler<FdcTransactionDoneEventArg> OnCurrentFuellingStatusChange;
  81. protected void FireOnStateChangeEvent(LogicalDeviceState state, LogicalNozzle stateChangedNozzle)
  82. {
  83. try
  84. {
  85. var safe = this.OnStateChange;
  86. safe?.Invoke(this, new FdcPumpControllerOnStateChangeEventArg(state, stateChangedNozzle));
  87. }
  88. catch (Exception exx)
  89. {
  90. logger.Info("exceptioned when FireOnStateChangeEvent: " + exx + Environment.NewLine + "Will Ignore and do nothing");
  91. }
  92. }
  93. protected void FireOnCurrentFuellingStatusChangeEvent(FdcTransaction trx)
  94. {
  95. try
  96. {
  97. var safe = this.OnCurrentFuellingStatusChange;
  98. safe?.Invoke(this, new FdcTransactionDoneEventArg(trx));
  99. }
  100. catch (Exception exx)
  101. {
  102. logger.Info("exceptioned when FireOnCurrentFuellingStatusChangeEvent: " + exx + Environment.NewLine + "Will Ignore and do nothing");
  103. }
  104. }
  105. public virtual void Init(IContext<byte[], IfsfMessageBase> context)
  106. {
  107. this.context = context;
  108. }
  109. public virtual Task Process(IContext<byte[], IfsfMessageBase> context)
  110. {
  111. this.context = context;
  112. switch (context.Incoming.Message)
  113. {
  114. case FuellingPointDb_FpStatus_Event fpStatusEvent:
  115. {
  116. logger.Info("Pump " + this.pumpId + ", receiving Ifsf PumpState(by fpStatusEvent): "
  117. + fpStatusEvent.FuelPointState
  118. + "(internal FdcState: " + this.lastLogicalDeviceState + ")");
  119. // send query only when at cold start.
  120. if (fpStatusEvent.FuelPointState == FuellingPointStatus.Idle
  121. && this.lastLogicalDeviceState == LogicalDeviceState.FDC_CLOSED)
  122. {
  123. logger.Info("Pump " + this.pumpId + ", State changing from Fdc_CLOSED to Ifsf IDLE, always send a query to see any open trx stacked in TQC pump side");
  124. context.Outgoing.Write(
  125. new FuelTrxDb_Read_QueryTransaction(this.recipientSubnet, this.recipientNode, PumpGroupHandler.originatorSubnet, PumpGroupHandler.originatorNode,
  126. this.msgTokenGenerator(), this.ifsfFuelPointId, null));
  127. }
  128. // when trx event piped in, there's no nozzle info linked it within the event(ifsf bad design?), so here always track
  129. // and keep the state of the last calling or fuelling nozzle.
  130. if (fpStatusEvent.FuelPointState == FuellingPointStatus.CALLING
  131. || fpStatusEvent.FuelPointState == FuellingPointStatus.FUELLING)
  132. {
  133. var operatingNozzlePhysicalId = (byte)(fpStatusEvent.RemovedNozzleIndexes.First() + 0x10);
  134. if (this.nozzles.Any(n => n.PhysicalId == operatingNozzlePhysicalId))
  135. this.currentCallingNozzleLogicalId = this.nozzles.First(n => n.PhysicalId == operatingNozzlePhysicalId).LogicalId;
  136. else
  137. this.currentCallingNozzleLogicalId = fpStatusEvent.RemovedNozzleIndexes.FirstOrDefault();
  138. logger.Info("Pump " + this.pumpId + ", reporting removed(lifted) ifsf NozzleId is 0x"
  139. + operatingNozzlePhysicalId.ToHexLogString()
  140. + ", correlated Fdc Nozzle logical Id is " + this.currentCallingNozzleLogicalId);
  141. }
  142. this.HandleFpStatusChange(fpStatusEvent.FuelPointState,
  143. this.nozzles.FirstOrDefault(n => n.LogicalId == this.currentCallingNozzleLogicalId));
  144. break;
  145. }
  146. case FuellingPointDb_FpStatus_Answer fpStatusAnswer:
  147. {
  148. // send query only when at cold start.
  149. if (fpStatusAnswer.FuelPointState == FuellingPointStatus.Idle && this.lastLogicalDeviceState == LogicalDeviceState.FDC_CLOSED)
  150. {
  151. logger.Info("Pump " + this.pumpId + ", State changed from CLOSED to IDLE, likely a cold start, send query to see any open trx");
  152. context.Outgoing.Write(
  153. new FuelTrxDb_Read_QueryTransaction(this.recipientSubnet, this.recipientNode, PumpGroupHandler.originatorSubnet, PumpGroupHandler.originatorNode,
  154. this.msgTokenGenerator(), this.ifsfFuelPointId, null));
  155. }
  156. this.HandleFpStatusChange(fpStatusAnswer.FuelPointState, this.nozzles.FirstOrDefault(n => n.LogicalId == this.currentCallingNozzleLogicalId));
  157. break;
  158. }
  159. case FuellingPointDb_FpRunningTransaction_Event fpRunningTrxEvent:
  160. {
  161. logger.Debug("Pump " + this.pumpId + ", fpRunningTrxEvent ifsf FpId: 0x" + fpRunningTrxEvent.TargetFuelPointId.ToHexLogString()
  162. + ", CurAmt and CurVol(no decimal points): " + fpRunningTrxEvent.CurrentAmount
  163. + " - " + fpRunningTrxEvent.CurrentVolume);
  164. var operatingNozzle = this.nozzles.First(f => f.LogicalId == this.currentCallingNozzleLogicalId);
  165. var operatingNozzleProductPrice =
  166. this.initor.PriceBook[
  167. this.nozzleExtraInfos.First(c => c.PumpId == operatingNozzle.PumpId
  168. && c.NozzleLogicalId == operatingNozzle.LogicalId).ProductBarcode];
  169. //fire fuelling progress.
  170. var safe1 = this.OnCurrentFuellingStatusChange;
  171. safe1?.Invoke(this, new FdcTransactionDoneEventArg(new FdcTransaction()
  172. {
  173. Nozzle = operatingNozzle,
  174. Amount = fpRunningTrxEvent.CurrentAmount,
  175. Volumn = fpRunningTrxEvent.CurrentVolume,
  176. Price = operatingNozzleProductPrice,
  177. Finished = false,
  178. }));
  179. break;
  180. }
  181. case FuellingTrxDb_TransactionBufferStatus_Event trxBufferStatusEvent:
  182. {
  183. if (trxBufferStatusEvent.State == FuellingTrxDb_TransactionBufferStatus_Event.TransactionState.PAYABLE
  184. && (trxBufferStatusEvent.Volume != 0 || trxBufferStatusEvent.Amount != 0))
  185. {
  186. logger.Debug("Pump " + this.pumpId + ", received a Payable trx from TQC with Vol and Amount(without decimal points): "
  187. + trxBufferStatusEvent.Volume + " - " + trxBufferStatusEvent.Amount
  188. + ", will send clear to clear it in pump side anyway");
  189. context.Outgoing.WriteAsync(
  190. new FuellingPointDbRequest_Write_ClearTransaction(this.recipientSubnet,
  191. this.recipientNode,
  192. PumpGroupHandler.originatorSubnet,
  193. PumpGroupHandler.originatorNode,
  194. this.msgTokenGenerator(), this.ifsfFuelPointId, trxBufferStatusEvent.TransactionSeqNumber.ToString()),
  195. (request, response) => response is AcknowledgeMessage rp && request is IfsfMessage rq && rp.MessageToken == rp.MessageToken,
  196. (_, expectedResponse) =>
  197. {
  198. if (expectedResponse != null)
  199. { }
  200. else logger.Info("Pump " + this.pumpId + ", Clear transaction in TQC side failed");
  201. var operatingNozzle = this.nozzles.First(f => f.LogicalId == this.currentCallingNozzleLogicalId);
  202. var operatingNozzleProductPrice = this.initor.PriceBook[this.nozzleExtraInfos.First(c => c.PumpId == operatingNozzle.PumpId && c.NozzleLogicalId == operatingNozzle.LogicalId).ProductBarcode];
  203. var safe1 = this.OnCurrentFuellingStatusChange;
  204. safe1?.Invoke(this, new FdcTransactionDoneEventArg(new FdcTransaction()
  205. {
  206. Nozzle = operatingNozzle,
  207. Amount = trxBufferStatusEvent.Amount,
  208. Volumn = trxBufferStatusEvent.Volume,
  209. Price = operatingNozzleProductPrice,
  210. SequenceNumberGeneratedOnPhysicalPump = trxBufferStatusEvent.TransactionSeqNumber,
  211. Finished = true,
  212. }));
  213. }, 12000);
  214. }
  215. break;
  216. }
  217. case FuellingTrxDb_TransactionBufferStatus_Answer trxBufferStatusAnswer:
  218. {
  219. if (trxBufferStatusAnswer.State.HasValue
  220. && trxBufferStatusAnswer.State == FuellingTrxDb_TransactionBufferStatus_Event.TransactionState.PAYABLE)
  221. {
  222. logger.Debug("Pump " + this.pumpId + ", received a Payable trx from TQC with Vol and Amount(without decimal points): "
  223. + trxBufferStatusAnswer.Volume + " - " + trxBufferStatusAnswer.Amount
  224. + ", sequenceNo.: " + trxBufferStatusAnswer.TransactionSeqNumber
  225. + ", will send ClearTransaction to clear it now");
  226. context.Outgoing.WriteAsync(
  227. new FuellingPointDbRequest_Write_ClearTransaction(this.recipientSubnet,
  228. this.recipientNode,
  229. PumpGroupHandler.originatorSubnet,
  230. PumpGroupHandler.originatorNode,
  231. this.msgTokenGenerator(), this.ifsfFuelPointId, trxBufferStatusAnswer.TransactionSeqNumber.ToString()),
  232. (request, response) => response is AcknowledgeMessage rp && request is IfsfMessage rq && rp.MessageToken == rp.MessageToken,
  233. (_, expectedResponse) =>
  234. {
  235. if (expectedResponse != null)
  236. {
  237. var operatingNozzle = this.nozzles.First(f => f.LogicalId == this.currentCallingNozzleLogicalId);
  238. var operatingNozzleProductPrice = this.initor.PriceBook[this.nozzleExtraInfos.First(c => c.PumpId == operatingNozzle.PumpId && c.NozzleLogicalId == operatingNozzle.LogicalId).ProductBarcode];
  239. var safe1 = this.OnCurrentFuellingStatusChange;
  240. safe1?.Invoke(this, new FdcTransactionDoneEventArg(new FdcTransaction()
  241. {
  242. Nozzle = operatingNozzle,
  243. Amount = trxBufferStatusAnswer.Amount,
  244. Volumn = trxBufferStatusAnswer.Volume,
  245. Price = operatingNozzleProductPrice,
  246. SequenceNumberGeneratedOnPhysicalPump = trxBufferStatusAnswer.TransactionSeqNumber,
  247. Finished = true,
  248. }));
  249. }
  250. else logger.Error("Clear transaction in TQC side failed");
  251. }, 8000);
  252. }
  253. break;
  254. }
  255. case IfsfMessage ifsfMessage:
  256. {
  257. var dbParser = DatabaseDataParser.New().Convert(ifsfMessage.RawDatabaseData.ToArray());
  258. break;
  259. }
  260. }
  261. //if (context.Incoming.Message is FuellingPointDb_FpStatus_Event fpStatusChangeEvent && fpStatusChangeEvent.TargetFuelPointId == this.ifsfFuelPointId)
  262. //{
  263. // this.lastLogicalDeviceState = LogicalDeviceState.FDC_READY;
  264. //}
  265. return Task.CompletedTask;
  266. }
  267. public virtual void HandleFpStatusChange(FuellingPointStatus newStatus, LogicalNozzle stateChangedNozzle)
  268. {
  269. this.lastLogicalDeviceStateReceivedTime = DateTime.Now;
  270. switch (newStatus)
  271. {
  272. case FuellingPointStatus.Idle:
  273. {
  274. if (this.lastLogicalDeviceState != LogicalDeviceState.FDC_READY)
  275. {
  276. this.lastLogicalDeviceState = LogicalDeviceState.FDC_READY;
  277. this.FireOnStateChangeEvent(LogicalDeviceState.FDC_READY, null);
  278. }
  279. break;
  280. }
  281. case FuellingPointStatus.CALLING:
  282. {
  283. if (this.lastLogicalDeviceState != LogicalDeviceState.FDC_CALLING)
  284. {
  285. this.lastLogicalDeviceState = LogicalDeviceState.FDC_CALLING;
  286. this.FireOnStateChangeEvent(LogicalDeviceState.FDC_CALLING, stateChangedNozzle);
  287. }
  288. break;
  289. }
  290. case FuellingPointStatus.AUTHORISED:
  291. {
  292. if (this.lastLogicalDeviceState != LogicalDeviceState.FDC_AUTHORISED)
  293. {
  294. this.lastLogicalDeviceState = LogicalDeviceState.FDC_AUTHORISED;
  295. this.FireOnStateChangeEvent(LogicalDeviceState.FDC_AUTHORISED, stateChangedNozzle);
  296. }
  297. break;
  298. }
  299. case FuellingPointStatus.STARTED:
  300. {
  301. if (this.lastLogicalDeviceState != LogicalDeviceState.FDC_STARTED)
  302. {
  303. // simulate a FDC_AUTHORISED event since TQC will not send this state in.
  304. this.lastLogicalDeviceState = LogicalDeviceState.FDC_AUTHORISED;
  305. this.FireOnStateChangeEvent(LogicalDeviceState.FDC_AUTHORISED, stateChangedNozzle);
  306. this.lastLogicalDeviceState = LogicalDeviceState.FDC_STARTED;
  307. this.FireOnStateChangeEvent(LogicalDeviceState.FDC_STARTED, stateChangedNozzle);
  308. }
  309. break;
  310. }
  311. case FuellingPointStatus.FUELLING:
  312. {
  313. if (this.lastLogicalDeviceState != LogicalDeviceState.FDC_FUELLING)
  314. {
  315. this.lastLogicalDeviceState = LogicalDeviceState.FDC_FUELLING;
  316. this.FireOnStateChangeEvent(LogicalDeviceState.FDC_FUELLING, stateChangedNozzle);
  317. }
  318. break;
  319. }
  320. case FuellingPointStatus.Inoperative:
  321. {
  322. if (this.lastLogicalDeviceState != LogicalDeviceState.FDC_OFFLINE)
  323. {
  324. this.lastLogicalDeviceState = LogicalDeviceState.FDC_OFFLINE;
  325. this.FireOnStateChangeEvent(LogicalDeviceState.FDC_OFFLINE, null);
  326. }
  327. break;
  328. }
  329. case FuellingPointStatus.Closed:
  330. {
  331. this.lastLogicalDeviceState = LogicalDeviceState.FDC_CLOSED;
  332. logger.Info("Pump " + this.pumpId + " with ifsf fuelPoint id: 0x" + this.ifsfFuelPointId.ToHexLogString() + " is in Closed state, will open it...");
  333. this.FireOnStateChangeEvent(LogicalDeviceState.FDC_CLOSED, null);
  334. context.Outgoing.WriteAsync(
  335. new FuellingPointDbRequest_Write_OpenFuelPoint(this.recipientSubnet,
  336. this.recipientNode,
  337. PumpGroupHandler.originatorSubnet,
  338. PumpGroupHandler.originatorNode,
  339. this.msgTokenGenerator(), this.ifsfFuelPointId),
  340. (request, response) => (response is IfsfMessage rp) && (request is IfsfMessage rq) && rp.MessageToken == rq.MessageToken
  341. && rp.MessageType == MessageType.IFSF_MESSAGE_TYPE_ACK, (_, response) =>
  342. {
  343. if (response != null)
  344. logger.Debug("Pump " + this.pumpId + ", Open FP 0x" + this.ifsfFuelPointId.ToHexLogString() + " Acked succeed");
  345. else
  346. logger.Info("Pump " + this.pumpId + ", Open FP 0x" + this.ifsfFuelPointId.ToHexLogString() + " timedout for Ack, failed");
  347. }, 8000);
  348. break;
  349. }
  350. }
  351. }
  352. public virtual async Task<bool> AuthorizeAsync(byte logicalNozzleId)
  353. {
  354. //bool authSucceed = false;
  355. //AutoResetEvent blocker = new AutoResetEvent(false);
  356. var authResponse = await this.context.Outgoing.WriteAsync(new FuellingPointDbRequest_Write_AuthorizeFuelPoint(this.recipientSubnet, this.recipientNode,
  357. PumpGroupHandler.originatorSubnet, PumpGroupHandler.originatorNode, this.msgTokenGenerator(), this.ifsfFuelPointId, null),
  358. (request, response) =>
  359. (response is AcknowledgeMessage rp) && (request is IfsfMessage rq)
  360. && rp.MessageToken == rq.MessageToken
  361. && rp.MessageType == MessageType.IFSF_MESSAGE_TYPE_ACK, 6000);
  362. var authSucceed = false;
  363. if (authResponse is AcknowledgeMessage ackMsg)
  364. {
  365. if (ackMsg.OverallStatus == MessageAcknowledgeStatus.ACK_PositiveAcknowledgeDataReceived)
  366. {
  367. //context.Outgoing.Write(new FuellingPointDbRequest_Read_FuelPointState(this.recipientSubnet,
  368. // this.recipientNode,
  369. // PumpGroupHandler.originatorSubnet,
  370. // PumpGroupHandler.originatorNode,
  371. // this.msgTokenGenerator(), this.ifsfFuelPointId));
  372. logger.Debug("Pump " + this.pumpId + ", Auth FP: 0x" + this.ifsfFuelPointId.ToHexLogString() + " ACKed with succeed");
  373. authSucceed = true;
  374. }
  375. else
  376. {
  377. logger.Info("Pump " + this.pumpId + ", Auth FP: 0x" + this.ifsfFuelPointId.ToHexLogString() + " ACKed but failed with internal reason: \r\n" + ackMsg.ToLogString()
  378. + "\r\n it may caused by unpaid trx still stacked in TQC pump side and then refuse to be authorized, here send query payable trx request anyway");
  379. context.Outgoing.Write(
  380. new FuelTrxDb_Read_QueryTransaction(this.recipientSubnet, this.recipientNode, PumpGroupHandler.originatorSubnet, PumpGroupHandler.originatorNode,
  381. this.msgTokenGenerator(), this.ifsfFuelPointId, null));
  382. authSucceed = false;
  383. }
  384. }
  385. else
  386. logger.Info("Pump " + this.pumpId + ", Auth FP: 0x" + this.ifsfFuelPointId.ToHexLogString() + " timed out for ACK");
  387. return authSucceed;
  388. }
  389. public virtual async Task<bool> AuthorizeWithAmountAsync(int moneyAmountWithoutDecimalPoint, byte logicalNozzleId)
  390. {
  391. // temp fake change!!!
  392. return await this.AuthorizeAsync(logicalNozzleId);
  393. }
  394. public virtual async Task<bool> AuthorizeWithVolumeAsync(int volumnWithoutDecimalPoint, byte logicalNozzleId)
  395. {
  396. throw new NotImplementedException();
  397. }
  398. public virtual async Task<bool> ChangeFuelPriceAsync(int newPriceWithoutDecimalPoint, byte logicalNozzleId)
  399. {
  400. var productNo = this.nozzleExtraInfos.FirstOrDefault(c => c.PumpId == this.pumpId && c.NozzleLogicalId == logicalNozzleId)?.ProductBarcode;
  401. if (productNo == null)
  402. {
  403. logger.Error("Pump " + this.pumpId + ", Change Price for productNo: " + productNo + " with new price: " + newPriceWithoutDecimalPoint + " failed due to product not found in config for target pump");
  404. return false;
  405. }
  406. logger.Info("Pump: " + this.pumpId + ", " + "Change Fuel Price for LogicalNozzle: "
  407. + logicalNozzleId + " with newPriceWithoutDecimalPoint: " + newPriceWithoutDecimalPoint);
  408. var priceChangeResponse = await this.context.Outgoing.WriteAsync(new ProductPerFuellingModeDbRequest_Write_SetPrice(this.recipientSubnet, this.recipientNode,
  409. PumpGroupHandler.originatorSubnet, PumpGroupHandler.originatorNode, this.msgTokenGenerator(),
  410. productNo.ToString(),
  411. newPriceWithoutDecimalPoint.ToString(),
  412. 0x11),
  413. (request, response) =>
  414. (response is AcknowledgeMessage rp) && (request is IfsfMessage rq)
  415. && rp.MessageToken == rq.MessageToken
  416. && rp.MessageType == MessageType.IFSF_MESSAGE_TYPE_ACK,
  417. 8000);
  418. bool changePriceSucceed = false;
  419. if (priceChangeResponse is AcknowledgeMessage ackMsg
  420. && ackMsg.OverallStatus == MessageAcknowledgeStatus.ACK_PositiveAcknowledgeDataReceived)
  421. {
  422. logger.Info("Pump " + this.pumpId + ", Change Price for productNo: " + productNo + " with new price: " + newPriceWithoutDecimalPoint + " ACKed with Positive but still querying the price again for double confirm...");
  423. var doubleConfirmQueryPriceResponse = await this.context.Outgoing.WriteAsync(
  424. new ProductPerFuellingModeDbRequest_Read_ProductPrice(this.recipientSubnet, this.recipientNode,
  425. PumpGroupHandler.originatorSubnet, PumpGroupHandler.originatorNode, this.msgTokenGenerator(),
  426. productNo.ToString(), 0x11),
  427. (readPriceRequest, readPriceResponse) =>
  428. (readPriceResponse is ProductPerFuellingModeDb_ProductPrice_Answer rp)
  429. && (readPriceRequest is IfsfMessage rq)
  430. && rp.MessageToken == rq.MessageToken
  431. && rp.MessageType == MessageType.IFSF_MESSAGE_TYPE_ANSWER
  432. && rp.FuelModeId == 0x11,
  433. 5000) as ProductPerFuellingModeDb_ProductPrice_Answer;
  434. if (doubleConfirmQueryPriceResponse != null)
  435. {
  436. logger.Info("Pump " + this.pumpId + ", doubleConfirmQueryPrice, Price for productNo: " + productNo
  437. + " queried with price(without decimal points): " + doubleConfirmQueryPriceResponse.Price);
  438. int queriedPumpSidePrice;
  439. if (!int.TryParse(doubleConfirmQueryPriceResponse.Price, out queriedPumpSidePrice))
  440. {
  441. logger.Info("Pump " + this.pumpId + ", Change Price for productNo: " + productNo
  442. + " with new price(without decimal points): "
  443. + newPriceWithoutDecimalPoint + " failed due to double confirm price response price value is un-recognize: " + (doubleConfirmQueryPriceResponse.Price ?? ""));
  444. changePriceSucceed = false;
  445. }
  446. else
  447. {
  448. if (queriedPumpSidePrice != newPriceWithoutDecimalPoint)
  449. {
  450. logger.Info("Pump " + this.pumpId + ", doubleConfirmQueryPrice, Price for productNo: " + productNo
  451. + " queried with price(without decimal points): " + doubleConfirmQueryPriceResponse.Price
  452. + " does not match expected new price: " + newPriceWithoutDecimalPoint);
  453. changePriceSucceed = false;
  454. }
  455. else
  456. {
  457. logger.Info("Pump " + this.pumpId + ", doubleConfirmQueryPrice, Price for productNo: " + productNo
  458. + " has been double confirmed and it's aligned with TQC side, change price succeed.");
  459. changePriceSucceed = true;
  460. this.nozzles.First(n => n.LogicalId == logicalNozzleId).RealPriceOnPhysicalPump = newPriceWithoutDecimalPoint;
  461. this.initor.PriceBook[productNo.Value] = newPriceWithoutDecimalPoint;
  462. logger.Info("Pump " + this.pumpId + ", PriceBook updated to: \r\n"
  463. + this.initor.PriceBook.Keys.Select(s => "productNo: " + s + ", price: " + this.initor.PriceBook[s])
  464. .Aggregate((acc, n) => acc + "\r\n" + n));
  465. }
  466. }
  467. }
  468. else
  469. {
  470. logger.Info("Pump " + this.pumpId + ", doubleConfirmQueryPrice timedout, but still treat this Price change as succeed since Acked with Positive");
  471. changePriceSucceed = true;
  472. this.nozzles.First(n => n.LogicalId == logicalNozzleId).RealPriceOnPhysicalPump = newPriceWithoutDecimalPoint;
  473. this.initor.PriceBook[productNo.Value] = newPriceWithoutDecimalPoint;
  474. logger.Info("Pump " + this.pumpId + ", PriceBook updated to: \r\n"
  475. + this.initor.PriceBook.Keys.Select(s => "productNo: " + s + ", price: " + this.initor.PriceBook[s])
  476. .Aggregate((acc, n) => acc + "\r\n" + n));
  477. }
  478. }
  479. else
  480. {
  481. logger.Info("Pump " + this.pumpId + ", Change Price for productNo: " + productNo + " with new price(without decimal points): "
  482. + newPriceWithoutDecimalPoint + " ACK timed out or ACKed with non-positive, price change failed!");
  483. changePriceSucceed = false;
  484. }
  485. return changePriceSucceed;
  486. }
  487. public virtual async Task<bool> FuelingRoundUpByAmountAsync(int amount)
  488. {
  489. // temp fake change!!!
  490. return await Task.FromResult(true);
  491. }
  492. public virtual async Task<bool> FuelingRoundUpByVolumeAsync(int volume)
  493. {
  494. // temp fake change!!!
  495. return await Task.FromResult(true);
  496. }
  497. public virtual async Task<LogicalDeviceState> QueryStatusAsync()
  498. {
  499. if (!this.initor.IsInitDone) return LogicalDeviceState.FDC_CLOSED;
  500. if (this.lastLogicalDeviceState == LogicalDeviceState.FDC_CLOSED)
  501. {
  502. logger.Debug("Pump " + this.pumpId + ", QueryStatus(), FP: 0x" + this.ifsfFuelPointId.ToHexLogString() + " still in Closed state, will send a real status query to TQC");
  503. this.context.Outgoing.Write(
  504. new FuellingPointDbRequest_Read_FuelPointState(this.recipientSubnet,
  505. this.recipientNode,
  506. PumpGroupHandler.originatorSubnet, PumpGroupHandler.originatorNode, this.msgTokenGenerator(),
  507. this.ifsfFuelPointId));
  508. }
  509. return this.lastLogicalDeviceState;
  510. }
  511. /// <summary>
  512. /// no decimal point value.
  513. /// </summary>
  514. /// <returns>MoneyTotalizer:VolumnTotalizer</returns>
  515. public virtual async Task<System.Tuple<int, int>> QueryTotalizerAsync(byte logicalNozzleId)
  516. {
  517. System.Tuple<int, int> result = new System.Tuple<int, int>(-1, -1);
  518. if (!this.initor.IsInitDone)
  519. return result;
  520. var tqcLogicalNozzleId = this.nozzles.First(n => n.LogicalId == logicalNozzleId).PhysicalId;
  521. var queryResponse = await this.context.Outgoing.WriteAsync(
  522. new LogicalNozzleDb_Read_QueryTotalizer(this.recipientSubnet, this.recipientNode,
  523. PumpGroupHandler.originatorSubnet, PumpGroupHandler.originatorNode, this.msgTokenGenerator(), this.ifsfFuelPointId, tqcLogicalNozzleId)
  524. , (request, response) =>
  525. (response is LogicalNozzleDb_NozzleTotalizer_Answer rp) && (request is IfsfMessage rq)
  526. && rp.MessageToken == rq.MessageToken
  527. && rp.MessageType == MessageType.IFSF_MESSAGE_TYPE_ANSWER, 8000);
  528. if (queryResponse != null && queryResponse is LogicalNozzleDb_NozzleTotalizer_Answer ___)
  529. {
  530. result = new System.Tuple<int, int>(Convert.ToInt32(___.MoneyTotal * Math.Pow(10, this.AmountDecimalDigits)), Convert.ToInt32(___.VolumeTotal * Math.Pow(10, this.VolumeDecimalDigits)));
  531. logger.Debug("Pump " + this.pumpId + ", QueryTotalizer(), FP: 0x" + this.ifsfFuelPointId.ToHexLogString()
  532. + ", FC logicalNozzleId: " + logicalNozzleId + ", Tqc ifsf logicalNozzleId: 0x" + tqcLogicalNozzleId.ToHexLogString()
  533. + " succeed, no decimal point money and vol acc: " + result.Item1 + " - " + result.Item2);
  534. }
  535. else
  536. {
  537. }
  538. return result;
  539. }
  540. public virtual async Task<bool> ResumeFuellingAsync()
  541. {
  542. throw new NotImplementedException();
  543. }
  544. public virtual async Task<bool> SuspendFuellingAsync()
  545. {
  546. throw new NotImplementedException();
  547. }
  548. public virtual async Task<bool> UnAuthorizeAsync(byte logicalNozzleId)
  549. {
  550. // temp fake change!!!
  551. return await Task.FromResult(true);
  552. //throw new NotImplementedException();
  553. }
  554. public async Task<bool> LockNozzleAsync(byte logicalNozzleId)
  555. {
  556. return false;
  557. }
  558. public async Task<bool> UnlockNozzleAsync(byte logicalNozzleId)
  559. {
  560. return false;
  561. }
  562. #region IDisposable Support
  563. private bool disposedValue = false; // To detect redundant calls
  564. protected virtual void Dispose(bool disposing)
  565. {
  566. if (!disposedValue)
  567. {
  568. if (disposing)
  569. {
  570. // TODO: dispose managed state (managed objects).
  571. }
  572. // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
  573. // TODO: set large fields to null.
  574. disposedValue = true;
  575. }
  576. }
  577. // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
  578. // ~PumpHandler() {
  579. // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  580. // Dispose(false);
  581. // }
  582. // This code added to correctly implement the disposable pattern.
  583. public void Dispose()
  584. {
  585. // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  586. Dispose(true);
  587. // TODO: uncomment the following line if the finalizer is overridden above.
  588. // GC.SuppressFinalize(this);
  589. }
  590. public void OnFdcServerInit(Dictionary<string, object> parameters)
  591. {
  592. if (parameters != null && parameters.TryGetValue("NozzleProductMapping", out object param))
  593. {
  594. this.nozzleExtraInfos = param as IEnumerable<NozzleExtraInfo>;
  595. }
  596. }
  597. #endregion
  598. }
  599. }