HengshanPayTermHandler.cs 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  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. }
  382. }
  383. public string CommIdentity { get; private set; }
  384. public async Task Process(IContext<byte[], CommonMessage> context)
  385. {
  386. logger.Info($"获取到信息:{JsonConvert.SerializeObject(context.Incoming.Message)}");
  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. logger.Info($"订单信息");
  402. OrderFromMachine orderFromMachine = (OrderFromMachine)context.Incoming.Message;
  403. if(nozzlePumpCode.TryGetValue(orderFromMachine.nozzleNum, out string pumpCodeAndTTC))
  404. {
  405. if($"{orderFromMachine.pumpCode}_{orderFromMachine.ttc}".Equals(pumpCodeAndTTC))
  406. {
  407. logger.Info($"收到油机订单,泵码与流水号一致,为重复发送");
  408. return;
  409. }
  410. }
  411. logger.Info($"收到油机订单,泵码与流水号不一致,更新信息");
  412. nozzlePumpCode[orderFromMachine.nozzleNum] = $"{orderFromMachine.pumpCode}_{orderFromMachine.ttc}";
  413. FccOrderInfo fccOrderInfo = UpLoadOrder(orderFromMachine);
  414. logger.Info($"receive order from machine,database had change");
  415. CreateOrRedeemTransaction(fccOrderInfo);
  416. break;
  417. }
  418. /**
  419. //普通应答
  420. case 0x55:
  421. {
  422. CommonAnswerBack commonAnswerBack = (CommonAnswerBack)context.Incoming.Message;
  423. if (commonAnswerBack.Command == 0x63) //二维码回复
  424. {
  425. byte[] keyBytes = { commonAnswerBack.Command, (byte)commonAnswerBack.NozzleNum };
  426. var key = BitConverter.ToString(keyBytes).Replace("-", "");
  427. if (_tcsDictionary.TryGetValue(key, out var value))
  428. {
  429. value.SetResult(commonAnswerBack);
  430. }
  431. else
  432. {
  433. logger.Info($"qrcode response:can not get tcs for dictionary");
  434. }
  435. }
  436. break;
  437. }
  438. // 授权回复
  439. case 0x65:
  440. {
  441. AuthorizationResponse authorizationResponse = (AuthorizationResponse)context.Incoming.Message;
  442. byte[] keyBytes = { authorizationResponse.Handle, (byte)authorizationResponse.NozzleNum };
  443. var key = BitConverter.ToString(keyBytes).Replace("-", "");
  444. if (_tcsDictionary.TryGetValue(key, out var value))
  445. {
  446. value.SetResult(authorizationResponse);
  447. }
  448. else
  449. {
  450. logger.Info($"authorization response:can not get tcs for dictionary");
  451. }
  452. break;
  453. }
  454. // 取消授权回复
  455. case 0x66:
  456. {
  457. UnAhorizationResponse unauthorizationResponse = (UnAhorizationResponse)context.Incoming.Message;
  458. byte[] keyBytes = { unauthorizationResponse.Handle, (byte)unauthorizationResponse.NozzleNum };
  459. var key = BitConverter.ToString(keyBytes).Replace("-", "");
  460. if (_tcsDictionary.TryGetValue(key, out var value))
  461. {
  462. value.SetResult(unauthorizationResponse);
  463. }
  464. else
  465. {
  466. logger.Info($"unauthorization response:can not get tcs for dictionary");
  467. }
  468. break;
  469. }
  470. */
  471. }
  472. //油机的应答不用回复
  473. if (context.Incoming.Message.Handle != 0x55 && isSendHeart) context.Outgoing.Write(context.Incoming.Message);
  474. }
  475. private void CheckStatus(CheckCmdRequest request)
  476. {
  477. if (!statusDict.ContainsKey(request.FuelingPoint.PumpNo))
  478. {
  479. var result = statusDict.TryAdd(request.FuelingPoint.PumpNo,
  480. new PumpStateHolder
  481. {
  482. PumpNo = request.FuelingPoint.PumpNo,
  483. NozzleNo = 1,
  484. State = request,
  485. OperationType = LockUnlockOperation.None
  486. });
  487. logger.Info($"Adding FuelingPoint {request.FuelingPoint.PumpNo} to dict");
  488. if (!result)
  489. {
  490. statusDict.TryAdd(request.FuelingPoint.PumpNo, null);
  491. }
  492. }
  493. else
  494. {
  495. PumpStateHolder stateHolder = null;
  496. statusDict.TryGetValue(request.FuelingPoint.PumpNo, out stateHolder);
  497. if (stateHolder != null)
  498. {
  499. logger.Debug($"State holder, PumpNo: {stateHolder.PumpNo}, dispenser state: {stateHolder.State.DispenserState}, " +
  500. $"operation: {stateHolder.OperationType}");
  501. }
  502. if (stateHolder != null && stateHolder.OperationType != LockUnlockOperation.None)
  503. {
  504. logger.Debug($"PumpNo: {request.FuelingPoint.PumpNo}, Last Dispenser State: {stateHolder.State.DispenserState}, " +
  505. $"Current Dispenser State: {request.DispenserState}");
  506. if (stateHolder.State.DispenserState == 3 && request.DispenserState == 2)
  507. {
  508. //Pump is locked due to lock operation
  509. if (stateHolder.OperationType != LockUnlockOperation.None)
  510. {
  511. logger.Info("Locking done!");
  512. stateHolder.State = request; //Update the state
  513. OnLockUnlockCompleted?.Invoke(this, new LockUnlockEventArgs(stateHolder.OperationType, true));
  514. }
  515. }
  516. else if (stateHolder.State.DispenserState == 2 && request.DispenserState == 3)
  517. {
  518. //Pump is unlocked due to unlock operation
  519. if (stateHolder.OperationType != LockUnlockOperation.None)
  520. {
  521. logger.Info($"Unlocking done!");
  522. stateHolder.State = request; //Update the state
  523. OnLockUnlockCompleted?.Invoke(this, new LockUnlockEventArgs(stateHolder.OperationType, true));
  524. }
  525. }
  526. }
  527. else if (stateHolder != null && stateHolder.OperationType == LockUnlockOperation.None)
  528. {
  529. if (stateHolder.State.DispenserState != request.DispenserState)
  530. {
  531. logger.Warn($"Observed a pump state change, {stateHolder.State.DispenserState} -> {request.DispenserState}");
  532. stateHolder.State = request; //Update the state.
  533. }
  534. }
  535. }
  536. }
  537. public void Write(CommonMessage cardMessage)
  538. {
  539. _context.Outgoing.Write(cardMessage);
  540. }
  541. public async Task<CommonMessage> WriteAsync(CommonMessage request, Func<CommonMessage, CommonMessage, bool> responseCapture,
  542. int timeout)
  543. {
  544. var resp = await _context.Outgoing.WriteAsync(request, responseCapture, timeout);
  545. return resp;
  546. }
  547. #endregion
  548. #region IEnumerable<IFdcPumpController> implementation
  549. public IEnumerator<IFdcPumpController> GetEnumerator()
  550. {
  551. return pumpHandlers.GetEnumerator();
  552. }
  553. IEnumerator IEnumerable.GetEnumerator()
  554. {
  555. return pumpHandlers.GetEnumerator();
  556. }
  557. #endregion
  558. public void PendMessage(CardMessageBase message)
  559. {
  560. lock (syncObj)
  561. {
  562. queue.Enqueue(message);
  563. }
  564. }
  565. public bool TrySendNextMessage()
  566. {
  567. lock (syncObj)
  568. {
  569. if (queue.Count > 0)
  570. {
  571. DebugLog($"queue count: {queue.Count}");
  572. var message = commonQueue.Dequeue();
  573. Write(message);
  574. return true;
  575. }
  576. }
  577. return false;
  578. }
  579. public void StoreLatestFrameSqNo(int pumpId, byte frameSqNo)
  580. {
  581. var pump = GetPump(pumpId);
  582. if (pump != null)
  583. {
  584. pump.FrameSqNo = frameSqNo;
  585. }
  586. }
  587. public void UpdatePumpState(int pumpId, int logicId, LogicalDeviceState state)
  588. {
  589. var currentPump = GetPump(pumpId);
  590. currentPump?.FirePumpStateChange(state, Convert.ToByte(logicId));
  591. }
  592. public void UpdateFuelingStatus(int pumpId, FdcTransaction fuelingTransaction)
  593. {
  594. var currentPump = GetPump(pumpId);
  595. currentPump?.FireFuelingStatusChange(fuelingTransaction);
  596. }
  597. private HengshanPumpHandler GetPump(int pumpId)
  598. {
  599. return pumpHandlers.FirstOrDefault(p => p.PumpId == pumpId);
  600. }
  601. public void SetRealPrice(int pumpId, int price)
  602. {
  603. var currentPump = GetPump(pumpId);
  604. var nozzle = currentPump?.Nozzles.FirstOrDefault();
  605. if (nozzle != null)
  606. nozzle.RealPriceOnPhysicalPump = price;
  607. }
  608. #region Log methods
  609. private void InfoLog(string info)
  610. {
  611. logger.Info("PayTermHdlr " + info);
  612. }
  613. private void DebugLog(string debugMsg)
  614. {
  615. logger.Debug("PayTermHdlr " + debugMsg);
  616. }
  617. #endregion
  618. #region 二维码加油机相关方法
  619. /// <summary>
  620. /// 获取站点信息
  621. /// </summary>
  622. private async void GetInfo()
  623. {
  624. MysqlDbContext mysqlDbContext = new MysqlDbContext();
  625. Edge.Core.Domain.FccStationInfo.FccStationInfo? fccStationInfo = mysqlDbContext.FccStationInfos.FirstOrDefault();
  626. if(fccStationInfo != null)
  627. {
  628. stationInfo = new StationInfo(fccStationInfo);
  629. buildID = stationInfo.BuildId;
  630. string paymentType = stationInfo.PaymentType;
  631. string[] paymentGround = paymentType.Split(",");
  632. foreach (var item in paymentGround)
  633. {
  634. string[] payment = item.Split("+");
  635. if (payment.Length == 2)
  636. {
  637. if (long.TryParse(payment[0], out long id))
  638. {
  639. stationPayment.Add(id, payment[1]);
  640. }
  641. }
  642. }
  643. }
  644. Edge.Core.Domain.FccMachineInfo.FccMachineInfo? fccMachineInfo = await mysqlDbContext.FccMachineInfos.FirstOrDefaultAsync(machine => machine.Port == serverPort);
  645. if(fccMachineInfo == null)
  646. {
  647. nozzleInfoList = new List<DetailsNozzleInfoOutput>();
  648. } else
  649. {
  650. nozzleInfoList = mysqlDbContext.NozzleInfos.Where(nozzle => nozzle.MachineId == fccMachineInfo.Id).Select(n => new DetailsNozzleInfoOutput(n)).ToList();
  651. }
  652. }
  653. /// <summary>
  654. /// 接收到MQTT
  655. /// </summary>
  656. /// <param name="message"></param>
  657. public async void OnReceiveMqttMessage(string topic,string message)
  658. {
  659. logger.Info($"getMqtt topic:{topic},and message is {message}");
  660. MqttRequest? mqttRequest = JsonConvert.DeserializeObject<MqttRequest>(message);
  661. if (mqttRequest == null)
  662. {
  663. logger.Error($"mqtt message turn on object fail,message:{message}");
  664. return;
  665. }
  666. if ($"authorization/{buildID}".Equals(topic))
  667. {
  668. MqttAuthorizationRequest? mqttAuthorizationRequest = JsonConvert.DeserializeObject<MqttAuthorizationRequest>(mqttRequest.data);
  669. await SendAuthorizationAsync(mqttAuthorizationRequest, mqttRequest.UserName, mqttRequest.UserPhoneNumber);
  670. }
  671. if($"unAuthorization/{buildID}".Equals(topic))
  672. {
  673. MqttUnAhorizationRequest? mqttUnAhorizationRequest = JsonConvert.DeserializeObject<MqttUnAhorizationRequest>(mqttRequest.data);
  674. await SendUnAuthorizartion(mqttUnAhorizationRequest);
  675. }
  676. if ($"paid/{buildID}".Equals (topic))
  677. {
  678. MqttPaidRequest? mqttPaidRequest = JsonConvert.DeserializeObject<MqttPaidRequest>(mqttRequest.data);
  679. await SendActuallyPaid(mqttPaidRequest, mqttRequest.UserName, mqttRequest.UserPhoneNumber);
  680. }
  681. if ($"refund/{buildID}".Equals(topic))
  682. {
  683. MqttRefundRequest? mqttRefundRequest = JsonConvert.DeserializeObject<MqttRefundRequest>(mqttRequest.data);
  684. await OnRecieveOrderRefund(mqttRefundRequest);
  685. }
  686. //switch (mqttRequest.type)
  687. //{
  688. // case MQTT_TYPE.AUTHORIZATION:
  689. // {
  690. // MqttAuthorizationRequest? mqttAuthorizationRequest = JsonConvert.DeserializeObject<MqttAuthorizationRequest>(mqttRequest.data);
  691. // await SendAuthorizationAsync(mqttAuthorizationRequest);
  692. // break;
  693. // }
  694. // case MQTT_TYPE.UNAUTHORIZATION:
  695. // {
  696. // MqttUnAhorizationRequest? mqttUnAhorizationRequest = JsonConvert.DeserializeObject<MqttUnAhorizationRequest>(mqttRequest.data);
  697. // await SendUnAuthorizartion(mqttUnAhorizationRequest);
  698. // break;
  699. // }
  700. // case MQTT_TYPE.PAID:
  701. // {
  702. // MqttPaidRequest? mqttPaidRequest = JsonConvert.DeserializeObject<MqttPaidRequest>(mqttRequest.data);
  703. // await SendActuallyPaid(mqttPaidRequest, mqttRequest.UserName, mqttRequest.UserPhoneNumber);
  704. // break;
  705. // }
  706. // case MQTT_TYPE.REFUND:
  707. // {
  708. // MqttRefundRequest? mqttRefundRequest = JsonConvert.DeserializeObject<MqttRefundRequest>(mqttRequest.data);
  709. // await OnRecieveOrderRefund(mqttRefundRequest);
  710. // break;
  711. // }
  712. //}
  713. }
  714. /// <summary>
  715. /// 发送二维码信息给油机
  716. /// </summary>
  717. /// <param name="tcpClient"></param>
  718. public async void SendQRCodeAsync()
  719. {
  720. string smallProgram = stationInfo?.SmallProgram ?? "";
  721. if (string.IsNullOrEmpty(smallProgram))
  722. {
  723. logger.Info($"can not get smallProgram link");
  724. return;
  725. }
  726. foreach (var item in nozzleInfoList)
  727. {
  728. //List<Byte> list = new List<Byte>();
  729. //byte[] commandAndNozzle = { 0x63, (byte)item.NozzleNum };
  730. //string qrCode = smallProgram + "/" + item.NozzleNum;
  731. //byte[] qrCodeBytes = Encoding.ASCII.GetBytes(qrCode);
  732. //list.AddRange(commandAndNozzle);
  733. //list.Add((byte)qrCodeBytes.Length);
  734. //list.AddRange(qrCodeBytes);
  735. //byte[] sendBytes = content2data(list.ToArray(), null);
  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. //CommonMessage commonMessage = await SendMessageToMaichine("发送二维码", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendQrCode);
  749. //CommonMessage commonMessage = await SendRequestToMachine("发送二维码", BitConverter.ToString(commandAndNozzle).Replace("-", ""), sendBytes);
  750. if (commonMessage.IsError && commonMessage.TheErrorType == CommonMessage.ErrorType.DISCONNECT) break;
  751. }
  752. //var testAuthorization = new MqttAuthorizationRequest()
  753. //{
  754. // NozzleNum = 1,
  755. // AuthorizationTime = DateTime.Now,
  756. // AuthorizationType = 1,
  757. // Value = 3.00m
  758. //};
  759. //await SendAuthorization(testAuthorization);
  760. //var testUnAuthorization = new MqttUnAhorizationRequest()
  761. //{
  762. // NozzleNum = 1,
  763. // AuthorizationTime = DateTime.Now,
  764. // Ttc = 111
  765. //};
  766. //await SendUnAuthorizartion(testUnAuthorization);
  767. }
  768. /// <summary>
  769. /// 发送实付金额给油机
  770. /// </summary>
  771. /// <param name="orderInfo"></param>
  772. public async Task SendActuallyPaid(MqttPaidRequest? request,string? userName,string? phoneNumber)
  773. {
  774. MysqlDbContext mysqlDbContext = new MysqlDbContext();
  775. if (request == null)
  776. {
  777. logger.Error($"mqtt get paid request is null");
  778. return;
  779. }
  780. //通知云端当前已收到消息
  781. OnGetPaidInfo onGetPaidInfo = new OnGetPaidInfo()
  782. {
  783. Id = request.Id,
  784. Result = 1
  785. };
  786. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendRecievePaidNotice(JsonConvert.SerializeObject(onGetPaidInfo));
  787. logger.Info($"send actuallyPaid result response:{JsonConvert.SerializeObject(httpResponseMessage.Content.ReadAsStringAsync())}");
  788. FccOrderInfo? fccOrderInfo = mysqlDbContext.FccOrderInfos.FirstOrDefault(order => order.CloundOrderId == request.Id);
  789. if (fccOrderInfo == null)
  790. {
  791. //未找到证明为预支付,这里插入订单
  792. logger.Info($"[mqtt paid order notice]:can not find order by clounid:{request.Id},is perpay");
  793. string paymentName = "未知类型";
  794. if (request.PaymentMethod != null)
  795. {
  796. paymentName = stationPayment[request.PaymentMethod ?? 0] ?? "未知类型";
  797. }
  798. fccOrderInfo = request.ToComponent(userName,phoneNumber, paymentName);
  799. mysqlDbContext.Add(fccOrderInfo);
  800. } else
  801. {
  802. logger.Info($"[mqtt paid order notice]:find order,update order right now");
  803. //后支付,这里更新支付信息
  804. fccOrderInfo.AmountPayable = request.ActualPaymentAmount;
  805. fccOrderInfo.VolumePayable = request.OriginalQty;
  806. fccOrderInfo.PaymentTime = request.TransactionTime;
  807. if (request.PaymentMethod != null)
  808. {
  809. fccOrderInfo.PayType = (int)request.PaymentMethod;
  810. fccOrderInfo.PaymentName = stationPayment[request.PaymentMethod ?? 0] ?? "未知类型";
  811. }
  812. fccOrderInfo.UserName = userName ?? "";
  813. fccOrderInfo.PhoneNumber = phoneNumber ?? string.Empty;
  814. fccOrderInfo.PaymentStatus = 1;
  815. }
  816. mysqlDbContext.SaveChanges();
  817. SendActuallyPaid sendActuallyPaid = new SendActuallyPaid(fccOrderInfo.NozzleNum, fccOrderInfo.Ttc, fccOrderInfo.AmountPayable ?? fccOrderInfo.Amount, getFrame(null));
  818. byte[] commandAndNozzle = { sendActuallyPaid.Handle, (byte)sendActuallyPaid.NozzleNum };
  819. await SendMessageToMaichine("发送实付金额", (request, response) =>
  820. {
  821. if (response.Handle == (byte)CommonMessage.Command.SEND_NEED_AMOUNT)
  822. {
  823. CommonAnswerBack commonAnswerBack = (CommonAnswerBack)response;
  824. return commonAnswerBack.Command == (byte)CommonMessage.Command.SEND_NEED_AMOUNT && commonAnswerBack.NozzleNum == sendActuallyPaid.NozzleNum;
  825. }
  826. return false;
  827. }, sendActuallyPaid);
  828. }
  829. /// <summary>
  830. /// 发送授权请求给油机
  831. /// </summary>
  832. /// <param name="request"></param>
  833. /// <returns></returns>
  834. public async Task SendAuthorizationAsync(MqttAuthorizationRequest? request, string? userName, string? phoneNumber)
  835. {
  836. MysqlDbContext mysqlDbContext = new MysqlDbContext();
  837. if(request == null)
  838. {
  839. logger.Error($"mqtt authorization request is null");
  840. return;
  841. }
  842. //添加订单到数据库
  843. DateTime authorizationTime = request.AuthorizationTime ?? DateTime.Now;
  844. FccOrderInfo? fccOrderInfo = await mysqlDbContext.FccOrderInfos.FirstOrDefaultAsync(order => order.CloundOrderId == request.Id);
  845. if(fccOrderInfo == null)
  846. {
  847. logger.Error($"authorization find order by clound id:{request.Id} is null");
  848. return;
  849. }
  850. fccOrderInfo.AuthorizationTime = authorizationTime;
  851. //发送授权申请到油机
  852. SendAuthorization sendAuthorization = new SendAuthorization((int)request.NozzleId, authorizationTime, 1, request.OriginalAmount, getFrame(null));
  853. byte[] commandAndNozzle = { sendAuthorization.Handle, (byte)sendAuthorization.NozzleNum };
  854. CommonMessage commonMessage = await SendMessageToMaichine("发送授权请求", (request, response) =>
  855. {
  856. if (response.Handle == (byte)CommonMessage.Command.ACCREDIT)
  857. {
  858. AuthorizationResponse authorization = (AuthorizationResponse)response;
  859. return authorization.NozzleNum == sendAuthorization.NozzleNum;
  860. }
  861. return false;
  862. }, sendAuthorization);
  863. logger.Info($"获取到授权结果:{JsonConvert.SerializeObject(commonMessage)}");
  864. //发送授权结果给云端
  865. string authorizationResultJson = string.Empty;
  866. SendAuthorizationResult sendAuthorizationResult = new SendAuthorizationResult();
  867. sendAuthorizationResult.NozzleId = request.NozzleId;
  868. if (commonMessage.IsError)
  869. {
  870. ErrorMessage errorMessage = (ErrorMessage)commonMessage;
  871. switch (errorMessage.TheErrorType)
  872. {
  873. case CommonMessage.ErrorType.DISCONNECT:
  874. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.Disconnected;
  875. break;
  876. case CommonMessage.ErrorType.TIMEOUT:
  877. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.AuthorizationTimeout;
  878. break;
  879. }
  880. }
  881. else
  882. {
  883. AuthorizationResponse authorization = (AuthorizationResponse)commonMessage;
  884. if (authorization.Result == 0)
  885. {
  886. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.Failed;
  887. }
  888. else
  889. {
  890. sendAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  891. sendAuthorizationResult.TransactionNumber = authorization.Ttc.ToString();
  892. fccOrderInfo.Ttc = authorization.Ttc;
  893. fccOrderInfo.AuthorizationStatus = 1;
  894. }
  895. }
  896. //SendAuthorizationResult sendAuthorizationResult = new SendAuthorizationResult()
  897. //{
  898. // NozzleId = request.NozzleId,
  899. // TransactionNumber = "1",
  900. // OilMachineStatus = OilMachineStatus.Success
  901. //};
  902. logger.Info($"发送授权结果:{JsonConvert.SerializeObject(sendAuthorizationResult)}");
  903. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendAuthorizationResult(JsonConvert.SerializeObject(sendAuthorizationResult));
  904. logger.Info($"send authorization result response:{JsonConvert.SerializeObject(httpResponseMessage.Content.ReadAsStringAsync())}");
  905. //更新订单
  906. mysqlDbContext.SaveChanges();
  907. }
  908. /// <summary>
  909. /// 发送取消授权请求给油机
  910. /// </summary>
  911. /// <param name="request"></param>
  912. public async Task SendUnAuthorizartion(MqttUnAhorizationRequest? request)
  913. {
  914. MysqlDbContext mysqlDbContext = new MysqlDbContext();
  915. if (request == null)
  916. {
  917. logger.Error($"mqtt unauthorization request is null");
  918. return;
  919. }
  920. //先从数据库查找,查看是否已取消授权
  921. int ttc = 0;
  922. DateTime authorizationTime = request.AuthorizationTime ?? DateTime.Now;
  923. FccOrderInfo? fccOrderInfo = mysqlDbContext.FccOrderInfos.FirstOrDefault(order => order.CloundOrderId == request.Id);
  924. bool isUnauthorization = false;
  925. if (fccOrderInfo != null)
  926. {
  927. ttc = fccOrderInfo.Ttc;
  928. authorizationTime = fccOrderInfo.AuthorizationTime;
  929. isUnauthorization = fccOrderInfo.AuthorizationStatus == 0;
  930. }
  931. SendUnAuthorizationResult sendUnAuthorizationResult = new SendUnAuthorizationResult();
  932. sendUnAuthorizationResult.NozzleId = request.NozzleId;
  933. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  934. if (ttc != 0 && !isUnauthorization)
  935. {
  936. SendUnAuthorization sendUnAuthorization = new SendUnAuthorization((int)request.NozzleId, authorizationTime, ttc, getFrame(null));
  937. byte[] commandAndNozzle = { sendUnAuthorization.Handle, (byte)sendUnAuthorization.NozzleNum };
  938. //发送取消授权命令并获取响应
  939. CommonMessage commonMessage = await SendMessageToMaichine("发送取消授权请求", (request, response) =>
  940. {
  941. if (response.Handle == (byte)CommonMessage.Command.CANCEL_ACCREDIT)
  942. {
  943. UnAhorizationResponse unauthorization = (UnAhorizationResponse)response;
  944. return unauthorization.NozzleNum == sendUnAuthorization.NozzleNum;
  945. }
  946. return false;
  947. }, sendUnAuthorization);
  948. if (commonMessage.IsError)
  949. {
  950. //响应错误
  951. ErrorMessage errorMessage = (ErrorMessage)commonMessage;
  952. switch (errorMessage.TheErrorType)
  953. {
  954. case CommonMessage.ErrorType.DISCONNECT:
  955. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Disconnected;
  956. break;
  957. case CommonMessage.ErrorType.TIMEOUT:
  958. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.AuthorizationTimeout;
  959. break;
  960. }
  961. }
  962. else
  963. {
  964. //正常响应
  965. UnAhorizationResponse unAuthorization = (UnAhorizationResponse)commonMessage;
  966. if (unAuthorization.Result == 0)
  967. {
  968. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Failed;
  969. }
  970. else
  971. {
  972. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  973. fccOrderInfo.AuthorizationStatus = 0;
  974. }
  975. }
  976. }
  977. else if (!isUnauthorization)
  978. {
  979. //若已经未授权
  980. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  981. }
  982. else
  983. { //未找到流水号
  984. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.TransactionNumberNotFound;
  985. }
  986. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendUnAuthorizationResult(JsonConvert.SerializeObject(sendUnAuthorizationResult));
  987. logger.Info($"send Unauthorization result response:{JsonConvert.SerializeObject(httpResponseMessage.Content.ReadAsStringAsync())}");
  988. }
  989. /// <summary>
  990. /// 接收到云端发送订单退款信息
  991. /// </summary>
  992. /// <param name="request"></param>
  993. /// <returns></returns>
  994. private async Task OnRecieveOrderRefund(MqttRefundRequest? request)
  995. {
  996. MysqlDbContext mysqlDbContext = new MysqlDbContext();
  997. if (request == null)
  998. {
  999. logger.Error($"mqtt OnRecieveOrderRefund request is null");
  1000. return;
  1001. }
  1002. //通知云端当前已收到消息
  1003. OnGetRefundInfo onGetRefundInfo = new OnGetRefundInfo()
  1004. {
  1005. Id = request.Id,
  1006. Result = 1
  1007. };
  1008. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendRecieveRefundNotice(JsonConvert.SerializeObject(onGetRefundInfo));
  1009. logger.Info($"send refund result response:{JsonConvert.SerializeObject(httpResponseMessage.Content.ReadAsStringAsync())}");
  1010. //通知油机已退款
  1011. SendRefund sendRefund = new SendRefund((int)request.NozzleId, request.TransactionNumber, request.OriginalAmount, request.ActualPaymentAmount ?? 0m, request.RefundAmount ?? 0m, getFrame(null));
  1012. byte[] commandAndNozzle = { sendRefund.Handle, (byte)sendRefund.NozzleNum };
  1013. await SendMessageToMaichine("发送退款信息", (request, response) =>
  1014. {
  1015. if (response.Handle == (byte)CommonMessage.Command.SEND_NEED_AMOUNT)
  1016. {
  1017. CommonAnswerBack commonAnswerBack = (CommonAnswerBack)response;
  1018. return commonAnswerBack.Command == (byte)CommonMessage.Command.SEND_NEED_AMOUNT && commonAnswerBack.NozzleNum == sendRefund.NozzleNum;
  1019. }
  1020. return false;
  1021. }, sendRefund);
  1022. FccOrderInfo? fccOrderInfo = mysqlDbContext.FccOrderInfos.FirstOrDefault(order => order.CloundOrderId == request.Id);
  1023. if (fccOrderInfo == null)
  1024. {
  1025. logger.Error($"[mqtt refund order notice]:can not find order by clounid:{request.Id}");
  1026. return;
  1027. }
  1028. fccOrderInfo.AmountPayable = request.ActualPaymentAmount;
  1029. fccOrderInfo.RefundAmount = request.RefundAmount;
  1030. fccOrderInfo.PaymentStatus = (int)request.OrderStatus;
  1031. fccOrderInfo.RefundStatus = (int)request.RefundStatus;
  1032. mysqlDbContext.SaveChanges();
  1033. }
  1034. //public void SetTcpClient(TcpClient? tcpClient, int? serverPort)
  1035. //{
  1036. // this.client = tcpClient;
  1037. // this.serverPort = serverPort;
  1038. // checkDisConnectTask = new TaskCompletionSource<ErrorMessage>();
  1039. //}
  1040. //public void OnTcpDisconnect()
  1041. //{
  1042. // this.client = null;
  1043. // ErrorMessage errorMessage = new ErrorMessage()
  1044. // {
  1045. // IsError = true,
  1046. // TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  1047. // ErrorMessage = $"the client is disconnet"
  1048. // };
  1049. // checkDisConnectTask.SetResult(errorMessage);
  1050. //}
  1051. /// <summary>
  1052. /// 发送消息到油机,3秒的超时,重试三次
  1053. /// </summary>
  1054. /// <param name="sendTag">发送的消息类型,用于日志记录</param>
  1055. /// <param name="sendKey">发送的消息key,用于存储 TaskCompletionSource</param>
  1056. /// <param name="requestBytes">实际发送消息</param>
  1057. /// <returns></returns>
  1058. private async Task<CommonMessage> SendMessageToMaichine(string sendTag, Func<CommonMessage, CommonMessage, bool> responseCapture,CommonMessage sendMessage)
  1059. {
  1060. logger.Info($"send request to machine:{sendTag}");
  1061. isSendHeart = false;
  1062. int retryCount = 0;
  1063. while (retryCount < 3)
  1064. {
  1065. try
  1066. {
  1067. var response = await this.Context.Outgoing.WriteAsyncAndCheckIsConnect(sendMessage, responseCapture, 3000);
  1068. //超时重试
  1069. if (response.ResponseType == WriteResponseType.TIME_OUT || response.Data == null)
  1070. {
  1071. retryCount++;
  1072. logger.Info($"{sendTag}: time out,retrying... ({retryCount} / 3)");
  1073. continue;
  1074. }
  1075. //链接断开不再发送
  1076. if (response.ResponseType == WriteResponseType.DISCONNECT)
  1077. {
  1078. var isConnect = (bool)(response.Data ?? false);
  1079. if (!isConnect) return new ErrorMessage()
  1080. {
  1081. IsError = true,
  1082. TheErrorType = CommonMessage.ErrorType.DISCONNECT,
  1083. ErrorMessage = $"the client is disconnet"
  1084. };
  1085. }
  1086. Console.WriteLine("");
  1087. isSendHeart = true;
  1088. //返回信息
  1089. return (CommonMessage)response.Data;
  1090. }
  1091. catch (Exception)
  1092. {
  1093. retryCount++;
  1094. logger.Info($"{sendTag}: error,retrying... ({retryCount} / 3)");
  1095. }
  1096. finally
  1097. {
  1098. if (retryCount >= 3)
  1099. {
  1100. logger.Info($"{sendTag}: is time out add retry 3 time");
  1101. isSendHeart = true;
  1102. }
  1103. }
  1104. }
  1105. isSendHeart = true;
  1106. return new ErrorMessage()
  1107. {
  1108. IsError = true,
  1109. TheErrorType = CommonMessage.ErrorType.TIMEOUT,
  1110. ErrorMessage = $"{sendTag}: can not receive response after 3 retries"
  1111. };
  1112. }
  1113. /// <summary>
  1114. /// 取消授权
  1115. /// </summary>
  1116. /// <returns></returns>
  1117. private async Task SendUnAuthorizationTimerAsync()
  1118. {
  1119. MysqlDbContext mysqlDbContext = new MysqlDbContext();
  1120. DateTime timeOut = DateTime.Now.AddMonths(stationInfo.CheckOrderInterval);
  1121. FccOrderInfo? fccOrderInfo = await mysqlDbContext.FccOrderInfos.FirstOrDefaultAsync(order => order.AuthorizationStatus == 1 && order.AuthorizationTime < timeOut);
  1122. if (fccOrderInfo == null)
  1123. {
  1124. logger.Info($"当前没有待取消授权的订单");
  1125. return;
  1126. }
  1127. SendUnAuthorizationResult sendUnAuthorizationResult = new SendUnAuthorizationResult();
  1128. sendUnAuthorizationResult.NozzleId = fccOrderInfo.NozzleNum;
  1129. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  1130. SendUnAuthorization sendUnAuthorization = new SendUnAuthorization(fccOrderInfo.NozzleNum, fccOrderInfo.AuthorizationTime, fccOrderInfo.Ttc, getFrame(null));
  1131. byte[] commandAndNozzle = { sendUnAuthorization.Handle, (byte)sendUnAuthorization.NozzleNum };
  1132. //发送取消授权命令并获取响应
  1133. CommonMessage commonMessage = await SendMessageToMaichine("定时发送取消授权请求", (request, response) =>
  1134. {
  1135. if (response.Handle == (byte)CommonMessage.Command.CANCEL_ACCREDIT)
  1136. {
  1137. UnAhorizationResponse unauthorization = (UnAhorizationResponse)response;
  1138. return unauthorization.NozzleNum == sendUnAuthorization.NozzleNum;
  1139. }
  1140. return false;
  1141. }, sendUnAuthorization);
  1142. if (commonMessage.IsError)
  1143. {
  1144. //响应错误
  1145. ErrorMessage errorMessage = (ErrorMessage)commonMessage;
  1146. switch (errorMessage.TheErrorType)
  1147. {
  1148. case CommonMessage.ErrorType.DISCONNECT:
  1149. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Disconnected;
  1150. break;
  1151. case CommonMessage.ErrorType.TIMEOUT:
  1152. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.AuthorizationTimeout;
  1153. break;
  1154. }
  1155. }
  1156. else
  1157. {
  1158. //正常响应
  1159. UnAhorizationResponse unAuthorization = (UnAhorizationResponse)commonMessage;
  1160. if (unAuthorization.Result == 0)
  1161. {
  1162. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Failed;
  1163. }
  1164. else
  1165. {
  1166. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  1167. fccOrderInfo.AuthorizationStatus = 0;
  1168. }
  1169. }
  1170. mysqlDbContext.SaveChanges();
  1171. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendUnAuthorizationResult(JsonConvert.SerializeObject(sendUnAuthorizationResult));
  1172. logger.Info($"定时任务取消授权:send Unauthorization timer result response:{JsonConvert.SerializeObject(httpResponseMessage.Content.ReadAsStringAsync())}");
  1173. }
  1174. /// <summary>
  1175. /// 添加或修改订单
  1176. /// </summary>
  1177. /// <param name="order">接收到油机的订单信息</param>
  1178. /// <returns></returns>
  1179. public FccOrderInfo UpLoadOrder(OrderFromMachine order)
  1180. {
  1181. MysqlDbContext mysqlDbContext = new MysqlDbContext();
  1182. //接收到油机发送过来的订单信息
  1183. OrderFromMachine orderFromMachine = (OrderFromMachine)order;
  1184. string? oilName = mysqlDbContext.OilInfos.Where(oil => orderFromMachine.oilCode.Equals(oil.Code)).Select(oil => oil.Name).FirstOrDefault();
  1185. FccOrderInfo orderByMessage = orderFromMachine.ToComponent(oilName);
  1186. /** 根据枪号+流水号+授权时间来确定订单,因为冷启动后流水号会从头开始计算
  1187. * 后支付时直接将数据库直接插入
  1188. * 预支付时由于是云端先创建订单,发起授权响应成功后会插入数据库,响应成功时会回复授权时间,枪号,流水号
  1189. */
  1190. FccOrderInfo? fccOrderInfo = mysqlDbContext.FccOrderInfos
  1191. .Where(order =>
  1192. order.NozzleNum == orderFromMachine.nozzleNum && order.Ttc == orderFromMachine.ttc
  1193. && order.AuthorizationTime == orderFromMachine.dispenserTime)
  1194. .FirstOrDefault();
  1195. if (fccOrderInfo == null)
  1196. {
  1197. logger.Info($"receive order from machine,find order from database is null");
  1198. mysqlDbContext.FccOrderInfos.Add(orderByMessage);
  1199. mysqlDbContext.SaveChanges();
  1200. return orderByMessage;
  1201. }
  1202. else
  1203. {
  1204. logger.Info($"receive order from machine,padding data right now");
  1205. orderFromMachine.PaddingAuthorizationOrderData(fccOrderInfo);
  1206. mysqlDbContext.SaveChanges();
  1207. return fccOrderInfo;
  1208. }
  1209. }
  1210. private async void CreateOrRedeemTransaction(FccOrderInfo fccOrderInfo)
  1211. {
  1212. MysqlDbContext mysqlDbContext = new MysqlDbContext();
  1213. if (fccOrderInfo.CloundOrderId == null)
  1214. {
  1215. CreateTransaction createTransaction = new CreateTransaction(fccOrderInfo);
  1216. logger.Info($"create transaction, {JsonConvert.SerializeObject(createTransaction)}");
  1217. HttpResponseMessage httpResponseMessage = await httpClientUtil.CreateTransaction(JsonConvert.SerializeObject(createTransaction));
  1218. string responseStr = await httpResponseMessage.Content.ReadAsStringAsync();
  1219. Response<CreateTransactionResponse>? response = JsonConvert.DeserializeObject<Response<CreateTransactionResponse>>(responseStr);
  1220. logger.Info($"reveice create transaction response:{JsonConvert.SerializeObject(response)}");
  1221. fccOrderInfo.CloundOrderId = response?.data?.Id;
  1222. fccOrderInfo.UploadState = response?.data == null ? 0 : 1;
  1223. mysqlDbContext.SaveChanges();
  1224. } else
  1225. {
  1226. //MysqlDbContext mysqlDbContext = new MysqlDbContext();
  1227. if(fccOrderInfo.Amount == 0 && fccOrderInfo.Volume == 0)
  1228. {
  1229. //0交易订单,证明为取消授权后产生的订单,不走核销,而是在小程序上显示为授权失败,让其重新发起授权或退款
  1230. logger.Info("0交易,取消授权");
  1231. fccOrderInfo.AuthorizationStatus = 0; //存在油机手动取消授权的情况,因此这里也要更新授权状态
  1232. mysqlDbContext.SaveChanges();
  1233. SendUnAuthorizationResult sendUnAuthorizationResult = new SendUnAuthorizationResult();
  1234. sendUnAuthorizationResult.NozzleId = fccOrderInfo.NozzleNum;
  1235. sendUnAuthorizationResult.TransactionNumber = fccOrderInfo.Ttc.ToString();
  1236. sendUnAuthorizationResult.OilMachineStatus = OilMachineStatus.Success;
  1237. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendUnAuthorizationResult(JsonConvert.SerializeObject(sendUnAuthorizationResult));
  1238. logger.Info($"手动取消授权:send Unauthorization result response:{JsonConvert.SerializeObject(httpResponseMessage.Content.ReadAsStringAsync())}");
  1239. }
  1240. else
  1241. {
  1242. //核销
  1243. Redeem redeem = new Redeem();
  1244. redeem.trxId = (int)fccOrderInfo.CloundOrderId;
  1245. redeem.OriginalQty = fccOrderInfo.Volume;
  1246. string param = JsonConvert.SerializeObject(redeem);
  1247. logger.Info($"Redeem order:{param}");
  1248. HttpResponseMessage httpResponseMessage = await httpClientUtil.Redeem(param);
  1249. string responseStr = await httpResponseMessage.Content.ReadAsStringAsync();
  1250. Response<CreateTransactionResponse>? response = JsonConvert.DeserializeObject<Response<CreateTransactionResponse>>(responseStr);
  1251. logger.Info($"Redeem order response:{JsonConvert.SerializeObject(response)}");
  1252. //fccOrderInfo.CloundOrderId = response?.data?.Id;
  1253. //fccOrderInfo.UploadState = response?.data == null ? 0 : 1;
  1254. //mysqlDbContext.SaveChanges();
  1255. }
  1256. //mysqlDbContext.SaveChanges();
  1257. }
  1258. }
  1259. /// <summary>
  1260. /// 发送油枪状态给云端
  1261. /// </summary>
  1262. /// <param name="nozzleState"></param>
  1263. private async void SendNozzleStatus(HeartBeatMessage heartBeatMessage)
  1264. {
  1265. //提取出状态有变化的油枪,打包成要发送至云端的数据,添加到列表
  1266. List<SendNozzleStatu> sendNozzleStatus = new List<SendNozzleStatu>();
  1267. List<int> fuelingNozzle = new List<int>();
  1268. foreach (var nozzleState in heartBeatMessage.NozzleStatus)
  1269. {
  1270. if (nozzleStatusDic.TryGetValue(nozzleState.NozzleNum, out var value))
  1271. {
  1272. if (nozzleState.STATU == value) continue;
  1273. }
  1274. //保存变量
  1275. nozzleStatusDic[nozzleState.NozzleNum] = nozzleState.STATU;
  1276. if (nozzleState.STATU == 8) fuelingNozzle.Add(nozzleState.NozzleNum);
  1277. //查找fcc数据库油枪id
  1278. DetailsNozzleInfoOutput? detailsNozzleInfoOutput = nozzleInfoList.Find(nozzle => nozzle.NozzleNum == nozzleState.NozzleNum);
  1279. if (detailsNozzleInfoOutput == null)
  1280. {
  1281. logger.Error($"can not find nozzleInfo from nozzleInfoList:{nozzleState.NozzleNum} ,send nozzle state fail");
  1282. continue;
  1283. }
  1284. SendNozzleStatu sendNozzleStatu = new SendNozzleStatu(detailsNozzleInfoOutput.CloundNozzleId, nozzleState);
  1285. sendNozzleStatus.Add(sendNozzleStatu);
  1286. }
  1287. if (!sendNozzleStatus.IsNullOrEmpty())
  1288. {
  1289. //发送云端
  1290. string reuqestJson = JsonConvert.SerializeObject(sendNozzleStatus);
  1291. logger.Info($"send nozzle state to cloud,{reuqestJson}");
  1292. try
  1293. {
  1294. HttpResponseMessage httpResponseMessage = await httpClientUtil.SendNozzleStatu(reuqestJson);
  1295. Response<object>? response = JsonConvert.DeserializeObject<Response<object>>(await httpResponseMessage.Content.ReadAsStringAsync());
  1296. logger.Info($"reveice send nozzle state response:{JsonConvert.SerializeObject(response)}");
  1297. }
  1298. catch (Exception ex)
  1299. {
  1300. logger.Error($"send nozzle stat fail:{ex.Message}");
  1301. }
  1302. }
  1303. //当前油枪为加油态,找到该油枪最近一笔已授权的订单,将其赋为加油中
  1304. MysqlDbContext mysqlDbContext = new MysqlDbContext();
  1305. foreach(int nozzleNum in fuelingNozzle)
  1306. {
  1307. FccOrderInfo? fccOrderInfo = await mysqlDbContext.FccOrderInfos
  1308. .OrderByDescending(order => order.AuthorizationTime)
  1309. .FirstOrDefaultAsync(order => order.NozzleNum == nozzleNum && order.AuthorizationStatus == 1);
  1310. if(fccOrderInfo != null)
  1311. {
  1312. fccOrderInfo.AuthorizationStatus = 3;
  1313. }
  1314. }
  1315. mysqlDbContext.SaveChanges();
  1316. }
  1317. /// <summary>
  1318. /// 获取发送帧号
  1319. /// </summary>
  1320. /// <param name="sendFrame"></param>
  1321. /// <returns></returns>
  1322. private byte getFrame(byte? sendFrame)
  1323. {
  1324. byte frameNo = 0x00;
  1325. if (sendFrame == null)
  1326. {
  1327. lock (lockFrame)
  1328. {
  1329. if (frame == 0x3f)
  1330. {
  1331. frameNo = 0x00;
  1332. }
  1333. else
  1334. {
  1335. frameNo = (byte)(frame++);
  1336. }
  1337. }
  1338. }
  1339. else
  1340. {
  1341. frameNo = sendFrame.Value;
  1342. }
  1343. return frameNo;
  1344. }
  1345. ///// <summary>
  1346. ///// 传入有效数据,拼接为要发送给油机包
  1347. ///// </summary>
  1348. ///// <param name="content"></param>
  1349. ///// <returns></returns>
  1350. //public byte[] content2data(byte[] content, byte? sendFrame)
  1351. //{
  1352. // List<byte> list = new List<byte>();
  1353. // //目标地址,源地址,帧号
  1354. // byte frameNo = 0x00;
  1355. // if (sendFrame == null)
  1356. // {
  1357. // lock (lockFrame)
  1358. // {
  1359. // if (frame == 0x3f)
  1360. // {
  1361. // frameNo = 0x00;
  1362. // }
  1363. // else
  1364. // {
  1365. // frameNo = (byte)(frame++);
  1366. // }
  1367. // }
  1368. // }
  1369. // else
  1370. // {
  1371. // frameNo = sendFrame.Value;
  1372. // }
  1373. // byte[] head = new byte[] { 0xFF, 0xE0, frameNo };
  1374. // byte[] length = Int2BCD(content.Length);
  1375. // list.AddRange(head);
  1376. // list.AddRange(length);
  1377. // list.AddRange(content);
  1378. // byte[] crc = HengshanCRC16.ComputeChecksumToBytes(list.ToArray());
  1379. // list.AddRange(crc);
  1380. // List<byte> addFAList = addFA(list);
  1381. // addFAList.Insert(0, 0xFA);
  1382. // return addFAList.ToArray();
  1383. //}
  1384. //public int Bcd2Int(byte byte1, byte byte2)
  1385. //{
  1386. // // 提取第一个字节的高四位和低四位
  1387. // int digit1 = (byte1 >> 4) & 0x0F; // 高四位
  1388. // int digit2 = byte1 & 0x0F; // 低四位
  1389. // // 提取第二个字节的高四位和低四位
  1390. // int digit3 = (byte2 >> 4) & 0x0F; // 高四位
  1391. // int digit4 = byte2 & 0x0F; // 低四位
  1392. // // 组合成一个整数
  1393. // int result = digit1 * 1000 + digit2 * 100 + digit3 * 10 + digit4;
  1394. // return result;
  1395. //}
  1396. //public byte[] Int2BCD(int number)
  1397. //{
  1398. // // 提取千位、百位、十位和个位
  1399. // int thousands = number / 1000;
  1400. // int hundreds = (number / 100) % 10;
  1401. // int tens = (number / 10) % 10;
  1402. // int units = number % 10;
  1403. // // 将千位和百位组合成一个字节(千位在高四位,百位在低四位)
  1404. // byte firstByte = (byte)((thousands * 16) + hundreds); // 乘以16相当于左移4位
  1405. // // 将十位和个位组合成一个字节(十位在高四位,个位在低四位)
  1406. // byte secondByte = (byte)((tens * 16) + units);
  1407. // // 返回结果数组
  1408. // return new byte[] { firstByte, secondByte };
  1409. //}
  1410. //public List<Byte> addFA(List<Byte> list)
  1411. //{
  1412. // List<byte> result = new List<byte>();
  1413. // foreach (byte b in list)
  1414. // {
  1415. // if (b == 0xFA)
  1416. // {
  1417. // result.Add(0xFA);
  1418. // result.Add(0xFA);
  1419. // }
  1420. // else
  1421. // {
  1422. // result.Add(b);
  1423. // }
  1424. // }
  1425. // return result;
  1426. //}
  1427. ///// <summary>
  1428. ///// 将数值转为byte[]
  1429. ///// </summary>
  1430. ///// <param name="value">数值</param>
  1431. ///// <param name="length">数组长度,不够高位补0</param>
  1432. ///// <returns></returns>
  1433. ///// <exception cref="ArgumentException"></exception>
  1434. //public static byte[] NumberToByteArrayWithPadding(int value, int length)
  1435. //{
  1436. // if (length < 0)
  1437. // {
  1438. // throw new ArgumentException("Length must be non-negative.");
  1439. // }
  1440. // // 创建一个指定长度的字节数组
  1441. // byte[] paddedBytes = new byte[length];
  1442. // // 确保是大端序
  1443. // for (int i = 0; i < length && i < 4; i++)
  1444. // {
  1445. // paddedBytes[length - 1 - i] = (byte)(value >> (i * 8));
  1446. // }
  1447. // return paddedBytes;
  1448. //}
  1449. //public static byte[] FormatDecimal(decimal value)
  1450. //{
  1451. // // 四舍五入到两位小数
  1452. // decimal roundedValue = Math.Round(value, 2, MidpointRounding.AwayFromZero);
  1453. // int valueInt = (int)(roundedValue * 100m);
  1454. // return NumberToByteArrayWithPadding(valueInt, 3); ;
  1455. //}
  1456. ///// <summary>
  1457. ///// 将时间转为 BCD
  1458. ///// </summary>
  1459. ///// <param name="dateTime"></param>
  1460. ///// <returns></returns>
  1461. //public static byte[] ConvertDateTimeToByteArray(DateTime dateTime)
  1462. //{
  1463. // // 创建byte数组
  1464. // byte[] result = new byte[7];
  1465. // // 年份处理
  1466. // int year = dateTime.Year;
  1467. // result[0] = (byte)((year / 1000) * 16 + (year / 100) % 10); // 千年和百年
  1468. // result[1] = (byte)((year / 10) % 10 * 16 + year % 10); // 十年和个年
  1469. // // 月、日、小时、分钟、秒直接转换为BCD
  1470. // result[2] = (byte)(dateTime.Month / 10 * 16 + dateTime.Month % 10);
  1471. // result[3] = (byte)(dateTime.Day / 10 * 16 + dateTime.Day % 10);
  1472. // result[4] = (byte)(dateTime.Hour / 10 * 16 + dateTime.Hour % 10);
  1473. // result[5] = (byte)(dateTime.Minute / 10 * 16 + dateTime.Minute % 10);
  1474. // result[6] = (byte)(dateTime.Second / 10 * 16 + dateTime.Second % 10);
  1475. // return result;
  1476. //}
  1477. // CRC16 constants
  1478. const ushort CRC_ORDER16 = 16;
  1479. const ushort CRC_POLYNOM16 = 0x1021;
  1480. const ushort CRC_CRCINIT16 = 0xFFFF;
  1481. const ushort CRC_CRCXOR16 = 0x0000;
  1482. const ushort CRC_MASK = 0xFFFF;
  1483. const ushort CRC_HIGHEST_BIT = (ushort)(1 << (CRC_ORDER16 - 1));
  1484. const ushort TGT_CRC_DEFAULT_INIT = 0xFFFF;
  1485. public static ushort Crc16(byte[] buffer, ushort length)
  1486. {
  1487. ushort crc_rc = TGT_CRC_DEFAULT_INIT;
  1488. for (int i = 0; i < length; i++)
  1489. {
  1490. byte c = buffer[i];
  1491. for (ushort j = 0x80; j != 0; j >>= 1)
  1492. {
  1493. ushort crc_bit = (ushort)((crc_rc & CRC_HIGHEST_BIT) != 0 ? 1 : 0);
  1494. crc_rc <<= 1;
  1495. if ((c & j) != 0)
  1496. {
  1497. crc_bit = (ushort)((crc_bit == 0) ? 1 : 0);
  1498. }
  1499. if (crc_bit != 0)
  1500. {
  1501. crc_rc ^= CRC_POLYNOM16;
  1502. }
  1503. }
  1504. }
  1505. return (ushort)((crc_rc ^ CRC_CRCXOR16) & CRC_MASK);
  1506. }
  1507. #endregion
  1508. }
  1509. public class HengshanPayTerminalHanlderGroupConfigV1
  1510. {
  1511. public string PumpIds { get; set; }
  1512. public List<PumpSubAddress> PumpSubAddresses { get; set; }
  1513. }
  1514. public class HengshanPayTerminalHanlderGroupConfigV2
  1515. {
  1516. public string PumpIds { get; set; }
  1517. public List<PumpSubAddress> PumpSubAddresses { get; set; }
  1518. public List<PumpNozzleLogicId> PumpNozzleLogicIds { get; set; }
  1519. public List<PumpSiteNozzleNo> PumpSiteNozzleNos { get; set; }
  1520. public List<NozzleLogicId> NozzleLogicIds { get; set; }
  1521. }
  1522. public class PumpSubAddress
  1523. {
  1524. public byte PumpId { get; set; }
  1525. public byte SubAddress { get; set; }
  1526. }
  1527. public class PumpNozzleLogicId
  1528. {
  1529. public byte PumpId { get; set; }
  1530. public string LogicIds { get; set; }
  1531. }
  1532. public class PumpSiteNozzleNo
  1533. {
  1534. public byte PumpId { get; set; }
  1535. public string SiteNozzleNos { get; set; }
  1536. }
  1537. public class NozzleLogicId
  1538. {
  1539. public byte NozzleNo { get; set; }
  1540. public byte LogicId { get; set; }
  1541. }
  1542. }