HengshanPayTermHandler.cs 75 KB

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