NumMachine.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. using centralController;
  2. using parkMonitor.entity;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Diagnostics;
  7. using System.Drawing;
  8. using System.IO;
  9. using System.Net;
  10. using System.Runtime.InteropServices;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Windows.Forms;
  14. using VzClientSDKDemo;
  15. namespace NumMachine
  16. {
  17. /// <summary>
  18. /// 号牌机通信类
  19. /// </summary>
  20. public partial class NumMachineLinker : INumMachineLinker
  21. {
  22. /// <summary>
  23. /// 刷新时间间隔与个数
  24. /// </summary>
  25. public const int REFRESHINGTIME = 500, FILTERINGNUMBER = 4;
  26. ///<summary>通过设备句柄访问pic;链接时add,系统关闭时remove</summary>
  27. private static Dictionary<int, IntPtr> devPicMap = new Dictionary<int, IntPtr>();
  28. ///<summary>通过名字获取pic对象;创建pic时add,系统关闭remove</summary>
  29. private static Dictionary<string, IntPtr> namePicMap = new Dictionary<string, IntPtr>();
  30. ///<summary>通过ip获取设备id;产生ip时创建</summary>
  31. private static Dictionary<string, int> ipIdMap = new Dictionary<string, int>();
  32. ///<summary>通过ip获取设备句柄;产生句柄时创建</summary>
  33. private static Dictionary<string, int> ipHandleMap = new Dictionary<string, int>();
  34. /// <summary>句柄到号牌回调映射</summary>
  35. private static Dictionary<int, VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK> handleCallbackMap = new Dictionary<int, VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK>();
  36. ///<summary>号牌队列</summary>
  37. private static Queue<NumberMachineNode> LicBuffer = new Queue<NumberMachineNode>();
  38. ///<summary>计数Map</summary>
  39. private static Dictionary<string, Dictionary<NumberMachineNode, int>> filterMap = new Dictionary<string, Dictionary<NumberMachineNode, int>>();
  40. /// <summary>号牌机编号与激活计数</summary>
  41. private Dictionary<int, int> idCountMap = new Dictionary<int, int>();
  42. /// <summary>筛选计数</summary>
  43. private static int filterCount = 0;
  44. private static double filterRatio = 0.7;
  45. /// <summary>系统关闭</summary>
  46. private static bool isClosing = false;
  47. /// <summary>开启拍照的设备</summary>
  48. private static int snapshotDevHandle = -1;
  49. /// <summary>允许无号牌时拍照</summary>
  50. private static bool enableEmptySnapshot = true;
  51. private static NumberMachineMessage nmMsg = new NumberMachineMessage();
  52. private static VzClientSDK.VZLPRC_FIND_DEVICE_CALLBACK_EX find_DeviceCB = null;
  53. private const int MSG_PLATE_INFO = 0x901;
  54. private const int MSG_DEVICE_INFO = 0x902;
  55. /// <summary>
  56. /// 用于消息传递机制
  57. /// </summary>
  58. //public static IntPtr hwndMain;
  59. /// <summary>
  60. /// 定义时钟委托
  61. /// </summary>
  62. private delegate void SetDateTime();
  63. private static IntPtr flowLayoutPanel1;
  64. private static ToolStripStatusLabel timeLabel;
  65. /// <summary>
  66. /// 号牌机类构造函数
  67. /// </summary>
  68. public NumMachineLinker(IntPtr flpHandle)
  69. {
  70. //Control.CheckForIllegalCrossThreadCalls = false;
  71. //Thread thread = new Thread(new ThreadStart(DateTimeInfo));
  72. //thread.IsBackground = true;
  73. //thread.Start(); //显示当前时间
  74. flowLayoutPanel1 = flpHandle;
  75. //timeLabel = new ToolStripStatusLabel();
  76. try
  77. {
  78. VzClientSDK.VzLPRClient_Setup();
  79. filterRatio = Double.Parse(ConfigurationManager.AppSettings.Get("filterRatio"));
  80. }
  81. catch (Exception e) { Console.WriteLine(e.Message + ",号牌机配置文件异常"); }
  82. //m_sAppPath = System.IO.Directory.GetCurrentDirectory();
  83. }
  84. private void DateTimeInfo()
  85. {
  86. try
  87. {
  88. while (!isClosing)
  89. {
  90. SetDateTime setDate = new SetDateTime(
  91. delegate
  92. {
  93. timeLabel.Text = DateTime.Now.ToString();
  94. });
  95. setDate();
  96. Thread.Sleep(1000);
  97. }
  98. // ReSharper disable once FunctionNeverReturns
  99. }
  100. catch (Exception e) { Debug.Print(e.StackTrace); }
  101. }
  102. //******************************************************************************************************************
  103. private void UpdateStatus(NumberMachineNode nmn)
  104. {
  105. //提示次数计数
  106. int count = 0;
  107. while (!isClosing)
  108. {
  109. if (GetStatus(nmn.ip) == 1)
  110. {
  111. nmn.status = EnumNumberMachineStatus.Normal;
  112. count = 0;
  113. }
  114. else
  115. {
  116. count++;
  117. //号牌机断线写日志
  118. nmn.status = EnumNumberMachineStatus.Offline;
  119. if (count == 1)
  120. {
  121. Console.WriteLine("正在与ip为 " + nmn.ip + " 的号牌机 进行连接。");
  122. }
  123. else if (count == 30)
  124. {
  125. nmMsg.data.Remove(nmn);
  126. }
  127. Thread.Sleep(10000);
  128. }
  129. }
  130. }
  131. private void UpdateIpId()
  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 = (NumberMachineNode)LicBuffer.Dequeue().Clone();
  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. nmn.SetLic(strIP, nmn.id, plateInformation.plate, DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"), GetStatus(strIP));
  376. FilterLic(strIP, (NumberMachineNode)nmn.Clone());
  377. }
  378. //号牌为空
  379. else
  380. {
  381. nmn.SetLic(strIP, nmn.id, "", "", GetStatus(strIP));
  382. FilterLic(strIP, null);
  383. }
  384. }
  385. }
  386. //新设备
  387. if (!found)
  388. {
  389. lock (ipIdMap)
  390. {
  391. if (!(plateInformation.plate.Contains("_无_")) && ipIdMap.TryGetValue(strIP, out id))
  392. {
  393. NumberMachineNode nmn = new NumberMachineNode(strIP, id, plateInformation.plate, DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"), GetStatus(strIP));
  394. NumberMachineNode nmnc = (NumberMachineNode)nmn.Clone();
  395. nmMsg.data.Add(nmnc);
  396. FilterLic(strIP, nmnc);
  397. }
  398. else
  399. {
  400. nmMsg.data.Add(new NumberMachineNode(strIP, id, "", "", GetStatus(strIP)));
  401. FilterLic(strIP, null);
  402. }
  403. }
  404. }
  405. }
  406. ///<summary>筛选号牌</summary>
  407. private void FilterLic(string ip, NumberMachineNode nmn)
  408. {
  409. int id = 0, activeCount = 0;
  410. if (ipIdMap.TryGetValue(ip, out id) && idCountMap.TryGetValue(id, out activeCount) && activeCount < FILTERINGNUMBER)
  411. {
  412. Dictionary<NumberMachineNode, int> filter;
  413. //该filter不存在则创建
  414. if (!filterMap.ContainsKey(ip))
  415. {
  416. filter = new Dictionary<NumberMachineNode, int>();
  417. filterMap.Add(ip, filter);
  418. }
  419. else if (!filterMap.TryGetValue(ip, out filter))//计数器异常
  420. {
  421. return;
  422. }
  423. else if (activeCount == 0) //刚接到拍摄命令
  424. {
  425. filter.Clear();
  426. }
  427. //激活次数统计
  428. idCountMap[id] = activeCount + 1;
  429. //filter计数
  430. int count = 0;
  431. if (nmn == null)
  432. {
  433. if (activeCount >= FILTERINGNUMBER - 1)
  434. {
  435. //UILogServer.ins.error("本轮未扫描到号牌,请重新点击按钮停车");
  436. //string context = System.DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ":" + "号牌未扫描到,请重发指令";
  437. //string sql = "insert into messagequeue(userID,context,messageType) values (1,'" + context + "',1)";
  438. //List<string> strs = new List<string>();
  439. //strs.Add(sql);
  440. //DBOperation.InsertMessageQueue(EntityForCore.remoteBQ, strs);
  441. }
  442. return;
  443. }
  444. else if (filter.ContainsKey(nmn) && filter.TryGetValue(nmn, out count))//存在则数量+1
  445. {
  446. filter[nmn] = count + 1;
  447. }
  448. else//不存在则计数1
  449. {
  450. filter.Add(nmn, 1);
  451. }
  452. //计算总数
  453. filterCount = 0;
  454. Dictionary<NumberMachineNode, int>.Enumerator countEnumer = filter.GetEnumerator();
  455. while (countEnumer.MoveNext())
  456. {
  457. filterCount += countEnumer.Current.Value;
  458. }
  459. //达到计数限制,计算总数是否达标,达标则入队
  460. if (filterCount >= FILTERINGNUMBER)
  461. {
  462. lock (LicBuffer)
  463. {
  464. Dictionary<NumberMachineNode, int>.Enumerator enumer = filter.GetEnumerator();
  465. int maxCount = 0;
  466. NumberMachineNode node = null;
  467. while (enumer.MoveNext())
  468. {
  469. ////遍历,计数达标且队列中无此号牌
  470. //if (enumer.Current.Value >= (int)(filterCount * filterRatio) && enumer.Current.Key != null && !LicBuffer.Contains(enumer.Current.Key))
  471. //找到最大计数及相应号牌信息
  472. if (enumer.Current.Value >= maxCount && enumer.Current.Key != null && !LicBuffer.Contains(enumer.Current.Key))
  473. {
  474. //输出节点为空或与该号牌不同
  475. if (nmMsg.aNode == null || nmMsg.aNode.LicenseNum == null || nmMsg.aNode.LicenseNum != enumer.Current.Key.LicenseNum)
  476. {
  477. maxCount = enumer.Current.Value;
  478. node = (NumberMachineNode)enumer.Current.Key.Clone();
  479. if (node != null && ipIdMap.TryGetValue(node.ip, out node.id))
  480. {
  481. LicBuffer.Enqueue((NumberMachineNode)node.Clone());
  482. if (Monitor.Monitor.allInOneMachine != null)
  483. {
  484. Monitor.Monitor.allInOneMachine.DispForAWhile(2, node.LicenseNum, 25, 1, node.LicenseNum + ",入场");
  485. Monitor.Monitor.allInOneMachine.DispForAWhile(3, "号牌机编号:" + node.id, 25, 1, "");
  486. }
  487. }
  488. }
  489. }
  490. }
  491. }
  492. filterCount = 0;
  493. filter.Clear();
  494. }
  495. }
  496. }
  497. ///<summary>停止播放与设备句柄关联的视频</summary>
  498. private void StopPlay(int handleInput)
  499. {
  500. if (handleInput != 0)
  501. {
  502. int ret = VzClientSDK.VzLPRClient_StopRealPlay(handleInput);
  503. }
  504. }
  505. ///<summary>强制获取号牌</summary>
  506. private void ActivateSnap(int handle)
  507. {
  508. if (handle > 0)
  509. {
  510. VzClientSDK.VzLPRClient_ForceTrigger(handle);
  511. }
  512. }
  513. ///<summary>ip+port字符串转ipe</summary>
  514. private void GetIpEndPoint(string ipp, out IPEndPoint ipe)
  515. {
  516. IPAddress myIP = IPAddress.Parse(ipp.Remove(ipp.LastIndexOf(':')) + "");
  517. string myPort = ipp.Substring(ipp.IndexOf(':') + 1);
  518. ipe = new IPEndPoint(myIP, int.Parse(myPort));
  519. }
  520. ///<summary>创建新pic并记录在picNameMap</summary>
  521. private bool CreatePic(int index, int handle, out IntPtr pic)
  522. {
  523. pic = IntPtr.Zero;
  524. PictureBox pb = new PictureBox
  525. {
  526. Width = 179,
  527. Height = 127,
  528. //Bounds = new System.Drawing.Rectangle(0, 0, 230, 180),
  529. Name = "PictureBox" + Convert.ToString(index)
  530. };
  531. lock (namePicMap)
  532. {
  533. if (!namePicMap.ContainsKey(pb.Name))
  534. {
  535. PictureBox temp = pb;
  536. IntPtr picHandle = IntPtr.Zero;
  537. try
  538. {
  539. Control flp = Control.FromHandle(flowLayoutPanel1);
  540. //创建tableLayoutPanel显示号牌机信息
  541. string ip = Get_IP(handle);
  542. int id = 0;
  543. ipIdMap.TryGetValue(ip, out id);
  544. TableLayoutPanel tlp = new TableLayoutPanel()
  545. {
  546. Name = "tlp" + Convert.ToString(id),
  547. ColumnCount = 1,
  548. RowCount = 2,
  549. Size = new Size(185, 168),
  550. TabIndex = 3,
  551. };
  552. Label lb_numMachine = new Label()
  553. {
  554. Text = "编号" + id + "\nIP:" + ip,
  555. TextAlign = ContentAlignment.MiddleCenter,
  556. Size = new Size(179, 27)
  557. };
  558. //temp.Dock = DockStyle.Bottom;
  559. //lb_numMachine.Dock = DockStyle.Top;
  560. tlp.Controls.Add(temp, 0, 1);
  561. tlp.Controls.Add(lb_numMachine, 0, 0);
  562. tlp.RowStyles.Add(new RowStyle(SizeType.Percent, 20.00f));
  563. tlp.RowStyles.Add(new RowStyle(SizeType.Percent, 80.00f));
  564. temp.Click += delegate (object o, EventArgs e)
  565. {
  566. //Console.WriteLine(((PictureBox)o).TopLevelControl.Name+","+e.ToString());
  567. try
  568. {
  569. if (((PictureBox)o).TopLevelControl.Name != "FormNumberMachinePreview")
  570. {
  571. FormNumberMachinePreview form = new FormNumberMachinePreview("编号" + id + ", IP:" + ip, temp, tlp);
  572. form.ShowDialog();
  573. }
  574. }
  575. catch { }
  576. };
  577. //Control.FromHandle(flowLayoutPanel1).Controls.Add(temp);
  578. if (flp.InvokeRequired)
  579. {
  580. flp.Invoke(new Action(() =>
  581. {
  582. flp.Controls.Add(tlp);
  583. //for (int i = 0; i < 12; i++)
  584. //{
  585. // TableLayoutPanel tlpTemp = new TableLayoutPanel();
  586. // tlpTemp.Width = 200;
  587. // tlpTemp.Height = 200;
  588. // flp.Controls.Add(tlpTemp);
  589. //}
  590. Control.ControlCollection flpCC = flp.Controls;
  591. try
  592. {
  593. int rows = (int)Math.Sqrt(flp.Controls.Count + 1);
  594. int columns = (int)(flp.Controls.Count * 1.0 / rows + 1);
  595. //tlp.Width = (int)(flp.Width * 1.0 / (columns * 1.05));
  596. //tlp.Height = (int)(flp.Height * 1.0 / (rows * 1.05));
  597. for (int i = 0; i < flpCC.Count; i++)
  598. {
  599. flpCC[i].Width = (int)(flp.Width * 1.0 / (columns * 1.1));
  600. flpCC[i].Height = (int)(flp.Height * 1.0 / (rows * 1.15));
  601. Console.WriteLine("flp::" + flp.Width + "," + flp.Height);
  602. //Console.WriteLine("tlp--"+flpCC[i].Width + "," + flpCC[i].Height);
  603. Control.ControlCollection tlpCC = flpCC[i].Controls;
  604. if (tlpCC.Count == 2)
  605. {
  606. tlpCC[0].Width = (int)(flpCC[i].Width * 0.95);
  607. tlpCC[0].Height = (int)(flpCC[i].Height * 0.79);
  608. tlpCC[1].Width = (int)(flpCC[i].Width * 0.95);
  609. tlpCC[1].Height = (int)(flpCC[i].Height * 0.20);
  610. }
  611. }
  612. lb_numMachine.BackColor = Color.BurlyWood;
  613. }
  614. catch (Exception ex) { Console.WriteLine(ex.Message); }
  615. picHandle = temp.Handle;
  616. }));
  617. }
  618. else
  619. {
  620. flp.Controls.Add(pb);
  621. picHandle = temp.Handle;
  622. }
  623. }
  624. catch (Exception e) { Console.WriteLine(e.Message); }
  625. namePicMap.Add(pb.Name, picHandle);
  626. pic = picHandle;
  627. //Console.WriteLine(picHandle.ToString());
  628. return true;
  629. }
  630. else
  631. return false;
  632. }
  633. }
  634. ///<summary>更新设备状态</summary>
  635. private int GetStatus(string devIP)
  636. {
  637. int myHandle;
  638. byte stat = 0;
  639. if (ipHandleMap.TryGetValue(devIP, out myHandle))
  640. {
  641. VzClientSDK.VzLPRClient_IsConnected(myHandle, ref stat);
  642. return stat;
  643. }
  644. return -1;
  645. }
  646. private string Get_IP(int lprHandle)
  647. {
  648. byte[] strDecIP = new byte[32];
  649. int max_count = 32;
  650. int ret = VzClientSDK.VzLPRClient_GetDeviceIP(lprHandle, ref strDecIP[0], max_count);
  651. string strIP = System.Text.Encoding.Default.GetString(strDecIP);
  652. strIP = strIP.TrimEnd('\0');
  653. return strIP;
  654. }
  655. private bool NodeValidation(NumberMachineNode node)
  656. {
  657. return (node != null && node.ip != null && node.ip != "" && node.ip != "used" && node.LicenseNum != null && node.LicenseNum != "") ? true : false;
  658. }
  659. /// <summary>
  660. /// 系统启动
  661. /// </summary>
  662. public void Start()
  663. {
  664. Task.Factory.StartNew(() =>
  665. {
  666. isClosing = false;
  667. try
  668. {
  669. VzClientSDK.VZLPRClient_StopFindDevice();
  670. find_DeviceCB = new VzClientSDK.VZLPRC_FIND_DEVICE_CALLBACK_EX(FIND_DEVICE_CALLBACK_EX);
  671. int ret = VzClientSDK.VZLPRClient_StartFindDeviceEx(find_DeviceCB, IntPtr.Zero);
  672. }
  673. catch (Exception ex)
  674. {
  675. Debug.WriteLine(ex.ToString());
  676. }
  677. });
  678. Task.Factory.StartNew(() =>
  679. {
  680. Run();
  681. });
  682. //Task imgTest = Task.Factory.StartNew(() =>
  683. //{
  684. // while (!isClosing)
  685. // {
  686. // Command cmd = new Command
  687. // {
  688. // id = 1
  689. // };
  690. // SetMessage(cmd);
  691. // Thread.Sleep(30000);
  692. // Command cmd2 = new Command
  693. // {
  694. // id = 2
  695. // };
  696. // SetMessage(cmd2);
  697. // Thread.Sleep(30000);
  698. // }
  699. //});
  700. }
  701. /// <summary>
  702. /// 系统关闭
  703. /// </summary>
  704. public void Stop()
  705. {
  706. VzClientSDK.VZLPRClient_StopFindDevice();
  707. lock (devPicMap)
  708. {
  709. Dictionary<int, IntPtr>.Enumerator enumer = devPicMap.GetEnumerator();
  710. while (enumer.MoveNext())
  711. {
  712. if (enumer.Current.Key != 0)
  713. {
  714. StopPlay(enumer.Current.Key);
  715. VzClientSDK.VzLPRClient_Close(enumer.Current.Key);
  716. //flowLayoutPanel1.Controls.Remove(enumer.Current.Value);
  717. }
  718. }
  719. isClosing = true;
  720. devPicMap.Clear();
  721. }
  722. lock (namePicMap) { namePicMap.Clear(); }
  723. lock (ipIdMap) { ipIdMap.Clear(); }
  724. lock (ipHandleMap) { ipHandleMap.Clear(); }
  725. //this.Close();
  726. }
  727. /// <summary>
  728. /// 监控线程获取号牌机信息,核心线程获取号牌信息
  729. /// </summary>
  730. public AbstractMessage GetMessage()
  731. {
  732. //lock (LicBuffer)
  733. //{
  734. // //准备输出的数据中存在非法Node,且LicBuffer可出队产生一个合法Node,则替换该非法Node
  735. // if (!NodeValidation(nmMsg.aNode))
  736. // {
  737. // for (int i = 0; i < LicBuffer.Count; i++)
  738. // {
  739. // NumberMachineNode n = LicBuffer.Dequeue();
  740. // if (NodeValidation(n))
  741. // {
  742. // if (nmMsg.aNode != null && nmMsg.aNode.ip != null)
  743. // {
  744. // LicBuffer.Enqueue((NumberMachineNode)nmMsg.aNode.Clone());
  745. // }
  746. // nmMsg.aNode = n;
  747. // break;
  748. // }
  749. // else
  750. // {
  751. // LicBuffer.Enqueue(n);
  752. // }
  753. // }
  754. // //遍历licBuffer后仍不合法,则丢入队列,将node置为null
  755. // if (!NodeValidation(nmMsg.aNode))
  756. // {
  757. // if (nmMsg.aNode != null && nmMsg.aNode.ip != null)
  758. // {
  759. // LicBuffer.Enqueue((NumberMachineNode)nmMsg.aNode.Clone());
  760. // }
  761. // nmMsg.aNode = null;
  762. // }
  763. // }
  764. //}
  765. return nmMsg;
  766. }
  767. /// <summary>
  768. /// 一次停车流程完成时调用该方法,发送已完成车辆号牌信息
  769. /// </summary>
  770. /// <param name="message">已完成车辆的号牌相关信息存于message的aNode中,用于标记需清空的号牌</param>
  771. public void SetMessage(AbstractMessage message)
  772. {
  773. if (message.GetType().Equals(typeof(NumberMachineMessage)))
  774. {
  775. NumberMachineNode n = ((NumberMachineMessage)message).aNode;
  776. lock (LicBuffer)
  777. {
  778. //输入号牌格式无误
  779. if (n != null && n.ip != null && n.ip == "")
  780. {
  781. //与类成员变量中aNode号牌相同,将其ip复位表示已使用,重新入队等待清除
  782. if (nmMsg != null && nmMsg.aNode != null && nmMsg.aNode.LicenseNum == n.LicenseNum)
  783. {
  784. nmMsg.aNode.ip = "";
  785. LicBuffer.Enqueue((NumberMachineNode)nmMsg.aNode.Clone());
  786. nmMsg.aNode = null;
  787. }
  788. //搜索号牌队列,将相应号牌置空,准备清除
  789. else
  790. {
  791. for (int i = 0; i < LicBuffer.Count; i++)
  792. {
  793. NumberMachineNode temp = LicBuffer.Dequeue();
  794. //已匹配上,ip置空
  795. if (temp.LicenseNum == n.LicenseNum)
  796. {
  797. temp.ip = "";
  798. LicBuffer.Enqueue(temp);
  799. break;
  800. }
  801. LicBuffer.Enqueue(temp);
  802. }
  803. }
  804. }
  805. }
  806. }
  807. if (message.GetType().Equals(typeof(Command)))
  808. {
  809. Command cmd = (Command)message;
  810. if (cmd != null && cmd.id != 0)
  811. {
  812. //拍照功能根据ip找到handle,改变snapshotDevHandle的值在回调函数中截图
  813. lock (ipIdMap)
  814. {
  815. Dictionary<string, int>.Enumerator enumerator = ipIdMap.GetEnumerator();
  816. while (enumerator.MoveNext())
  817. {
  818. // if (enumerator.Current.Value == cmd.id && ipHandleMap.TryGetValue(enumerator.Current.Key, out int handle))
  819. int handle = 0;
  820. if (enumerator.Current.Value == cmd.id && ipHandleMap.TryGetValue(enumerator.Current.Key, out handle))
  821. {
  822. snapshotDevHandle = handle;
  823. break;
  824. }
  825. }
  826. }
  827. }
  828. else
  829. {
  830. Console.WriteLine("参数错误,图片未保存");
  831. }
  832. }
  833. }
  834. public string GetLicensePlate(int id)
  835. {
  836. string license = "";
  837. Task.Factory.StartNew(() =>
  838. {
  839. //将相应计数器归零,启动号牌记录
  840. lock (idCountMap)
  841. {
  842. if (idCountMap.ContainsKey(id))
  843. {
  844. Dictionary<string, int>.Enumerator ipidEnumer = ipIdMap.GetEnumerator();
  845. int handle = 0;
  846. while (ipidEnumer.MoveNext())
  847. {
  848. if(ipidEnumer.Current.Value == id)
  849. {
  850. ipHandleMap.TryGetValue(ipidEnumer.Current.Key, out handle);
  851. break;
  852. }
  853. }
  854. while (idCountMap[id] < FILTERINGNUMBER)
  855. {
  856. Console.WriteLine(handle);
  857. ActivateSnap(handle);
  858. Thread.Sleep((int)(REFRESHINGTIME*0.6));
  859. }
  860. idCountMap[id] = 0;
  861. }
  862. }
  863. NumberMachineNode node = null;
  864. int timeLimit = FILTERINGNUMBER+2;
  865. while (node == null && timeLimit-- > 0)
  866. {
  867. lock (LicBuffer)
  868. {
  869. for (int i = 0; i < LicBuffer.Count; i++)
  870. {
  871. node = LicBuffer.Dequeue();
  872. if (node != null)
  873. {
  874. if (node.id == id)
  875. {
  876. license = node.LicenseNum;
  877. break;
  878. }
  879. else
  880. {
  881. LicBuffer.Enqueue(node);
  882. }
  883. }
  884. }
  885. }
  886. Thread.Sleep(REFRESHINGTIME);
  887. if (timeLimit == 0) { Console.WriteLine("本次未找到号牌"); }
  888. }
  889. }).Wait();
  890. return license;
  891. }
  892. public Image GetImage(int id)
  893. {
  894. return null;
  895. }
  896. public Dictionary<string, int> GetIpIdMap()
  897. {
  898. return ipIdMap;
  899. }
  900. public void SetRatio(double ratio)
  901. {
  902. filterRatio = ratio;
  903. }
  904. }
  905. }