HengshanPayTermHandler.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. using HengshanPaymentTerminal.MessageEntity.Incoming;
  2. using HengshanPaymentTerminal.MessageEntity;
  3. using HengshanPaymentTerminal.Support;
  4. using HengshanPaymentTerminal;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using Edge.Core.Processor.Dispatcher.Attributes;
  13. using Edge.Core.IndustryStandardInterface.Pump;
  14. using Edge.Core.IndustryStandardInterface.Pump.Fdc;
  15. using Edge.Core.Processor;
  16. using Edge.Core.Core.database;
  17. using Edge.Core.Domain.FccStationInfo.Output;
  18. using Edge.Core.Domain.FccNozzleInfo;
  19. using Edge.Core.Domain.FccNozzleInfo.Output;
  20. using System.Net.Sockets;
  21. using Edge.Core.Domain.FccOrderInfo;
  22. using Microsoft.EntityFrameworkCore;
  23. using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities;
  24. using static Microsoft.AspNetCore.Hosting.Internal.HostingApplication;
  25. using HengshanPaymentTerminal.Mqtt.Request;
  26. namespace HengshanPaymentTerminal
  27. {
  28. /// <summary>
  29. /// Handler that communicates directly with the Hengshan Payment Terminal for card handling and pump handling via serial port.
  30. /// </summary>
  31. [MetaPartsDescriptor(
  32. "lang-zh-cn:恒山IC卡终端(UI板) App lang-en-us:Hengshan IC card terminal (UI Board)",
  33. "lang-zh-cn:用于与UI板通讯控制加油机" +
  34. "lang-en-us:Used for terminal communication to control pumps",
  35. new[]
  36. {
  37. "lang-zh-cn:恒山IC卡终端lang-en-us:HengshanICTerminal"
  38. })]
  39. public class HengshanPayTermHandler : IEnumerable<IFdcPumpController>, IDeviceHandler<byte[], CommonMessage>
  40. {
  41. #region Fields
  42. private string pumpIds;
  43. private string pumpSubAddresses;
  44. private string pumpNozzles;
  45. private string pumpSiteNozzleNos;
  46. private string nozzleLogicIds;
  47. private IContext<byte[], CommonMessage> _context;
  48. private List<HengshanPumpHandler> pumpHandlers = new List<HengshanPumpHandler>();
  49. public Queue<CardMessageBase> queue = new Queue<CardMessageBase>();
  50. public Queue<CommonMessage> commonQueue = new Queue<CommonMessage>();
  51. private object syncObj = new object();
  52. private ConcurrentDictionary<int, PumpStateHolder> statusDict = new ConcurrentDictionary<int, PumpStateHolder>();
  53. public ConcurrentDictionary<int, PumpStateHolder> PumpStatusDict => statusDict;
  54. private Dictionary<int, int> pumpIdSubAddressDict;
  55. public Dictionary<int, List<int>> PumpNozzlesDict { get; private set; }
  56. public Dictionary<int, int> NozzleLogicIdDict { get; private set; }
  57. public Dictionary<int, List<int>> PumpSiteNozzleNoDict { get; private set; }
  58. public MysqlDbContext MysqlDbContext { get; private set; }
  59. public StationInfo stationInfo { get; set; }
  60. public List<DetailsNozzleInfoOutput> nozzleInfoList { get; private set; }
  61. public TcpClient? client { get; set; }
  62. private readonly ConcurrentDictionary<string,TaskCompletionSource<CommonMessage>> _tcsDictionary = new ConcurrentDictionary<string, TaskCompletionSource<CommonMessage>>();
  63. private byte frame = 0x00;
  64. private object lockFrame = new object();
  65. #endregion
  66. #region Logger
  67. private static NLog.Logger logger = NLog.LogManager.LoadConfiguration("NLog.config").GetLogger("IPosPlusApp");
  68. #endregion
  69. #region Constructor
  70. //private static List<object> ResolveCtorMetaPartsConfigCompatibility(string incompatibleCtorParamsJsonStr)
  71. //{
  72. // var jsonParams = JsonDocument.Parse(incompatibleCtorParamsJsonStr).RootElement.EnumerateArray().ToArray();
  73. // //sample: "UITemplateVersion":"1.0"
  74. // string uiTemplateVersionRegex = @"(?<=""UITemplateVersion""\:\"").+?(?="")";
  75. // var match = Regex.Match(jsonParams.First().GetRawText(), uiTemplateVersionRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline);
  76. // if (match.Success)
  77. // {
  78. // var curVersion = match.Value;
  79. // if (curVersion == "1.0")
  80. // {
  81. // var existsAppConfigV1 = JsonSerializer.Deserialize(jsonParams.First().GetRawText(), typeof(HengshanPayTerminalHanlderGroupConfigV1));
  82. // }
  83. // else
  84. // {
  85. // }
  86. // }
  87. // return null;
  88. //}
  89. [ParamsJsonSchemas("TermHandlerGroupCtorParamsJsonSchemas")]
  90. public HengshanPayTermHandler(HengshanPayTerminalHanlderGroupConfigV2 config)
  91. : this(config.PumpIds,
  92. string.Join(";", config.PumpSubAddresses.Select(m => $"{m.PumpId}={m.SubAddress}")),
  93. string.Join(";", config.PumpNozzleLogicIds.Select(m => $"{m.PumpId}={m.LogicIds}")),
  94. string.Join(";", config.PumpSiteNozzleNos.Select(m => $"{m.PumpId}={m.SiteNozzleNos}")),
  95. string.Join(";", config.NozzleLogicIds.Select(m => $"{m.NozzleNo}={m.LogicId}")))
  96. {
  97. }
  98. public HengshanPayTermHandler(
  99. string pumpIds,
  100. string pumpSubAddresses,
  101. string pumpNozzles,
  102. string pumpSiteNozzleNos,
  103. string nozzleLogicIds)
  104. {
  105. this.pumpIds = pumpIds;
  106. this.pumpSubAddresses = pumpSubAddresses;
  107. this.pumpNozzles = pumpNozzles;
  108. this.pumpSiteNozzleNos = pumpSiteNozzleNos;
  109. this.nozzleLogicIds = nozzleLogicIds;
  110. this.MysqlDbContext = new MysqlDbContext();
  111. GetInfo();
  112. AssociatedPumpIds = GetPumpIdList(pumpIds);
  113. pumpIdSubAddressDict = InitializePumpSubAddressMapping();
  114. PumpNozzlesDict = ParsePumpNozzlesList(pumpNozzles);
  115. PumpSiteNozzleNoDict = ParsePumpSiteNozzleNoList(pumpSiteNozzleNos);
  116. NozzleLogicIdDict = InitializeNozzleLogicIdMapping(nozzleLogicIds);
  117. InitializePumpHandlers();
  118. }
  119. #endregion
  120. public void OnFdcServerInit(Dictionary<string, object> parameters)
  121. {
  122. logger.Info("OnFdcServerInit called");
  123. if (parameters.ContainsKey("LastPriceChange"))
  124. {
  125. // nozzle logical id:rawPrice
  126. var lastPriceChanges = parameters["LastPriceChange"] as Dictionary<byte, int>;
  127. foreach (var priceChange in lastPriceChanges)
  128. {
  129. }
  130. }
  131. }
  132. #region Event handler
  133. public event EventHandler<TerminalMessageEventArgs> OnTerminalMessageReceived;
  134. public event EventHandler<TotalizerDataEventArgs> OnTotalizerReceived;
  135. public event EventHandler<FuelPriceChangeRequestEventArgs> OnFuelPriceChangeRequested;
  136. public event EventHandler<FuelPriceDownloadRequestedEventArgs> OnTerminalFuelPriceDownloadRequested;
  137. public event EventHandler<CheckCommandEventArgs> OnCheckCommandReceived;
  138. public event EventHandler<LockUnlockEventArgs> OnLockUnlockCompleted;
  139. #endregion
  140. #region Properties
  141. public List<int> AssociatedPumpIds { get; private set; }
  142. public IContext<byte[], CommonMessage> Context
  143. {
  144. get { return _context; }
  145. }
  146. public string PumpIdList => pumpIds;
  147. //public LockUnlockOperation LockUnlockOperationType { get; set; } = LockUnlockOperation.Undefined;
  148. #endregion
  149. #region Methods
  150. public int GetSubAddressForPump(int pumpId)
  151. {
  152. return pumpIdSubAddressDict.First(d => d.Key == pumpId).Value;
  153. }
  154. private List<int> GetPumpIdList(string pumpIds)
  155. {
  156. var pumpIdList = new List<int>();
  157. if (!string.IsNullOrEmpty(pumpIds) && pumpIds.Contains(',')) //multiple pumps per serial port, Hengshan TQC pump
  158. {
  159. var arr = pumpIds.Split(',');
  160. foreach (var item in arr)
  161. {
  162. pumpIdList.Add(int.Parse(item));
  163. }
  164. return pumpIdList;
  165. }
  166. else if (!string.IsNullOrEmpty(pumpIds) && pumpIds.Length == 1 || pumpIds.Length == 2) //only 1 pump per serial port, Hengshan pump
  167. {
  168. return new List<int> { int.Parse(pumpIds) };
  169. }
  170. else
  171. {
  172. throw new ArgumentException("Pump id list not specified!");
  173. }
  174. }
  175. private Dictionary<int, int> InitializePumpSubAddressMapping()
  176. {
  177. var dict = new Dictionary<int, int>();
  178. if (!string.IsNullOrEmpty(pumpSubAddresses))
  179. {
  180. var sequence = pumpSubAddresses.Split(';')
  181. .Select(s => s.Split('='))
  182. .Select(a => new { PumpId = int.Parse(a[0]), SubAddress = int.Parse(a[1]) });
  183. foreach (var pair in sequence)
  184. {
  185. if (!dict.ContainsKey(pair.PumpId))
  186. {
  187. dict.Add(pair.PumpId, pair.SubAddress);
  188. }
  189. }
  190. return dict;
  191. }
  192. else
  193. {
  194. throw new ArgumentException("Pump id and sub address mapping does not exist");
  195. }
  196. }
  197. private Dictionary<int, List<int>> ParsePumpNozzlesList(string pumpNozzles)
  198. {
  199. Dictionary<int, List<int>> pumpNozzlesDict = new Dictionary<int, List<int>>();
  200. if (!string.IsNullOrEmpty(pumpNozzles) && pumpNozzles.Contains(';'))
  201. {
  202. var arr = pumpNozzles.Split(';');
  203. foreach (var subMapping in arr)
  204. {
  205. var pair = new KeyValuePair<int, int>(int.Parse(subMapping.Split('=')[0]), int.Parse(subMapping.Split('=')[1]));
  206. Console.WriteLine($"{pair.Key}, {pair.Value}");
  207. if (!pumpNozzlesDict.ContainsKey(pair.Key))
  208. {
  209. pumpNozzlesDict.Add(pair.Key, new List<int> { pair.Value });
  210. }
  211. else
  212. {
  213. List<int> nozzlesForThisPump;
  214. pumpNozzlesDict.TryGetValue(pair.Key, out nozzlesForThisPump);
  215. if (nozzlesForThisPump != null && !nozzlesForThisPump.Contains(pair.Value))
  216. {
  217. nozzlesForThisPump.Add(pair.Value);
  218. }
  219. }
  220. }
  221. }
  222. else if (!string.IsNullOrEmpty(pumpNozzles) && pumpNozzles.Count(c => c == '=') == 1) // only one pump per serial port
  223. {
  224. try
  225. {
  226. pumpNozzlesDict.Add(
  227. int.Parse(pumpNozzles.Split('=')[0]),
  228. new List<int> { int.Parse(pumpNozzles.Split('=')[1]) });
  229. }
  230. catch (Exception ex)
  231. {
  232. Console.WriteLine(ex);
  233. }
  234. }
  235. else
  236. {
  237. throw new ArgumentException("Wrong mapping between pump and its associated nozzles!");
  238. }
  239. return pumpNozzlesDict;
  240. }
  241. static Dictionary<int, List<int>> ParsePumpSiteNozzleNoList(string pumpSiteNozzleNos)
  242. {
  243. Dictionary<int, List<int>> pumpSiteNozzleNoDict = new Dictionary<int, List<int>>();
  244. if (!string.IsNullOrEmpty(pumpSiteNozzleNos) && pumpSiteNozzleNos.Contains(';'))
  245. {
  246. var arr = pumpSiteNozzleNos.Split(';');
  247. foreach (var subMapping in arr)
  248. {
  249. var pair = new KeyValuePair<int, List<int>>(
  250. int.Parse(subMapping.Split('=')[0]), subMapping.Split('=')[1].Split(',').Select(a => int.Parse(a)).ToList());
  251. Console.WriteLine($"{pair.Key}, {pair.Value}");
  252. if (!pumpSiteNozzleNoDict.ContainsKey(pair.Key))
  253. {
  254. pumpSiteNozzleNoDict.Add(pair.Key, pair.Value);
  255. }
  256. }
  257. }
  258. else if (!string.IsNullOrEmpty(pumpSiteNozzleNos) && pumpSiteNozzleNos.Count(c => c == '=') == 1)
  259. {
  260. try
  261. {
  262. string[] strArr = pumpSiteNozzleNos.Split('=');
  263. pumpSiteNozzleNoDict.Add(
  264. int.Parse(strArr[0]), new List<int> { int.Parse(strArr[1]) });
  265. }
  266. catch (Exception ex)
  267. {
  268. Console.WriteLine(ex);
  269. }
  270. }
  271. else
  272. {
  273. throw new ArgumentException("Wrong mapping between pump and its associated nozzles!");
  274. }
  275. return pumpSiteNozzleNoDict;
  276. }
  277. private Dictionary<int, int> InitializeNozzleLogicIdMapping(string nozzleLogicIds)
  278. {
  279. var dict = new Dictionary<int, int>();
  280. if (!string.IsNullOrEmpty(nozzleLogicIds))
  281. {
  282. var sequence = nozzleLogicIds.Split(';')
  283. .Select(s => s.Split('='))
  284. .Select(a => new { NozzleNo = int.Parse(a[0]), LogicId = int.Parse(a[1]) });
  285. foreach (var pair in sequence)
  286. {
  287. if (!dict.ContainsKey(pair.NozzleNo))
  288. {
  289. Console.WriteLine($"nozzle, logic id: {pair.NozzleNo} - {pair.LogicId}");
  290. dict.Add(pair.NozzleNo, pair.LogicId);
  291. }
  292. }
  293. return dict;
  294. }
  295. else if (!string.IsNullOrEmpty(nozzleLogicIds) && nozzleLogicIds.Count(c => c == '=') == 1)
  296. {
  297. try
  298. {
  299. string[] sequence = nozzleLogicIds.Split('=');
  300. dict.Add(int.Parse(sequence[0]), int.Parse(sequence[1]));
  301. }
  302. catch (Exception ex)
  303. {
  304. Console.WriteLine(ex);
  305. }
  306. return dict;
  307. }
  308. else
  309. {
  310. throw new ArgumentException("Pump id and sub address mapping does not exist");
  311. }
  312. }
  313. private void InitializePumpHandlers()
  314. {
  315. var pumpIdList = GetPumpIdList(pumpIds);
  316. foreach (var item in pumpIdList)
  317. {
  318. var nozzleList = GetNozzleListForPump(item);
  319. var siteNozzleNoList = PumpSiteNozzleNoDict[item];
  320. HengshanPumpHandler pumpHandler = new HengshanPumpHandler(this, $"Pump_{item}", item, nozzleList, siteNozzleNoList);
  321. pumpHandler.OnFuelPriceChangeRequested += PumpHandler_OnFuelPriceChangeRequested;
  322. pumpHandlers.Add(pumpHandler);
  323. }
  324. }
  325. private List<int> GetNozzleListForPump(int pumpId)
  326. {
  327. List<int> nozzles;
  328. PumpNozzlesDict.TryGetValue(pumpId, out nozzles);
  329. return nozzles;
  330. }
  331. private void PumpHandler_OnFuelPriceChangeRequested(object sender, FuelPriceChangeRequestEventArgs e)
  332. {
  333. InfoLog($"Change price, Pump {e.PumpId}, Nozzle {e.NozzleId}, Price {e.Price}");
  334. OnFuelPriceChangeRequested?.Invoke(sender, e);
  335. }
  336. IEnumerator<IFdcPumpController> IEnumerable<IFdcPumpController>.GetEnumerator()
  337. {
  338. return pumpHandlers.GetEnumerator();
  339. }
  340. #endregion
  341. #region IHandler implementation
  342. public void Init(IContext<byte[], CommonMessage> context)
  343. {
  344. CommIdentity = context.Processor.Communicator.Identity;
  345. _context = context;
  346. }
  347. public string CommIdentity { get; private set; }
  348. public async Task Process(IContext<byte[], CommonMessage> context)
  349. {
  350. switch(context.Incoming.Message.Handle)
  351. {
  352. //订单
  353. case 0x18:
  354. {
  355. //添加或修改数据库订单
  356. OrderFromMachine orderFromMachine = (OrderFromMachine)context.Incoming.Message;
  357. int row = UpLoadOrder(orderFromMachine);
  358. logger.Info($"receive order from machine,database had ${row} count change");
  359. break;
  360. }
  361. //普通应答
  362. case 0x55:
  363. {
  364. CommonAnswerBack commonAnswerBack = (CommonAnswerBack)context.Incoming.Message;
  365. if (commonAnswerBack.Command == 0x63) //二维码回复
  366. {
  367. byte[] keyBytes = { commonAnswerBack.Command, (byte)commonAnswerBack.NozzleNum };
  368. var key = BitConverter.ToString(keyBytes).Replace("-", "");
  369. if (_tcsDictionary.TryGetValue(key, out var value))
  370. {
  371. value.SetResult(commonAnswerBack);
  372. }
  373. else
  374. {
  375. logger.Info($"qrcode response:can not get tcs for dictionary");
  376. }
  377. }
  378. break;
  379. }
  380. // 授权回复
  381. case 0x65:
  382. {
  383. AuthorizationResponse authorizationResponse = (AuthorizationResponse)context.Incoming.Message;
  384. byte[] keyBytes = { authorizationResponse.Handle, (byte)authorizationResponse.NozzleNum };
  385. var key = BitConverter.ToString(keyBytes).Replace("-", "");
  386. if (_tcsDictionary.TryGetValue(key, out var value))
  387. {
  388. value.SetResult(authorizationResponse);
  389. }
  390. else
  391. {
  392. logger.Info($"authorization response:can not get tcs for dictionary");
  393. }
  394. break;
  395. }
  396. // 取消授权回复
  397. case 0x66:
  398. {
  399. UnAhorizationResponse unauthorizationResponse = (UnAhorizationResponse)context.Incoming.Message;
  400. byte[] keyBytes = { unauthorizationResponse.Handle, (byte)unauthorizationResponse.NozzleNum };
  401. var key = BitConverter.ToString(keyBytes).Replace("-", "");
  402. if (_tcsDictionary.TryGetValue(key, out var value))
  403. {
  404. value.SetResult(unauthorizationResponse);
  405. }
  406. else
  407. {
  408. logger.Info($"unauthorization response:can not get tcs for dictionary");
  409. }
  410. break;
  411. }
  412. }
  413. context.Outgoing.Write(context.Incoming.Message);
  414. }
  415. private void CheckStatus(CheckCmdRequest request)
  416. {
  417. if (!statusDict.ContainsKey(request.FuelingPoint.PumpNo))
  418. {
  419. var result = statusDict.TryAdd(request.FuelingPoint.PumpNo,
  420. new PumpStateHolder
  421. {
  422. PumpNo = request.FuelingPoint.PumpNo,
  423. NozzleNo = 1,
  424. State = request,
  425. OperationType = LockUnlockOperation.None
  426. });
  427. logger.Info($"Adding FuelingPoint {request.FuelingPoint.PumpNo} to dict");
  428. if (!result)
  429. {
  430. statusDict.TryAdd(request.FuelingPoint.PumpNo, null);
  431. }
  432. }
  433. else
  434. {
  435. PumpStateHolder stateHolder = null;
  436. statusDict.TryGetValue(request.FuelingPoint.PumpNo, out stateHolder);
  437. if (stateHolder != null)
  438. {
  439. logger.Debug($"State holder, PumpNo: {stateHolder.PumpNo}, dispenser state: {stateHolder.State.DispenserState}, " +
  440. $"operation: {stateHolder.OperationType}");
  441. }
  442. if (stateHolder != null && stateHolder.OperationType != LockUnlockOperation.None)
  443. {
  444. logger.Debug($"PumpNo: {request.FuelingPoint.PumpNo}, Last Dispenser State: {stateHolder.State.DispenserState}, " +
  445. $"Current Dispenser State: {request.DispenserState}");
  446. if (stateHolder.State.DispenserState == 3 && request.DispenserState == 2)
  447. {
  448. //Pump is locked due to lock operation
  449. if (stateHolder.OperationType != LockUnlockOperation.None)
  450. {
  451. logger.Info("Locking done!");
  452. stateHolder.State = request; //Update the state
  453. OnLockUnlockCompleted?.Invoke(this, new LockUnlockEventArgs(stateHolder.OperationType, true));
  454. }
  455. }
  456. else if (stateHolder.State.DispenserState == 2 && request.DispenserState == 3)
  457. {
  458. //Pump is unlocked due to unlock operation
  459. if (stateHolder.OperationType != LockUnlockOperation.None)
  460. {
  461. logger.Info($"Unlocking done!");
  462. stateHolder.State = request; //Update the state
  463. OnLockUnlockCompleted?.Invoke(this, new LockUnlockEventArgs(stateHolder.OperationType, true));
  464. }
  465. }
  466. }
  467. else if (stateHolder != null && stateHolder.OperationType == LockUnlockOperation.None)
  468. {
  469. if (stateHolder.State.DispenserState != request.DispenserState)
  470. {
  471. logger.Warn($"Observed a pump state change, {stateHolder.State.DispenserState} -> {request.DispenserState}");
  472. stateHolder.State = request; //Update the state.
  473. }
  474. }
  475. }
  476. }
  477. public void Write(CommonMessage cardMessage)
  478. {
  479. _context.Outgoing.Write(cardMessage);
  480. }
  481. public async Task<CommonMessage> WriteAsync(CommonMessage request, Func<CommonMessage, CommonMessage, bool> responseCapture,
  482. int timeout)
  483. {
  484. var resp = await _context.Outgoing.WriteAsync(request, responseCapture, timeout);
  485. return resp;
  486. }
  487. #endregion
  488. #region IEnumerable<IFdcPumpController> implementation
  489. public IEnumerator<IFdcPumpController> GetEnumerator()
  490. {
  491. return pumpHandlers.GetEnumerator();
  492. }
  493. IEnumerator IEnumerable.GetEnumerator()
  494. {
  495. return pumpHandlers.GetEnumerator();
  496. }
  497. #endregion
  498. public void PendMessage(CardMessageBase message)
  499. {
  500. lock (syncObj)
  501. {
  502. queue.Enqueue(message);
  503. }
  504. }
  505. public bool TrySendNextMessage()
  506. {
  507. lock (syncObj)
  508. {
  509. if (queue.Count > 0)
  510. {
  511. DebugLog($"queue count: {queue.Count}");
  512. var message = commonQueue.Dequeue();
  513. Write(message);
  514. return true;
  515. }
  516. }
  517. return false;
  518. }
  519. public void StoreLatestFrameSqNo(int pumpId, byte frameSqNo)
  520. {
  521. var pump = GetPump(pumpId);
  522. if (pump != null)
  523. {
  524. pump.FrameSqNo = frameSqNo;
  525. }
  526. }
  527. public void UpdatePumpState(int pumpId, int logicId, LogicalDeviceState state)
  528. {
  529. var currentPump = GetPump(pumpId);
  530. currentPump?.FirePumpStateChange(state, Convert.ToByte(logicId));
  531. }
  532. public void UpdateFuelingStatus(int pumpId, FdcTransaction fuelingTransaction)
  533. {
  534. var currentPump = GetPump(pumpId);
  535. currentPump?.FireFuelingStatusChange(fuelingTransaction);
  536. }
  537. private HengshanPumpHandler GetPump(int pumpId)
  538. {
  539. return pumpHandlers.FirstOrDefault(p => p.PumpId == pumpId);
  540. }
  541. public void SetRealPrice(int pumpId, int price)
  542. {
  543. var currentPump = GetPump(pumpId);
  544. var nozzle = currentPump?.Nozzles.FirstOrDefault();
  545. if (nozzle != null)
  546. nozzle.RealPriceOnPhysicalPump = price;
  547. }
  548. #region Log methods
  549. private void InfoLog(string info)
  550. {
  551. logger.Info("PayTermHdlr " + info);
  552. }
  553. private void DebugLog(string debugMsg)
  554. {
  555. logger.Debug("PayTermHdlr " + debugMsg);
  556. }
  557. #endregion
  558. #region 二维码加油机相关方法
  559. /// <summary>
  560. /// 获取站点信息
  561. /// </summary>
  562. private void GetInfo()
  563. {
  564. Edge.Core.Domain.FccStationInfo.FccStationInfo? fccStationInfo = MysqlDbContext.FccStationInfos.FirstOrDefault();
  565. if(fccStationInfo != null) stationInfo = new StationInfo(fccStationInfo);
  566. nozzleInfoList = MysqlDbContext.NozzleInfos.ToList().Select(n => new DetailsNozzleInfoOutput(n)).ToList();
  567. }
  568. /// <summary>
  569. /// 发送二维码信息给油机
  570. /// </summary>
  571. /// <param name="tcpClient"></param>
  572. public async void SendQRCodeAsync()
  573. {
  574. string? smallProgram = stationInfo?.SmallProgram;
  575. if (smallProgram == null)
  576. {
  577. logger.Info($"can not get smallProgram link");
  578. return;
  579. }
  580. System.Net.EndPoint? remoteEndPoint = this.client?.Client.RemoteEndPoint;
  581. if (remoteEndPoint == null)
  582. {
  583. logger.Info($"can not get client");
  584. return;
  585. }
  586. string[] remoteAddr = remoteEndPoint.ToString().Split(":");
  587. string ip = remoteAddr[0];
  588. List<DetailsNozzleInfoOutput> nozzles = nozzleInfoList.FindAll(nozzle => nozzle.Ip == ip);
  589. foreach (var item in nozzles)
  590. {
  591. List<Byte> list = new List<Byte>();
  592. byte[] commandAndNozzle = { 0x63, (byte)item.NozzleNum };
  593. string qrCode = smallProgram + "/" + item.NozzleNum;
  594. byte[] qrCodeBytes = Encoding.ASCII.GetBytes(qrCode);
  595. list.AddRange(commandAndNozzle);
  596. list.Add((byte)qrCodeBytes.Length);
  597. list.AddRange(qrCodeBytes);
  598. byte[] sendBytes = content2data(list.ToArray(),null);
  599. await SendRequestToMachine("发送二维码", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendBytes);
  600. }
  601. }
  602. /// <summary>
  603. /// 发送实付金额给油机
  604. /// </summary>
  605. /// <param name="orderInfo"></param>
  606. public async void SendActuallyPaid(FccOrderInfo orderInfo)
  607. {
  608. List<Byte> list = new List<Byte>();
  609. byte[] commandAndNozzle = { 0x19, (byte)orderInfo.NozzleNum };
  610. byte[] ttcBytes = NumberToByteArrayWithPadding(orderInfo.Ttc, 4);
  611. byte[] amountPayableBytes = FormatDecimal(orderInfo.AmountPayable);
  612. list.AddRange(commandAndNozzle); //添加命令字和枪号
  613. list.AddRange(ttcBytes); //添加流水号
  614. list.Add(0x21); //由fcc推送实付金额表示该订单是二维码小程序支付的
  615. list.AddRange(amountPayableBytes); //添加实付金额
  616. //添加3位交易金额1,3位交易金额2,2位优惠规则代码,10位卡应用号,4位消息鉴别码
  617. list.AddRange(new byte[] { 0x00,0x00,0x00, 0x00,0x00,0x00, 0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00 });
  618. byte[] sendBytes = content2data(list.ToArray(), null);
  619. await SendRequestToMachine("发送实付金额", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendBytes);
  620. }
  621. public async Task<CommonMessage> SendAuthorization(MqttAuthorizationRequest request)
  622. {
  623. List<Byte> list = new List<Byte>();
  624. byte[] commandAndNozzle = { 0x65, (byte)request.NozzleNum };
  625. byte[] authorizationTimeBytes = ConvertDateTimeToByteArray(request.AuthorizationTime);
  626. //将小数点后移两位,因为油机只支持两位小数点,这边传过去的3位字节转为int后取后两位为十分位和百分位
  627. int value = (int)request.Value * 100;
  628. byte[] valueBytes = NumberToByteArrayWithPadding(value, 3);
  629. list.AddRange(commandAndNozzle);
  630. list.AddRange(authorizationTimeBytes);
  631. list.Add((byte)request.AuthorizationType);
  632. list.AddRange(valueBytes);
  633. byte[] sendBytes = content2data(list.ToArray(), null);
  634. return await SendRequestToMachine("发送授权请求", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendBytes);
  635. }
  636. public async Task<CommonMessage> SendUnAuthorizartion(MqttUnAhorizationRequest request)
  637. {
  638. List<Byte> list = new List<Byte>();
  639. byte[] commandAndNozzle = { 0x66, (byte)request.NozzleNum };
  640. byte[] authorizationTimeBytes = ConvertDateTimeToByteArray(request.AuthorizationTime);
  641. byte[] ttcBytes = NumberToByteArrayWithPadding(request.Ttc, 4);
  642. list.AddRange(commandAndNozzle);
  643. list.AddRange(authorizationTimeBytes);
  644. list.AddRange(ttcBytes);
  645. byte[] sendBytes = content2data(list.ToArray(), null);
  646. return await SendRequestToMachine("发送取消授权请求", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendBytes);
  647. }
  648. public void SetTcpClinet(TcpClient? tcpClient)
  649. {
  650. this.client = tcpClient;
  651. }
  652. /// <summary>
  653. /// 发送消息到油机,3秒的超时,重试三次
  654. /// </summary>
  655. /// <param name="sendTag">发送的消息类型,用于日志记录</param>
  656. /// <param name="sendKey">发送的消息key,用于存储 TaskCompletionSource</param>
  657. /// <param name="requestBytes">实际发送消息</param>
  658. /// <returns></returns>
  659. /// <exception cref="TimeoutException"></exception>
  660. private async Task<CommonMessage> SendRequestToMachine(string sendTag,string sendKey, byte[] requestBytes)
  661. {
  662. int retryCount = 0;
  663. while(retryCount < 3)
  664. {
  665. var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
  666. bool isAdd = _tcsDictionary.TryAdd(sendKey, new TaskCompletionSource<CommonMessage>());
  667. logger.Info($"{sendTag}: add request {sendKey} to dic is {isAdd}");
  668. client?.Client.Send(requestBytes);
  669. try
  670. {
  671. TaskCompletionSource<CommonMessage>? value;
  672. TaskCompletionSource<CommonMessage> tcs;
  673. if(_tcsDictionary.TryGetValue(sendKey, out value))
  674. {
  675. tcs = value;
  676. } else
  677. {
  678. tcs = new TaskCompletionSource<CommonMessage>();
  679. }
  680. CommonMessage response = await tcs.Task.WaitAsync(cts.Token);
  681. return response;
  682. } catch (OperationCanceledException)
  683. {
  684. retryCount++;
  685. logger.Info($"{sendTag}: time out,retrying... ({retryCount} / 3)");
  686. } finally
  687. {
  688. if(retryCount >= 3)
  689. {
  690. logger.Info($"{sendTag}: is time out add retry 3 time");
  691. _tcsDictionary.TryRemove(sendKey,out _);
  692. }
  693. }
  694. }
  695. return new ErrorMessage()
  696. {
  697. IsError = true,
  698. ErrorMessage = $"{sendTag}: can not receive response after 3 retries"
  699. };
  700. }
  701. /// <summary>
  702. /// 添加或修改订单
  703. /// </summary>
  704. /// <param name="order">接收到油机的订单信息</param>
  705. /// <returns></returns>
  706. public int UpLoadOrder(CommonMessage order)
  707. {
  708. //接收到油机发送过来的订单信息
  709. if(order is OrderFromMachine)
  710. {
  711. OrderFromMachine orderFromMachine = (OrderFromMachine)order;
  712. FccOrderInfo orderByMessage = orderFromMachine.ToComponent();
  713. FccOrderInfo? fccOrderInfo = MysqlDbContext.fccOrderInfos.FirstOrDefault(fccOrder =>
  714. fccOrder.NozzleNum == orderFromMachine.nozzleNum && fccOrder.Ttc == orderFromMachine.ttc);
  715. if (fccOrderInfo == null)
  716. {
  717. logger.Info($"receive order from machine,find order from database is null");
  718. MysqlDbContext.fccOrderInfos.Add(orderByMessage);
  719. }
  720. else
  721. {
  722. logger.Info($"receive order from machine,padding data right now");
  723. orderFromMachine.PaddingAuthorizationOrderData(fccOrderInfo);
  724. }
  725. }
  726. return MysqlDbContext.SaveChanges();
  727. }
  728. /// <summary>
  729. /// 传入有效数据,拼接为要发送给油机包
  730. /// </summary>
  731. /// <param name="content"></param>
  732. /// <returns></returns>
  733. public byte[] content2data(byte[] content,byte? sendFrame)
  734. {
  735. List<byte> list = new List<byte>();
  736. //目标地址,源地址,帧号
  737. byte frameNo = 0x00;
  738. if(sendFrame == null)
  739. {
  740. lock (lockFrame)
  741. {
  742. if (frame == 0x3f)
  743. {
  744. frameNo = 0x00;
  745. }
  746. else
  747. {
  748. frameNo = (byte)(frame + 1);
  749. }
  750. }
  751. } else
  752. {
  753. frameNo = sendFrame.Value;
  754. }
  755. byte[] head = new byte[] { 0xFF, 0xE0, frameNo };
  756. byte[] length = Int2BCD(content.Length);
  757. list.AddRange(head);
  758. list.AddRange(length);
  759. list.AddRange(content);
  760. byte[] crc = HengshanCRC16.ComputeChecksumToBytes(list.ToArray());
  761. list.AddRange(crc);
  762. List<byte> addFAList = addFA(list);
  763. addFAList.Insert(0, 0xFA);
  764. return addFAList.ToArray();
  765. }
  766. public int Bcd2Int(byte byte1, byte byte2)
  767. {
  768. // 提取第一个字节的高四位和低四位
  769. int digit1 = (byte1 >> 4) & 0x0F; // 高四位
  770. int digit2 = byte1 & 0x0F; // 低四位
  771. // 提取第二个字节的高四位和低四位
  772. int digit3 = (byte2 >> 4) & 0x0F; // 高四位
  773. int digit4 = byte2 & 0x0F; // 低四位
  774. // 组合成一个整数
  775. int result = digit1 * 1000 + digit2 * 100 + digit3 * 10 + digit4;
  776. return result;
  777. }
  778. public byte[] Int2BCD(int number)
  779. {
  780. // 提取千位、百位、十位和个位
  781. int thousands = number / 1000;
  782. int hundreds = (number / 100) % 10;
  783. int tens = (number / 10) % 10;
  784. int units = number % 10;
  785. // 将千位和百位组合成一个字节(千位在高四位,百位在低四位)
  786. byte firstByte = (byte)((thousands * 16) + hundreds); // 乘以16相当于左移4位
  787. // 将十位和个位组合成一个字节(十位在高四位,个位在低四位)
  788. byte secondByte = (byte)((tens * 16) + units);
  789. // 返回结果数组
  790. return new byte[] { firstByte, secondByte };
  791. }
  792. public List<Byte> addFA(List<Byte> list)
  793. {
  794. List<byte> result = new List<byte>();
  795. foreach (byte b in list)
  796. {
  797. if (b == 0xFA)
  798. {
  799. result.Add(0xFA);
  800. result.Add(0xFA);
  801. }
  802. else
  803. {
  804. result.Add(b);
  805. }
  806. }
  807. return result;
  808. }
  809. /// <summary>
  810. /// 将数值转为byte[]
  811. /// </summary>
  812. /// <param name="value">数值</param>
  813. /// <param name="length">数组长度,不够高位补0</param>
  814. /// <returns></returns>
  815. /// <exception cref="ArgumentException"></exception>
  816. public static byte[] NumberToByteArrayWithPadding(int value, int length)
  817. {
  818. if (length < 0)
  819. {
  820. throw new ArgumentException("Length must be non-negative.");
  821. }
  822. // 创建一个指定长度的字节数组
  823. byte[] paddedBytes = new byte[length];
  824. // 确保是大端序
  825. for (int i = 0; i < length && i < 4; i++)
  826. {
  827. paddedBytes[length - 1 - i] = (byte)(value >> (i * 8));
  828. }
  829. return paddedBytes;
  830. }
  831. public static byte[] FormatDecimal(decimal value)
  832. {
  833. // 四舍五入到两位小数
  834. decimal roundedValue = Math.Round(value, 2, MidpointRounding.AwayFromZero);
  835. int valueInt = (int)(roundedValue * 100m);
  836. return NumberToByteArrayWithPadding(valueInt, 3); ;
  837. }
  838. /// <summary>
  839. /// 将时间转为 BCD
  840. /// </summary>
  841. /// <param name="dateTime"></param>
  842. /// <returns></returns>
  843. public static byte[] ConvertDateTimeToByteArray(DateTime dateTime)
  844. {
  845. // 创建byte数组
  846. byte[] result = new byte[7];
  847. // 年份处理
  848. int year = dateTime.Year;
  849. result[0] = (byte)((year / 1000) * 16 + (year / 100) % 10); // 千年和百年
  850. result[1] = (byte)((year / 10) % 10 * 16 + year % 10); // 十年和个年
  851. // 月、日、小时、分钟、秒直接转换为BCD
  852. result[2] = (byte)(dateTime.Month / 10 * 16 + dateTime.Month % 10);
  853. result[3] = (byte)(dateTime.Day / 10 * 16 + dateTime.Day % 10);
  854. result[4] = (byte)(dateTime.Hour / 10 * 16 + dateTime.Hour % 10);
  855. result[5] = (byte)(dateTime.Minute / 10 * 16 + dateTime.Minute % 10);
  856. result[6] = (byte)(dateTime.Second / 10 * 16 + dateTime.Second % 10);
  857. return result;
  858. }
  859. // CRC16 constants
  860. const ushort CRC_ORDER16 = 16;
  861. const ushort CRC_POLYNOM16 = 0x1021;
  862. const ushort CRC_CRCINIT16 = 0xFFFF;
  863. const ushort CRC_CRCXOR16 = 0x0000;
  864. const ushort CRC_MASK = 0xFFFF;
  865. const ushort CRC_HIGHEST_BIT = (ushort)(1 << (CRC_ORDER16 - 1));
  866. const ushort TGT_CRC_DEFAULT_INIT = 0xFFFF;
  867. public static ushort Crc16(byte[] buffer, ushort length)
  868. {
  869. ushort crc_rc = TGT_CRC_DEFAULT_INIT;
  870. for (int i = 0; i < length; i++)
  871. {
  872. byte c = buffer[i];
  873. for (ushort j = 0x80; j != 0; j >>= 1)
  874. {
  875. ushort crc_bit = (ushort)((crc_rc & CRC_HIGHEST_BIT) != 0 ? 1 : 0);
  876. crc_rc <<= 1;
  877. if ((c & j) != 0)
  878. {
  879. crc_bit = (ushort)((crc_bit == 0) ? 1 : 0);
  880. }
  881. if (crc_bit != 0)
  882. {
  883. crc_rc ^= CRC_POLYNOM16;
  884. }
  885. }
  886. }
  887. return (ushort)((crc_rc ^ CRC_CRCXOR16) & CRC_MASK);
  888. }
  889. #endregion
  890. }
  891. public class HengshanPayTerminalHanlderGroupConfigV1
  892. {
  893. public string PumpIds { get; set; }
  894. public List<PumpSubAddress> PumpSubAddresses { get; set; }
  895. }
  896. public class HengshanPayTerminalHanlderGroupConfigV2
  897. {
  898. public string PumpIds { get; set; }
  899. public List<PumpSubAddress> PumpSubAddresses { get; set; }
  900. public List<PumpNozzleLogicId> PumpNozzleLogicIds { get; set; }
  901. public List<PumpSiteNozzleNo> PumpSiteNozzleNos { get; set; }
  902. public List<NozzleLogicId> NozzleLogicIds { get; set; }
  903. }
  904. public class PumpSubAddress
  905. {
  906. public byte PumpId { get; set; }
  907. public byte SubAddress { get; set; }
  908. }
  909. public class PumpNozzleLogicId
  910. {
  911. public byte PumpId { get; set; }
  912. public string LogicIds { get; set; }
  913. }
  914. public class PumpSiteNozzleNo
  915. {
  916. public byte PumpId { get; set; }
  917. public string SiteNozzleNos { get; set; }
  918. }
  919. public class NozzleLogicId
  920. {
  921. public byte NozzleNo { get; set; }
  922. public byte LogicId { get; set; }
  923. }
  924. }