HengshanPayTermHandler.cs 68 KB

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