NumMachine.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. using centralController;
  2. using parkMonitor.entity;
  3. using parkMonitor.LOG;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Configuration;
  7. using System.Diagnostics;
  8. using System.Drawing;
  9. using System.IO;
  10. using System.Net;
  11. using System.Runtime.InteropServices;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Windows.Forms;
  15. using VzClientSDKDemo;
  16. namespace NumMachine
  17. {
  18. /// <summary>
  19. /// 号牌机通信类
  20. /// </summary>
  21. public partial class NumMachineLinker : INumMachineLinker
  22. {
  23. /// <summary>
  24. /// 刷新时间间隔与个数
  25. /// </summary>
  26. public const int REFRESHINGTIME = 500, FILTERINGNUMBER = 5;
  27. ///<summary>通过设备句柄访问pic;链接时add,系统关闭时remove</summary>
  28. private static Dictionary<int, IntPtr> devPicMap = new Dictionary<int, IntPtr>();
  29. ///<summary>通过名字获取pic对象;创建pic时add,系统关闭remove</summary>
  30. private static Dictionary<string, IntPtr> namePicMap = new Dictionary<string, IntPtr>();
  31. ///<summary>通过ip获取设备id;产生ip时创建</summary>
  32. private static Dictionary<string, int> ipIdMap = new Dictionary<string, int>();
  33. ///<summary>通过ip获取设备句柄;产生句柄时创建</summary>
  34. private static Dictionary<string, int> ipHandleMap = new Dictionary<string, int>();
  35. /// <summary>句柄到号牌回调映射</summary>
  36. private static Dictionary<int, VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK> handleCallbackMap = new Dictionary<int, VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK>();
  37. ///<summary>号牌队列</summary>
  38. private static Queue<NumberMachineNode> LicBuffer = new Queue<NumberMachineNode>();
  39. ///<summary>计数Map</summary>
  40. private static Dictionary<string, Dictionary<NumberMachineNode, int>> filterMap = new Dictionary<string, Dictionary<NumberMachineNode, int>>();
  41. /// <summary> 终端编号与当前号牌映射表</summary>
  42. private static Dictionary<int, string> idLicenseMap = new Dictionary<int, string>();
  43. /// <summary>号牌机编号与激活计数</summary>
  44. private Dictionary<int, int> idCountMap = new Dictionary<int, int>();
  45. /// <summary>筛选计数</summary>
  46. private static int filterCount = 0;
  47. private static double filterRatio = 0.7;
  48. /// <summary>系统关闭</summary>
  49. private static bool isClosing = false;
  50. /// <summary>开启拍照的设备</summary>
  51. private static int snapshotDevHandle = -1;
  52. /// <summary>允许无号牌时拍照</summary>
  53. private static bool enableEmptySnapshot = true;
  54. private static NumberMachineMessage nmMsg = new NumberMachineMessage();
  55. private static VzClientSDK.VZLPRC_FIND_DEVICE_CALLBACK_EX find_DeviceCB = null;
  56. private const int MSG_PLATE_INFO = 0x901;
  57. private const int MSG_DEVICE_INFO = 0x902;
  58. /// <summary>
  59. /// 用于消息传递机制
  60. /// </summary>
  61. //public static IntPtr hwndMain;
  62. /// <summary>
  63. /// 定义时钟委托
  64. /// </summary>
  65. private delegate void SetDateTime();
  66. private static IntPtr flowLayoutPanel1;
  67. private static ToolStripStatusLabel timeLabel;
  68. /// <summary>
  69. /// 号牌机类构造函数
  70. /// </summary>
  71. public NumMachineLinker(IntPtr flpHandle)
  72. {
  73. //Control.CheckForIllegalCrossThreadCalls = false;
  74. //Thread thread = new Thread(new ThreadStart(DateTimeInfo));
  75. //thread.IsBackground = true;
  76. //thread.Start(); //显示当前时间
  77. flowLayoutPanel1 = flpHandle;
  78. //timeLabel = new ToolStripStatusLabel();
  79. try
  80. {
  81. VzClientSDK.VzLPRClient_Setup();
  82. filterRatio = Double.Parse(ConfigurationManager.AppSettings.Get("filterRatio"));
  83. }
  84. catch (Exception e) { Console.WriteLine(e.Message + ",号牌机配置文件异常"); }
  85. //m_sAppPath = System.IO.Directory.GetCurrentDirectory();
  86. }
  87. private void DateTimeInfo()
  88. {
  89. try
  90. {
  91. while (!isClosing)
  92. {
  93. SetDateTime setDate = new SetDateTime(
  94. delegate
  95. {
  96. timeLabel.Text = DateTime.Now.ToString();
  97. });
  98. setDate();
  99. Thread.Sleep(1000);
  100. }
  101. // ReSharper disable once FunctionNeverReturns
  102. }
  103. catch (Exception e) { Debug.Print(e.StackTrace); }
  104. }
  105. //******************************************************************************************************************
  106. private void UpdateStatus(NumberMachineNode nmn)
  107. {
  108. //提示次数计数
  109. int count = 0;
  110. while (!isClosing)
  111. {
  112. if (GetStatus(nmn.ip) == 1)
  113. {
  114. nmn.status = EnumNumberMachineStatus.Normal;
  115. count = 0;
  116. }
  117. else
  118. {
  119. count++;
  120. //号牌机断线写日志
  121. nmn.status = EnumNumberMachineStatus.Offline;
  122. if (count == 1)
  123. {
  124. Console.WriteLine("正在与ip为 " + nmn.ip + " 的号牌机 进行连接。");
  125. }
  126. else if (count == 30)
  127. {
  128. nmMsg.data.Remove(nmn);
  129. }
  130. Thread.Sleep(10000);
  131. }
  132. }
  133. }
  134. private void Run()
  135. {
  136. try
  137. {
  138. while (!isClosing)
  139. {
  140. Thread.Sleep(REFRESHINGTIME);
  141. ////定时更新号牌
  142. //lock (ipHandleMap)
  143. //{
  144. // Dictionary<string, int>.Enumerator HandleEnumer = ipHandleMap.GetEnumerator();
  145. // while (HandleEnumer.MoveNext())
  146. // {
  147. // ActivateSnap(HandleEnumer.Current.Value);
  148. // }
  149. //}
  150. ////读取设备ip与id映射关系
  151. //lock (ipHandleMap)
  152. //{
  153. // Dictionary<string, int>.Enumerator ipEnumer = ipHandleMap.GetEnumerator();
  154. // while (ipEnumer.MoveNext())
  155. // {
  156. // //映射关系不存在则读取配置文件
  157. // lock (ipIdMap)
  158. // {
  159. // if (ipEnumer.Current.Key != null && !ipIdMap.ContainsKey(ipEnumer.Current.Key))
  160. // {
  161. // try
  162. // {
  163. // int id = Int32.Parse(ConfigurationManager.AppSettings.Get(ipEnumer.Current.Key));
  164. // ipIdMap.Add(ipEnumer.Current.Key, id);
  165. // idCountMap.Add(id, FILTERINGNUMBER);
  166. // }
  167. // catch (Exception) { Console.WriteLine("读取号牌机编号映射失败,配置文件填写有误"); }
  168. // }
  169. // }
  170. // }
  171. //}
  172. lock (LicBuffer)
  173. {
  174. //删除已停好车的号牌
  175. for (int i = 0; i < LicBuffer.Count; i++)
  176. {
  177. NumberMachineNode n = LicBuffer.Dequeue();
  178. if (n.ip != "")
  179. {
  180. LicBuffer.Enqueue((NumberMachineNode)n.Clone());
  181. }
  182. }
  183. }
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. Debug.WriteLine(ex.ToString());
  189. }
  190. }
  191. ///<summary>寻找设备回调函数</summary>
  192. private void FIND_DEVICE_CALLBACK_EX(string pStrDevName, string pStrIPAddr, ushort usPort1, ushort usPort2, uint SL, uint SH, string netmask, string gateway, IntPtr pUserData)
  193. {
  194. string pStrDev = pStrIPAddr.ToString() + ":" + usPort1.ToString();
  195. string serialNO = SL.ToString() + ":" + SH.ToString() + ":" + netmask + ":" + gateway;
  196. VzClientSDK.VZ_LPR_DEVICE_INFO device_info = new VzClientSDK.VZ_LPR_DEVICE_INFO();
  197. device_info.device_ip = pStrDev;
  198. device_info.serial_no = serialNO;
  199. DeviceLink(pStrDev, serialNO);
  200. }
  201. ///<summary>与设备连接,启动更新设备状态线程,输出视频</summary>
  202. private void DeviceLink(string pStrDev, string serialNO)
  203. {
  204. IPEndPoint ipe;
  205. GetIpEndPoint(pStrDev, out ipe);
  206. string ip = ipe.Address.ToString();
  207. if (ipHandleMap.ContainsKey(ip))
  208. {
  209. //MessageBox.Show("设备已分配句柄");
  210. return;
  211. }
  212. int handle = 0;
  213. handle = VzClientSDK.VzLPRClient_Open(ip, (ushort)80, "admin", "admin");
  214. if (handle == 0)
  215. {
  216. return;
  217. }
  218. VzClientSDK.VzLPRClient_SetVideoEncodeType(handle, 0);
  219. //将句柄加入
  220. lock (ipHandleMap)
  221. {
  222. ipHandleMap.Add(ip, handle);
  223. }
  224. //MessageBox.Show("摄像头打开成功");
  225. lock (handleCallbackMap)
  226. {
  227. handleCallbackMap.Add(handle, null);
  228. }
  229. int id = 0;
  230. //读到设备则添加id映射并初始化号牌计数器
  231. lock (ipIdMap)
  232. {
  233. if (!ipIdMap.ContainsKey(ip))
  234. {
  235. try
  236. {
  237. id = Int32.Parse(ConfigurationManager.AppSettings.Get(ip));
  238. ipIdMap.Add(ip, id);
  239. idCountMap.Add(id, FILTERINGNUMBER);
  240. GetLicensePlate(id);
  241. }
  242. catch (Exception) { Console.WriteLine("读取号牌机编号映射失败,配置文件填写有误"); }
  243. }
  244. }
  245. //找到设备,加入list
  246. NumberMachineNode node = new NumberMachineNode(ip, id, "", "", 1);
  247. nmMsg.data.Add(node);
  248. Task.Factory.StartNew(() =>
  249. {
  250. UpdateStatus(node);
  251. });
  252. //链接句柄到新PictureBox
  253. VideoOutput(handle);
  254. }
  255. ///<summary>视频输出</summary>
  256. private void VideoOutput(int handle)
  257. {
  258. try
  259. {
  260. lock (devPicMap)
  261. {
  262. lock (handleCallbackMap)
  263. {
  264. //存在设备则复位并在原pic上输出
  265. if (devPicMap.ContainsKey(handle))
  266. {
  267. VzClientSDK.VzLPRClient_SetPlateInfoCallBack(handle, null, IntPtr.Zero, 0);
  268. IntPtr pic;
  269. if (devPicMap.TryGetValue(handle, out pic) && handleCallbackMap.ContainsKey(handle))
  270. {
  271. int playHandle = VzClientSDK.VzLPRClient_StartRealPlay(handle, pic);
  272. // 设置车牌识别结果回调
  273. handleCallbackMap[handle] = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateResult);
  274. VzClientSDK.VzLPRClient_SetPlateInfoCallBack(handle, handleCallbackMap[handle], IntPtr.Zero, 1);
  275. //m_PlateResultCB = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateResult);
  276. //VzClientSDK.VzLPRClient_SetPlateInfoCallBack(handle, m_PlateResultCB, IntPtr.Zero, 1);
  277. //VzClientSDK.VzLPRClient_StopRealPlay(handle);
  278. }
  279. }
  280. else//否则找一个空位加pic
  281. {
  282. for (int i = 0; i < 20; i++)
  283. {
  284. string str = "PictureBox" + Convert.ToString(i);
  285. //该名称对应控件不存在,则创建并链接pic
  286. lock (namePicMap)
  287. {
  288. if (!namePicMap.ContainsKey(str) && handleCallbackMap.ContainsKey(handle))
  289. {
  290. IntPtr pic;
  291. if (CreatePic(i, handle, out pic))
  292. {
  293. devPicMap.Add(handle, pic);
  294. //ipIdMap.Add(Get_IP(handle), i);
  295. VzClientSDK.VzLPRClient_SetPlateInfoCallBack(handle, null, IntPtr.Zero, 0);
  296. //Console.WriteLine(handle+","+pic.ToString());
  297. int playHandle = VzClientSDK.VzLPRClient_StartRealPlay(handle, pic);
  298. // 设置车牌识别结果回调
  299. handleCallbackMap[handle] = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateResult);
  300. VzClientSDK.VzLPRClient_SetPlateInfoCallBack(handle, handleCallbackMap[handle], IntPtr.Zero, 1);
  301. //m_PlateResultCB = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateResult);
  302. //VzClientSDK.VzLPRClient_SetPlateInfoCallBack(handle, m_PlateResultCB, IntPtr.Zero, 1);
  303. //VzClientSDK.VzLPRClient_StopRealPlay(handle);
  304. break;
  305. }
  306. }
  307. }
  308. }
  309. }
  310. }
  311. }
  312. }
  313. catch (Exception e)
  314. {
  315. Debug.WriteLine(e.Message + ",jumped out");
  316. }
  317. }
  318. ///<summary>号牌信息回调</summary>
  319. private int OnPlateResult(int handle, IntPtr pUserData,
  320. IntPtr pResult, uint uNumPlates,
  321. VzClientSDK.VZ_LPRC_RESULT_TYPE eResultType,
  322. IntPtr pImgFull,
  323. IntPtr pImgPlateClip)
  324. {
  325. if (eResultType != VzClientSDK.VZ_LPRC_RESULT_TYPE.VZ_LPRC_RESULT_REALTIME)
  326. {
  327. VzClientSDK.TH_PlateResult result = (VzClientSDK.TH_PlateResult)Marshal.PtrToStructure(pResult, typeof(VzClientSDK.TH_PlateResult));
  328. string strLicense = (new string(result.license)).Split('\0')[0];
  329. VzClientSDK.VZ_LPR_MSG_PLATE_INFO plateInfo = new VzClientSDK.VZ_LPR_MSG_PLATE_INFO();
  330. plateInfo.plate = strLicense;
  331. SetDetail(plateInfo, Get_IP(handle));
  332. //根据setMessage中通过id信息找到的handle保存图片
  333. if (handle == snapshotDevHandle)
  334. {
  335. if (enableEmptySnapshot || !strLicense.Contains("_无_"))
  336. {
  337. string strFilePath = ConfigurationManager.AppSettings["LogPath"] + DateTime.Now.ToString("yyyyMMdd") + "\\";
  338. if (!Directory.Exists(strFilePath))
  339. {
  340. Directory.CreateDirectory(strFilePath);
  341. }
  342. string ip = Get_IP(handle);
  343. string path = strFilePath + ip + "-" + DateTime.Now.ToString("hh_mm_ss") + ".jpg";
  344. int temp = VzClientSDK.VzLPRClient_ImageSaveToJpeg(pImgFull, path, 50);
  345. if (temp != -1)
  346. {
  347. Console.WriteLine("号牌机" + ip + "已拍照,图片保存于 " + strFilePath);
  348. }
  349. else
  350. {
  351. Console.WriteLine("图片保存失败");
  352. }
  353. }
  354. snapshotDevHandle = -1;
  355. }
  356. }
  357. return 0;
  358. }
  359. ///<summary>记录车牌,时间,状态信息;刷新本地entity,并且入buffer</summary>
  360. private void SetDetail(VzClientSDK.VZ_LPR_MSG_PLATE_INFO plateInformation, string strIP)
  361. {
  362. int stat = GetStatus(strIP);
  363. bool found = false;
  364. int id = 0;
  365. //检查设备是否存在
  366. foreach (NumberMachineNode nmn in nmMsg.data)
  367. {
  368. //相同设备
  369. if (nmn.ip == strIP)
  370. {
  371. found = true;
  372. //号牌不为空
  373. if (!(plateInformation.plate.Contains("_无_")))
  374. {
  375. //Log.WriteLog(LogType.process, LogFile.INFO, nmn.id + "收到号牌回调信息: [" + plateInformation.plate + "]");
  376. nmn.SetLic(strIP, nmn.id, plateInformation.plate, DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"), GetStatus(strIP));
  377. FilterLic(strIP, (NumberMachineNode)nmn.Clone());
  378. }
  379. //号牌为空
  380. else
  381. {
  382. nmn.SetLic(strIP, nmn.id, "", "", GetStatus(strIP));
  383. FilterLic(strIP, null);
  384. }
  385. }
  386. }
  387. //新设备
  388. if (!found)
  389. {
  390. lock (ipIdMap)
  391. {
  392. if (!(plateInformation.plate.Contains("_无_")) && ipIdMap.TryGetValue(strIP, out id))
  393. {
  394. NumberMachineNode nmn = new NumberMachineNode(strIP, id, plateInformation.plate, DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"), GetStatus(strIP));
  395. NumberMachineNode nmnc = (NumberMachineNode)nmn.Clone();
  396. nmMsg.data.Add(nmnc);
  397. FilterLic(strIP, nmnc);
  398. }
  399. else
  400. {
  401. nmMsg.data.Add(new NumberMachineNode(strIP, id, "", "", GetStatus(strIP)));
  402. FilterLic(strIP, null);
  403. }
  404. }
  405. }
  406. }
  407. ///<summary>筛选号牌</summary>
  408. private void FilterLic(string ip, NumberMachineNode nmn)
  409. {
  410. int id = 0, activeCount = 0;
  411. if (ipIdMap.TryGetValue(ip, out id) && idCountMap.TryGetValue(id, out activeCount))// && activeCount < FILTERINGNUMBER)
  412. {
  413. Dictionary<NumberMachineNode, int> filter;
  414. //该filter不存在则创建
  415. if (!filterMap.ContainsKey(ip))
  416. {
  417. filter = new Dictionary<NumberMachineNode, int>();
  418. filterMap.Add(ip, filter);
  419. }
  420. else if (!filterMap.TryGetValue(ip, out filter))//计数器异常
  421. {
  422. return;
  423. }
  424. else if (activeCount == 0) //刚接到拍摄命令
  425. {
  426. filter.Clear();
  427. }
  428. //激活次数统计
  429. idCountMap[id] = activeCount + 1;
  430. //filter计数
  431. int count = 0;
  432. if (nmn == null)
  433. {
  434. if (activeCount >= FILTERINGNUMBER - 1)
  435. {
  436. //UILogServer.ins.error("本轮未扫描到号牌,请重新点击按钮停车");
  437. //string context = System.DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ":" + "号牌未扫描到,请重发指令";
  438. //string sql = "insert into messagequeue(userID,context,messageType) values (1,'" + context + "',1)";
  439. //List<string> strs = new List<string>();
  440. //strs.Add(sql);
  441. //DBOperation.InsertMessageQueue(EntityForCore.remoteBQ, strs);
  442. }
  443. return;
  444. }
  445. else if (filter.ContainsKey(nmn) && filter.TryGetValue(nmn, out count))//存在则数量+1
  446. {
  447. filter[nmn] = count + 1;
  448. }
  449. else//不存在则计数1
  450. {
  451. filter.Add(nmn, 1);
  452. }
  453. //计算总数
  454. filterCount = 0;
  455. Dictionary<NumberMachineNode, int>.Enumerator countEnumer = filter.GetEnumerator();
  456. while (countEnumer.MoveNext())
  457. {
  458. filterCount += countEnumer.Current.Value;
  459. }
  460. //达到计数限制,计算总数是否达标,达标则入队
  461. if (filterCount >= FILTERINGNUMBER)
  462. {
  463. lock (LicBuffer)
  464. {
  465. Dictionary<NumberMachineNode, int>.Enumerator enumer = filter.GetEnumerator();
  466. int maxCount = 0;
  467. NumberMachineNode node = null;
  468. while (enumer.MoveNext())
  469. {
  470. ////遍历,计数达标且队列中无此号牌
  471. //Log.WriteLog(LogType.process, LogFile.INFO, "filter中号牌:" + enumer.Current.Key.LicenseNum + ", 个数:" + enumer.Current.Value);
  472. //if (enumer.Current.Value >= (int)(filterCount * filterRatio) && enumer.Current.Key != null && !LicBuffer.Contains(enumer.Current.Key))
  473. //找到最大计数及相应号牌信息
  474. if (enumer.Current.Value >= maxCount && enumer.Current.Key != null)// && !LicBuffer.Contains(enumer.Current.Key))
  475. {
  476. ////输出节点为空或与该号牌不同
  477. //if (nmMsg.aNode == null || nmMsg.aNode.LicenseNum == null || nmMsg.aNode.LicenseNum != enumer.Current.Key.LicenseNum)
  478. //{
  479. maxCount = enumer.Current.Value;
  480. node = (NumberMachineNode)enumer.Current.Key.Clone();
  481. //Log.WriteLog(LogType.process, LogFile.INFO, "筛出号牌:" + node);
  482. //}
  483. }
  484. }
  485. if (node != null)
  486. //if (node != null && ipIdMap.TryGetValue(node.ip, out node.id))
  487. {
  488. //LicBuffer.Enqueue((NumberMachineNode)node.Clone());
  489. LicBuffer.Enqueue(node);
  490. Log.WriteLog(LogType.process, LogFile.INFO, "号牌入队:" + node.LicenseNum);
  491. if (Monitor.Monitor.allInOneMachine != null)
  492. {
  493. //Monitor.Monitor.allInOneMachine.DispForAWhile(2, node.LicenseNum, 25, 1, node.LicenseNum + ",入场");
  494. //Monitor.Monitor.allInOneMachine.DispForAWhile(3, "号牌机编号:" + node.id, 25, 1, "");
  495. }
  496. }
  497. }
  498. //filterCount = 0;
  499. filter.Clear();
  500. }
  501. }
  502. }
  503. ///<summary>停止播放与设备句柄关联的视频</summary>
  504. private void StopPlay(int handleInput)
  505. {
  506. if (handleInput != 0)
  507. {
  508. int ret = VzClientSDK.VzLPRClient_StopRealPlay(handleInput);
  509. }
  510. }
  511. ///<summary>强制获取号牌</summary>
  512. private void ActivateSnap(int handle)
  513. {
  514. if (handle > 0)
  515. {
  516. VzClientSDK.VzLPRClient_ForceTrigger(handle);
  517. }
  518. }
  519. ///<summary>ip+port字符串转ipe</summary>
  520. private void GetIpEndPoint(string ipp, out IPEndPoint ipe)
  521. {
  522. IPAddress myIP = IPAddress.Parse(ipp.Remove(ipp.LastIndexOf(':')) + "");
  523. string myPort = ipp.Substring(ipp.IndexOf(':') + 1);
  524. ipe = new IPEndPoint(myIP, int.Parse(myPort));
  525. }
  526. ///<summary>创建新pic并记录在picNameMap</summary>
  527. private bool CreatePic(int index, int handle, out IntPtr pic)
  528. {
  529. pic = IntPtr.Zero;
  530. PictureBox pb = new PictureBox
  531. {
  532. Width = 179,
  533. Height = 127,
  534. //Bounds = new System.Drawing.Rectangle(0, 0, 230, 180),
  535. Name = "PictureBox" + Convert.ToString(index)
  536. };
  537. lock (namePicMap)
  538. {
  539. if (!namePicMap.ContainsKey(pb.Name))
  540. {
  541. PictureBox temp = pb;
  542. IntPtr picHandle = IntPtr.Zero;
  543. try
  544. {
  545. Control flp = Control.FromHandle(flowLayoutPanel1);
  546. //创建tableLayoutPanel显示号牌机信息
  547. string ip = Get_IP(handle);
  548. int id = 0;
  549. ipIdMap.TryGetValue(ip, out id);
  550. TableLayoutPanel tlp = new TableLayoutPanel()
  551. {
  552. Name = "tlp" + Convert.ToString(id),
  553. ColumnCount = 1,
  554. RowCount = 2,
  555. Size = new Size(185, 168),
  556. TabIndex = 3,
  557. };
  558. Label lb_numMachine = new Label()
  559. {
  560. Text = "编号" + id + "\nIP:" + ip,
  561. TextAlign = ContentAlignment.MiddleCenter,
  562. Size = new Size(179, 27)
  563. };
  564. //temp.Dock = DockStyle.Bottom;
  565. //lb_numMachine.Dock = DockStyle.Top;
  566. tlp.Controls.Add(temp, 0, 1);
  567. tlp.Controls.Add(lb_numMachine, 0, 0);
  568. tlp.RowStyles.Add(new RowStyle(SizeType.Percent, 20.00f));
  569. tlp.RowStyles.Add(new RowStyle(SizeType.Percent, 80.00f));
  570. temp.Click += delegate (object o, EventArgs e)
  571. {
  572. //Console.WriteLine(((PictureBox)o).TopLevelControl.Name+","+e.ToString());
  573. try
  574. {
  575. if (((PictureBox)o).TopLevelControl.Name != "FormNumberMachinePreview")
  576. {
  577. FormNumberMachinePreview form = new FormNumberMachinePreview("编号" + id + ", IP:" + ip, temp, tlp);
  578. form.ShowDialog();
  579. }
  580. }
  581. catch { }
  582. };
  583. //Control.FromHandle(flowLayoutPanel1).Controls.Add(temp);
  584. if (flp.InvokeRequired)
  585. {
  586. flp.Invoke(new Action(() =>
  587. {
  588. flp.Controls.Add(tlp);
  589. //for (int i = 0; i < 12; i++)
  590. //{
  591. // TableLayoutPanel tlpTemp = new TableLayoutPanel();
  592. // tlpTemp.Width = 200;
  593. // tlpTemp.Height = 200;
  594. // flp.Controls.Add(tlpTemp);
  595. //}
  596. Control.ControlCollection flpCC = flp.Controls;
  597. try
  598. {
  599. int rows = (int)Math.Sqrt(flp.Controls.Count + 1);
  600. int columns = (int)(flp.Controls.Count * 1.0 / rows + 1);
  601. //tlp.Width = (int)(flp.Width * 1.0 / (columns * 1.05));
  602. //tlp.Height = (int)(flp.Height * 1.0 / (rows * 1.05));
  603. for (int i = 0; i < flpCC.Count; i++)
  604. {
  605. flpCC[i].Width = (int)(flp.Width * 1.0 / (columns * 1.1));
  606. flpCC[i].Height = (int)(flp.Height * 1.0 / (rows * 1.15));
  607. Console.WriteLine("flp::" + flp.Width + "," + flp.Height);
  608. //Console.WriteLine("tlp--"+flpCC[i].Width + "," + flpCC[i].Height);
  609. Control.ControlCollection tlpCC = flpCC[i].Controls;
  610. if (tlpCC.Count == 2)
  611. {
  612. tlpCC[0].Width = (int)(flpCC[i].Width * 0.95);
  613. tlpCC[0].Height = (int)(flpCC[i].Height * 0.79);
  614. tlpCC[1].Width = (int)(flpCC[i].Width * 0.95);
  615. tlpCC[1].Height = (int)(flpCC[i].Height * 0.20);
  616. }
  617. }
  618. lb_numMachine.BackColor = Color.BurlyWood;
  619. }
  620. catch (Exception ex) { Console.WriteLine(ex.Message); }
  621. picHandle = temp.Handle;
  622. }));
  623. }
  624. else
  625. {
  626. flp.Controls.Add(pb);
  627. picHandle = temp.Handle;
  628. }
  629. }
  630. catch (Exception e) { Console.WriteLine(e.Message); }
  631. namePicMap.Add(pb.Name, picHandle);
  632. pic = picHandle;
  633. //Console.WriteLine(picHandle.ToString());
  634. return true;
  635. }
  636. else
  637. return false;
  638. }
  639. }
  640. ///<summary>更新设备状态</summary>
  641. private int GetStatus(string devIP)
  642. {
  643. int myHandle;
  644. byte stat = 0;
  645. try
  646. {
  647. if (ipHandleMap.TryGetValue(devIP, out myHandle))
  648. {
  649. VzClientSDK.VzLPRClient_IsConnected(myHandle, ref stat);
  650. return stat;
  651. }
  652. }
  653. catch { Console.WriteLine("获取设备状态异常"); }
  654. return -1;
  655. }
  656. private string Get_IP(int lprHandle)
  657. {
  658. byte[] strDecIP = new byte[32];
  659. int max_count = 32;
  660. int ret = VzClientSDK.VzLPRClient_GetDeviceIP(lprHandle, ref strDecIP[0], max_count);
  661. string strIP = System.Text.Encoding.Default.GetString(strDecIP);
  662. strIP = strIP.TrimEnd('\0');
  663. return strIP;
  664. }
  665. private bool NodeValidation(NumberMachineNode node)
  666. {
  667. return (node != null && node.ip != null && node.ip != "" && node.ip != "used" && node.LicenseNum != null && node.LicenseNum != "") ? true : false;
  668. }
  669. /// <summary>
  670. /// 更新终端编号与号牌映射表
  671. /// </summary>
  672. /// <param name="license"></param>
  673. /// <param name="clearBuffer"></param>
  674. private void UpdateIdLicenseMap(bool clearBuffer)
  675. {
  676. NumberMachineNode node = null;
  677. lock (LicBuffer)
  678. {
  679. idLicenseMap.Clear();
  680. for (int i = 0; i < LicBuffer.Count; i++)
  681. {
  682. node = LicBuffer.Dequeue();
  683. if (node != null)
  684. {
  685. if (!idLicenseMap.ContainsKey(node.id))
  686. {
  687. idLicenseMap.Add(node.id, node.LicenseNum);
  688. }
  689. else
  690. {
  691. idLicenseMap[node.id] = node.LicenseNum;
  692. }
  693. }
  694. if (!clearBuffer)
  695. LicBuffer.Enqueue(node);
  696. }
  697. }
  698. }
  699. /// <summary>
  700. /// 系统启动
  701. /// </summary>
  702. public void Start()
  703. {
  704. Task.Factory.StartNew(() =>
  705. {
  706. isClosing = false;
  707. try
  708. {
  709. VzClientSDK.VZLPRClient_StopFindDevice();
  710. find_DeviceCB = new VzClientSDK.VZLPRC_FIND_DEVICE_CALLBACK_EX(FIND_DEVICE_CALLBACK_EX);
  711. int ret = VzClientSDK.VZLPRClient_StartFindDeviceEx(find_DeviceCB, IntPtr.Zero);
  712. }
  713. catch (Exception ex)
  714. {
  715. Debug.WriteLine(ex.ToString());
  716. }
  717. });
  718. //应答模式下号牌机不需要清除号牌
  719. //Task.Factory.StartNew(() =>
  720. //{
  721. // Run();
  722. //});
  723. //Task imgTest = Task.Factory.StartNew(() =>
  724. //{
  725. // while (!isClosing)
  726. // {
  727. // Command cmd = new Command
  728. // {
  729. // id = 1
  730. // };
  731. // SetMessage(cmd);
  732. // Thread.Sleep(30000);
  733. // Command cmd2 = new Command
  734. // {
  735. // id = 2
  736. // };
  737. // SetMessage(cmd2);
  738. // Thread.Sleep(30000);
  739. // }
  740. //});
  741. }
  742. /// <summary>
  743. /// 系统关闭
  744. /// </summary>
  745. public void Stop()
  746. {
  747. VzClientSDK.VZLPRClient_StopFindDevice();
  748. lock (devPicMap)
  749. {
  750. Dictionary<int, IntPtr>.Enumerator enumer = devPicMap.GetEnumerator();
  751. while (enumer.MoveNext())
  752. {
  753. if (enumer.Current.Key != 0)
  754. {
  755. StopPlay(enumer.Current.Key);
  756. VzClientSDK.VzLPRClient_Close(enumer.Current.Key);
  757. //flowLayoutPanel1.Controls.Remove(enumer.Current.Value);
  758. }
  759. }
  760. isClosing = true;
  761. devPicMap.Clear();
  762. }
  763. lock (namePicMap) { namePicMap.Clear(); }
  764. lock (ipIdMap) { ipIdMap.Clear(); }
  765. lock (ipHandleMap) { ipHandleMap.Clear(); }
  766. //this.Close();
  767. }
  768. /// <summary>
  769. /// 监控线程获取号牌机信息,核心线程获取号牌信息
  770. /// </summary>
  771. public AbstractMessage GetMessage()
  772. {
  773. //lock (LicBuffer)
  774. //{
  775. // //准备输出的数据中存在非法Node,且LicBuffer可出队产生一个合法Node,则替换该非法Node
  776. // if (!NodeValidation(nmMsg.aNode))
  777. // {
  778. // for (int i = 0; i < LicBuffer.Count; i++)
  779. // {
  780. // NumberMachineNode n = LicBuffer.Dequeue();
  781. // if (NodeValidation(n))
  782. // {
  783. // if (nmMsg.aNode != null && nmMsg.aNode.ip != null)
  784. // {
  785. // LicBuffer.Enqueue((NumberMachineNode)nmMsg.aNode.Clone());
  786. // }
  787. // nmMsg.aNode = n;
  788. // break;
  789. // }
  790. // else
  791. // {
  792. // LicBuffer.Enqueue(n);
  793. // }
  794. // }
  795. // //遍历licBuffer后仍不合法,则丢入队列,将node置为null
  796. // if (!NodeValidation(nmMsg.aNode))
  797. // {
  798. // if (nmMsg.aNode != null && nmMsg.aNode.ip != null)
  799. // {
  800. // LicBuffer.Enqueue((NumberMachineNode)nmMsg.aNode.Clone());
  801. // }
  802. // nmMsg.aNode = null;
  803. // }
  804. // }
  805. //}
  806. return nmMsg;
  807. }
  808. /// <summary>
  809. /// 一次停车流程完成时调用该方法,发送已完成车辆号牌信息
  810. /// </summary>
  811. /// <param name="message">已完成车辆的号牌相关信息存于message的aNode中,用于标记需清空的号牌</param>
  812. public void SetMessage(AbstractMessage message)
  813. {
  814. if (message.GetType().Equals(typeof(NumberMachineMessage)))
  815. {
  816. NumberMachineNode n = ((NumberMachineMessage)message).aNode;
  817. lock (LicBuffer)
  818. {
  819. //输入号牌格式无误
  820. if (n != null && n.ip != null && n.ip == "")
  821. {
  822. //与类成员变量中aNode号牌相同,将其ip复位表示已使用,重新入队等待清除
  823. if (nmMsg != null && nmMsg.aNode != null && nmMsg.aNode.LicenseNum == n.LicenseNum)
  824. {
  825. nmMsg.aNode.ip = "";
  826. LicBuffer.Enqueue((NumberMachineNode)nmMsg.aNode.Clone());
  827. nmMsg.aNode = null;
  828. }
  829. //搜索号牌队列,将相应号牌置空,准备清除
  830. else
  831. {
  832. for (int i = 0; i < LicBuffer.Count; i++)
  833. {
  834. NumberMachineNode temp = LicBuffer.Dequeue();
  835. //已匹配上,ip置空
  836. if (temp.LicenseNum == n.LicenseNum)
  837. {
  838. temp.ip = "";
  839. LicBuffer.Enqueue(temp);
  840. break;
  841. }
  842. LicBuffer.Enqueue(temp);
  843. }
  844. }
  845. }
  846. }
  847. }
  848. if (message.GetType().Equals(typeof(Command)))
  849. {
  850. Command cmd = (Command)message;
  851. if (cmd != null && cmd.id != 0)
  852. {
  853. //拍照功能根据ip找到handle,改变snapshotDevHandle的值在回调函数中截图
  854. lock (ipIdMap)
  855. {
  856. Dictionary<string, int>.Enumerator enumerator = ipIdMap.GetEnumerator();
  857. while (enumerator.MoveNext())
  858. {
  859. // if (enumerator.Current.Value == cmd.id && ipHandleMap.TryGetValue(enumerator.Current.Key, out int handle))
  860. int handle = 0;
  861. if (enumerator.Current.Value == cmd.id && ipHandleMap.TryGetValue(enumerator.Current.Key, out handle))
  862. {
  863. snapshotDevHandle = handle;
  864. break;
  865. }
  866. }
  867. }
  868. }
  869. else
  870. {
  871. Console.WriteLine("参数错误,图片未保存");
  872. }
  873. }
  874. }
  875. /// <summary>
  876. /// 根据id获取号牌
  877. /// </summary>
  878. /// <param name="id"></param>
  879. /// <returns></returns>
  880. public string GetLicensePlate(int id)
  881. {
  882. string license = "空";
  883. NumberMachineNode node = null;
  884. //Task.Factory.StartNew(() =>
  885. //{
  886. //清除同终端号过期号牌
  887. lock (LicBuffer)
  888. {
  889. for (int i = 0; i < LicBuffer.Count; i++)
  890. {
  891. node = LicBuffer.Dequeue();
  892. if (node != null)
  893. {
  894. if (node.id != id)
  895. {
  896. LicBuffer.Enqueue(node);
  897. }
  898. }
  899. }
  900. }
  901. //将相应计数器归零,启动号牌记录
  902. lock (idCountMap)
  903. {
  904. if (idCountMap.ContainsKey(id))
  905. {
  906. Dictionary<string, int>.Enumerator ipidEnumer = ipIdMap.GetEnumerator();
  907. int handle = 0;
  908. while (ipidEnumer.MoveNext())
  909. {
  910. if (ipidEnumer.Current.Value == id)
  911. {
  912. ipHandleMap.TryGetValue(ipidEnumer.Current.Key, out handle);
  913. break;
  914. }
  915. }
  916. idCountMap[id] = 0;
  917. int count = 0;
  918. while (count <= FILTERINGNUMBER)
  919. {
  920. //Console.WriteLine(handle);
  921. ActivateSnap(handle);
  922. count++;
  923. Thread.Sleep((int)(REFRESHINGTIME));
  924. }
  925. }
  926. }
  927. node = null;
  928. int timeLimit = FILTERINGNUMBER * 2;
  929. while (node == null && timeLimit-- > 0)
  930. {
  931. lock (LicBuffer)
  932. {
  933. //Log.WriteLog(LogType.process, LogFile.INFO, "licBuffer 元素个数:" + LicBuffer.Count);
  934. for (int i = 0; i < LicBuffer.Count; i++)
  935. {
  936. node = LicBuffer.Dequeue();
  937. if (node != null)
  938. {
  939. if (node.id == id && node.LicenseNum != "")
  940. {
  941. license = node.LicenseNum;
  942. //Log.WriteLog(LogType.process, LogFile.INFO, "license: " + license + ", id: " + id);
  943. break;
  944. }
  945. else
  946. {
  947. //Log.WriteLog(LogType.process, LogFile.INFO, "other license: " + node.LicenseNum + ", id: " + node.id);
  948. LicBuffer.Enqueue(node);
  949. }
  950. }
  951. }
  952. }
  953. Thread.Sleep(REFRESHINGTIME);
  954. }
  955. if (timeLimit <= 0) { Console.WriteLine("本次未找到号牌"); Log.WriteLog(LogType.process, LogFile.INFO, id + "号号牌机未找到号牌"); }
  956. else { Log.WriteLog(LogType.process, LogFile.INFO, id + "号号牌机本次号牌: [" + license + "]"); }
  957. //}).Wait();
  958. return license == "空" ? "" : license;
  959. }
  960. /// <summary>
  961. /// 获取号牌对应ID,以在手机停取时确定终端编号
  962. /// </summary>
  963. /// <param name="license"></param>
  964. /// <returns></returns>
  965. public int GetLicenseID(string license)
  966. {
  967. int id = 0;
  968. //启动所有号牌记录
  969. lock (ipHandleMap)
  970. {
  971. for (int i = 0; i < FILTERINGNUMBER; i++)
  972. {
  973. Dictionary<string, int>.Enumerator HandleEnumer = ipHandleMap.GetEnumerator();
  974. while (HandleEnumer.MoveNext())
  975. {
  976. ActivateSnap(HandleEnumer.Current.Value);
  977. Thread.Sleep(50);
  978. }
  979. Thread.Sleep((int)(REFRESHINGTIME * 0.8));
  980. }
  981. }
  982. Thread.Sleep(REFRESHINGTIME);
  983. UpdateIdLicenseMap(true);
  984. Dictionary<int, string>.Enumerator idEnumer = idLicenseMap.GetEnumerator();
  985. while (idEnumer.MoveNext())
  986. {
  987. if (idEnumer.Current.Value == license)
  988. {
  989. id = idEnumer.Current.Key;
  990. break;
  991. }
  992. }
  993. return id;
  994. }
  995. public Image GetImage(int id)
  996. {
  997. return null;
  998. }
  999. public Dictionary<string, int> GetIpIdMap()
  1000. {
  1001. return ipIdMap;
  1002. }
  1003. public void SetRatio(double ratio)
  1004. {
  1005. filterRatio = ratio;
  1006. }
  1007. }
  1008. }