WebServer.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. using centralController.model;
  2. using db;
  3. using nettyCommunication;
  4. using parkMonitor.LOG;
  5. using PLCS7;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Terminal;
  13. namespace centralController.WebServer
  14. {
  15. class MyWebServer : IWebServer
  16. {
  17. private Queue<MessageUTF8> waitToReserveQueue = null;
  18. private Queue<MessageUTF8> reservedQueue = null;
  19. private object waitToReserveLock = new object();
  20. private object reservedLock = new object();
  21. private object parkLock = new object();
  22. private object fetchLock = new object();
  23. private Communication comm = null;
  24. private Thread receiveMsg = null;
  25. private bool isClosing { get; set; }
  26. /// <summary>
  27. /// 是否正在调用函数进行连接
  28. /// </summary>
  29. private bool connecting { get; set; }
  30. /// <summary>
  31. /// 连接状态
  32. /// </summary>
  33. private bool connected { get; set; }
  34. public void BookFetchRecord()
  35. {
  36. throw new NotImplementedException();
  37. }
  38. public void BookParkRecord()
  39. {
  40. throw new NotImplementedException();
  41. }
  42. /// <summary>
  43. /// 更新预约车车辆状态
  44. /// </summary>
  45. /// <param name="localDB"></param>
  46. /// <param name="state"></param>
  47. /// <param name="orderRecordsID"></param>
  48. /// <param name="license"></param>
  49. /// <returns></returns>
  50. private bool UpdateVehicleState(bool localDB, int state, int orderRecordsID, string license)
  51. {
  52. string vehicleUpdateSql = "";
  53. string vehicleInsertSql = "";
  54. if (orderRecordsID > 0)
  55. {
  56. if (state >= 0)
  57. {
  58. vehicleUpdateSql = "update vehicle set vehiclepParkState = " + state + " ,orderRecordsID = " + orderRecordsID + " where numberPlate = '" + license + "';";
  59. vehicleInsertSql = "insert into vehicle (numberPlate,vehiclepParkState,orderRecordsID) values " +
  60. "('" + license + "'," + state + "," + orderRecordsID + ");";
  61. }
  62. else
  63. {
  64. vehicleUpdateSql = "update vehicle set orderRecordsID = " + orderRecordsID + " where numberPlate = '" + license + "';";
  65. vehicleInsertSql = "insert into vehicle (numberPlate,orderRecordsID) values " +
  66. "('" + license + "'," + orderRecordsID + ");";
  67. }
  68. }
  69. else
  70. {
  71. if (state >= 0)
  72. {
  73. vehicleUpdateSql = "update vehicle set vehiclepParkState = " + state + " where numberPlate = '" + license + "';";
  74. vehicleInsertSql = "insert into vehicle (numberPlate,vehiclepParkState) values " +
  75. "('" + license + "'," + state + ");";
  76. }
  77. else
  78. {
  79. return false;
  80. }
  81. }
  82. List<string> vehicleUpdateList = new List<string>();
  83. List<string> vehicleInsertList = new List<string>();
  84. vehicleUpdateList.Add(vehicleUpdateSql);
  85. vehicleInsertList.Add(vehicleInsertSql);
  86. DBOperation dbHandle = null;
  87. if (localDB)
  88. dbHandle = Monitor.Monitor.localDBOper;
  89. else
  90. dbHandle = Monitor.Monitor.remoteDBOper;
  91. if (!dbHandle.UpdateTransaction(vehicleUpdateList))
  92. {
  93. int id = 0;
  94. if (!dbHandle.Insert(vehicleInsertList, out id))
  95. return false;
  96. else
  97. return true;
  98. }
  99. else return true;
  100. }
  101. /// <summary>
  102. /// 插入预约记录
  103. /// </summary>
  104. /// <param name="localDB"></param>
  105. /// <param name="userID"></param>
  106. /// <param name="parking"></param>
  107. /// <param name="license"></param>
  108. /// <param name="orderTime"></param>
  109. /// <param name="orderLength"></param>
  110. /// <returns></returns>
  111. private bool InsertOrderRecord(bool localDB, string userID, bool parking, string license, string orderTime, int orderLength, out int id)
  112. {
  113. bool result = false;
  114. string orderRecordInsertSql;
  115. if (parking)
  116. {
  117. orderRecordInsertSql = "insert into orderrecords (userID,numberPlate,garageID, bookParkTime, bookHour, bookPrice,bookState) " +
  118. "VALUES (" + userID + ", '" + license + "', '" + Monitor.Monitor.garageID + "', '" + orderTime + "', " + orderLength + ",NULL, '0');";
  119. }
  120. else
  121. {
  122. orderRecordInsertSql = "insert into orderrecords (userID,numberPlate,garageID, bookFetchTime, bookHour, bookPrice,bookState) " +
  123. "VALUES (" + userID + ", '" + license + "', '" + Monitor.Monitor.garageID + "', '" + orderTime + "', " + orderLength + ",NULL, '2');";
  124. }
  125. List<string> orderList = new List<string>();
  126. orderList.Add(orderRecordInsertSql);
  127. if (localDB)
  128. result = Monitor.Monitor.localDBOper.Insert(orderList, out id);
  129. else
  130. result = Monitor.Monitor.remoteDBOper.Insert(orderList, out id);
  131. return result;
  132. }
  133. /// <summary>
  134. /// 找到当前预约记录ID,暂未使用
  135. /// </summary>
  136. /// <param name="localDB"></param>
  137. /// <param name="license"></param>
  138. /// <param name="latestIndex">最近第几条记录,1表示最新一条</param>
  139. /// <returns></returns>
  140. private int FindCurrentOrderRecordID(bool localDB, string license, int latestIndex = 1)
  141. {
  142. int currentID = 0;
  143. int count = 10;
  144. while (count-- > 0 && currentID == 0)
  145. {
  146. List<object[]> orderRecords = Monitor.Monitor.GetOrderRecords(localDB, license, DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"));
  147. if (orderRecords.Count != 0)
  148. {
  149. try
  150. {
  151. currentID = (int)(UInt32)orderRecords[latestIndex - 1][0];
  152. }
  153. catch { }
  154. }
  155. }
  156. return currentID;
  157. }
  158. /// <summary>
  159. /// 预约数据库操作
  160. /// </summary>
  161. /// <param name="localDB"></param>
  162. /// <param name="userID"></param>
  163. /// <param name="parking"></param>
  164. /// <param name="license"></param>
  165. /// <param name="orderTime"></param>
  166. /// <param name="orderLength"></param>
  167. /// <returns></returns>
  168. private bool ReserveDBOperation(bool localDB, string userID, bool parking, string license, string orderTime, int orderLength)
  169. {
  170. UpdateVehicleState(localDB, parking ? 4 : 5, 0, license);
  171. //预约记录插入db
  172. int currentID = 0;
  173. InsertOrderRecord(localDB, userID, parking, license, orderTime, orderLength, out currentID);
  174. ////查询预约记录id号
  175. //int currentID = FindCurrentOrderRecordID(localDB, license);
  176. if (currentID == 0) { /*反馈web,预约失败*/ return false; }
  177. //更新车辆状态
  178. UpdateVehicleState(localDB, parking ? 4 : 5, currentID, license);
  179. return true;
  180. }
  181. /// <summary>
  182. /// 检查预约指令是否可行
  183. /// </summary>
  184. /// <param name="msg"></param>
  185. /// <returns></returns>
  186. private bool ReservationValidate(MessageUTF8 msg)
  187. {
  188. int allBookableSpace, count;
  189. lock (waitToReserveLock)
  190. {
  191. //可预约车位总数
  192. allBookableSpace = Monitor.Monitor.ins.GetFreeSpaceCount(4);
  193. count = 0;
  194. DateTime start, end;
  195. try
  196. {
  197. start = DateTime.Parse(msg.bookTime);
  198. end = start.AddHours(msg.bookLength);
  199. //Console.WriteLine("--------"+msg.bookTime+","+msg.bookLength);
  200. }
  201. catch { Console.WriteLine("时间解析异常1"); return false; }
  202. Queue<MessageUTF8>.Enumerator enumer = waitToReserveQueue.GetEnumerator();
  203. while (enumer.MoveNext())
  204. {
  205. DateTime tempStart, tempEnd;
  206. try
  207. {
  208. tempStart = DateTime.Parse(enumer.Current.bookTime);
  209. tempEnd = tempStart.AddHours(enumer.Current.bookLength);
  210. //Console.WriteLine("#########" + enumer.Current.bookTime + "," + enumer.Current.bookLength);
  211. }
  212. catch { Console.WriteLine("时间解析异常2"); return false; }
  213. //Console.WriteLine("**********" + start.ToString() + "," + end.ToString() + "," + tempStart.ToString() + "," + tempEnd.ToString());
  214. //Console.WriteLine("**********" + ((tempStart - end).TotalMinutes > 0)+","+ ((start - tempEnd).TotalMinutes > 0));
  215. if (!((tempStart - end).TotalMinutes > 0 || (start - tempEnd).TotalMinutes > 0)) { count += 1; }
  216. }
  217. Queue<MessageUTF8>.Enumerator enumer2 = reservedQueue.GetEnumerator();
  218. while (enumer2.MoveNext())
  219. {
  220. DateTime tempStart, tempEnd;
  221. try
  222. {
  223. tempStart = DateTime.Parse(enumer2.Current.bookTime);
  224. tempEnd = tempStart.AddHours(enumer2.Current.bookLength);
  225. //Console.WriteLine("#########" + enumer.Current.bookTime + "," + enumer.Current.bookLength);
  226. }
  227. catch { Console.WriteLine("时间解析异常2"); return false; }
  228. //Console.WriteLine("**********" + start.ToString() + "," + end.ToString() + "," + tempStart.ToString() + "," + tempEnd.ToString());
  229. //Console.WriteLine("**********" + ((tempStart - end).TotalMinutes > 0)+","+ ((start - tempEnd).TotalMinutes > 0));
  230. if (!((tempStart - end).TotalMinutes > 0 || (start - tempEnd).TotalMinutes > 0)) { count += 1; }
  231. }
  232. }
  233. Console.WriteLine("----------" + msg.context + ":" + allBookableSpace + "," + count);
  234. if (allBookableSpace > count)
  235. return true;
  236. else
  237. return false;
  238. }
  239. /// <summary>
  240. /// 根据消息类型分别处理
  241. /// </summary>
  242. /// <param name="msg"></param>
  243. private void MsgHandling(MessageUTF8 msg)
  244. {
  245. try
  246. {
  247. MessageUTF8 returnMsg = new MessageUTF8();
  248. switch (msg.cmd)
  249. {
  250. //预约停
  251. case "RESERVE":
  252. if (msg.userID != "" && msg.bookTime != "" && msg.bookLength != 0)
  253. {
  254. if (!ReservationValidate(msg))
  255. {
  256. //回复预约失败给web
  257. returnMsg.cmd = "RESERVEFAILED";
  258. returnMsg.userID = msg.userID;
  259. returnMsg.context = msg.context;
  260. returnMsg.garageID = ClientSettings.GarageID;
  261. comm.SendMessage(returnMsg);
  262. Monitor.Monitor.SetNotification("车辆" + msg.context + "预约停车,已无可预约车位", parkMonitor.model.TextColor.Warning);
  263. }
  264. else
  265. {
  266. bool DBOperResult = true;
  267. lock (waitToReserveLock)
  268. {
  269. waitToReserveQueue.Enqueue(msg);
  270. }
  271. //预约记录与车辆状态写入数据库
  272. DBOperResult = DBOperResult && ReserveDBOperation(true, msg.userID, true, msg.context, msg.bookTime, msg.bookLength);
  273. DBOperResult = DBOperResult && ReserveDBOperation(false, msg.userID, true, msg.context, msg.bookTime, msg.bookLength);
  274. //回复成功给web
  275. if (!DBOperResult)
  276. Log.WriteLog(LogType.process, LogFile.WARNING, msg.context + "从" + msg.bookTime + "开始预约" + msg.bookLength + "小时,预约指令数据库操作未获得记录ID");
  277. returnMsg.cmd = "RESERVEOK";
  278. returnMsg.userID = msg.userID;
  279. returnMsg.context = msg.context;
  280. returnMsg.garageID = ClientSettings.GarageID;
  281. comm.SendMessage(returnMsg);
  282. Monitor.Monitor.SetNotification("车辆" + msg.context + "预约停车,操作成功", parkMonitor.model.TextColor.Log);
  283. }
  284. }
  285. break;
  286. case "CANCELRESERVE":
  287. //IEqualityComparer<MessageUTF8> comparer ;
  288. //if(waitToReserveQueue.Contains(msg, )
  289. break;
  290. //预约取
  291. case "PREFETCH":
  292. break;
  293. //停车
  294. case "PARK":
  295. lock (parkLock)
  296. {
  297. returnMsg = new MessageUTF8();
  298. int id = 0;
  299. int countdown = 2;
  300. bool success = true;
  301. //根据号牌寻找对应号牌机编号,找不到则返回失败信息
  302. if (msg.context != "" && msg.userID != "")
  303. {
  304. while (id == 0 && countdown-- > 0)
  305. {
  306. try
  307. {
  308. //id = 1;
  309. id = Monitor.Monitor.numMachineLinker.GetLicenseID(msg.context.Split('.')[2]);
  310. }
  311. catch { Console.WriteLine("号牌截取异常"); }
  312. }
  313. }
  314. if (id != 0)
  315. //判断号牌机编号对应PLC数据块是否空闲,空闲则判断按钮状态并发送停车指令与号牌到PLC,否则返回失败信息
  316. {
  317. try
  318. {
  319. success = TerminalSimul.ParkTermOper(id, msg.context);
  320. }
  321. catch { success = false; }
  322. }
  323. else { success = false; }
  324. Thread.Sleep(1500);
  325. if (success)
  326. {
  327. returnMsg.cmd = "PARKOK";
  328. Monitor.Monitor.SetNotification("车辆" + msg.context.Split('.')[2] + "正在进行停车", parkMonitor.model.TextColor.Info);
  329. }
  330. else
  331. {
  332. returnMsg.cmd = "PARKFAILED";
  333. Monitor.Monitor.SetNotification("未识别到车辆" + msg.context.Split('.')[2] + "停放位置,请确认车辆已入场", parkMonitor.model.TextColor.Warning);
  334. }
  335. returnMsg.userID = msg.userID;
  336. returnMsg.garageID = Monitor.Monitor.garageID;
  337. returnMsg.context = msg.context;
  338. comm.SendMessage(returnMsg);
  339. }
  340. break;
  341. //取车
  342. case "FETCH":
  343. lock (fetchLock)
  344. {
  345. returnMsg = new MessageUTF8();
  346. bool success = TerminalSimul.FetchTermOper(msg.context);
  347. Thread.Sleep(1500);
  348. if (success)
  349. {
  350. returnMsg.cmd = "FETCHOK";
  351. Monitor.Monitor.SetNotification("凭证号" + msg.context + "正在取车", parkMonitor.model.TextColor.Info);
  352. }
  353. else
  354. {
  355. returnMsg.cmd = "FETCHFAILED";
  356. Monitor.Monitor.SetNotification("凭证号" + msg.context + "异常,无法解析", parkMonitor.model.TextColor.Warning);
  357. }
  358. returnMsg.userID = msg.userID;
  359. returnMsg.garageID = Monitor.Monitor.garageID;
  360. returnMsg.context = msg.context;
  361. comm.SendMessage(returnMsg);
  362. }
  363. break;
  364. //连接断开消息
  365. case "DISCONNECT":
  366. Monitor.Monitor.SetNotification("收到连接断开提示消息", parkMonitor.model.TextColor.Warning);
  367. break;
  368. //更新广告
  369. case "ADVERT":
  370. string adAlert = "";
  371. bool result = Monitor.Monitor.advertMgr.UpdateAdvert(out adAlert);
  372. if (!result)
  373. {
  374. Monitor.Monitor.SetNotification("广告更新失败,请尝试手动更新", parkMonitor.model.TextColor.Warning);
  375. }
  376. else
  377. {
  378. Monitor.Monitor.SetNotification("广告更新成功\n" + adAlert, parkMonitor.model.TextColor.Log);
  379. }
  380. break;
  381. case "RESPONSE":
  382. if (msg.context == "REGSUCCESS")
  383. {
  384. Console.WriteLine("收到web注册指令");
  385. }
  386. else if (msg.context == "HEARTSUCCESS")
  387. {
  388. Console.WriteLine("收到web心跳指令");
  389. }
  390. break;
  391. default:
  392. Monitor.Monitor.SetNotification("接收到无法识别的指令", parkMonitor.model.TextColor.Warning);
  393. break;
  394. }
  395. }
  396. catch (Exception ex) { Console.WriteLine("收消息," + ex.Message + "\n" + ex.StackTrace); }
  397. }
  398. private void SendBookCmd(bool parking, int state)
  399. {
  400. int countdown = 5;
  401. while (countdown-- > 0)
  402. {
  403. if (Monitor.Monitor.mainBlockInfo.bookParkCmd != 0 && countdown > 1)
  404. {
  405. Thread.Sleep(300);
  406. if (countdown == 2)
  407. {
  408. Monitor.Monitor.SetNotification("未能获取预约指令位0状态,尝试手动清除", parkMonitor.model.TextColor.Warning);
  409. MainBlockStru mbs = new MainBlockStru
  410. {
  411. centralHearbeat = -1,
  412. bookParkCmd = parking ? (short)0 : (short)-1,
  413. bookFetchCmd = !parking ? (short)0 : (short)-1,
  414. processCompleted = (short)-1,
  415. licenseReceived = -1
  416. };
  417. Monitor.Monitor.PLC.WriteToPLC(mbs, PLCDataType.central);
  418. Thread.Sleep(500);
  419. }
  420. continue;
  421. }
  422. MainBlockStru mb = new MainBlockStru
  423. {
  424. centralHearbeat = -1,
  425. bookParkCmd = parking ? (short)state : (short)-1,
  426. bookFetchCmd = !parking ? (short)state : (short)-1,
  427. processCompleted = (short)-1,
  428. licenseReceived = -1
  429. };
  430. Monitor.Monitor.PLC.WriteToPLC(mb, PLCDataType.central);
  431. Monitor.Monitor.SetNotification(mb.bookParkCmd + "," + mb.bookFetchCmd + "; 预约停车指令写入PLC", parkMonitor.model.TextColor.Log);
  432. Log.WriteLog(LogType.process, LogFile.INFO, mb.bookParkCmd + "," + mb.bookFetchCmd + "预约停车指令写入PLC");
  433. break;
  434. }
  435. }
  436. /// <summary>
  437. /// 根据时间段处理所有准备预约及已预约指令
  438. /// </summary>
  439. private void ReserveMsgHandling()
  440. {
  441. while (!isClosing)
  442. {
  443. //处理准备预约指令队列
  444. lock (waitToReserveLock)
  445. {
  446. for (int i = 0; i < waitToReserveQueue.Count; i++)
  447. {
  448. try
  449. {
  450. MessageUTF8 msg = waitToReserveQueue.Dequeue();
  451. DateTime startTime = DateTime.Parse(msg.bookTime);
  452. TimeSpan ts = DateTime.Now - startTime;
  453. //达到预约启动时间,放入已预约队列
  454. Console.WriteLine("当前时间差:" + ts.TotalMinutes + ",指令类型:" + msg.cmd);
  455. if (ts.TotalMinutes >= 0)
  456. {
  457. //如果是预约停车,通知PLC减少一个可预约车位数
  458. if (msg.cmd == "RESERVE")
  459. {
  460. //本地车位更新,2->3
  461. for (int j = 0; j < Monitor.Monitor.parkingSpaceInfo.Count; j++)
  462. {
  463. if (Monitor.Monitor.parkingSpaceInfo[j].spaceStatus == 2)
  464. {
  465. ParkingSpaceStru ps = Monitor.Monitor.parkingSpaceInfo[j];
  466. ps.spaceStatus = 3;
  467. Monitor.Monitor.parkingSpaceInfo[j] = ps;
  468. break;
  469. }
  470. }
  471. SendBookCmd(true, 1);
  472. Monitor.Monitor.SetNotification("通知PLC减少可预约车位", parkMonitor.model.TextColor.Log);
  473. }
  474. reservedQueue.Enqueue(msg);
  475. }
  476. //还未达到启动时间
  477. else
  478. {
  479. waitToReserveQueue.Enqueue(msg);
  480. }
  481. }
  482. catch { }
  483. }
  484. }
  485. lock (reservedLock)
  486. {
  487. for (int i = 0; i < reservedQueue.Count; i++)
  488. {
  489. try
  490. {
  491. MessageUTF8 msg = reservedQueue.Dequeue();
  492. DateTime startTime = DateTime.Parse(msg.bookTime);
  493. TimeSpan ts = DateTime.Now - startTime;
  494. //预约超时
  495. if (ts.TotalMinutes > msg.bookLength * 60)
  496. {
  497. Monitor.Monitor.SetNotification(msg.context + " 预约已超时", parkMonitor.model.TextColor.Warning);
  498. Log.WriteLog(LogType.process, LogFile.INFO, msg.context + " 预约已超时");
  499. //本地车位更新,3->2
  500. for (int j = 0; j < Monitor.Monitor.parkingSpaceInfo.Count; j++)
  501. {
  502. if (Monitor.Monitor.parkingSpaceInfo[j].spaceStatus == 3)
  503. {
  504. ParkingSpaceStru ps = Monitor.Monitor.parkingSpaceInfo[j];
  505. ps.spaceStatus = 2;
  506. Monitor.Monitor.parkingSpaceInfo[j] = ps;
  507. break;
  508. }
  509. }
  510. //通知PLC将可预约车位数恢复一个
  511. SendBookCmd(true, 2);
  512. //恢复车辆状态
  513. UpdateVehicleState(true, 0, 0, msg.context);
  514. UpdateVehicleState(false, 0, 0, msg.context);
  515. }
  516. else
  517. {
  518. reservedQueue.Enqueue(msg);
  519. }
  520. }
  521. catch { }
  522. }
  523. }
  524. Thread.Sleep(5000);
  525. }
  526. }
  527. /// <summary>
  528. /// 启动消息接收,启动超时指令处理
  529. /// </summary>
  530. /// <param name="port"></param>
  531. /// <returns></returns>
  532. public bool Start(int port)
  533. {
  534. isClosing = false;
  535. connecting = false;
  536. waitToReserveQueue = new Queue<MessageUTF8>();
  537. reservedQueue = new Queue<MessageUTF8>();
  538. //MessageUTF8 message = new MessageUTF8();
  539. //message.context = "sending message test";
  540. //message.cmd = "S";
  541. //message.parkingRecordsID = 1;
  542. //持续进行连接尝试
  543. Task.Factory.StartNew(() =>
  544. {
  545. //初始化后与web持续连接
  546. try
  547. {
  548. Connections.Connection();
  549. connected = true;
  550. while (!isClosing)
  551. {
  552. if (Connections.isAlive())
  553. {
  554. comm = new Communication();
  555. break;
  556. }
  557. else
  558. {
  559. Connections.close();
  560. Connections.Connection();
  561. }
  562. Thread.Sleep(1000);
  563. }
  564. }
  565. catch (Exception)
  566. {
  567. connected = false;
  568. Console.WriteLine("初始web服务连接异常");
  569. }
  570. Connect();
  571. });
  572. //持续接收消息
  573. receiveMsg = new Thread(() =>
  574. {
  575. while (!isClosing)
  576. {
  577. try
  578. {
  579. if (connected && comm != null)
  580. {
  581. //byte[] bytes = new byte[256];
  582. MessageUTF8 msg = ((MessageUTF8)comm.ReceiveMessage());
  583. //string str = "";
  584. //str = Encoding.Default.GetString(bytes);
  585. //Console.WriteLine(str);
  586. if (msg != null)
  587. {
  588. MsgHandling(msg);
  589. }
  590. //Monitor.Monitor.SetNotification(msg.context);
  591. }
  592. Thread.Sleep(200);
  593. }
  594. catch { Console.WriteLine("线程已中断"); }
  595. }
  596. });
  597. receiveMsg.Start();
  598. //根据所处时间段处理预约指令
  599. Task.Factory.StartNew(() =>
  600. {
  601. ReserveMsgHandling();
  602. });
  603. return true;
  604. }
  605. /// <summary>
  606. /// 停止消息接收模块
  607. /// </summary>
  608. public void Stop()
  609. {
  610. isClosing = true;
  611. try
  612. {
  613. Connections.close();
  614. }
  615. catch { }
  616. //throw new NotImplementedException();
  617. }
  618. /// <summary>
  619. /// 预约车辆入场检测
  620. /// </summary>
  621. /// <param name="license"></param>
  622. /// <returns></returns>
  623. public bool ReservedCarCheck(string license)
  624. {
  625. //对提前入场车辆,将预约指令丢出
  626. lock (waitToReserveLock)
  627. {
  628. for (int i = 0; i < waitToReserveQueue.Count; i++)
  629. {
  630. MessageUTF8 msg = waitToReserveQueue.Dequeue();
  631. if (msg.context != license)
  632. {
  633. waitToReserveQueue.Enqueue(msg);
  634. }
  635. }
  636. }
  637. //已进入预约状态车辆入场,审核确认后指令丢出
  638. lock (reservedLock)
  639. {
  640. for (int i = 0; i < reservedQueue.Count; i++)
  641. {
  642. MessageUTF8 msg = reservedQueue.Dequeue();
  643. if (msg.context == license)
  644. {
  645. return true;
  646. }
  647. else
  648. {
  649. reservedQueue.Enqueue(msg);
  650. }
  651. }
  652. }
  653. return false;
  654. }
  655. /// <summary>
  656. /// 主动连接web服务器
  657. /// </summary>
  658. public void Connect()
  659. {
  660. //持续判断连接状态并重连
  661. if (!connecting)
  662. {
  663. connecting = true;
  664. int count = 3;
  665. while (!isClosing)
  666. {
  667. //if (receiveMsg != null)
  668. // Console.WriteLine(Connections.isAlive() + ", " + receiveMsg.ThreadState.ToString());
  669. Console.WriteLine(Connections.isAlive() + "," + count + "," + connected);
  670. if (Connections.isAlive())
  671. {
  672. if (!connected)
  673. {
  674. comm = new Communication();
  675. Monitor.Monitor.SetNotification("web已连接上", parkMonitor.model.TextColor.Info);
  676. }
  677. count = 3;
  678. connected = true;
  679. if (receiveMsg != null && receiveMsg.ThreadState == ThreadState.Aborted)
  680. {
  681. try
  682. {
  683. receiveMsg.Start();
  684. }
  685. catch (Exception ex) { Console.WriteLine(ex.Message); }
  686. }
  687. }
  688. else
  689. {
  690. if (count == 3 && connected)
  691. Monitor.Monitor.SetNotification("web连接已断开", parkMonitor.model.TextColor.Warning);
  692. else if (count == 0)
  693. {
  694. try
  695. {
  696. Connections.close();
  697. //comm = null;
  698. }
  699. catch (Exception ex) { Console.WriteLine("网络异常,停止尝试"); }
  700. break;
  701. }
  702. else if (connected)
  703. {
  704. try { Connections.close(); }
  705. catch (Exception) { Console.WriteLine("服务没有开启,请检查服务器"); }
  706. }
  707. connected = false;
  708. count--;
  709. try
  710. {
  711. if (receiveMsg != null && receiveMsg.ThreadState == ThreadState.WaitSleepJoin)
  712. {
  713. receiveMsg.Interrupt();
  714. }
  715. }
  716. catch (Exception ex)
  717. {
  718. Monitor.Monitor.SetNotification("连接断开,终止消息接收线程", parkMonitor.model.TextColor.Log);
  719. }
  720. Console.WriteLine(" 连接关闭,需要重新连接注册");
  721. try { Connections.Connection(); } catch { Console.WriteLine("尝试连接异常"); }
  722. }
  723. Thread.Sleep(1000);
  724. }
  725. Monitor.Monitor.SetNotification("重连web服务器超时,请检查网络并手动连接web服务器", parkMonitor.model.TextColor.Error);
  726. connecting = false;
  727. }
  728. else
  729. {
  730. if (!connected)
  731. Monitor.Monitor.SetNotification("正在尝试连接,请勿重复点击", parkMonitor.model.TextColor.Warning);
  732. else
  733. Monitor.Monitor.SetNotification("已连接,请勿重复点击", parkMonitor.model.TextColor.Info);
  734. }
  735. }
  736. /// <summary>
  737. /// 获取连接状态
  738. /// </summary>
  739. /// <returns></returns>
  740. public bool GetConnectStatus()
  741. {
  742. return Connections.isAlive();
  743. }
  744. }
  745. }