WebServer.cs 29 KB

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