WebServer.cs 23 KB

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