WebServer.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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;//Monitor.Monitor.numMachineLinker.GetLicenseID(msg.context.Split('.')[2]);
  309. }
  310. catch { Console.WriteLine("号牌截取异常"); }
  311. }
  312. }
  313. if (id != 0)
  314. //判断号牌机编号对应PLC数据块是否空闲,空闲则判断按钮状态并发送停车指令与号牌到PLC,否则返回失败信息
  315. {
  316. try
  317. {
  318. success = TerminalSimul.ParkTermOper(id, msg.context);
  319. }
  320. catch { success = false; }
  321. }
  322. else { success = false; }
  323. Thread.Sleep(1500);
  324. if (success)
  325. {
  326. returnMsg.cmd = "PARKOK";
  327. Monitor.Monitor.SetNotification("车辆" + msg.context.Split('.')[2] + "正在进行停车", parkMonitor.model.TextColor.Info);
  328. }
  329. else
  330. {
  331. returnMsg.cmd = "PARKFAILED";
  332. Monitor.Monitor.SetNotification("未识别到车辆" + msg.context.Split('.')[2] + "停放位置,请确认车辆已入场", parkMonitor.model.TextColor.Warning);
  333. }
  334. returnMsg.userID = msg.userID;
  335. returnMsg.garageID = Monitor.Monitor.garageID;
  336. returnMsg.context = msg.context;
  337. comm.SendMessage(returnMsg);
  338. }
  339. break;
  340. //取车
  341. case "FETCH":
  342. lock (fetchLock)
  343. {
  344. returnMsg = new MessageUTF8();
  345. bool success = TerminalSimul.FetchTermOper(msg.context);
  346. Thread.Sleep(1500);
  347. if (success)
  348. {
  349. returnMsg.cmd = "FETCHOK";
  350. Monitor.Monitor.SetNotification("凭证号" + msg.context + "正在取车", parkMonitor.model.TextColor.Info);
  351. }
  352. else
  353. {
  354. returnMsg.cmd = "FETCHFAILED";
  355. Monitor.Monitor.SetNotification("凭证号" + msg.context + "异常,无法解析", parkMonitor.model.TextColor.Warning);
  356. }
  357. returnMsg.userID = msg.userID;
  358. returnMsg.garageID = Monitor.Monitor.garageID;
  359. returnMsg.context = msg.context;
  360. comm.SendMessage(returnMsg);
  361. }
  362. break;
  363. //连接断开消息
  364. case "DISCONNECT":
  365. Monitor.Monitor.SetNotification("收到连接断开提示消息", parkMonitor.model.TextColor.Warning);
  366. break;
  367. //更新广告
  368. case "ADVERT":
  369. string adAlert = "";
  370. bool result = Monitor.Monitor.advertMgr.UpdateAdvert(out adAlert);
  371. if (!result)
  372. {
  373. Monitor.Monitor.SetNotification("广告更新失败,请尝试手动更新", parkMonitor.model.TextColor.Warning);
  374. }
  375. else
  376. {
  377. Monitor.Monitor.SetNotification("广告更新成功\n" + adAlert, parkMonitor.model.TextColor.Log);
  378. }
  379. break;
  380. case "RESPONSE":
  381. if (msg.context == "REGSUCCESS")
  382. {
  383. Console.WriteLine("收到web注册指令");
  384. }
  385. else if (msg.context == "HEARTSUCCESS")
  386. {
  387. Console.WriteLine("收到web心跳指令");
  388. }
  389. break;
  390. default:
  391. Monitor.Monitor.SetNotification("接收到无法识别的指令", parkMonitor.model.TextColor.Warning);
  392. break;
  393. }
  394. }
  395. catch (Exception ex) { Console.WriteLine("收消息," + ex.Message + "\n" + ex.StackTrace); }
  396. }
  397. private void SendBookCmd(bool parking, int state)
  398. {
  399. int countdown = 5;
  400. while (countdown-- > 0)
  401. {
  402. if (Monitor.Monitor.mainBlockInfo.bookParkCmd != 0 && countdown > 1)
  403. {
  404. Thread.Sleep(300);
  405. if (countdown == 2)
  406. {
  407. Monitor.Monitor.SetNotification("未能获取预约指令位0状态,尝试手动清除", parkMonitor.model.TextColor.Warning);
  408. MainBlockStru mbs = new MainBlockStru
  409. {
  410. centralHearbeat = -1,
  411. bookParkCmd = parking ? (short)0 : (short)-1,
  412. bookFetchCmd = !parking ? (short)0 : (short)-1,
  413. processCompleted = (short)-1,
  414. licenseReceived = -1
  415. };
  416. Monitor.Monitor.PLC.WriteToPLC(mbs, PLCDataType.central);
  417. Thread.Sleep(500);
  418. }
  419. continue;
  420. }
  421. MainBlockStru mb = new MainBlockStru
  422. {
  423. centralHearbeat = -1,
  424. bookParkCmd = parking ? (short)state : (short)-1,
  425. bookFetchCmd = !parking ? (short)state : (short)-1,
  426. processCompleted = (short)-1,
  427. licenseReceived = -1
  428. };
  429. Monitor.Monitor.PLC.WriteToPLC(mb, PLCDataType.central);
  430. Monitor.Monitor.SetNotification(mb.bookParkCmd + "," + mb.bookFetchCmd + "; 预约停车指令写入PLC", parkMonitor.model.TextColor.Log);
  431. Log.WriteLog(LogType.process, LogFile.INFO, mb.bookParkCmd + "," + mb.bookFetchCmd + "预约停车指令写入PLC");
  432. break;
  433. }
  434. }
  435. /// <summary>
  436. /// 根据时间段处理所有准备预约及已预约指令
  437. /// </summary>
  438. private void ReserveMsgHandling()
  439. {
  440. while (!isClosing)
  441. {
  442. //处理准备预约指令队列
  443. lock (waitToReserveLock)
  444. {
  445. for (int i = 0; i < waitToReserveQueue.Count; i++)
  446. {
  447. try
  448. {
  449. MessageUTF8 msg = waitToReserveQueue.Dequeue();
  450. DateTime startTime = DateTime.Parse(msg.bookTime);
  451. TimeSpan ts = DateTime.Now - startTime;
  452. //达到预约启动时间,放入已预约队列
  453. Console.WriteLine("当前时间差:" + ts.TotalMinutes + ",指令类型:" + msg.cmd);
  454. if (ts.TotalMinutes >= 0)
  455. {
  456. //如果是预约停车,通知PLC减少一个可预约车位数
  457. if (msg.cmd == "RESERVE")
  458. {
  459. //本地车位更新,2->3
  460. for (int j = 0; j < Monitor.Monitor.parkingSpaceInfo.Count; j++)
  461. {
  462. if (Monitor.Monitor.parkingSpaceInfo[j].spaceStatus == 2)
  463. {
  464. ParkingSpaceStru ps = Monitor.Monitor.parkingSpaceInfo[j];
  465. ps.spaceStatus = 3;
  466. Monitor.Monitor.parkingSpaceInfo[j] = ps;
  467. break;
  468. }
  469. }
  470. SendBookCmd(true, 1);
  471. Monitor.Monitor.SetNotification("通知PLC减少可预约车位", parkMonitor.model.TextColor.Log);
  472. }
  473. reservedQueue.Enqueue(msg);
  474. }
  475. //还未达到启动时间
  476. else
  477. {
  478. waitToReserveQueue.Enqueue(msg);
  479. }
  480. }
  481. catch { }
  482. }
  483. }
  484. lock (reservedLock)
  485. {
  486. for (int i = 0; i < reservedQueue.Count; i++)
  487. {
  488. try
  489. {
  490. MessageUTF8 msg = reservedQueue.Dequeue();
  491. DateTime startTime = DateTime.Parse(msg.bookTime);
  492. TimeSpan ts = DateTime.Now - startTime;
  493. //预约超时
  494. if (ts.TotalMinutes > msg.bookLength * 60)
  495. {
  496. Monitor.Monitor.SetNotification(msg.context + " 预约已超时", parkMonitor.model.TextColor.Warning);
  497. Log.WriteLog(LogType.process, LogFile.INFO, msg.context + " 预约已超时");
  498. //本地车位更新,3->2
  499. for (int j = 0; j < Monitor.Monitor.parkingSpaceInfo.Count; j++)
  500. {
  501. if (Monitor.Monitor.parkingSpaceInfo[j].spaceStatus == 3)
  502. {
  503. ParkingSpaceStru ps = Monitor.Monitor.parkingSpaceInfo[j];
  504. ps.spaceStatus = 2;
  505. Monitor.Monitor.parkingSpaceInfo[j] = ps;
  506. break;
  507. }
  508. }
  509. //通知PLC将可预约车位数恢复一个
  510. SendBookCmd(true, 2);
  511. //恢复车辆状态
  512. UpdateVehicleState(true, 0, 0, msg.context);
  513. UpdateVehicleState(false, 0, 0, msg.context);
  514. }
  515. else
  516. {
  517. reservedQueue.Enqueue(msg);
  518. }
  519. }
  520. catch { }
  521. }
  522. }
  523. Thread.Sleep(5000);
  524. }
  525. }
  526. /// <summary>
  527. /// 启动消息接收,启动超时指令处理
  528. /// </summary>
  529. /// <param name="port"></param>
  530. /// <returns></returns>
  531. public bool Start(int port)
  532. {
  533. isClosing = false;
  534. connecting = false;
  535. waitToReserveQueue = new Queue<MessageUTF8>();
  536. reservedQueue = new Queue<MessageUTF8>();
  537. //MessageUTF8 message = new MessageUTF8();
  538. //message.context = "sending message test";
  539. //message.cmd = "S";
  540. //message.parkingRecordsID = 1;
  541. //持续进行连接尝试
  542. Task.Factory.StartNew(() =>
  543. {
  544. //初始化后与web持续连接
  545. try
  546. {
  547. Connections.Connection();
  548. connected = true;
  549. while (!isClosing)
  550. {
  551. if (Connections.isAlive())
  552. {
  553. comm = new Communication();
  554. break;
  555. }
  556. else
  557. {
  558. Connections.close();
  559. Connections.Connection();
  560. }
  561. Thread.Sleep(1000);
  562. }
  563. }
  564. catch (Exception)
  565. {
  566. connected = false;
  567. Console.WriteLine("初始web服务连接异常");
  568. }
  569. Connect();
  570. });
  571. //持续接收消息
  572. receiveMsg = new Thread(() =>
  573. {
  574. while (!isClosing)
  575. {
  576. try
  577. {
  578. if (connected && comm != null)
  579. {
  580. //byte[] bytes = new byte[256];
  581. MessageUTF8 msg = ((MessageUTF8)comm.ReceiveMessage());
  582. //string str = "";
  583. //str = Encoding.Default.GetString(bytes);
  584. //Console.WriteLine(str);
  585. if (msg != null)
  586. {
  587. MsgHandling(msg);
  588. }
  589. //Monitor.Monitor.SetNotification(msg.context);
  590. }
  591. Thread.Sleep(200);
  592. }
  593. catch { Console.WriteLine("线程已中断"); }
  594. }
  595. });
  596. receiveMsg.Start();
  597. //根据所处时间段处理预约指令
  598. Task.Factory.StartNew(() =>
  599. {
  600. ReserveMsgHandling();
  601. });
  602. return true;
  603. }
  604. /// <summary>
  605. /// 停止消息接收模块
  606. /// </summary>
  607. public void Stop()
  608. {
  609. isClosing = true;
  610. try
  611. {
  612. Connections.close();
  613. }
  614. catch { }
  615. //throw new NotImplementedException();
  616. }
  617. /// <summary>
  618. /// 预约车辆入场检测
  619. /// </summary>
  620. /// <param name="license"></param>
  621. /// <returns></returns>
  622. public bool ReservedCarCheck(string license)
  623. {
  624. //对提前入场车辆,将预约指令丢出
  625. lock (waitToReserveLock)
  626. {
  627. for (int i = 0; i < waitToReserveQueue.Count; i++)
  628. {
  629. MessageUTF8 msg = waitToReserveQueue.Dequeue();
  630. if (msg.context != license)
  631. {
  632. waitToReserveQueue.Enqueue(msg);
  633. }
  634. }
  635. }
  636. //已进入预约状态车辆入场,审核确认后指令丢出
  637. lock (reservedLock)
  638. {
  639. for (int i = 0; i < reservedQueue.Count; i++)
  640. {
  641. MessageUTF8 msg = reservedQueue.Dequeue();
  642. if (msg.context == license)
  643. {
  644. return true;
  645. }
  646. else
  647. {
  648. reservedQueue.Enqueue(msg);
  649. }
  650. }
  651. }
  652. return false;
  653. }
  654. /// <summary>
  655. /// 主动连接web服务器
  656. /// </summary>
  657. public void Connect()
  658. {
  659. //持续判断连接状态并重连
  660. if (!connecting)
  661. {
  662. connecting = true;
  663. int count = 3;
  664. while (!isClosing)
  665. {
  666. //if (receiveMsg != null)
  667. // Console.WriteLine(Connections.isAlive() + ", " + receiveMsg.ThreadState.ToString());
  668. Console.WriteLine(Connections.isAlive()+","+count+","+connected);
  669. if (Connections.isAlive())
  670. {
  671. if (!connected)
  672. {
  673. comm = new Communication();
  674. Monitor.Monitor.SetNotification("web已连接上", parkMonitor.model.TextColor.Info);
  675. }
  676. count = 3;
  677. connected = true;
  678. if (receiveMsg != null && receiveMsg.ThreadState == ThreadState.Aborted)
  679. {
  680. try
  681. {
  682. receiveMsg.Start();
  683. }
  684. catch (Exception ex) { Console.WriteLine(ex.Message); }
  685. }
  686. }
  687. else
  688. {
  689. if (count == 3 && connected)
  690. Monitor.Monitor.SetNotification("web连接已断开", parkMonitor.model.TextColor.Warning);
  691. else if (count == 0)
  692. {
  693. try
  694. {
  695. Connections.close();
  696. //comm = null;
  697. }
  698. catch (Exception ex) { Console.WriteLine("网络异常,停止尝试"); }
  699. break;
  700. }
  701. else if(connected){
  702. try { Connections.close(); }
  703. catch (Exception) { Console.WriteLine("服务没有开启,请检查服务器"); }
  704. }
  705. connected = false;
  706. count--;
  707. try
  708. {
  709. if (receiveMsg != null && receiveMsg.ThreadState == ThreadState.WaitSleepJoin)
  710. {
  711. receiveMsg.Interrupt();
  712. }
  713. }
  714. catch (Exception ex)
  715. {
  716. Monitor.Monitor.SetNotification("连接断开,终止消息接收线程", parkMonitor.model.TextColor.Log);
  717. }
  718. Console.WriteLine(" 连接关闭,需要重新连接注册");
  719. try { Connections.Connection(); } catch { Console.WriteLine("尝试连接异常"); }
  720. }
  721. Thread.Sleep(1000);
  722. }
  723. Monitor.Monitor.SetNotification("重连web服务器超时,请检查网络并手动连接web服务器", parkMonitor.model.TextColor.Error);
  724. connecting = false;
  725. }
  726. else
  727. {
  728. if(!connected)
  729. Monitor.Monitor.SetNotification("正在尝试连接,请勿重复点击", parkMonitor.model.TextColor.Warning);
  730. else
  731. Monitor.Monitor.SetNotification("已连接,请勿重复点击", parkMonitor.model.TextColor.Info);
  732. }
  733. }
  734. /// <summary>
  735. /// 获取连接状态
  736. /// </summary>
  737. /// <returns></returns>
  738. public bool GetConnectStatus()
  739. {
  740. return Connections.isAlive();
  741. }
  742. }
  743. }