HengshanPayTermHandler.cs 68 KB

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