HengshanPayTermHandler.cs 45 KB

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