WebServer.cs 38 KB

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