WebServer.cs 37 KB

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