HengshanPayTermHandler.cs 76 KB

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