HengshanPayTermHandler.cs 77 KB

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