HengshanPayTermHandler.cs 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  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. using HengshanPaymentTerminal.MessageEntity.Outgoing;
  32. using Microsoft.IdentityModel.Tokens;
  33. using Org.BouncyCastle.Asn1.Ocsp;
  34. using Newtonsoft.Json.Linq;
  35. using System.Net;
  36. namespace HengshanPaymentTerminal
  37. {
  38. /// <summary>
  39. /// Handler that communicates directly with the Hengshan Payment Terminal for card handling and pump handling via serial port.
  40. /// </summary>
  41. [MetaPartsDescriptor(
  42. "lang-zh-cn:恒山IC卡终端(UI板) App lang-en-us:Hengshan IC card terminal (UI Board)",
  43. "lang-zh-cn:用于与UI板通讯控制加油机" +
  44. "lang-en-us:Used for terminal communication to control pumps",
  45. new[]
  46. {
  47. "lang-zh-cn:恒山IC卡终端lang-en-us:HengshanICTerminal"
  48. })]
  49. public class HengshanPayTermHandler : IEnumerable<IFdcPumpController>, IDeviceHandler<byte[], CommonMessage>
  50. {
  51. #region Fields
  52. private string pumpIds;
  53. private string pumpSubAddresses;
  54. private string pumpNozzles;
  55. private string pumpSiteNozzleNos;
  56. private string nozzleLogicIds;
  57. private IContext<byte[], CommonMessage> _context;
  58. private List<HengshanPumpHandler> pumpHandlers = new List<HengshanPumpHandler>();
  59. public Queue<CardMessageBase> queue = new Queue<CardMessageBase>();
  60. public Queue<CommonMessage> commonQueue = new Queue<CommonMessage>();
  61. private object syncObj = new object();
  62. private ConcurrentDictionary<int, PumpStateHolder> statusDict = new ConcurrentDictionary<int, PumpStateHolder>();
  63. public ConcurrentDictionary<int, PumpStateHolder> PumpStatusDict => statusDict;
  64. private Dictionary<int, int> pumpIdSubAddressDict;
  65. public Dictionary<int, List<int>> PumpNozzlesDict { get; private set; }
  66. public Dictionary<int, int> NozzleLogicIdDict { get; private set; }
  67. public Dictionary<int, List<int>> PumpSiteNozzleNoDict { get; private set; }
  68. public MysqlDbContext MysqlDbContext { get; private set; }
  69. public StationInfo stationInfo { get; set; }
  70. public List<DetailsNozzleInfoOutput> nozzleInfoList { get; private set; }
  71. public TcpClient? client { get; set; }
  72. public int? serverPort { get; set; }
  73. //private readonly ConcurrentDictionary<string,TaskCompletionSource<CommonMessage>> _tcsDictionary = new ConcurrentDictionary<string, TaskCompletionSource<CommonMessage>>();
  74. //private TaskCompletionSource<ErrorMessage> checkDisConnectTask = new TaskCompletionSource<ErrorMessage>();
  75. private byte frame = 0x00;
  76. private object lockFrame = new object();
  77. private IHttpClientUtil httpClientUtil;
  78. //记录油枪状态,key-枪号,value:01:离线 02:锁枪 03:空闲 04:提枪 06:开始加油 08:加油中
  79. private ConcurrentDictionary<int, int> nozzleStatusDic = new ConcurrentDictionary<int, int>();
  80. #endregion
  81. #region Logger
  82. private static NLog.Logger logger = NLog.LogManager.LoadConfiguration("NLog.config").GetLogger("IPosPlusApp");
  83. #endregion
  84. #region Constructor
  85. //private static List<object> ResolveCtorMetaPartsConfigCompatibility(string incompatibleCtorParamsJsonStr)
  86. //{
  87. // var jsonParams = JsonDocument.Parse(incompatibleCtorParamsJsonStr).RootElement.EnumerateArray().ToArray();
  88. // //sample: "UITemplateVersion":"1.0"
  89. // string uiTemplateVersionRegex = @"(?<=""UITemplateVersion""\:\"").+?(?="")";
  90. // var match = Regex.Match(jsonParams.First().GetRawText(), uiTemplateVersionRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline);
  91. // if (match.Success)
  92. // {
  93. // var curVersion = match.Value;
  94. // if (curVersion == "1.0")
  95. // {
  96. // var existsAppConfigV1 = JsonSerializer.Deserialize(jsonParams.First().GetRawText(), typeof(HengshanPayTerminalHanlderGroupConfigV1));
  97. // }
  98. // else
  99. // {
  100. // }
  101. // }
  102. // return null;
  103. //}
  104. [ParamsJsonSchemas("TermHandlerGroupCtorParamsJsonSchemas")]
  105. public HengshanPayTermHandler(HengshanPayTerminalHanlderGroupConfigV2 config)
  106. : this(config.PumpIds,
  107. string.Join(";", config.PumpSubAddresses.Select(m => $"{m.PumpId}={m.SubAddress}")),
  108. string.Join(";", config.PumpNozzleLogicIds.Select(m => $"{m.PumpId}={m.LogicIds}")),
  109. string.Join(";", config.PumpSiteNozzleNos.Select(m => $"{m.PumpId}={m.SiteNozzleNos}")),
  110. string.Join(";", config.NozzleLogicIds.Select(m => $"{m.NozzleNo}={m.LogicId}")))
  111. //clientUtil)
  112. {
  113. }
  114. public HengshanPayTermHandler(
  115. string pumpIds,
  116. string pumpSubAddresses,
  117. string pumpNozzles,
  118. string pumpSiteNozzleNos,
  119. string nozzleLogicIds)
  120. //IHttpClientUtil clientUtil)
  121. {
  122. this.pumpIds = pumpIds;
  123. this.pumpSubAddresses = pumpSubAddresses;
  124. this.pumpNozzles = pumpNozzles;
  125. this.pumpSiteNozzleNos = pumpSiteNozzleNos;
  126. this.nozzleLogicIds = nozzleLogicIds;
  127. AssociatedPumpIds = GetPumpIdList(pumpIds);
  128. pumpIdSubAddressDict = InitializePumpSubAddressMapping();
  129. PumpNozzlesDict = ParsePumpNozzlesList(pumpNozzles);
  130. PumpSiteNozzleNoDict = ParsePumpSiteNozzleNoList(pumpSiteNozzleNos);
  131. NozzleLogicIdDict = InitializeNozzleLogicIdMapping(nozzleLogicIds);
  132. InitializePumpHandlers();
  133. }
  134. #endregion
  135. public void OnFdcServerInit(Dictionary<string, object> parameters)
  136. {
  137. logger.Info("OnFdcServerInit called");
  138. if (parameters.ContainsKey("LastPriceChange"))
  139. {
  140. // nozzle logical id:rawPrice
  141. var lastPriceChanges = parameters["LastPriceChange"] as Dictionary<byte, int>;
  142. foreach (var priceChange in lastPriceChanges)
  143. {
  144. }
  145. }
  146. }
  147. #region Event handler
  148. public event EventHandler<TerminalMessageEventArgs> OnTerminalMessageReceived;
  149. public event EventHandler<TotalizerDataEventArgs> OnTotalizerReceived;
  150. public event EventHandler<FuelPriceChangeRequestEventArgs> OnFuelPriceChangeRequested;
  151. public event EventHandler<FuelPriceDownloadRequestedEventArgs> OnTerminalFuelPriceDownloadRequested;
  152. public event EventHandler<CheckCommandEventArgs> OnCheckCommandReceived;
  153. public event EventHandler<LockUnlockEventArgs> OnLockUnlockCompleted;
  154. #endregion
  155. #region Properties
  156. public List<int> AssociatedPumpIds { get; private set; }
  157. public IContext<byte[], CommonMessage> Context
  158. {
  159. get { return _context; }
  160. }
  161. public string PumpIdList => pumpIds;
  162. //public LockUnlockOperation LockUnlockOperationType { get; set; } = LockUnlockOperation.Undefined;
  163. #endregion
  164. #region Methods
  165. public int GetSubAddressForPump(int pumpId)
  166. {
  167. return pumpIdSubAddressDict.First(d => d.Key == pumpId).Value;
  168. }
  169. private List<int> GetPumpIdList(string pumpIds)
  170. {
  171. var pumpIdList = new List<int>();
  172. if (!string.IsNullOrEmpty(pumpIds) && pumpIds.Contains(',')) //multiple pumps per serial port, Hengshan TQC pump
  173. {
  174. var arr = pumpIds.Split(',');
  175. foreach (var item in arr)
  176. {
  177. pumpIdList.Add(int.Parse(item));
  178. }
  179. return pumpIdList;
  180. }
  181. else if (!string.IsNullOrEmpty(pumpIds) && pumpIds.Length == 1 || pumpIds.Length == 2) //only 1 pump per serial port, Hengshan pump
  182. {
  183. return new List<int> { int.Parse(pumpIds) };
  184. }
  185. else
  186. {
  187. throw new ArgumentException("Pump id list not specified!");
  188. }
  189. }
  190. private Dictionary<int, int> InitializePumpSubAddressMapping()
  191. {
  192. var dict = new Dictionary<int, int>();
  193. if (!string.IsNullOrEmpty(pumpSubAddresses))
  194. {
  195. var sequence = pumpSubAddresses.Split(';')
  196. .Select(s => s.Split('='))
  197. .Select(a => new { PumpId = int.Parse(a[0]), SubAddress = int.Parse(a[1]) });
  198. foreach (var pair in sequence)
  199. {
  200. if (!dict.ContainsKey(pair.PumpId))
  201. {
  202. dict.Add(pair.PumpId, pair.SubAddress);
  203. }
  204. }
  205. return dict;
  206. }
  207. else
  208. {
  209. throw new ArgumentException("Pump id and sub address mapping does not exist");
  210. }
  211. }
  212. private Dictionary<int, List<int>> ParsePumpNozzlesList(string pumpNozzles)
  213. {
  214. Dictionary<int, List<int>> pumpNozzlesDict = new Dictionary<int, List<int>>();
  215. if (!string.IsNullOrEmpty(pumpNozzles) && pumpNozzles.Contains(';'))
  216. {
  217. var arr = pumpNozzles.Split(';');
  218. foreach (var subMapping in arr)
  219. {
  220. var pair = new KeyValuePair<int, int>(int.Parse(subMapping.Split('=')[0]), int.Parse(subMapping.Split('=')[1]));
  221. Console.WriteLine($"{pair.Key}, {pair.Value}");
  222. if (!pumpNozzlesDict.ContainsKey(pair.Key))
  223. {
  224. pumpNozzlesDict.Add(pair.Key, new List<int> { pair.Value });
  225. }
  226. else
  227. {
  228. List<int> nozzlesForThisPump;
  229. pumpNozzlesDict.TryGetValue(pair.Key, out nozzlesForThisPump);
  230. if (nozzlesForThisPump != null && !nozzlesForThisPump.Contains(pair.Value))
  231. {
  232. nozzlesForThisPump.Add(pair.Value);
  233. }
  234. }
  235. }
  236. }
  237. else if (!string.IsNullOrEmpty(pumpNozzles) && pumpNozzles.Count(c => c == '=') == 1) // only one pump per serial port
  238. {
  239. try
  240. {
  241. pumpNozzlesDict.Add(
  242. int.Parse(pumpNozzles.Split('=')[0]),
  243. new List<int> { int.Parse(pumpNozzles.Split('=')[1]) });
  244. }
  245. catch (Exception ex)
  246. {
  247. Console.WriteLine(ex);
  248. }
  249. }
  250. else
  251. {
  252. throw new ArgumentException("Wrong mapping between pump and its associated nozzles!");
  253. }
  254. return pumpNozzlesDict;
  255. }
  256. static Dictionary<int, List<int>> ParsePumpSiteNozzleNoList(string pumpSiteNozzleNos)
  257. {
  258. Dictionary<int, List<int>> pumpSiteNozzleNoDict = new Dictionary<int, List<int>>();
  259. if (!string.IsNullOrEmpty(pumpSiteNozzleNos) && pumpSiteNozzleNos.Contains(';'))
  260. {
  261. var arr = pumpSiteNozzleNos.Split(';');
  262. foreach (var subMapping in arr)
  263. {
  264. var pair = new KeyValuePair<int, List<int>>(
  265. int.Parse(subMapping.Split('=')[0]), subMapping.Split('=')[1].Split(',').Select(a => int.Parse(a)).ToList());
  266. Console.WriteLine($"{pair.Key}, {pair.Value}");
  267. if (!pumpSiteNozzleNoDict.ContainsKey(pair.Key))
  268. {
  269. pumpSiteNozzleNoDict.Add(pair.Key, pair.Value);
  270. }
  271. }
  272. }
  273. else if (!string.IsNullOrEmpty(pumpSiteNozzleNos) && pumpSiteNozzleNos.Count(c => c == '=') == 1)
  274. {
  275. try
  276. {
  277. string[] strArr = pumpSiteNozzleNos.Split('=');
  278. pumpSiteNozzleNoDict.Add(
  279. int.Parse(strArr[0]), new List<int> { int.Parse(strArr[1]) });
  280. }
  281. catch (Exception ex)
  282. {
  283. Console.WriteLine(ex);
  284. }
  285. }
  286. else
  287. {
  288. throw new ArgumentException("Wrong mapping between pump and its associated nozzles!");
  289. }
  290. return pumpSiteNozzleNoDict;
  291. }
  292. private Dictionary<int, int> InitializeNozzleLogicIdMapping(string nozzleLogicIds)
  293. {
  294. var dict = new Dictionary<int, int>();
  295. if (!string.IsNullOrEmpty(nozzleLogicIds))
  296. {
  297. var sequence = nozzleLogicIds.Split(';')
  298. .Select(s => s.Split('='))
  299. .Select(a => new { NozzleNo = int.Parse(a[0]), LogicId = int.Parse(a[1]) });
  300. foreach (var pair in sequence)
  301. {
  302. if (!dict.ContainsKey(pair.NozzleNo))
  303. {
  304. Console.WriteLine($"nozzle, logic id: {pair.NozzleNo} - {pair.LogicId}");
  305. dict.Add(pair.NozzleNo, pair.LogicId);
  306. }
  307. }
  308. return dict;
  309. }
  310. else if (!string.IsNullOrEmpty(nozzleLogicIds) && nozzleLogicIds.Count(c => c == '=') == 1)
  311. {
  312. try
  313. {
  314. string[] sequence = nozzleLogicIds.Split('=');
  315. dict.Add(int.Parse(sequence[0]), int.Parse(sequence[1]));
  316. }
  317. catch (Exception ex)
  318. {
  319. Console.WriteLine(ex);
  320. }
  321. return dict;
  322. }
  323. else
  324. {
  325. throw new ArgumentException("Pump id and sub address mapping does not exist");
  326. }
  327. }
  328. private void InitializePumpHandlers()
  329. {
  330. var pumpIdList = GetPumpIdList(pumpIds);
  331. foreach (var item in pumpIdList)
  332. {
  333. var nozzleList = GetNozzleListForPump(item);
  334. var siteNozzleNoList = PumpSiteNozzleNoDict[item];
  335. HengshanPumpHandler pumpHandler = new HengshanPumpHandler(this, $"Pump_{item}", item, nozzleList, siteNozzleNoList);
  336. pumpHandler.OnFuelPriceChangeRequested += PumpHandler_OnFuelPriceChangeRequested;
  337. pumpHandlers.Add(pumpHandler);
  338. }
  339. }
  340. private List<int> GetNozzleListForPump(int pumpId)
  341. {
  342. List<int> nozzles;
  343. PumpNozzlesDict.TryGetValue(pumpId, out nozzles);
  344. return nozzles;
  345. }
  346. private void PumpHandler_OnFuelPriceChangeRequested(object sender, FuelPriceChangeRequestEventArgs e)
  347. {
  348. InfoLog($"Change price, Pump {e.PumpId}, Nozzle {e.NozzleId}, Price {e.Price}");
  349. OnFuelPriceChangeRequested?.Invoke(sender, e);
  350. }
  351. IEnumerator<IFdcPumpController> IEnumerable<IFdcPumpController>.GetEnumerator()
  352. {
  353. return pumpHandlers.GetEnumerator();
  354. }
  355. #endregion
  356. #region IHandler implementation
  357. public void Init(IContext<byte[], CommonMessage> context)
  358. {
  359. CommIdentity = context.Processor.Communicator.Identity;
  360. _context = context;
  361. this.MysqlDbContext = new MysqlDbContext();
  362. this.httpClientUtil = new HttpClientUtils();
  363. this.serverPort = CommIdentity.Replace("*:", "").ToInt();
  364. GetInfo();
  365. }
  366. public string CommIdentity { get; private set; }
  367. public async Task Process(IContext<byte[], CommonMessage> context)
  368. {
  369. switch(context.Incoming.Message.Handle)
  370. {
  371. //心跳,带油枪状态信息
  372. case 0x10:
  373. {
  374. //将油枪状态区分为空闲或非空闲,记录在内存。当状态有发生变化,发送到云端
  375. HeartBeatMessage heartBeatMessage = (HeartBeatMessage)context.Incoming.Message;
  376. SendNozzleStatus(heartBeatMessage);
  377. break;
  378. }
  379. //订单
  380. case 0x18:
  381. {
  382. //添加或修改数据库订单
  383. OrderFromMachine orderFromMachine = (OrderFromMachine)context.Incoming.Message;
  384. FccOrderInfo fccOrderInfo = UpLoadOrder(orderFromMachine);
  385. logger.Info($"receive order from machine,database had change");
  386. CreateTransaction(fccOrderInfo);
  387. break;
  388. }
  389. /**
  390. //普通应答
  391. case 0x55:
  392. {
  393. CommonAnswerBack commonAnswerBack = (CommonAnswerBack)context.Incoming.Message;
  394. if (commonAnswerBack.Command == 0x63) //二维码回复
  395. {
  396. byte[] keyBytes = { commonAnswerBack.Command, (byte)commonAnswerBack.NozzleNum };
  397. var key = BitConverter.ToString(keyBytes).Replace("-", "");
  398. if (_tcsDictionary.TryGetValue(key, out var value))
  399. {
  400. value.SetResult(commonAnswerBack);
  401. }
  402. else
  403. {
  404. logger.Info($"qrcode response:can not get tcs for dictionary");
  405. }
  406. }
  407. break;
  408. }
  409. // 授权回复
  410. case 0x65:
  411. {
  412. AuthorizationResponse authorizationResponse = (AuthorizationResponse)context.Incoming.Message;
  413. byte[] keyBytes = { authorizationResponse.Handle, (byte)authorizationResponse.NozzleNum };
  414. var key = BitConverter.ToString(keyBytes).Replace("-", "");
  415. if (_tcsDictionary.TryGetValue(key, out var value))
  416. {
  417. value.SetResult(authorizationResponse);
  418. }
  419. else
  420. {
  421. logger.Info($"authorization response:can not get tcs for dictionary");
  422. }
  423. break;
  424. }
  425. // 取消授权回复
  426. case 0x66:
  427. {
  428. UnAhorizationResponse unauthorizationResponse = (UnAhorizationResponse)context.Incoming.Message;
  429. byte[] keyBytes = { unauthorizationResponse.Handle, (byte)unauthorizationResponse.NozzleNum };
  430. var key = BitConverter.ToString(keyBytes).Replace("-", "");
  431. if (_tcsDictionary.TryGetValue(key, out var value))
  432. {
  433. value.SetResult(unauthorizationResponse);
  434. }
  435. else
  436. {
  437. logger.Info($"unauthorization response:can not get tcs for dictionary");
  438. }
  439. break;
  440. }
  441. */
  442. }
  443. //油机的应答不用回复
  444. if(context.Incoming.Message.Handle != 0x55) 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. /// 接收到MQTT
  601. /// </summary>
  602. /// <param name="message"></param>
  603. public async void OnReceiveMqttMessage(string message)
  604. {
  605. MqttRequest? mqttRequest = JsonConvert.DeserializeObject<MqttRequest>(message);
  606. if (mqttRequest == null)
  607. {
  608. logger.Error($"mqtt message turn on object fail,message:{message}");
  609. return;
  610. }
  611. switch (mqttRequest.type)
  612. {
  613. case MQTT_TYPE.AUTHORIZATION:
  614. {
  615. MqttAuthorizationRequest? mqttAuthorizationRequest = JsonConvert.DeserializeObject<MqttAuthorizationRequest>(mqttRequest.data);
  616. await SendAuthorizationAsync(mqttAuthorizationRequest);
  617. break;
  618. }
  619. case MQTT_TYPE.UNAUTHORIZATION:
  620. {
  621. MqttUnAhorizationRequest? mqttUnAhorizationRequest = JsonConvert.DeserializeObject<MqttUnAhorizationRequest>(mqttRequest.data);
  622. await SendUnAuthorizartion(mqttUnAhorizationRequest);
  623. break;
  624. }
  625. case MQTT_TYPE.PAID:
  626. {
  627. MqttPaidRequest? mqttPaidRequest = JsonConvert.DeserializeObject<MqttPaidRequest>(mqttRequest.data);
  628. await SendActuallyPaid(mqttPaidRequest);
  629. break;
  630. }
  631. case MQTT_TYPE.REFUND:
  632. {
  633. MqttRefundRequest? mqttRefundRequest = JsonConvert.DeserializeObject<MqttRefundRequest>(mqttRequest.data);
  634. await OnRecieveOrderRefund(mqttRefundRequest);
  635. break;
  636. }
  637. }
  638. }
  639. /// <summary>
  640. /// 发送二维码信息给油机
  641. /// </summary>
  642. /// <param name="tcpClient"></param>
  643. public async void SendQRCodeAsync()
  644. {
  645. string smallProgram = stationInfo?.SmallProgram ?? "";
  646. if (string.IsNullOrEmpty(smallProgram))
  647. {
  648. logger.Info($"can not get smallProgram link");
  649. return;
  650. }
  651. List<DetailsNozzleInfoOutput> nozzles = nozzleInfoList.FindAll(nozzle => nozzle.Port == serverPort);
  652. foreach (var item in nozzles)
  653. {
  654. //List<Byte> list = new List<Byte>();
  655. //byte[] commandAndNozzle = { 0x63, (byte)item.NozzleNum };
  656. //string qrCode = smallProgram + "/" + item.NozzleNum;
  657. //byte[] qrCodeBytes = Encoding.ASCII.GetBytes(qrCode);
  658. //list.AddRange(commandAndNozzle);
  659. //list.Add((byte)qrCodeBytes.Length);
  660. //list.AddRange(qrCodeBytes);
  661. //byte[] sendBytes = content2data(list.ToArray(), null);
  662. SendQrCode sendQrCode = new SendQrCode(item.NozzleNum, smallProgram, getFrame(null));
  663. byte[] commandAndNozzle = { sendQrCode.Handle, (byte)sendQrCode.NozzleNum };
  664. Thread.Sleep(5000);
  665. CommonMessage commonMessage = await SendMessageToMaichine($"发送{sendQrCode.NozzleNum}号枪二维码",(request,response) =>
  666. {
  667. if(response.Handle == (byte)CommonMessage.Command.COMMON)
  668. {
  669. CommonAnswerBack commonAnswerBack = (CommonAnswerBack)response;
  670. return commonAnswerBack.Command == (byte)CommonMessage.Command.SEND_QR_CODE && commonAnswerBack.NozzleNum == sendQrCode.NozzleNum;
  671. }
  672. return false;
  673. }, sendQrCode);
  674. //CommonMessage commonMessage = await SendMessageToMaichine("发送二维码", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendQrCode);
  675. //CommonMessage commonMessage = await SendRequestToMachine("发送二维码", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendBytes);
  676. if (commonMessage.IsError && commonMessage.TheErrorType == CommonMessage.ErrorType.DISCONNECT) break;
  677. }
  678. //var testAuthorization = new MqttAuthorizationRequest()
  679. //{
  680. // NozzleNum = 1,
  681. // AuthorizationTime = DateTime.Now,
  682. // AuthorizationType = 1,
  683. // Value = 3.00m
  684. //};
  685. //await SendAuthorization(testAuthorization);
  686. //var testUnAuthorization = new MqttUnAhorizationRequest()
  687. //{
  688. // NozzleNum = 1,
  689. // AuthorizationTime = DateTime.Now,
  690. // Ttc = 111
  691. //};
  692. //await SendUnAuthorizartion(testUnAuthorization);
  693. }
  694. /// <summary>
  695. /// 发送实付金额给油机
  696. /// </summary>
  697. /// <param name="orderInfo"></param>
  698. public async Task SendActuallyPaid(MqttPaidRequest? request)
  699. {
  700. if (request == null)
  701. {
  702. logger.Error($"mqtt get paid request is null");
  703. return;
  704. }
  705. //通知云端当前已收到消息
  706. OnGetPaidInfo onGetPaidInfo = new OnGetPaidInfo()
  707. {
  708. Id = request.Id,
  709. Result = 1
  710. };
  711. await httpClientUtil.SendRecievePaidNotice(JsonConvert.SerializeObject(onGetPaidInfo));
  712. FccOrderInfo? fccOrderInfo = MysqlDbContext.FccOrderInfos.FirstOrDefault(order => order.CloundOrderId == request.Id);
  713. if (fccOrderInfo == null)
  714. {
  715. logger.Error($"[mqtt paid order notice]:can not find order by clounid:{request.Id}");
  716. return;
  717. }
  718. fccOrderInfo.AmountPayable = request.ActualPaymentAmount;
  719. fccOrderInfo.PaymentTime = request.TransactionTime;
  720. fccOrderInfo.PaymentStatus = 1;
  721. MysqlDbContext.SaveChanges();
  722. //SendActuallyPaid sendActuallyPaid = new SendActuallyPaid(orderInfo.NozzleNum, orderInfo.Ttc, orderInfo.AmountPayable ?? orderInfo.Amount, getFrame(null));
  723. //byte[] commandAndNozzle = { sendActuallyPaid.Handle, (byte)sendActuallyPaid.NozzleNum };
  724. //await SendMessageToMaichine("发送实付金额", (request, response) =>
  725. //{
  726. // if (response.Handle == (byte)CommonMessage.Command.SEND_NEED_AMOUNT)
  727. // {
  728. // CommonAnswerBack commonAnswerBack = (CommonAnswerBack)response;
  729. // return commonAnswerBack.Command == (byte)CommonMessage.Command.SEND_NEED_AMOUNT && commonAnswerBack.NozzleNum == sendActuallyPaid.NozzleNum;
  730. // }
  731. // return false;
  732. //}, sendActuallyPaid);
  733. //await SendMessageToMaichine("发送实付金额", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendActuallyPaid);
  734. }
  735. /// <summary>
  736. /// 发送授权请求给油机
  737. /// </summary>
  738. /// <param name="request"></param>
  739. /// <returns></returns>
  740. public async Task SendAuthorizationAsync(MqttAuthorizationRequest? request)
  741. {
  742. if(request == null)
  743. {
  744. logger.Error($"mqtt authorization request is null");
  745. return;
  746. }
  747. //添加订单到数据库
  748. DateTime authorizationTime = request.AuthorizationTime ?? DateTime.Now;
  749. FccOrderInfo fccOrderInfo = request.ToComponent(authorizationTime);
  750. MysqlDbContext.FccOrderInfos.Add(fccOrderInfo);
  751. //发送授权申请到油机
  752. SendAuthorization sendAuthorization = new SendAuthorization((int)request.NozzleId, authorizationTime, 1,request.OriginalAmount, getFrame(null));
  753. byte[] commandAndNozzle = { sendAuthorization.Handle, (byte)sendAuthorization.NozzleNum };
  754. CommonMessage commonMessage = await SendMessageToMaichine("发送授权请求", (request, response) =>
  755. {
  756. if (response.Handle == (byte)CommonMessage.Command.ACCREDIT)
  757. {
  758. AuthorizationResponse authorization = (AuthorizationResponse)response;
  759. return authorization.NozzleNum == sendAuthorization.NozzleNum;
  760. }
  761. return false;
  762. }, sendAuthorization);
  763. //发送授权结果给云端
  764. string authorizationResultJson = string.Empty;
  765. SendAuthorizationResult sendAuthorizationResult = new SendAuthorizationResult();
  766. sendAuthorizationResult.NozzleId = request.NozzleId;
  767. if (commonMessage.IsError)
  768. {
  769. ErrorMessage errorMessage = (ErrorMessage)commonMessage;
  770. switch (errorMessage.TheErrorType)
  771. {
  772. case CommonMessage.ErrorType.DISCONNECT:
  773. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.Disconnected;
  774. break;
  775. case CommonMessage.ErrorType.TIMEOUT:
  776. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.AuthorizationTimeout;
  777. break;
  778. }
  779. }
  780. else
  781. {
  782. AuthorizationResponse authorization = (AuthorizationResponse)commonMessage;
  783. if (authorization.Result == 0)
  784. {
  785. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.Failed;
  786. }
  787. else
  788. {
  789. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  790. sendAuthorizationResult.TransactionNumber = authorization.Ttc.ToString();
  791. fccOrderInfo.Ttc = authorization.Result;
  792. }
  793. }
  794. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendAuthorizationResult(JsonConvert.SerializeObject(sendAuthorizationResult));
  795. logger.Info($"send authorization result response:{JsonConvert.SerializeObject(httpResponseMessage.Content)}");
  796. //更新订单
  797. MysqlDbContext.SaveChanges();
  798. }
  799. /// <summary>
  800. /// 发送取消授权请求给油机
  801. /// </summary>
  802. /// <param name="request"></param>
  803. public async Task SendUnAuthorizartion(MqttUnAhorizationRequest? request)
  804. {
  805. if (request == null)
  806. {
  807. logger.Error($"mqtt unauthorization request is null");
  808. return;
  809. }
  810. //从请求信息中获取流水号与授权时间,没有就到数据库查找
  811. int ttc = 0;
  812. DateTime authorizationTime = request.AuthorizationTime ?? DateTime.Now;
  813. bool ttsIntResult = int.TryParse(request.TransactionNumber, out ttc);
  814. if (request.AuthorizationTime == null || !ttsIntResult)
  815. {
  816. FccOrderInfo? fccOrderInfo = MysqlDbContext.FccOrderInfos.FirstOrDefault(order => order.CloundOrderId == request.Id);
  817. if(fccOrderInfo != null)
  818. {
  819. ttc = fccOrderInfo.Ttc;
  820. authorizationTime = fccOrderInfo.AuthorizationTime;
  821. }
  822. }
  823. SendUnAuthorizationResult sendUnAuthorizationResult = new SendUnAuthorizationResult();
  824. sendUnAuthorizationResult.NozzleId = request.NozzleId;
  825. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  826. if (ttc != 0)
  827. {
  828. SendUnAuthorization sendUnAuthorization = new SendUnAuthorization((int)request.NozzleId, authorizationTime, ttc, getFrame(null));
  829. byte[] commandAndNozzle = { sendUnAuthorization.Handle, (byte)sendUnAuthorization.NozzleNum };
  830. CommonMessage commonMessage = await SendMessageToMaichine("发送取消授权请求", (request, response) =>
  831. {
  832. if (response.Handle == (byte)CommonMessage.Command.CANCEL_ACCREDIT)
  833. {
  834. UnAhorizationResponse unauthorization = (UnAhorizationResponse)response;
  835. return unauthorization.NozzleNum == sendUnAuthorization.NozzleNum;
  836. }
  837. return false;
  838. }, sendUnAuthorization);
  839. if (commonMessage.IsError)
  840. {
  841. ErrorMessage errorMessage = (ErrorMessage)commonMessage;
  842. switch (errorMessage.TheErrorType)
  843. {
  844. case CommonMessage.ErrorType.DISCONNECT:
  845. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Disconnected;
  846. break;
  847. case CommonMessage.ErrorType.TIMEOUT:
  848. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.AuthorizationTimeout;
  849. break;
  850. }
  851. }
  852. else
  853. {
  854. UnAhorizationResponse unAuthorization = (UnAhorizationResponse)commonMessage;
  855. if (unAuthorization.Result == 0)
  856. {
  857. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Failed;
  858. }
  859. else
  860. {
  861. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  862. }
  863. }
  864. }
  865. else
  866. {
  867. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.TransactionNumberNotFound;
  868. }
  869. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendUnAuthorizationResult(JsonConvert.SerializeObject(sendUnAuthorizationResult));
  870. logger.Info($"send Unauthorization result response:{JsonConvert.SerializeObject(httpResponseMessage.Content)}");
  871. }
  872. /// <summary>
  873. /// 接收到云端发送订单退款信息
  874. /// </summary>
  875. /// <param name="request"></param>
  876. /// <returns></returns>
  877. private async Task OnRecieveOrderRefund(MqttRefundRequest? request)
  878. {
  879. if (request == null)
  880. {
  881. logger.Error($"mqtt OnRecieveOrderRefund request is null");
  882. return;
  883. }
  884. //通知云端当前已收到消息
  885. OnGetRefundInfo onGetRefundInfo = new OnGetRefundInfo()
  886. {
  887. Id = request.Id,
  888. Result = 1
  889. };
  890. await httpClientUtil.SendRecieveRefundNotice(JsonConvert.SerializeObject(onGetRefundInfo));
  891. FccOrderInfo? fccOrderInfo = MysqlDbContext.FccOrderInfos.FirstOrDefault(order => order.CloundOrderId == request.Id);
  892. if (fccOrderInfo == null)
  893. {
  894. logger.Error($"[mqtt refund order notice]:can not find order by clounid:{request.Id}");
  895. return;
  896. }
  897. fccOrderInfo.AmountPayable = request.ActualPaymentAmount;
  898. fccOrderInfo.PaymentStatus = 2;
  899. MysqlDbContext.SaveChanges();
  900. }
  901. //public void SetTcpClient(TcpClient? tcpClient, int? serverPort)
  902. //{
  903. // this.client = tcpClient;
  904. // this.serverPort = serverPort;
  905. // checkDisConnectTask = new TaskCompletionSource<ErrorMessage>();
  906. //}
  907. //public void OnTcpDisconnect()
  908. //{
  909. // this.client = null;
  910. // ErrorMessage errorMessage = new ErrorMessage()
  911. // {
  912. // IsError = true,
  913. // TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  914. // ErrorMessage = $"the client is disconnet"
  915. // };
  916. // checkDisConnectTask.SetResult(errorMessage);
  917. //}
  918. /// <summary>
  919. /// 发送消息到油机,3秒的超时,重试三次
  920. /// </summary>
  921. /// <param name="sendTag">发送的消息类型,用于日志记录</param>
  922. /// <param name="sendKey">发送的消息key,用于存储 TaskCompletionSource</param>
  923. /// <param name="requestBytes">实际发送消息</param>
  924. /// <returns></returns>
  925. private async Task<CommonMessage> SendMessageToMaichine(string sendTag, Func<CommonMessage, CommonMessage, bool> responseCapture,CommonMessage sendMessage)
  926. {
  927. int retryCount = 0;
  928. while (retryCount < 3)
  929. {
  930. try
  931. {
  932. var response = await this.Context.Outgoing.WriteAsyncAndCheckIsConnect(sendMessage, responseCapture, 3000);
  933. //超时重试
  934. if (response.ResponseType == WriteResponseType.TIME_OUT || response.Data == null)
  935. {
  936. retryCount++;
  937. logger.Info($"{sendTag}: time out,retrying... ({retryCount} / 3)");
  938. continue;
  939. }
  940. //链接断开不再发送
  941. if (response.ResponseType == WriteResponseType.DISCONNECT)
  942. {
  943. var isConnect = (bool)(response.Data ?? false);
  944. if (!isConnect) return new ErrorMessage()
  945. {
  946. IsError = true,
  947. TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  948. ErrorMessage = $"the client is disconnet"
  949. };
  950. }
  951. Console.WriteLine("");
  952. //返回信息
  953. return (CommonMessage)response.Data;
  954. }
  955. catch (Exception)
  956. {
  957. retryCount++;
  958. logger.Info($"{sendTag}: error,retrying... ({retryCount} / 3)");
  959. }
  960. finally
  961. {
  962. if (retryCount >= 3)
  963. {
  964. logger.Info($"{sendTag}: is time out add retry 3 time");
  965. }
  966. }
  967. }
  968. return new ErrorMessage()
  969. {
  970. IsError = true,
  971. TheErrorType = CommonMessage.ErrorType.TIMEOUT,
  972. ErrorMessage = $"{sendTag}: can not receive response after 3 retries"
  973. };
  974. }
  975. ///// <summary>
  976. ///// 发送消息到油机,3秒的超时,重试三次
  977. ///// </summary>
  978. ///// <param name="sendTag">发送的消息类型,用于日志记录</param>
  979. ///// <param name="sendKey">发送的消息key,用于存储 TaskCompletionSource</param>
  980. ///// <param name="requestBytes">实际发送消息</param>
  981. ///// <returns></returns>
  982. //private async Task<CommonMessage> SendMessageToMaichine(string sendTag, string sendKey,CommonMessage sendMessage)
  983. //{
  984. // int retryCount = 0;
  985. // while (retryCount < 3)
  986. // {
  987. // try
  988. // {
  989. // var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
  990. // bool isAdd = _tcsDictionary.TryAdd(sendKey, new TaskCompletionSource<CommonMessage>());
  991. // logger.Info($"{sendTag}: add request {sendKey} to dic is {isAdd}");
  992. // Write(sendMessage);
  993. // TaskCompletionSource<CommonMessage>? value;
  994. // TaskCompletionSource<CommonMessage> tcs;
  995. // if (_tcsDictionary.TryGetValue(sendKey, out value))
  996. // {
  997. // tcs = value;
  998. // }
  999. // else
  1000. // {
  1001. // tcs = new TaskCompletionSource<CommonMessage>();
  1002. // }
  1003. // Task checkOutTime = Task.Delay(Timeout.Infinite, cts.Token);
  1004. // var response = await Task.WhenAny(tcs.Task, checkOutTime, checkDisConnectTask.Task);
  1005. // //超时重试
  1006. // if (response == checkOutTime)
  1007. // {
  1008. // retryCount++;
  1009. // logger.Info($"{sendTag}-{sendKey}: time out,retrying... ({retryCount} / 3)");
  1010. // continue;
  1011. // }
  1012. // //CommonMessage response = await tcs.Task.WaitAsync(cts.Token);
  1013. // _tcsDictionary.TryRemove(sendKey, out _);
  1014. // //链接断开不再发送
  1015. // if(response == checkDisConnectTask.Task)
  1016. // {
  1017. // return new ErrorMessage()
  1018. // {
  1019. // IsError = true,
  1020. // TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  1021. // ErrorMessage = $"the client is disconnet"
  1022. // };
  1023. // }
  1024. // //返回信息
  1025. // return await (Task<CommonMessage>)response;
  1026. // }
  1027. // catch (Exception)
  1028. // {
  1029. // retryCount++;
  1030. // logger.Info($"{sendTag}-{sendKey}: error,retrying... ({retryCount} / 3)");
  1031. // }
  1032. // finally
  1033. // {
  1034. // if (retryCount >= 3)
  1035. // {
  1036. // logger.Info($"{sendTag}-{sendKey}: is time out add retry 3 time");
  1037. // _tcsDictionary.TryRemove(sendKey, out _);
  1038. // }
  1039. // }
  1040. // }
  1041. // return new ErrorMessage()
  1042. // {
  1043. // IsError = true,
  1044. // TheErrorType = CommonMessage.ErrorType.TIMEOUT,
  1045. // ErrorMessage = $"{sendTag}: can not receive response after 3 retries"
  1046. // };
  1047. //}
  1048. ///// <summary>
  1049. ///// 发送消息到油机,3秒的超时,重试三次
  1050. ///// </summary>
  1051. ///// <param name="sendTag">发送的消息类型,用于日志记录</param>
  1052. ///// <param name="sendKey">发送的消息key,用于存储 TaskCompletionSource</param>
  1053. ///// <param name="requestBytes">实际发送消息</param>
  1054. ///// <returns></returns>
  1055. ///// <exception cref="TimeoutException"></exception>
  1056. //private async Task<CommonMessage> SendRequestToMachine(string sendTag,string sendKey, byte[] requestBytes)
  1057. //{
  1058. // int retryCount = 0;
  1059. // while(retryCount < 3)
  1060. // {
  1061. // try
  1062. // {
  1063. // var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
  1064. // bool isAdd = _tcsDictionary.TryAdd(sendKey, new TaskCompletionSource<CommonMessage>());
  1065. // logger.Info($"{sendTag}: add request {sendKey} to dic is {isAdd}");
  1066. // if (client != null)
  1067. // {
  1068. // client?.Client?.Send(requestBytes);
  1069. // } else
  1070. // {
  1071. // return new ErrorMessage()
  1072. // {
  1073. // IsError = true,
  1074. // TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  1075. // ErrorMessage = $"the client is disconnet"
  1076. // };
  1077. // }
  1078. // logger.Info($"send request to machine:{BitConverter.ToString(requestBytes).Replace("-", " ")}");
  1079. // TaskCompletionSource<CommonMessage>? value;
  1080. // TaskCompletionSource<CommonMessage> tcs;
  1081. // if(_tcsDictionary.TryGetValue(sendKey, out value))
  1082. // {
  1083. // tcs = value;
  1084. // } else
  1085. // {
  1086. // tcs = new TaskCompletionSource<CommonMessage>();
  1087. // }
  1088. // Task checkOutTime = Task.Delay(Timeout.Infinite, cts.Token);
  1089. // var response = await Task.WhenAny(tcs.Task, checkOutTime, checkDisConnectTask.Task);
  1090. // if(response == checkOutTime)
  1091. // {
  1092. // retryCount++;
  1093. // logger.Info($"{sendTag}-{sendKey}: time out,retrying... ({retryCount} / 3)");
  1094. // continue;
  1095. // }
  1096. // //CommonMessage response = await tcs.Task.WaitAsync(cts.Token);
  1097. // _tcsDictionary.TryRemove(sendKey, out _);
  1098. // if (response == checkDisConnectTask.Task)
  1099. // {
  1100. // return new ErrorMessage()
  1101. // {
  1102. // IsError = true,
  1103. // TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  1104. // ErrorMessage = $"the client is disconnet"
  1105. // };
  1106. // }
  1107. // return await (Task<CommonMessage>)response;
  1108. // } catch (Exception)
  1109. // {
  1110. // retryCount++;
  1111. // logger.Info($"{sendTag}-{sendKey}: error,retrying... ({retryCount} / 3)");
  1112. // } finally
  1113. // {
  1114. // if(retryCount >= 3)
  1115. // {
  1116. // logger.Info($"{sendTag}-{sendKey}: is time out add retry 3 time");
  1117. // _tcsDictionary.TryRemove(sendKey,out _);
  1118. // }
  1119. // }
  1120. // }
  1121. // return new ErrorMessage()
  1122. // {
  1123. // IsError = true,
  1124. // TheErrorType = CommonMessage.ErrorType.TIMEOUT,
  1125. // ErrorMessage = $"{sendTag}: can not receive response after 3 retries"
  1126. // };
  1127. //}
  1128. /// <summary>
  1129. /// 添加或修改订单
  1130. /// </summary>
  1131. /// <param name="order">接收到油机的订单信息</param>
  1132. /// <returns></returns>
  1133. public FccOrderInfo UpLoadOrder(OrderFromMachine order)
  1134. {
  1135. //接收到油机发送过来的订单信息
  1136. OrderFromMachine orderFromMachine = (OrderFromMachine)order;
  1137. string? oilName = MysqlDbContext.OilInfos.Where(oil => orderFromMachine.oilCode.Equals(oil.Code)).Select(oil => oil.Name).FirstOrDefault();
  1138. FccOrderInfo orderByMessage = orderFromMachine.ToComponent(oilName);
  1139. /** 根据枪号+流水号+授权时间来确定订单,因为冷启动后流水号会从头开始计算
  1140. * 后支付时直接将数据库直接插入
  1141. * 预支付时由于是云端先创建订单,发起授权响应成功后会插入数据库,响应成功时会回复授权时间,枪号,流水号
  1142. */
  1143. FccOrderInfo? fccOrderInfo = MysqlDbContext.FccOrderInfos
  1144. .Where(order =>
  1145. order.NozzleNum == orderFromMachine.nozzleNum && order.Ttc == orderFromMachine.ttc
  1146. && order.AuthorizationTime == orderFromMachine.dispenserTime)
  1147. .FirstOrDefault();
  1148. if (fccOrderInfo == null)
  1149. {
  1150. logger.Info($"receive order from machine,find order from database is null");
  1151. MysqlDbContext.FccOrderInfos.Add(orderByMessage);
  1152. MysqlDbContext.SaveChanges();
  1153. return orderByMessage;
  1154. }
  1155. else
  1156. {
  1157. logger.Info($"receive order from machine,padding data right now");
  1158. orderFromMachine.PaddingAuthorizationOrderData(fccOrderInfo);
  1159. MysqlDbContext.SaveChanges();
  1160. return fccOrderInfo;
  1161. }
  1162. }
  1163. private async void CreateTransaction(FccOrderInfo fccOrderInfo)
  1164. {
  1165. CreateTransaction createTransaction = new CreateTransaction(fccOrderInfo);
  1166. logger.Info($"create transaction, {JsonConvert.SerializeObject(createTransaction)}");
  1167. HttpResponseMessage httpResponseMessage = await httpClientUtil.CreateTransaction(JsonConvert.SerializeObject(createTransaction));
  1168. //var b = httpResponseMessage.Content;
  1169. //var a = httpResponseMessage;
  1170. string responseStr = await httpResponseMessage.Content.ReadAsStringAsync();
  1171. Response<CreateTransactionResponse>? response = JsonConvert.DeserializeObject<Response<CreateTransactionResponse>>(responseStr);
  1172. logger.Info($"reveice create transaction response:{JsonConvert.SerializeObject(response)}");
  1173. fccOrderInfo.CloundOrderId = response?.data?.Id;
  1174. fccOrderInfo.UploadState = response?.data == null ? 0 : 1;
  1175. MysqlDbContext.SaveChanges();
  1176. }
  1177. /// <summary>
  1178. /// 发送油枪状态给云端
  1179. /// </summary>
  1180. /// <param name="nozzleState"></param>
  1181. private async void SendNozzleStatus(HeartBeatMessage heartBeatMessage)
  1182. {
  1183. //提取出状态有变化的油枪,打包成要发送至云端的数据,添加到列表
  1184. List<SendNozzleStatu> sendNozzleStatus = new List<SendNozzleStatu>();
  1185. foreach (var nozzleState in heartBeatMessage.NozzleStatus)
  1186. {
  1187. if (nozzleStatusDic.TryGetValue(nozzleState.NozzleNum, out var value))
  1188. {
  1189. if (nozzleState.STATU == value) continue;
  1190. }
  1191. //保存变量
  1192. nozzleStatusDic[nozzleState.NozzleNum] = nozzleState.STATU;
  1193. //查找fcc数据库油枪id
  1194. DetailsNozzleInfoOutput? detailsNozzleInfoOutput = nozzleInfoList.Find(nozzle => nozzle.NozzleNum == nozzleState.NozzleNum);
  1195. if (detailsNozzleInfoOutput == null)
  1196. {
  1197. logger.Error($"can not find nozzleInfo from nozzleInfoList:{nozzleState.NozzleNum} ,send nozzle state fail");
  1198. continue;
  1199. }
  1200. SendNozzleStatu sendNozzleStatu = new SendNozzleStatu(detailsNozzleInfoOutput.Id, nozzleState);
  1201. sendNozzleStatus.Add(sendNozzleStatu);
  1202. }
  1203. if (sendNozzleStatus.IsNullOrEmpty()) return;
  1204. //发送云端
  1205. string reuqestJson = JsonConvert.SerializeObject(sendNozzleStatus);
  1206. logger.Info($"send nozzle state to cloud,{reuqestJson}");
  1207. try
  1208. {
  1209. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendNozzleStatu(reuqestJson);
  1210. Response<object>? response = JsonConvert.DeserializeObject<Response<object>>(await httpResponseMessage.Content.ReadAsStringAsync());
  1211. logger.Info($"reveice send nozzle state response:{JsonConvert.SerializeObject(response)}");
  1212. } catch (Exception ex)
  1213. {
  1214. logger.Error($"send nozzle stat fail:{ex.Message}");
  1215. }
  1216. }
  1217. /// <summary>
  1218. /// 获取发送帧号
  1219. /// </summary>
  1220. /// <param name="sendFrame"></param>
  1221. /// <returns></returns>
  1222. private byte getFrame(byte? sendFrame)
  1223. {
  1224. byte frameNo = 0x00;
  1225. if (sendFrame == null)
  1226. {
  1227. lock (lockFrame)
  1228. {
  1229. if (frame == 0x3f)
  1230. {
  1231. frameNo = 0x00;
  1232. }
  1233. else
  1234. {
  1235. frameNo = (byte)(frame++);
  1236. }
  1237. }
  1238. }
  1239. else
  1240. {
  1241. frameNo = sendFrame.Value;
  1242. }
  1243. return frameNo;
  1244. }
  1245. ///// <summary>
  1246. ///// 传入有效数据,拼接为要发送给油机包
  1247. ///// </summary>
  1248. ///// <param name="content"></param>
  1249. ///// <returns></returns>
  1250. //public byte[] content2data(byte[] content, byte? sendFrame)
  1251. //{
  1252. // List<byte> list = new List<byte>();
  1253. // //目标地址,源地址,帧号
  1254. // byte frameNo = 0x00;
  1255. // if (sendFrame == null)
  1256. // {
  1257. // lock (lockFrame)
  1258. // {
  1259. // if (frame == 0x3f)
  1260. // {
  1261. // frameNo = 0x00;
  1262. // }
  1263. // else
  1264. // {
  1265. // frameNo = (byte)(frame++);
  1266. // }
  1267. // }
  1268. // }
  1269. // else
  1270. // {
  1271. // frameNo = sendFrame.Value;
  1272. // }
  1273. // byte[] head = new byte[] { 0xFF, 0xE0, frameNo };
  1274. // byte[] length = Int2BCD(content.Length);
  1275. // list.AddRange(head);
  1276. // list.AddRange(length);
  1277. // list.AddRange(content);
  1278. // byte[] crc = HengshanCRC16.ComputeChecksumToBytes(list.ToArray());
  1279. // list.AddRange(crc);
  1280. // List<byte> addFAList = addFA(list);
  1281. // addFAList.Insert(0, 0xFA);
  1282. // return addFAList.ToArray();
  1283. //}
  1284. //public int Bcd2Int(byte byte1, byte byte2)
  1285. //{
  1286. // // 提取第一个字节的高四位和低四位
  1287. // int digit1 = (byte1 >> 4) & 0x0F; // 高四位
  1288. // int digit2 = byte1 & 0x0F; // 低四位
  1289. // // 提取第二个字节的高四位和低四位
  1290. // int digit3 = (byte2 >> 4) & 0x0F; // 高四位
  1291. // int digit4 = byte2 & 0x0F; // 低四位
  1292. // // 组合成一个整数
  1293. // int result = digit1 * 1000 + digit2 * 100 + digit3 * 10 + digit4;
  1294. // return result;
  1295. //}
  1296. //public byte[] Int2BCD(int number)
  1297. //{
  1298. // // 提取千位、百位、十位和个位
  1299. // int thousands = number / 1000;
  1300. // int hundreds = (number / 100) % 10;
  1301. // int tens = (number / 10) % 10;
  1302. // int units = number % 10;
  1303. // // 将千位和百位组合成一个字节(千位在高四位,百位在低四位)
  1304. // byte firstByte = (byte)((thousands * 16) + hundreds); // 乘以16相当于左移4位
  1305. // // 将十位和个位组合成一个字节(十位在高四位,个位在低四位)
  1306. // byte secondByte = (byte)((tens * 16) + units);
  1307. // // 返回结果数组
  1308. // return new byte[] { firstByte, secondByte };
  1309. //}
  1310. //public List<Byte> addFA(List<Byte> list)
  1311. //{
  1312. // List<byte> result = new List<byte>();
  1313. // foreach (byte b in list)
  1314. // {
  1315. // if (b == 0xFA)
  1316. // {
  1317. // result.Add(0xFA);
  1318. // result.Add(0xFA);
  1319. // }
  1320. // else
  1321. // {
  1322. // result.Add(b);
  1323. // }
  1324. // }
  1325. // return result;
  1326. //}
  1327. ///// <summary>
  1328. ///// 将数值转为byte[]
  1329. ///// </summary>
  1330. ///// <param name="value">数值</param>
  1331. ///// <param name="length">数组长度,不够高位补0</param>
  1332. ///// <returns></returns>
  1333. ///// <exception cref="ArgumentException"></exception>
  1334. //public static byte[] NumberToByteArrayWithPadding(int value, int length)
  1335. //{
  1336. // if (length < 0)
  1337. // {
  1338. // throw new ArgumentException("Length must be non-negative.");
  1339. // }
  1340. // // 创建一个指定长度的字节数组
  1341. // byte[] paddedBytes = new byte[length];
  1342. // // 确保是大端序
  1343. // for (int i = 0; i < length && i < 4; i++)
  1344. // {
  1345. // paddedBytes[length - 1 - i] = (byte)(value >> (i * 8));
  1346. // }
  1347. // return paddedBytes;
  1348. //}
  1349. //public static byte[] FormatDecimal(decimal value)
  1350. //{
  1351. // // 四舍五入到两位小数
  1352. // decimal roundedValue = Math.Round(value, 2, MidpointRounding.AwayFromZero);
  1353. // int valueInt = (int)(roundedValue * 100m);
  1354. // return NumberToByteArrayWithPadding(valueInt, 3); ;
  1355. //}
  1356. ///// <summary>
  1357. ///// 将时间转为 BCD
  1358. ///// </summary>
  1359. ///// <param name="dateTime"></param>
  1360. ///// <returns></returns>
  1361. //public static byte[] ConvertDateTimeToByteArray(DateTime dateTime)
  1362. //{
  1363. // // 创建byte数组
  1364. // byte[] result = new byte[7];
  1365. // // 年份处理
  1366. // int year = dateTime.Year;
  1367. // result[0] = (byte)((year / 1000) * 16 + (year / 100) % 10); // 千年和百年
  1368. // result[1] = (byte)((year / 10) % 10 * 16 + year % 10); // 十年和个年
  1369. // // 月、日、小时、分钟、秒直接转换为BCD
  1370. // result[2] = (byte)(dateTime.Month / 10 * 16 + dateTime.Month % 10);
  1371. // result[3] = (byte)(dateTime.Day / 10 * 16 + dateTime.Day % 10);
  1372. // result[4] = (byte)(dateTime.Hour / 10 * 16 + dateTime.Hour % 10);
  1373. // result[5] = (byte)(dateTime.Minute / 10 * 16 + dateTime.Minute % 10);
  1374. // result[6] = (byte)(dateTime.Second / 10 * 16 + dateTime.Second % 10);
  1375. // return result;
  1376. //}
  1377. // CRC16 constants
  1378. const ushort CRC_ORDER16 = 16;
  1379. const ushort CRC_POLYNOM16 = 0x1021;
  1380. const ushort CRC_CRCINIT16 = 0xFFFF;
  1381. const ushort CRC_CRCXOR16 = 0x0000;
  1382. const ushort CRC_MASK = 0xFFFF;
  1383. const ushort CRC_HIGHEST_BIT = (ushort)(1 << (CRC_ORDER16 - 1));
  1384. const ushort TGT_CRC_DEFAULT_INIT = 0xFFFF;
  1385. public static ushort Crc16(byte[] buffer, ushort length)
  1386. {
  1387. ushort crc_rc = TGT_CRC_DEFAULT_INIT;
  1388. for (int i = 0; i < length; i++)
  1389. {
  1390. byte c = buffer[i];
  1391. for (ushort j = 0x80; j != 0; j >>= 1)
  1392. {
  1393. ushort crc_bit = (ushort)((crc_rc & CRC_HIGHEST_BIT) != 0 ? 1 : 0);
  1394. crc_rc <<= 1;
  1395. if ((c & j) != 0)
  1396. {
  1397. crc_bit = (ushort)((crc_bit == 0) ? 1 : 0);
  1398. }
  1399. if (crc_bit != 0)
  1400. {
  1401. crc_rc ^= CRC_POLYNOM16;
  1402. }
  1403. }
  1404. }
  1405. return (ushort)((crc_rc ^ CRC_CRCXOR16) & CRC_MASK);
  1406. }
  1407. #endregion
  1408. }
  1409. public class HengshanPayTerminalHanlderGroupConfigV1
  1410. {
  1411. public string PumpIds { get; set; }
  1412. public List<PumpSubAddress> PumpSubAddresses { get; set; }
  1413. }
  1414. public class HengshanPayTerminalHanlderGroupConfigV2
  1415. {
  1416. public string PumpIds { get; set; }
  1417. public List<PumpSubAddress> PumpSubAddresses { get; set; }
  1418. public List<PumpNozzleLogicId> PumpNozzleLogicIds { get; set; }
  1419. public List<PumpSiteNozzleNo> PumpSiteNozzleNos { get; set; }
  1420. public List<NozzleLogicId> NozzleLogicIds { get; set; }
  1421. }
  1422. public class PumpSubAddress
  1423. {
  1424. public byte PumpId { get; set; }
  1425. public byte SubAddress { get; set; }
  1426. }
  1427. public class PumpNozzleLogicId
  1428. {
  1429. public byte PumpId { get; set; }
  1430. public string LogicIds { get; set; }
  1431. }
  1432. public class PumpSiteNozzleNo
  1433. {
  1434. public byte PumpId { get; set; }
  1435. public string SiteNozzleNos { get; set; }
  1436. }
  1437. public class NozzleLogicId
  1438. {
  1439. public byte NozzleNo { get; set; }
  1440. public byte LogicId { get; set; }
  1441. }
  1442. }