HengshanPayTermHandler.cs 68 KB

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