WebServer.cs 25 KB

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