HengshanPayTermHandler.cs 32 KB

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