HengshanPayTermHandler.cs 49 KB

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