HengshanPayTermHandler.cs 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  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 async void GetInfo()
  594. {
  595. Edge.Core.Domain.FccStationInfo.FccStationInfo? fccStationInfo = MysqlDbContext.FccStationInfos.FirstOrDefault();
  596. if(fccStationInfo != null) stationInfo = new StationInfo(fccStationInfo);
  597. Edge.Core.Domain.FccMachineInfo.FccMachineInfo? fccMachineInfo = await MysqlDbContext.FccMachineInfos.FirstOrDefaultAsync(machine => machine.Port == serverPort);
  598. if(fccMachineInfo == null)
  599. {
  600. nozzleInfoList = new List<DetailsNozzleInfoOutput>();
  601. } else
  602. {
  603. nozzleInfoList = MysqlDbContext.NozzleInfos.Where(nozzle => nozzle.MachineId == fccMachineInfo.Id).Select(n => new DetailsNozzleInfoOutput(n)).ToList();
  604. }
  605. }
  606. /// <summary>
  607. /// 接收到MQTT
  608. /// </summary>
  609. /// <param name="message"></param>
  610. public async void OnReceiveMqttMessage(string message)
  611. {
  612. MqttRequest? mqttRequest = JsonConvert.DeserializeObject<MqttRequest>(message);
  613. if (mqttRequest == null)
  614. {
  615. logger.Error($"mqtt message turn on object fail,message:{message}");
  616. return;
  617. }
  618. switch (mqttRequest.type)
  619. {
  620. case MQTT_TYPE.AUTHORIZATION:
  621. {
  622. MqttAuthorizationRequest? mqttAuthorizationRequest = JsonConvert.DeserializeObject<MqttAuthorizationRequest>(mqttRequest.data);
  623. await SendAuthorizationAsync(mqttAuthorizationRequest);
  624. break;
  625. }
  626. case MQTT_TYPE.UNAUTHORIZATION:
  627. {
  628. MqttUnAhorizationRequest? mqttUnAhorizationRequest = JsonConvert.DeserializeObject<MqttUnAhorizationRequest>(mqttRequest.data);
  629. await SendUnAuthorizartion(mqttUnAhorizationRequest);
  630. break;
  631. }
  632. case MQTT_TYPE.PAID:
  633. {
  634. MqttPaidRequest? mqttPaidRequest = JsonConvert.DeserializeObject<MqttPaidRequest>(mqttRequest.data);
  635. await SendActuallyPaid(mqttPaidRequest);
  636. break;
  637. }
  638. case MQTT_TYPE.REFUND:
  639. {
  640. MqttRefundRequest? mqttRefundRequest = JsonConvert.DeserializeObject<MqttRefundRequest>(mqttRequest.data);
  641. await OnRecieveOrderRefund(mqttRefundRequest);
  642. break;
  643. }
  644. }
  645. }
  646. /// <summary>
  647. /// 发送二维码信息给油机
  648. /// </summary>
  649. /// <param name="tcpClient"></param>
  650. public async void SendQRCodeAsync()
  651. {
  652. string smallProgram = stationInfo?.SmallProgram ?? "";
  653. if (string.IsNullOrEmpty(smallProgram))
  654. {
  655. logger.Info($"can not get smallProgram link");
  656. return;
  657. }
  658. foreach (var item in nozzleInfoList)
  659. {
  660. //List<Byte> list = new List<Byte>();
  661. //byte[] commandAndNozzle = { 0x63, (byte)item.NozzleNum };
  662. //string qrCode = smallProgram + "/" + item.NozzleNum;
  663. //byte[] qrCodeBytes = Encoding.ASCII.GetBytes(qrCode);
  664. //list.AddRange(commandAndNozzle);
  665. //list.Add((byte)qrCodeBytes.Length);
  666. //list.AddRange(qrCodeBytes);
  667. //byte[] sendBytes = content2data(list.ToArray(), null);
  668. SendQrCode sendQrCode = new SendQrCode(item.NozzleNum, smallProgram, getFrame(null));
  669. byte[] commandAndNozzle = { sendQrCode.Handle, (byte)sendQrCode.NozzleNum };
  670. Thread.Sleep(5000);
  671. CommonMessage commonMessage = await SendMessageToMaichine($"发送{sendQrCode.NozzleNum}号枪二维码",(request,response) =>
  672. {
  673. if(response.Handle == (byte)CommonMessage.Command.COMMON)
  674. {
  675. CommonAnswerBack commonAnswerBack = (CommonAnswerBack)response;
  676. return commonAnswerBack.Command == (byte)CommonMessage.Command.SEND_QR_CODE && commonAnswerBack.NozzleNum == sendQrCode.NozzleNum;
  677. }
  678. return false;
  679. }, sendQrCode);
  680. //CommonMessage commonMessage = await SendMessageToMaichine("发送二维码", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendQrCode);
  681. //CommonMessage commonMessage = await SendRequestToMachine("发送二维码", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendBytes);
  682. if (commonMessage.IsError && commonMessage.TheErrorType == CommonMessage.ErrorType.DISCONNECT) break;
  683. }
  684. //var testAuthorization = new MqttAuthorizationRequest()
  685. //{
  686. // NozzleNum = 1,
  687. // AuthorizationTime = DateTime.Now,
  688. // AuthorizationType = 1,
  689. // Value = 3.00m
  690. //};
  691. //await SendAuthorization(testAuthorization);
  692. //var testUnAuthorization = new MqttUnAhorizationRequest()
  693. //{
  694. // NozzleNum = 1,
  695. // AuthorizationTime = DateTime.Now,
  696. // Ttc = 111
  697. //};
  698. //await SendUnAuthorizartion(testUnAuthorization);
  699. }
  700. /// <summary>
  701. /// 发送实付金额给油机
  702. /// </summary>
  703. /// <param name="orderInfo"></param>
  704. public async Task SendActuallyPaid(MqttPaidRequest? request)
  705. {
  706. if (request == null)
  707. {
  708. logger.Error($"mqtt get paid request is null");
  709. return;
  710. }
  711. //通知云端当前已收到消息
  712. OnGetPaidInfo onGetPaidInfo = new OnGetPaidInfo()
  713. {
  714. Id = request.Id,
  715. Result = 1
  716. };
  717. await httpClientUtil.SendRecievePaidNotice(JsonConvert.SerializeObject(onGetPaidInfo));
  718. FccOrderInfo? fccOrderInfo = MysqlDbContext.FccOrderInfos.FirstOrDefault(order => order.CloundOrderId == request.Id);
  719. if (fccOrderInfo == null)
  720. {
  721. logger.Error($"[mqtt paid order notice]:can not find order by clounid:{request.Id}");
  722. return;
  723. }
  724. fccOrderInfo.AmountPayable = request.ActualPaymentAmount;
  725. fccOrderInfo.PaymentTime = request.TransactionTime;
  726. fccOrderInfo.PaymentStatus = 1;
  727. MysqlDbContext.SaveChanges();
  728. //SendActuallyPaid sendActuallyPaid = new SendActuallyPaid(orderInfo.NozzleNum, orderInfo.Ttc, orderInfo.AmountPayable ?? orderInfo.Amount, getFrame(null));
  729. //byte[] commandAndNozzle = { sendActuallyPaid.Handle, (byte)sendActuallyPaid.NozzleNum };
  730. //await SendMessageToMaichine("发送实付金额", (request, response) =>
  731. //{
  732. // if (response.Handle == (byte)CommonMessage.Command.SEND_NEED_AMOUNT)
  733. // {
  734. // CommonAnswerBack commonAnswerBack = (CommonAnswerBack)response;
  735. // return commonAnswerBack.Command == (byte)CommonMessage.Command.SEND_NEED_AMOUNT && commonAnswerBack.NozzleNum == sendActuallyPaid.NozzleNum;
  736. // }
  737. // return false;
  738. //}, sendActuallyPaid);
  739. //await SendMessageToMaichine("发送实付金额", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendActuallyPaid);
  740. }
  741. /// <summary>
  742. /// 发送授权请求给油机
  743. /// </summary>
  744. /// <param name="request"></param>
  745. /// <returns></returns>
  746. public async Task SendAuthorizationAsync(MqttAuthorizationRequest? request)
  747. {
  748. if(request == null)
  749. {
  750. logger.Error($"mqtt authorization request is null");
  751. return;
  752. }
  753. //添加订单到数据库
  754. DateTime authorizationTime = request.AuthorizationTime ?? DateTime.Now;
  755. FccOrderInfo fccOrderInfo = request.ToComponent(authorizationTime);
  756. MysqlDbContext.FccOrderInfos.Add(fccOrderInfo);
  757. //发送授权申请到油机
  758. SendAuthorization sendAuthorization = new SendAuthorization((int)request.NozzleId, authorizationTime, 1,request.OriginalAmount, getFrame(null));
  759. byte[] commandAndNozzle = { sendAuthorization.Handle, (byte)sendAuthorization.NozzleNum };
  760. CommonMessage commonMessage = await SendMessageToMaichine("发送授权请求", (request, response) =>
  761. {
  762. if (response.Handle == (byte)CommonMessage.Command.ACCREDIT)
  763. {
  764. AuthorizationResponse authorization = (AuthorizationResponse)response;
  765. return authorization.NozzleNum == sendAuthorization.NozzleNum;
  766. }
  767. return false;
  768. }, sendAuthorization);
  769. //发送授权结果给云端
  770. string authorizationResultJson = string.Empty;
  771. SendAuthorizationResult sendAuthorizationResult = new SendAuthorizationResult();
  772. sendAuthorizationResult.NozzleId = request.NozzleId;
  773. if (commonMessage.IsError)
  774. {
  775. ErrorMessage errorMessage = (ErrorMessage)commonMessage;
  776. switch (errorMessage.TheErrorType)
  777. {
  778. case CommonMessage.ErrorType.DISCONNECT:
  779. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.Disconnected;
  780. break;
  781. case CommonMessage.ErrorType.TIMEOUT:
  782. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.AuthorizationTimeout;
  783. break;
  784. }
  785. }
  786. else
  787. {
  788. AuthorizationResponse authorization = (AuthorizationResponse)commonMessage;
  789. if (authorization.Result == 0)
  790. {
  791. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.Failed;
  792. }
  793. else
  794. {
  795. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  796. sendAuthorizationResult.TransactionNumber = authorization.Ttc.ToString();
  797. fccOrderInfo.Ttc = authorization.Result;
  798. }
  799. }
  800. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendAuthorizationResult(JsonConvert.SerializeObject(sendAuthorizationResult));
  801. logger.Info($"send authorization result response:{JsonConvert.SerializeObject(httpResponseMessage.Content)}");
  802. //更新订单
  803. MysqlDbContext.SaveChanges();
  804. }
  805. /// <summary>
  806. /// 发送取消授权请求给油机
  807. /// </summary>
  808. /// <param name="request"></param>
  809. public async Task SendUnAuthorizartion(MqttUnAhorizationRequest? request)
  810. {
  811. if (request == null)
  812. {
  813. logger.Error($"mqtt unauthorization request is null");
  814. return;
  815. }
  816. //从请求信息中获取流水号与授权时间,没有就到数据库查找
  817. int ttc = 0;
  818. DateTime authorizationTime = request.AuthorizationTime ?? DateTime.Now;
  819. bool ttsIntResult = int.TryParse(request.TransactionNumber, out ttc);
  820. if (request.AuthorizationTime == null || !ttsIntResult)
  821. {
  822. FccOrderInfo? fccOrderInfo = MysqlDbContext.FccOrderInfos.FirstOrDefault(order => order.CloundOrderId == request.Id);
  823. if(fccOrderInfo != null)
  824. {
  825. ttc = fccOrderInfo.Ttc;
  826. authorizationTime = fccOrderInfo.AuthorizationTime;
  827. }
  828. }
  829. SendUnAuthorizationResult sendUnAuthorizationResult = new SendUnAuthorizationResult();
  830. sendUnAuthorizationResult.NozzleId = request.NozzleId;
  831. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  832. if (ttc != 0)
  833. {
  834. SendUnAuthorization sendUnAuthorization = new SendUnAuthorization((int)request.NozzleId, authorizationTime, ttc, getFrame(null));
  835. byte[] commandAndNozzle = { sendUnAuthorization.Handle, (byte)sendUnAuthorization.NozzleNum };
  836. CommonMessage commonMessage = await SendMessageToMaichine("发送取消授权请求", (request, response) =>
  837. {
  838. if (response.Handle == (byte)CommonMessage.Command.CANCEL_ACCREDIT)
  839. {
  840. UnAhorizationResponse unauthorization = (UnAhorizationResponse)response;
  841. return unauthorization.NozzleNum == sendUnAuthorization.NozzleNum;
  842. }
  843. return false;
  844. }, sendUnAuthorization);
  845. if (commonMessage.IsError)
  846. {
  847. ErrorMessage errorMessage = (ErrorMessage)commonMessage;
  848. switch (errorMessage.TheErrorType)
  849. {
  850. case CommonMessage.ErrorType.DISCONNECT:
  851. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Disconnected;
  852. break;
  853. case CommonMessage.ErrorType.TIMEOUT:
  854. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.AuthorizationTimeout;
  855. break;
  856. }
  857. }
  858. else
  859. {
  860. UnAhorizationResponse unAuthorization = (UnAhorizationResponse)commonMessage;
  861. if (unAuthorization.Result == 0)
  862. {
  863. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Failed;
  864. }
  865. else
  866. {
  867. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  868. }
  869. }
  870. }
  871. else
  872. {
  873. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.TransactionNumberNotFound;
  874. }
  875. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendUnAuthorizationResult(JsonConvert.SerializeObject(sendUnAuthorizationResult));
  876. logger.Info($"send Unauthorization result response:{JsonConvert.SerializeObject(httpResponseMessage.Content)}");
  877. }
  878. /// <summary>
  879. /// 接收到云端发送订单退款信息
  880. /// </summary>
  881. /// <param name="request"></param>
  882. /// <returns></returns>
  883. private async Task OnRecieveOrderRefund(MqttRefundRequest? request)
  884. {
  885. if (request == null)
  886. {
  887. logger.Error($"mqtt OnRecieveOrderRefund request is null");
  888. return;
  889. }
  890. //通知云端当前已收到消息
  891. OnGetRefundInfo onGetRefundInfo = new OnGetRefundInfo()
  892. {
  893. Id = request.Id,
  894. Result = 1
  895. };
  896. await httpClientUtil.SendRecieveRefundNotice(JsonConvert.SerializeObject(onGetRefundInfo));
  897. FccOrderInfo? fccOrderInfo = MysqlDbContext.FccOrderInfos.FirstOrDefault(order => order.CloundOrderId == request.Id);
  898. if (fccOrderInfo == null)
  899. {
  900. logger.Error($"[mqtt refund order notice]:can not find order by clounid:{request.Id}");
  901. return;
  902. }
  903. fccOrderInfo.AmountPayable = request.ActualPaymentAmount;
  904. fccOrderInfo.PaymentStatus = 2;
  905. MysqlDbContext.SaveChanges();
  906. }
  907. //public void SetTcpClient(TcpClient? tcpClient, int? serverPort)
  908. //{
  909. // this.client = tcpClient;
  910. // this.serverPort = serverPort;
  911. // checkDisConnectTask = new TaskCompletionSource<ErrorMessage>();
  912. //}
  913. //public void OnTcpDisconnect()
  914. //{
  915. // this.client = null;
  916. // ErrorMessage errorMessage = new ErrorMessage()
  917. // {
  918. // IsError = true,
  919. // TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  920. // ErrorMessage = $"the client is disconnet"
  921. // };
  922. // checkDisConnectTask.SetResult(errorMessage);
  923. //}
  924. /// <summary>
  925. /// 发送消息到油机,3秒的超时,重试三次
  926. /// </summary>
  927. /// <param name="sendTag">发送的消息类型,用于日志记录</param>
  928. /// <param name="sendKey">发送的消息key,用于存储 TaskCompletionSource</param>
  929. /// <param name="requestBytes">实际发送消息</param>
  930. /// <returns></returns>
  931. private async Task<CommonMessage> SendMessageToMaichine(string sendTag, Func<CommonMessage, CommonMessage, bool> responseCapture,CommonMessage sendMessage)
  932. {
  933. int retryCount = 0;
  934. while (retryCount < 3)
  935. {
  936. try
  937. {
  938. var response = await this.Context.Outgoing.WriteAsyncAndCheckIsConnect(sendMessage, responseCapture, 3000);
  939. //超时重试
  940. if (response.ResponseType == WriteResponseType.TIME_OUT || response.Data == null)
  941. {
  942. retryCount++;
  943. logger.Info($"{sendTag}: time out,retrying... ({retryCount} / 3)");
  944. continue;
  945. }
  946. //链接断开不再发送
  947. if (response.ResponseType == WriteResponseType.DISCONNECT)
  948. {
  949. var isConnect = (bool)(response.Data ?? false);
  950. if (!isConnect) return new ErrorMessage()
  951. {
  952. IsError = true,
  953. TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  954. ErrorMessage = $"the client is disconnet"
  955. };
  956. }
  957. Console.WriteLine("");
  958. //返回信息
  959. return (CommonMessage)response.Data;
  960. }
  961. catch (Exception)
  962. {
  963. retryCount++;
  964. logger.Info($"{sendTag}: error,retrying... ({retryCount} / 3)");
  965. }
  966. finally
  967. {
  968. if (retryCount >= 3)
  969. {
  970. logger.Info($"{sendTag}: is time out add retry 3 time");
  971. }
  972. }
  973. }
  974. return new ErrorMessage()
  975. {
  976. IsError = true,
  977. TheErrorType = CommonMessage.ErrorType.TIMEOUT,
  978. ErrorMessage = $"{sendTag}: can not receive response after 3 retries"
  979. };
  980. }
  981. ///// <summary>
  982. ///// 发送消息到油机,3秒的超时,重试三次
  983. ///// </summary>
  984. ///// <param name="sendTag">发送的消息类型,用于日志记录</param>
  985. ///// <param name="sendKey">发送的消息key,用于存储 TaskCompletionSource</param>
  986. ///// <param name="requestBytes">实际发送消息</param>
  987. ///// <returns></returns>
  988. //private async Task<CommonMessage> SendMessageToMaichine(string sendTag, string sendKey,CommonMessage sendMessage)
  989. //{
  990. // int retryCount = 0;
  991. // while (retryCount < 3)
  992. // {
  993. // try
  994. // {
  995. // var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
  996. // bool isAdd = _tcsDictionary.TryAdd(sendKey, new TaskCompletionSource<CommonMessage>());
  997. // logger.Info($"{sendTag}: add request {sendKey} to dic is {isAdd}");
  998. // Write(sendMessage);
  999. // TaskCompletionSource<CommonMessage>? value;
  1000. // TaskCompletionSource<CommonMessage> tcs;
  1001. // if (_tcsDictionary.TryGetValue(sendKey, out value))
  1002. // {
  1003. // tcs = value;
  1004. // }
  1005. // else
  1006. // {
  1007. // tcs = new TaskCompletionSource<CommonMessage>();
  1008. // }
  1009. // Task checkOutTime = Task.Delay(Timeout.Infinite, cts.Token);
  1010. // var response = await Task.WhenAny(tcs.Task, checkOutTime, checkDisConnectTask.Task);
  1011. // //超时重试
  1012. // if (response == checkOutTime)
  1013. // {
  1014. // retryCount++;
  1015. // logger.Info($"{sendTag}-{sendKey}: time out,retrying... ({retryCount} / 3)");
  1016. // continue;
  1017. // }
  1018. // //CommonMessage response = await tcs.Task.WaitAsync(cts.Token);
  1019. // _tcsDictionary.TryRemove(sendKey, out _);
  1020. // //链接断开不再发送
  1021. // if(response == checkDisConnectTask.Task)
  1022. // {
  1023. // return new ErrorMessage()
  1024. // {
  1025. // IsError = true,
  1026. // TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  1027. // ErrorMessage = $"the client is disconnet"
  1028. // };
  1029. // }
  1030. // //返回信息
  1031. // return await (Task<CommonMessage>)response;
  1032. // }
  1033. // catch (Exception)
  1034. // {
  1035. // retryCount++;
  1036. // logger.Info($"{sendTag}-{sendKey}: error,retrying... ({retryCount} / 3)");
  1037. // }
  1038. // finally
  1039. // {
  1040. // if (retryCount >= 3)
  1041. // {
  1042. // logger.Info($"{sendTag}-{sendKey}: is time out add retry 3 time");
  1043. // _tcsDictionary.TryRemove(sendKey, out _);
  1044. // }
  1045. // }
  1046. // }
  1047. // return new ErrorMessage()
  1048. // {
  1049. // IsError = true,
  1050. // TheErrorType = CommonMessage.ErrorType.TIMEOUT,
  1051. // ErrorMessage = $"{sendTag}: can not receive response after 3 retries"
  1052. // };
  1053. //}
  1054. ///// <summary>
  1055. ///// 发送消息到油机,3秒的超时,重试三次
  1056. ///// </summary>
  1057. ///// <param name="sendTag">发送的消息类型,用于日志记录</param>
  1058. ///// <param name="sendKey">发送的消息key,用于存储 TaskCompletionSource</param>
  1059. ///// <param name="requestBytes">实际发送消息</param>
  1060. ///// <returns></returns>
  1061. ///// <exception cref="TimeoutException"></exception>
  1062. //private async Task<CommonMessage> SendRequestToMachine(string sendTag,string sendKey, byte[] requestBytes)
  1063. //{
  1064. // int retryCount = 0;
  1065. // while(retryCount < 3)
  1066. // {
  1067. // try
  1068. // {
  1069. // var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
  1070. // bool isAdd = _tcsDictionary.TryAdd(sendKey, new TaskCompletionSource<CommonMessage>());
  1071. // logger.Info($"{sendTag}: add request {sendKey} to dic is {isAdd}");
  1072. // if (client != null)
  1073. // {
  1074. // client?.Client?.Send(requestBytes);
  1075. // } else
  1076. // {
  1077. // return new ErrorMessage()
  1078. // {
  1079. // IsError = true,
  1080. // TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  1081. // ErrorMessage = $"the client is disconnet"
  1082. // };
  1083. // }
  1084. // logger.Info($"send request to machine:{BitConverter.ToString(requestBytes).Replace("-", " ")}");
  1085. // TaskCompletionSource<CommonMessage>? value;
  1086. // TaskCompletionSource<CommonMessage> tcs;
  1087. // if(_tcsDictionary.TryGetValue(sendKey, out value))
  1088. // {
  1089. // tcs = value;
  1090. // } else
  1091. // {
  1092. // tcs = new TaskCompletionSource<CommonMessage>();
  1093. // }
  1094. // Task checkOutTime = Task.Delay(Timeout.Infinite, cts.Token);
  1095. // var response = await Task.WhenAny(tcs.Task, checkOutTime, checkDisConnectTask.Task);
  1096. // if(response == checkOutTime)
  1097. // {
  1098. // retryCount++;
  1099. // logger.Info($"{sendTag}-{sendKey}: time out,retrying... ({retryCount} / 3)");
  1100. // continue;
  1101. // }
  1102. // //CommonMessage response = await tcs.Task.WaitAsync(cts.Token);
  1103. // _tcsDictionary.TryRemove(sendKey, out _);
  1104. // if (response == checkDisConnectTask.Task)
  1105. // {
  1106. // return new ErrorMessage()
  1107. // {
  1108. // IsError = true,
  1109. // TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  1110. // ErrorMessage = $"the client is disconnet"
  1111. // };
  1112. // }
  1113. // return await (Task<CommonMessage>)response;
  1114. // } catch (Exception)
  1115. // {
  1116. // retryCount++;
  1117. // logger.Info($"{sendTag}-{sendKey}: error,retrying... ({retryCount} / 3)");
  1118. // } finally
  1119. // {
  1120. // if(retryCount >= 3)
  1121. // {
  1122. // logger.Info($"{sendTag}-{sendKey}: is time out add retry 3 time");
  1123. // _tcsDictionary.TryRemove(sendKey,out _);
  1124. // }
  1125. // }
  1126. // }
  1127. // return new ErrorMessage()
  1128. // {
  1129. // IsError = true,
  1130. // TheErrorType = CommonMessage.ErrorType.TIMEOUT,
  1131. // ErrorMessage = $"{sendTag}: can not receive response after 3 retries"
  1132. // };
  1133. //}
  1134. /// <summary>
  1135. /// 添加或修改订单
  1136. /// </summary>
  1137. /// <param name="order">接收到油机的订单信息</param>
  1138. /// <returns></returns>
  1139. public FccOrderInfo UpLoadOrder(OrderFromMachine order)
  1140. {
  1141. //接收到油机发送过来的订单信息
  1142. OrderFromMachine orderFromMachine = (OrderFromMachine)order;
  1143. string? oilName = MysqlDbContext.OilInfos.Where(oil => orderFromMachine.oilCode.Equals(oil.Code)).Select(oil => oil.Name).FirstOrDefault();
  1144. FccOrderInfo orderByMessage = orderFromMachine.ToComponent(oilName);
  1145. /** 根据枪号+流水号+授权时间来确定订单,因为冷启动后流水号会从头开始计算
  1146. * 后支付时直接将数据库直接插入
  1147. * 预支付时由于是云端先创建订单,发起授权响应成功后会插入数据库,响应成功时会回复授权时间,枪号,流水号
  1148. */
  1149. FccOrderInfo? fccOrderInfo = MysqlDbContext.FccOrderInfos
  1150. .Where(order =>
  1151. order.NozzleNum == orderFromMachine.nozzleNum && order.Ttc == orderFromMachine.ttc
  1152. && order.AuthorizationTime == orderFromMachine.dispenserTime)
  1153. .FirstOrDefault();
  1154. if (fccOrderInfo == null)
  1155. {
  1156. logger.Info($"receive order from machine,find order from database is null");
  1157. MysqlDbContext.FccOrderInfos.Add(orderByMessage);
  1158. MysqlDbContext.SaveChanges();
  1159. return orderByMessage;
  1160. }
  1161. else
  1162. {
  1163. logger.Info($"receive order from machine,padding data right now");
  1164. orderFromMachine.PaddingAuthorizationOrderData(fccOrderInfo);
  1165. MysqlDbContext.SaveChanges();
  1166. return fccOrderInfo;
  1167. }
  1168. }
  1169. private async void CreateTransaction(FccOrderInfo fccOrderInfo)
  1170. {
  1171. CreateTransaction createTransaction = new CreateTransaction(fccOrderInfo);
  1172. logger.Info($"create transaction, {JsonConvert.SerializeObject(createTransaction)}");
  1173. HttpResponseMessage httpResponseMessage = await httpClientUtil.CreateTransaction(JsonConvert.SerializeObject(createTransaction));
  1174. //var b = httpResponseMessage.Content;
  1175. //var a = httpResponseMessage;
  1176. string responseStr = await httpResponseMessage.Content.ReadAsStringAsync();
  1177. Response<CreateTransactionResponse>? response = JsonConvert.DeserializeObject<Response<CreateTransactionResponse>>(responseStr);
  1178. logger.Info($"reveice create transaction response:{JsonConvert.SerializeObject(response)}");
  1179. fccOrderInfo.CloundOrderId = response?.data?.Id;
  1180. fccOrderInfo.UploadState = response?.data == null ? 0 : 1;
  1181. MysqlDbContext.SaveChanges();
  1182. }
  1183. /// <summary>
  1184. /// 发送油枪状态给云端
  1185. /// </summary>
  1186. /// <param name="nozzleState"></param>
  1187. private async void SendNozzleStatus(HeartBeatMessage heartBeatMessage)
  1188. {
  1189. //提取出状态有变化的油枪,打包成要发送至云端的数据,添加到列表
  1190. List<SendNozzleStatu> sendNozzleStatus = new List<SendNozzleStatu>();
  1191. foreach (var nozzleState in heartBeatMessage.NozzleStatus)
  1192. {
  1193. if (nozzleStatusDic.TryGetValue(nozzleState.NozzleNum, out var value))
  1194. {
  1195. if (nozzleState.STATU == value) continue;
  1196. }
  1197. //保存变量
  1198. nozzleStatusDic[nozzleState.NozzleNum] = nozzleState.STATU;
  1199. //查找fcc数据库油枪id
  1200. DetailsNozzleInfoOutput? detailsNozzleInfoOutput = nozzleInfoList.Find(nozzle => nozzle.NozzleNum == nozzleState.NozzleNum);
  1201. if (detailsNozzleInfoOutput == null)
  1202. {
  1203. logger.Error($"can not find nozzleInfo from nozzleInfoList:{nozzleState.NozzleNum} ,send nozzle state fail");
  1204. continue;
  1205. }
  1206. SendNozzleStatu sendNozzleStatu = new SendNozzleStatu(detailsNozzleInfoOutput.Id, nozzleState);
  1207. sendNozzleStatus.Add(sendNozzleStatu);
  1208. }
  1209. if (sendNozzleStatus.IsNullOrEmpty()) return;
  1210. //发送云端
  1211. string reuqestJson = JsonConvert.SerializeObject(sendNozzleStatus);
  1212. logger.Info($"send nozzle state to cloud,{reuqestJson}");
  1213. try
  1214. {
  1215. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendNozzleStatu(reuqestJson);
  1216. Response<object>? response = JsonConvert.DeserializeObject<Response<object>>(await httpResponseMessage.Content.ReadAsStringAsync());
  1217. logger.Info($"reveice send nozzle state response:{JsonConvert.SerializeObject(response)}");
  1218. } catch (Exception ex)
  1219. {
  1220. logger.Error($"send nozzle stat fail:{ex.Message}");
  1221. }
  1222. }
  1223. /// <summary>
  1224. /// 获取发送帧号
  1225. /// </summary>
  1226. /// <param name="sendFrame"></param>
  1227. /// <returns></returns>
  1228. private byte getFrame(byte? sendFrame)
  1229. {
  1230. byte frameNo = 0x00;
  1231. if (sendFrame == null)
  1232. {
  1233. lock (lockFrame)
  1234. {
  1235. if (frame == 0x3f)
  1236. {
  1237. frameNo = 0x00;
  1238. }
  1239. else
  1240. {
  1241. frameNo = (byte)(frame++);
  1242. }
  1243. }
  1244. }
  1245. else
  1246. {
  1247. frameNo = sendFrame.Value;
  1248. }
  1249. return frameNo;
  1250. }
  1251. ///// <summary>
  1252. ///// 传入有效数据,拼接为要发送给油机包
  1253. ///// </summary>
  1254. ///// <param name="content"></param>
  1255. ///// <returns></returns>
  1256. //public byte[] content2data(byte[] content, byte? sendFrame)
  1257. //{
  1258. // List<byte> list = new List<byte>();
  1259. // //目标地址,源地址,帧号
  1260. // byte frameNo = 0x00;
  1261. // if (sendFrame == null)
  1262. // {
  1263. // lock (lockFrame)
  1264. // {
  1265. // if (frame == 0x3f)
  1266. // {
  1267. // frameNo = 0x00;
  1268. // }
  1269. // else
  1270. // {
  1271. // frameNo = (byte)(frame++);
  1272. // }
  1273. // }
  1274. // }
  1275. // else
  1276. // {
  1277. // frameNo = sendFrame.Value;
  1278. // }
  1279. // byte[] head = new byte[] { 0xFF, 0xE0, frameNo };
  1280. // byte[] length = Int2BCD(content.Length);
  1281. // list.AddRange(head);
  1282. // list.AddRange(length);
  1283. // list.AddRange(content);
  1284. // byte[] crc = HengshanCRC16.ComputeChecksumToBytes(list.ToArray());
  1285. // list.AddRange(crc);
  1286. // List<byte> addFAList = addFA(list);
  1287. // addFAList.Insert(0, 0xFA);
  1288. // return addFAList.ToArray();
  1289. //}
  1290. //public int Bcd2Int(byte byte1, byte byte2)
  1291. //{
  1292. // // 提取第一个字节的高四位和低四位
  1293. // int digit1 = (byte1 >> 4) & 0x0F; // 高四位
  1294. // int digit2 = byte1 & 0x0F; // 低四位
  1295. // // 提取第二个字节的高四位和低四位
  1296. // int digit3 = (byte2 >> 4) & 0x0F; // 高四位
  1297. // int digit4 = byte2 & 0x0F; // 低四位
  1298. // // 组合成一个整数
  1299. // int result = digit1 * 1000 + digit2 * 100 + digit3 * 10 + digit4;
  1300. // return result;
  1301. //}
  1302. //public byte[] Int2BCD(int number)
  1303. //{
  1304. // // 提取千位、百位、十位和个位
  1305. // int thousands = number / 1000;
  1306. // int hundreds = (number / 100) % 10;
  1307. // int tens = (number / 10) % 10;
  1308. // int units = number % 10;
  1309. // // 将千位和百位组合成一个字节(千位在高四位,百位在低四位)
  1310. // byte firstByte = (byte)((thousands * 16) + hundreds); // 乘以16相当于左移4位
  1311. // // 将十位和个位组合成一个字节(十位在高四位,个位在低四位)
  1312. // byte secondByte = (byte)((tens * 16) + units);
  1313. // // 返回结果数组
  1314. // return new byte[] { firstByte, secondByte };
  1315. //}
  1316. //public List<Byte> addFA(List<Byte> list)
  1317. //{
  1318. // List<byte> result = new List<byte>();
  1319. // foreach (byte b in list)
  1320. // {
  1321. // if (b == 0xFA)
  1322. // {
  1323. // result.Add(0xFA);
  1324. // result.Add(0xFA);
  1325. // }
  1326. // else
  1327. // {
  1328. // result.Add(b);
  1329. // }
  1330. // }
  1331. // return result;
  1332. //}
  1333. ///// <summary>
  1334. ///// 将数值转为byte[]
  1335. ///// </summary>
  1336. ///// <param name="value">数值</param>
  1337. ///// <param name="length">数组长度,不够高位补0</param>
  1338. ///// <returns></returns>
  1339. ///// <exception cref="ArgumentException"></exception>
  1340. //public static byte[] NumberToByteArrayWithPadding(int value, int length)
  1341. //{
  1342. // if (length < 0)
  1343. // {
  1344. // throw new ArgumentException("Length must be non-negative.");
  1345. // }
  1346. // // 创建一个指定长度的字节数组
  1347. // byte[] paddedBytes = new byte[length];
  1348. // // 确保是大端序
  1349. // for (int i = 0; i < length && i < 4; i++)
  1350. // {
  1351. // paddedBytes[length - 1 - i] = (byte)(value >> (i * 8));
  1352. // }
  1353. // return paddedBytes;
  1354. //}
  1355. //public static byte[] FormatDecimal(decimal value)
  1356. //{
  1357. // // 四舍五入到两位小数
  1358. // decimal roundedValue = Math.Round(value, 2, MidpointRounding.AwayFromZero);
  1359. // int valueInt = (int)(roundedValue * 100m);
  1360. // return NumberToByteArrayWithPadding(valueInt, 3); ;
  1361. //}
  1362. ///// <summary>
  1363. ///// 将时间转为 BCD
  1364. ///// </summary>
  1365. ///// <param name="dateTime"></param>
  1366. ///// <returns></returns>
  1367. //public static byte[] ConvertDateTimeToByteArray(DateTime dateTime)
  1368. //{
  1369. // // 创建byte数组
  1370. // byte[] result = new byte[7];
  1371. // // 年份处理
  1372. // int year = dateTime.Year;
  1373. // result[0] = (byte)((year / 1000) * 16 + (year / 100) % 10); // 千年和百年
  1374. // result[1] = (byte)((year / 10) % 10 * 16 + year % 10); // 十年和个年
  1375. // // 月、日、小时、分钟、秒直接转换为BCD
  1376. // result[2] = (byte)(dateTime.Month / 10 * 16 + dateTime.Month % 10);
  1377. // result[3] = (byte)(dateTime.Day / 10 * 16 + dateTime.Day % 10);
  1378. // result[4] = (byte)(dateTime.Hour / 10 * 16 + dateTime.Hour % 10);
  1379. // result[5] = (byte)(dateTime.Minute / 10 * 16 + dateTime.Minute % 10);
  1380. // result[6] = (byte)(dateTime.Second / 10 * 16 + dateTime.Second % 10);
  1381. // return result;
  1382. //}
  1383. // CRC16 constants
  1384. const ushort CRC_ORDER16 = 16;
  1385. const ushort CRC_POLYNOM16 = 0x1021;
  1386. const ushort CRC_CRCINIT16 = 0xFFFF;
  1387. const ushort CRC_CRCXOR16 = 0x0000;
  1388. const ushort CRC_MASK = 0xFFFF;
  1389. const ushort CRC_HIGHEST_BIT = (ushort)(1 << (CRC_ORDER16 - 1));
  1390. const ushort TGT_CRC_DEFAULT_INIT = 0xFFFF;
  1391. public static ushort Crc16(byte[] buffer, ushort length)
  1392. {
  1393. ushort crc_rc = TGT_CRC_DEFAULT_INIT;
  1394. for (int i = 0; i < length; i++)
  1395. {
  1396. byte c = buffer[i];
  1397. for (ushort j = 0x80; j != 0; j >>= 1)
  1398. {
  1399. ushort crc_bit = (ushort)((crc_rc & CRC_HIGHEST_BIT) != 0 ? 1 : 0);
  1400. crc_rc <<= 1;
  1401. if ((c & j) != 0)
  1402. {
  1403. crc_bit = (ushort)((crc_bit == 0) ? 1 : 0);
  1404. }
  1405. if (crc_bit != 0)
  1406. {
  1407. crc_rc ^= CRC_POLYNOM16;
  1408. }
  1409. }
  1410. }
  1411. return (ushort)((crc_rc ^ CRC_CRCXOR16) & CRC_MASK);
  1412. }
  1413. #endregion
  1414. }
  1415. public class HengshanPayTerminalHanlderGroupConfigV1
  1416. {
  1417. public string PumpIds { get; set; }
  1418. public List<PumpSubAddress> PumpSubAddresses { get; set; }
  1419. }
  1420. public class HengshanPayTerminalHanlderGroupConfigV2
  1421. {
  1422. public string PumpIds { get; set; }
  1423. public List<PumpSubAddress> PumpSubAddresses { get; set; }
  1424. public List<PumpNozzleLogicId> PumpNozzleLogicIds { get; set; }
  1425. public List<PumpSiteNozzleNo> PumpSiteNozzleNos { get; set; }
  1426. public List<NozzleLogicId> NozzleLogicIds { get; set; }
  1427. }
  1428. public class PumpSubAddress
  1429. {
  1430. public byte PumpId { get; set; }
  1431. public byte SubAddress { get; set; }
  1432. }
  1433. public class PumpNozzleLogicId
  1434. {
  1435. public byte PumpId { get; set; }
  1436. public string LogicIds { get; set; }
  1437. }
  1438. public class PumpSiteNozzleNo
  1439. {
  1440. public byte PumpId { get; set; }
  1441. public string SiteNozzleNos { get; set; }
  1442. }
  1443. public class NozzleLogicId
  1444. {
  1445. public byte NozzleNo { get; set; }
  1446. public byte LogicId { get; set; }
  1447. }
  1448. }