HengshanPayTermHandler.cs 66 KB

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