HengshanPayTermHandler.cs 59 KB

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