WebServer.cs 38 KB

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